diff options
Diffstat (limited to 'source/Host/common')
| -rw-r--r-- | source/Host/common/Editline.cpp | 246 | ||||
| -rw-r--r-- | source/Host/common/File.cpp | 81 | ||||
| -rw-r--r-- | source/Host/common/FileSpec.cpp | 358 | ||||
| -rw-r--r-- | source/Host/common/Host.cpp | 71 | ||||
| -rw-r--r-- | source/Host/common/HostInfoBase.cpp | 34 | ||||
| -rw-r--r-- | source/Host/common/HostProcess.cpp | 4 | ||||
| -rw-r--r-- | source/Host/common/MonitoringProcessLauncher.cpp | 4 | ||||
| -rw-r--r-- | source/Host/common/NativeBreakpointList.cpp | 13 | ||||
| -rw-r--r-- | source/Host/common/NativeProcessProtocol.cpp | 56 | ||||
| -rw-r--r-- | source/Host/common/OptionParser.cpp | 6 | ||||
| -rw-r--r-- | source/Host/common/Socket.cpp | 2 | ||||
| -rw-r--r-- | source/Host/common/SocketAddress.cpp | 6 | ||||
| -rw-r--r-- | source/Host/common/SoftwareBreakpoint.cpp | 1 | ||||
| -rw-r--r-- | source/Host/common/TCPSocket.cpp | 3 | ||||
| -rw-r--r-- | source/Host/common/UDPSocket.cpp | 8 |
15 files changed, 509 insertions, 384 deletions
diff --git a/source/Host/common/Editline.cpp b/source/Host/common/Editline.cpp index 4640154c6cb1..d7209feb46db 100644 --- a/source/Host/common/Editline.cpp +++ b/source/Host/common/Editline.cpp @@ -19,7 +19,6 @@ #include "lldb/Host/FileSpec.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" -#include "lldb/Host/Mutex.h" #include "lldb/Utility/LLDBAssert.h" using namespace lldb_private; @@ -227,9 +226,9 @@ namespace lldb_private GetHistory (const std::string &prefix) { typedef std::map<std::string, EditlineHistoryWP> WeakHistoryMap; - static Mutex g_mutex (Mutex::eMutexTypeRecursive); + static std::recursive_mutex g_mutex; static WeakHistoryMap g_weak_map; - Mutex::Locker locker (g_mutex); + std::lock_guard<std::recursive_mutex> guard(g_mutex); WeakHistoryMap::const_iterator pos = g_weak_map.find (prefix); EditlineHistorySP history_sp; if (pos != g_weak_map.end()) @@ -587,9 +586,9 @@ Editline::GetCharacter (EditLineCharType * c) // (blocking operation), so we do not hold the mutex indefinitely. This gives a chance // for someone to interrupt us. After Read returns, immediately lock the mutex again and // check if we were interrupted. - m_output_mutex.Unlock(); + m_output_mutex.unlock(); int read_count = m_input_connection.Read(&ch, 1, UINT32_MAX, status, NULL); - m_output_mutex.Lock(); + m_output_mutex.lock(); if (m_editor_status == EditorStatus::Interrupted) { while (read_count > 0 && status == lldb::eConnectionStatusSuccess) @@ -658,41 +657,9 @@ Editline::BreakLineCommand (int ch) // Establish the new cursor position at the start of a line when inserting a line break m_revert_cursor_index = 0; - // Don't perform end of input detection or automatic formatting when pasting + // Don't perform automatic formatting when pasting if (!IsInputPending (m_input_file)) { - // If this is the end of the last line, treat this as a potential exit - if (m_current_line_index == m_input_lines.size() - 1 && new_line_fragment.length() == 0) - { - bool end_of_input = true; - if (m_is_input_complete_callback) - { - SaveEditedLine(); - auto lines = GetInputAsStringList(); - end_of_input = m_is_input_complete_callback (this, lines, m_is_input_complete_callback_baton); - - // The completion test is allowed to change the input lines when complete - if (end_of_input) - { - m_input_lines.clear(); - for (unsigned index = 0; index < lines.GetSize(); index++) - { -#if LLDB_EDITLINE_USE_WCHAR - m_input_lines.insert (m_input_lines.end(), m_utf8conv.from_bytes (lines[index])); -#else - m_input_lines.insert (m_input_lines.end(), lines[index]); -#endif - } - } - } - if (end_of_input) - { - fprintf (m_output_file, "\n"); - m_editor_status = EditorStatus::Complete; - return CC_NEWLINE; - } - } - // Apply smart indentation if (m_fix_indentation_callback) { @@ -721,7 +688,49 @@ Editline::BreakLineCommand (int ch) } unsigned char -Editline::DeleteNextCharCommand (int ch) +Editline::EndOrAddLineCommand(int ch) +{ + // Don't perform end of input detection when pasting, always treat this as a line break + if (IsInputPending(m_input_file)) + { + return BreakLineCommand(ch); + } + + // Save any edits to this line + SaveEditedLine(); + + // If this is the end of the last line, consider whether to add a line instead + const LineInfoW *info = el_wline(m_editline); + if (m_current_line_index == m_input_lines.size() - 1 && info->cursor == info->lastchar) + { + if (m_is_input_complete_callback) + { + auto lines = GetInputAsStringList(); + if (!m_is_input_complete_callback(this, lines, m_is_input_complete_callback_baton)) + { + return BreakLineCommand(ch); + } + + // The completion test is allowed to change the input lines when complete + m_input_lines.clear(); + for (unsigned index = 0; index < lines.GetSize(); index++) + { +#if LLDB_EDITLINE_USE_WCHAR + m_input_lines.insert(m_input_lines.end(), m_utf8conv.from_bytes(lines[index])); +#else + m_input_lines.insert(m_input_lines.end(), lines[index]); +#endif + } + } + } + MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockEnd); + fprintf(m_output_file, "\n"); + m_editor_status = EditorStatus::Complete; + return CC_NEWLINE; +} + +unsigned char +Editline::DeleteNextCharCommand(int ch) { LineInfoW * info = const_cast<LineInfoW *>(el_wline (m_editline)); @@ -861,7 +870,23 @@ Editline::NextLineCommand (int ch) } unsigned char -Editline::FixIndentationCommand (int ch) +Editline::PreviousHistoryCommand(int ch) +{ + SaveEditedLine(); + + return RecallHistory(true); +} + +unsigned char +Editline::NextHistoryCommand(int ch) +{ + SaveEditedLine(); + + return RecallHistory(false); +} + +unsigned char +Editline::FixIndentationCommand(int ch) { if (!m_fix_indentation_callback) return CC_NORM; @@ -1075,36 +1100,46 @@ Editline::ConfigureEditor (bool multiline) })); // Commands used for multiline support, registered whether or not they're used - el_set (m_editline, EL_ADDFN, "lldb-break-line", "Insert a line break", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->BreakLineCommand (ch); - })); - el_set (m_editline, EL_ADDFN, "lldb-delete-next-char", "Delete next character", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->DeleteNextCharCommand (ch); - })); - el_set (m_editline, EL_ADDFN, "lldb-delete-previous-char", "Delete previous character", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->DeletePreviousCharCommand (ch); - })); - el_set (m_editline, EL_ADDFN, "lldb-previous-line", "Move to previous line", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->PreviousLineCommand (ch); - })); - el_set (m_editline, EL_ADDFN, "lldb-next-line", "Move to next line", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->NextLineCommand (ch); - })); - el_set (m_editline, EL_ADDFN, "lldb-buffer-start", "Move to start of buffer", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->BufferStartCommand (ch); - })); - el_set (m_editline, EL_ADDFN, "lldb-buffer-end", "Move to end of buffer", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->BufferEndCommand (ch); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-break-line"), EditLineConstString("Insert a line break"), + (EditlineCommandCallbackType)( + [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->BreakLineCommand(ch); })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-end-or-add-line"), + EditLineConstString("End editing or continue when incomplete"), + (EditlineCommandCallbackType)( + [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->EndOrAddLineCommand(ch); })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-next-char"), + EditLineConstString("Delete next character"), (EditlineCommandCallbackType)([](EditLine *editline, int ch) { + return Editline::InstanceFor(editline)->DeleteNextCharCommand(ch); + })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-delete-previous-char"), + EditLineConstString("Delete previous character"), + (EditlineCommandCallbackType)([](EditLine *editline, int ch) { + return Editline::InstanceFor(editline)->DeletePreviousCharCommand(ch); })); - el_set (m_editline, EL_ADDFN, "lldb-fix-indentation", "Fix line indentation", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-line"), + EditLineConstString("Move to previous line"), (EditlineCommandCallbackType)([](EditLine *editline, int ch) { + return Editline::InstanceFor(editline)->PreviousLineCommand(ch); + })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-line"), EditLineConstString("Move to next line"), + (EditlineCommandCallbackType)( + [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->NextLineCommand(ch); })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-previous-history"), + EditLineConstString("Move to previous history"), + (EditlineCommandCallbackType)([](EditLine *editline, int ch) { + return Editline::InstanceFor(editline)->PreviousHistoryCommand(ch); + })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-next-history"), EditLineConstString("Move to next history"), + (EditlineCommandCallbackType)( + [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->NextHistoryCommand(ch); })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-start"), + EditLineConstString("Move to start of buffer"), + (EditlineCommandCallbackType)( + [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->BufferStartCommand(ch); })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-buffer-end"), EditLineConstString("Move to end of buffer"), + (EditlineCommandCallbackType)( + [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->BufferEndCommand(ch); })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-fix-indentation"), + EditLineConstString("Fix line indentation"), (EditlineCommandCallbackType)([](EditLine *editline, int ch) { return Editline::InstanceFor (editline)->FixIndentationCommand (ch); })); @@ -1115,9 +1150,11 @@ Editline::ConfigureEditor (bool multiline) EditlineCommandCallbackType complete_callback = [] (EditLine * editline, int ch) { return Editline::InstanceFor (editline)->TabCommand (ch); }; - el_set (m_editline, EL_ADDFN, "lldb-complete", "Invoke completion", complete_callback); - el_set (m_editline, EL_ADDFN, "lldb_complete", "Invoke completion", complete_callback); - + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-complete"), EditLineConstString("Invoke completion"), + complete_callback); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb_complete"), EditLineConstString("Invoke completion"), + complete_callback); + // General bindings we don't mind being overridden if (!multiline) { el_set (m_editline, EL_BIND, "^r", "em-inc-search-prev", NULL); // Cycle through backwards search, entering string @@ -1129,10 +1166,10 @@ Editline::ConfigureEditor (bool multiline) el_source (m_editline, NULL); // Register an internal binding that external developers shouldn't use - el_set (m_editline, EL_ADDFN, "lldb-revert-line", "Revert line to saved state", - (EditlineCommandCallbackType)([] (EditLine * editline, int ch) { - return Editline::InstanceFor (editline)->RevertLineCommand (ch); - })); + el_wset(m_editline, EL_ADDFN, EditLineConstString("lldb-revert-line"), + EditLineConstString("Revert line to saved state"), + (EditlineCommandCallbackType)( + [](EditLine *editline, int ch) { return Editline::InstanceFor(editline)->RevertLineCommand(ch); })); // Register keys that perform auto-indent correction if (m_fix_indentation_callback && m_fix_indentation_callback_chars) @@ -1150,8 +1187,10 @@ Editline::ConfigureEditor (bool multiline) // Multi-line editor bindings if (multiline) { - el_set (m_editline, EL_BIND, "\n", "lldb-break-line", NULL); - el_set (m_editline, EL_BIND, "\r", "lldb-break-line", NULL); + el_set(m_editline, EL_BIND, "\n", "lldb-end-or-add-line", NULL); + el_set(m_editline, EL_BIND, "\r", "lldb-end-or-add-line", NULL); + el_set(m_editline, EL_BIND, ESCAPE "\n", "lldb-break-line", NULL); + el_set(m_editline, EL_BIND, ESCAPE "\r", "lldb-break-line", NULL); el_set (m_editline, EL_BIND, "^p", "lldb-previous-line", NULL); el_set (m_editline, EL_BIND, "^n", "lldb-next-line", NULL); el_set (m_editline, EL_BIND, "^?", "lldb-delete-previous-char", NULL); @@ -1166,6 +1205,10 @@ Editline::ConfigureEditor (bool multiline) el_set (m_editline, EL_BIND, ESCAPE ">", "lldb-buffer-end", NULL); el_set (m_editline, EL_BIND, ESCAPE "[A", "lldb-previous-line", NULL); el_set (m_editline, EL_BIND, ESCAPE "[B", "lldb-next-line", NULL); + el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[A", "lldb-previous-history", NULL); + el_set(m_editline, EL_BIND, ESCAPE ESCAPE "[B", "lldb-next-history", NULL); + el_set(m_editline, EL_BIND, ESCAPE "[1;3A", "lldb-previous-history", NULL); + el_set(m_editline, EL_BIND, ESCAPE "[1;3B", "lldb-next-history", NULL); } else { @@ -1209,6 +1252,32 @@ Editline::Editline (const char * editline_name, FILE * input_file, FILE * output // Get a shared history instance m_editor_name = (editline_name == nullptr) ? "lldb-tmp" : editline_name; m_history_sp = EditlineHistory::GetHistory (m_editor_name); + +#ifdef USE_SETUPTERM_WORKAROUND + if (m_output_file) + { + const int term_fd = fileno(m_output_file); + if (term_fd != -1) + { + static std::mutex *g_init_terminal_fds_mutex_ptr = nullptr; + static std::set<int> *g_init_terminal_fds_ptr = nullptr; + static std::once_flag g_once_flag; + std::call_once(g_once_flag, [&]() { + g_init_terminal_fds_mutex_ptr = new std::mutex(); // NOTE: Leak to avoid C++ destructor chain issues + g_init_terminal_fds_ptr = new std::set<int>(); // NOTE: Leak to avoid C++ destructor chain issues + }); + + // We must make sure to initialize the terminal a given file descriptor + // only once. If we do this multiple times, we start leaking memory. + std::lock_guard<std::mutex> guard(*g_init_terminal_fds_mutex_ptr); + if (g_init_terminal_fds_ptr->find(term_fd) == g_init_terminal_fds_ptr->end()) + { + g_init_terminal_fds_ptr->insert(term_fd); + setupterm((char *)0, term_fd, (int *)0); + } + } + } +#endif } Editline::~Editline() @@ -1284,7 +1353,7 @@ bool Editline::Interrupt() { bool result = true; - Mutex::Locker locker(m_output_mutex); + std::lock_guard<std::mutex> guard(m_output_mutex); if (m_editor_status == EditorStatus::Editing) { fprintf(m_output_file, "^C\n"); result = m_input_connection.InterruptRead(); @@ -1297,7 +1366,7 @@ bool Editline::Cancel() { bool result = true; - Mutex::Locker locker(m_output_mutex); + std::lock_guard<std::mutex> guard(m_output_mutex); if (m_editor_status == EditorStatus::Editing) { MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart); fprintf(m_output_file, ANSI_CLEAR_BELOW); @@ -1338,8 +1407,8 @@ Editline::GetLine (std::string &line, bool &interrupted) ConfigureEditor (false); m_input_lines = std::vector<EditLineStringType>(); m_input_lines.insert (m_input_lines.begin(), EditLineConstString("")); - - Mutex::Locker locker(m_output_mutex); + + std::lock_guard<std::mutex> guard(m_output_mutex); lldbassert(m_editor_status != EditorStatus::Editing); if (m_editor_status == EditorStatus::Interrupted) @@ -1354,10 +1423,6 @@ Editline::GetLine (std::string &line, bool &interrupted) m_editor_status = EditorStatus::Editing; m_revert_cursor_index = -1; -#ifdef USE_SETUPTERM_WORKAROUND - setupterm((char *)0, fileno(m_output_file), (int *)0); -#endif - int count; auto input = el_wgets (m_editline, &count); @@ -1392,8 +1457,8 @@ Editline::GetLines (int first_line_number, StringList &lines, bool &interrupted) SetBaseLineNumber (first_line_number); m_input_lines = std::vector<EditLineStringType>(); m_input_lines.insert (m_input_lines.begin(), EditLineConstString("")); - - Mutex::Locker locker(m_output_mutex); + + std::lock_guard<std::mutex> guard(m_output_mutex); // Begin the line editing loop DisplayInput(); SetCurrentLine (0); @@ -1404,9 +1469,6 @@ Editline::GetLines (int first_line_number, StringList &lines, bool &interrupted) m_revert_cursor_index = -1; while (m_editor_status == EditorStatus::Editing) { -#ifdef USE_SETUPTERM_WORKAROUND - setupterm((char *)0, fileno(m_output_file), (int *)0); -#endif int count; m_current_line_rows = -1; el_wpush (m_editline, EditLineConstString("\x1b[^")); // Revert to the existing line content @@ -1427,7 +1489,7 @@ Editline::GetLines (int first_line_number, StringList &lines, bool &interrupted) void Editline::PrintAsync (Stream *stream, const char *s, size_t len) { - Mutex::Locker locker(m_output_mutex); + std::lock_guard<std::mutex> guard(m_output_mutex); if (m_editor_status == EditorStatus::Editing) { MoveCursor(CursorLocation::EditingCursor, CursorLocation::BlockStart); diff --git a/source/Host/common/File.cpp b/source/Host/common/File.cpp index 71a6149cd614..9d4ab3d9c55e 100644 --- a/source/Host/common/File.cpp +++ b/source/Host/common/File.cpp @@ -14,7 +14,6 @@ #include <limits.h> #include <stdarg.h> #include <stdio.h> -#include <sys/stat.h> #ifdef _WIN32 #include "lldb/Host/windows/windows.h" @@ -22,6 +21,7 @@ #include <sys/ioctl.h> #endif +#include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Process.h" // for llvm::sys::Process::FileDescriptorHasColors() #include "lldb/Core/DataBufferHeap.h" @@ -29,6 +29,7 @@ #include "lldb/Core/Log.h" #include "lldb/Host/Config.h" #include "lldb/Host/FileSpec.h" +#include "lldb/Host/FileSystem.h" using namespace lldb; using namespace lldb_private; @@ -109,27 +110,6 @@ File::File (const FileSpec& filespec, } } -File::File (const File &rhs) : - IOObject(eFDTypeFile, false), - m_descriptor (kInvalidDescriptor), - m_stream (kInvalidStream), - m_options (0), - m_own_stream (false), - m_is_interactive (eLazyBoolCalculate), - m_is_real_terminal (eLazyBoolCalculate) -{ - Duplicate (rhs); -} - - -File & -File::operator = (const File &rhs) -{ - if (this != &rhs) - Duplicate (rhs); - return *this; -} - File::~File() { Close (); @@ -191,7 +171,7 @@ File::GetStream () #ifdef _WIN32 m_descriptor = ::_dup(GetDescriptor()); #else - m_descriptor = ::fcntl(GetDescriptor(), F_DUPFD); + m_descriptor = dup(GetDescriptor()); #endif m_should_close_fd = true; } @@ -215,7 +195,6 @@ File::GetStream () return m_stream; } - void File::SetStream (FILE *fh, bool transfer_ownership) { @@ -226,35 +205,6 @@ File::SetStream (FILE *fh, bool transfer_ownership) } Error -File::Duplicate (const File &rhs) -{ - Error error; - if (IsValid ()) - Close(); - - if (rhs.DescriptorIsValid()) - { -#ifdef _WIN32 - m_descriptor = ::_dup(rhs.GetDescriptor()); -#else - m_descriptor = ::fcntl(rhs.GetDescriptor(), F_DUPFD); -#endif - if (!DescriptorIsValid()) - error.SetErrorToErrno(); - else - { - m_options = rhs.m_options; - m_should_close_fd = true; - } - } - else - { - error.SetErrorString ("invalid file to duplicate"); - } - return error; -} - -Error File::Open (const char *path, uint32_t options, uint32_t permissions) { Error error; @@ -288,7 +238,7 @@ File::Open (const char *path, uint32_t options, uint32_t permissions) oflag |= O_RDONLY; #ifndef _WIN32 - if (options & eOpenoptionDontFollowSymlinks) + if (options & eOpenOptionDontFollowSymlinks) oflag |= O_NOFOLLOW; #endif } @@ -318,7 +268,18 @@ File::Open (const char *path, uint32_t options, uint32_t permissions) do { +#ifdef _WIN32 + std::wstring wpath; + if (!llvm::ConvertUTF8toWide(path, wpath)) + { + m_descriptor = -1; + error.SetErrorString("Error converting path to UTF-16"); + return error; + } + ::_wsopen_s(&m_descriptor, wpath.c_str(), oflag, _SH_DENYNO, mode); +#else m_descriptor = ::open(path, oflag, mode); +#endif } while (m_descriptor < 0 && errno == EINTR); if (!DescriptorIsValid()) @@ -338,7 +299,8 @@ File::GetPermissions(const FileSpec &file_spec, Error &error) if (file_spec) { struct stat file_stats; - if (::stat(file_spec.GetCString(), &file_stats) == -1) + int stat_result = FileSystem::Stat(file_spec.GetCString(), &file_stats); + if (stat_result == -1) error.SetErrorToErrno(); else { @@ -399,6 +361,15 @@ File::Close () return error; } +void +File::Clear () +{ + m_stream = nullptr; + m_descriptor = -1; + m_options = 0; + m_own_stream = false; + m_is_interactive = m_supports_colors = m_is_real_terminal = eLazyBoolCalculate; +} Error File::GetFileSpec (FileSpec &file_spec) const diff --git a/source/Host/common/FileSpec.cpp b/source/Host/common/FileSpec.cpp index 8885a791d88c..53c0ab40e676 100644 --- a/source/Host/common/FileSpec.cpp +++ b/source/Host/common/FileSpec.cpp @@ -17,7 +17,6 @@ #ifndef _MSC_VER #include <libgen.h> #endif -#include <sys/stat.h> #include <set> #include <string.h> #include <fstream> @@ -40,6 +39,7 @@ #include "lldb/Utility/CleanUp.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Support/ConvertUTF.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/Program.h" @@ -57,10 +57,22 @@ PathSyntaxIsPosix(FileSpec::PathSyntax syntax) FileSystem::GetNativePathSyntax() == FileSpec::ePathSyntaxPosix)); } +const char * +GetPathSeparators(FileSpec::PathSyntax syntax) +{ + return PathSyntaxIsPosix(syntax) ? "/" : "\\/"; +} + char -GetPathSeparator(FileSpec::PathSyntax syntax) +GetPrefferedPathSeparator(FileSpec::PathSyntax syntax) +{ + return GetPathSeparators(syntax)[0]; +} + +bool +IsPathSeparator(char value, FileSpec::PathSyntax syntax) { - return PathSyntaxIsPosix(syntax) ? '/' : '\\'; + return value == '/' || (!PathSyntaxIsPosix(syntax) && value == '\\'); } void @@ -90,12 +102,73 @@ GetFileStats (const FileSpec *file_spec, struct stat *stats_ptr) { char resolved_path[PATH_MAX]; if (file_spec->GetPath (resolved_path, sizeof(resolved_path))) - return ::stat (resolved_path, stats_ptr) == 0; + return FileSystem::Stat(resolved_path, stats_ptr) == 0; return false; } +size_t +FilenamePos(llvm::StringRef str, FileSpec::PathSyntax syntax) +{ + if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1]) + return 0; + + if (str.size() > 0 && IsPathSeparator(str.back(), syntax)) + return str.size() - 1; + + size_t pos = str.find_last_of(GetPathSeparators(syntax), str.size() - 1); + + if (!PathSyntaxIsPosix(syntax) && pos == llvm::StringRef::npos) + pos = str.find_last_of(':', str.size() - 2); + + if (pos == llvm::StringRef::npos || (pos == 1 && IsPathSeparator(str[0], syntax))) + return 0; + + return pos + 1; +} + +size_t +RootDirStart(llvm::StringRef str, FileSpec::PathSyntax syntax) +{ + // case "c:/" + if (!PathSyntaxIsPosix(syntax) && (str.size() > 2 && str[1] == ':' && IsPathSeparator(str[2], syntax))) + return 2; + + // case "//" + if (str.size() == 2 && IsPathSeparator(str[0], syntax) && str[0] == str[1]) + return llvm::StringRef::npos; + + // case "//net" + if (str.size() > 3 && IsPathSeparator(str[0], syntax) && str[0] == str[1] && !IsPathSeparator(str[2], syntax)) + return str.find_first_of(GetPathSeparators(syntax), 2); + + // case "/" + if (str.size() > 0 && IsPathSeparator(str[0], syntax)) + return 0; + + return llvm::StringRef::npos; } +size_t +ParentPathEnd(llvm::StringRef path, FileSpec::PathSyntax syntax) +{ + size_t end_pos = FilenamePos(path, syntax); + + bool filename_was_sep = path.size() > 0 && IsPathSeparator(path[end_pos], syntax); + + // Skip separators except for root dir. + size_t root_dir_pos = RootDirStart(path.substr(0, end_pos), syntax); + + while (end_pos > 0 && (end_pos - 1) != root_dir_pos && IsPathSeparator(path[end_pos - 1], syntax)) + --end_pos; + + if (end_pos == 1 && root_dir_pos == 0 && filename_was_sep) + return llvm::StringRef::npos; + + return end_pos; +} + +} // end anonymous namespace + // Resolves the username part of a path of the form ~user/other/directories, and // writes the result into dst_path. This will also resolve "~" to the current user. // If you want to complete "~" to the list of users, pass it to ResolvePartialUsername. @@ -112,8 +185,22 @@ FileSpec::ResolveUsername (llvm::SmallVectorImpl<char> &path) { // A path of ~/ resolves to the current user's home dir llvm::SmallString<64> home_dir; + // llvm::sys::path::home_directory() only checks if "HOME" is set in the + // environment and does nothing else to locate the user home directory if (!llvm::sys::path::home_directory(home_dir)) - return; + { + struct passwd *pw = getpwuid(getuid()); + if (pw && pw->pw_dir && pw->pw_dir[0]) + { + // Update our environemnt so llvm::sys::path::home_directory() works next time + setenv("HOME", pw->pw_dir, 0); + home_dir.assign(llvm::StringRef(pw->pw_dir)); + } + else + { + return; + } + } // Overwrite the ~ with the first character of the homedir, and insert // the rest. This way we only trigger one move, whereas an insert @@ -206,15 +293,10 @@ FileSpec::Resolve (llvm::SmallVectorImpl<char> &path) #endif // #ifdef LLDB_CONFIG_TILDE_RESOLVES_TO_USER // Save a copy of the original path that's passed in - llvm::SmallString<PATH_MAX> original_path(path.begin(), path.end()); + llvm::SmallString<128> original_path(path.begin(), path.end()); llvm::sys::fs::make_absolute(path); - - - path.push_back(0); // Be sure we have a nul terminated string - path.pop_back(); - struct stat file_stats; - if (::stat (path.data(), &file_stats) != 0) + if (!llvm::sys::fs::exists(path)) { path.clear(); path.append(original_path.begin(), original_path.end()); @@ -318,30 +400,34 @@ FileSpec::SetFile (const char *pathname, bool resolve, PathSyntax syntax) if (pathname == NULL || pathname[0] == '\0') return; - llvm::SmallString<64> normalized(pathname); + llvm::SmallString<64> resolved(pathname); if (resolve) { - FileSpec::Resolve (normalized); + FileSpec::Resolve (resolved); m_is_resolved = true; } - // Only normalize after resolving the path. Resolution will modify the path - // string, potentially adding wrong kinds of slashes to the path, that need - // to be re-normalized. - Normalize(normalized, syntax); + Normalize(resolved, syntax); - llvm::StringRef resolve_path_ref(normalized.c_str()); - llvm::StringRef filename_ref = llvm::sys::path::filename(resolve_path_ref); - if (!filename_ref.empty()) + llvm::StringRef resolve_path_ref(resolved.c_str()); + size_t dir_end = ParentPathEnd(resolve_path_ref, syntax); + if (dir_end == 0) { - m_filename.SetString (filename_ref); - llvm::StringRef directory_ref = llvm::sys::path::parent_path(resolve_path_ref); - if (!directory_ref.empty()) - m_directory.SetString(directory_ref); + m_filename.SetString(resolve_path_ref); + return; } - else - m_directory.SetCString(normalized.c_str()); + + m_directory.SetString(resolve_path_ref.substr(0, dir_end)); + + size_t filename_begin = dir_end; + size_t root_dir_start = RootDirStart(resolve_path_ref, syntax); + while (filename_begin != llvm::StringRef::npos && filename_begin < resolve_path_ref.size() && + filename_begin != root_dir_start && IsPathSeparator(resolve_path_ref[filename_begin], syntax)) + ++filename_begin; + m_filename.SetString((filename_begin == llvm::StringRef::npos || filename_begin >= resolve_path_ref.size()) + ? "." + : resolve_path_ref.substr(filename_begin)); } void @@ -390,66 +476,78 @@ FileSpec::operator!() const return !m_directory && !m_filename; } +bool +FileSpec::DirectoryEquals(const FileSpec &rhs) const +{ + const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive(); + return ConstString::Equals(m_directory, rhs.m_directory, case_sensitive); +} + +bool +FileSpec::FileEquals(const FileSpec &rhs) const +{ + const bool case_sensitive = IsCaseSensitive() || rhs.IsCaseSensitive(); + return ConstString::Equals(m_filename, rhs.m_filename, case_sensitive); +} + //------------------------------------------------------------------ // Equal to operator //------------------------------------------------------------------ bool FileSpec::operator== (const FileSpec& rhs) const { - if (m_filename == rhs.m_filename) + if (!FileEquals(rhs)) + return false; + if (DirectoryEquals(rhs)) + return true; + + // TODO: determine if we want to keep this code in here. + // The code below was added to handle a case where we were + // trying to set a file and line breakpoint and one path + // was resolved, and the other not and the directory was + // in a mount point that resolved to a more complete path: + // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling + // this out... + if (IsResolved() && rhs.IsResolved()) { - if (m_directory == rhs.m_directory) - return true; - - // TODO: determine if we want to keep this code in here. - // The code below was added to handle a case where we were - // trying to set a file and line breakpoint and one path - // was resolved, and the other not and the directory was - // in a mount point that resolved to a more complete path: - // "/tmp/a.c" == "/private/tmp/a.c". I might end up pulling - // this out... - if (IsResolved() && rhs.IsResolved()) - { - // Both paths are resolved, no need to look further... - return false; - } - - FileSpec resolved_lhs(*this); + // Both paths are resolved, no need to look further... + return false; + } - // If "this" isn't resolved, resolve it - if (!IsResolved()) + FileSpec resolved_lhs(*this); + + // If "this" isn't resolved, resolve it + if (!IsResolved()) + { + if (resolved_lhs.ResolvePath()) { - if (resolved_lhs.ResolvePath()) - { - // This path wasn't resolved but now it is. Check if the resolved - // directory is the same as our unresolved directory, and if so, - // we can mark this object as resolved to avoid more future resolves - m_is_resolved = (m_directory == resolved_lhs.m_directory); - } - else - return false; + // This path wasn't resolved but now it is. Check if the resolved + // directory is the same as our unresolved directory, and if so, + // we can mark this object as resolved to avoid more future resolves + m_is_resolved = (m_directory == resolved_lhs.m_directory); } - - FileSpec resolved_rhs(rhs); - if (!rhs.IsResolved()) + else + return false; + } + + FileSpec resolved_rhs(rhs); + if (!rhs.IsResolved()) + { + if (resolved_rhs.ResolvePath()) { - if (resolved_rhs.ResolvePath()) - { - // rhs's path wasn't resolved but now it is. Check if the resolved - // directory is the same as rhs's unresolved directory, and if so, - // we can mark this object as resolved to avoid more future resolves - rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory); - } - else - return false; + // rhs's path wasn't resolved but now it is. Check if the resolved + // directory is the same as rhs's unresolved directory, and if so, + // we can mark this object as resolved to avoid more future resolves + rhs.m_is_resolved = (rhs.m_directory == resolved_rhs.m_directory); } - - // If we reach this point in the code we were able to resolve both paths - // and since we only resolve the paths if the basenames are equal, then - // we can just check if both directories are equal... - return resolved_lhs.GetDirectory() == resolved_rhs.GetDirectory(); + else + return false; } - return false; + + // If we reach this point in the code we were able to resolve both paths + // and since we only resolve the paths if the basenames are equal, then + // we can just check if both directories are equal... + return DirectoryEquals(rhs); } //------------------------------------------------------------------ @@ -507,6 +605,9 @@ FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full) { int result = 0; + // case sensitivity of compare + const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive(); + // If full is true, then we must compare both the directory and filename. // If full is false, then if either directory is empty, then we match on @@ -516,32 +617,35 @@ FileSpec::Compare(const FileSpec& a, const FileSpec& b, bool full) if (full || (a.m_directory && b.m_directory)) { - result = ConstString::Compare(a.m_directory, b.m_directory); + result = ConstString::Compare(a.m_directory, b.m_directory, case_sensitive); if (result) return result; } - return ConstString::Compare (a.m_filename, b.m_filename); + return ConstString::Compare(a.m_filename, b.m_filename, case_sensitive); } bool FileSpec::Equal (const FileSpec& a, const FileSpec& b, bool full, bool remove_backups) { + // case sensitivity of equality test + const bool case_sensitive = a.IsCaseSensitive() || b.IsCaseSensitive(); + if (!full && (a.GetDirectory().IsEmpty() || b.GetDirectory().IsEmpty())) - return a.m_filename == b.m_filename; + return ConstString::Equals(a.m_filename, b.m_filename, case_sensitive); else if (remove_backups == false) return a == b; else { - if (a.m_filename != b.m_filename) + if (!ConstString::Equals(a.m_filename, b.m_filename, case_sensitive)) return false; - if (a.m_directory == b.m_directory) + if (ConstString::Equals(a.m_directory, b.m_directory, case_sensitive)) return true; ConstString a_without_dots; ConstString b_without_dots; RemoveBackupDots (a.m_directory, a_without_dots); RemoveBackupDots (b.m_directory, b_without_dots); - return a_without_dots == b_without_dots; + return ConstString::Equals(a_without_dots, b_without_dots, case_sensitive); } } @@ -670,7 +774,7 @@ FileSpec::Dump(Stream *s) const { std::string path{GetPath(true)}; s->PutCString(path.c_str()); - char path_separator = GetPathSeparator(m_syntax); + char path_separator = GetPrefferedPathSeparator(m_syntax); if (!m_filename && !path.empty() && path.back() != path_separator) s->PutChar(path_separator); } @@ -797,7 +901,10 @@ FileSpec::IsSymbolicLink () const return false; #ifdef _WIN32 - auto attrs = ::GetFileAttributes (resolved_path); + std::wstring wpath; + if (!llvm::ConvertUTF8toWide(resolved_path, wpath)) + return false; + auto attrs = ::GetFileAttributesW(wpath.c_str()); if (attrs == INVALID_FILE_ATTRIBUTES) return false; @@ -900,11 +1007,10 @@ void FileSpec::GetPath(llvm::SmallVectorImpl<char> &path, bool denormalize) const { path.append(m_directory.GetStringRef().begin(), m_directory.GetStringRef().end()); - if (m_directory) - path.insert(path.end(), '/'); + if (m_directory && m_filename && !IsPathSeparator(m_directory.GetStringRef().back(), m_syntax)) + path.insert(path.end(), GetPrefferedPathSeparator(m_syntax)); path.append(m_filename.GetStringRef().begin(), m_filename.GetStringRef().end()); Normalize(path, m_syntax); - if (path.size() > 1 && path.back() == '/') path.pop_back(); if (denormalize && !path.empty()) Denormalize(path, m_syntax); } @@ -1096,12 +1202,18 @@ FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const { if (dir_path && dir_path[0]) { -#if _WIN32 +#ifdef _WIN32 std::string szDir(dir_path); szDir += "\\*"; - WIN32_FIND_DATA ffd; - HANDLE hFind = FindFirstFile(szDir.c_str(), &ffd); + std::wstring wszDir; + if (!llvm::ConvertUTF8toWide(szDir, wszDir)) + { + return eEnumerateDirectoryResultNext; + } + + WIN32_FIND_DATAW ffd; + HANDLE hFind = FindFirstFileW(wszDir.c_str(), &ffd); if (hFind == INVALID_HANDLE_VALUE) { @@ -1113,12 +1225,12 @@ FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const FileSpec::FileType file_type = eFileTypeUnknown; if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - size_t len = strlen(ffd.cFileName); + size_t len = wcslen(ffd.cFileName); - if (len == 1 && ffd.cFileName[0] == '.') + if (len == 1 && ffd.cFileName[0] == L'.') continue; - if (len == 2 && ffd.cFileName[0] == '.' && ffd.cFileName[1] == '.') + if (len == 2 && ffd.cFileName[0] == L'.' && ffd.cFileName[1] == L'.') continue; file_type = eFileTypeDirectory; @@ -1132,12 +1244,19 @@ FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const file_type = eFileTypeRegular; } - char child_path[MAX_PATH]; - const int child_path_len = ::snprintf (child_path, sizeof(child_path), "%s\\%s", dir_path, ffd.cFileName); - if (child_path_len < (int)(sizeof(child_path) - 1)) + std::string fileName; + if (!llvm::convertWideToUTF8(ffd.cFileName, fileName)) + { + continue; + } + + std::vector<char> child_path(PATH_MAX); + const int child_path_len = + ::snprintf(child_path.data(), child_path.size(), "%s\\%s", dir_path, fileName.c_str()); + if (child_path_len < (int)(child_path.size() - 1)) { // Don't resolve the file type or path - FileSpec child_path_spec (child_path, false); + FileSpec child_path_spec(child_path.data(), false); EnumerateDirectoryResult result = callback (file_type, child_path_spec); @@ -1150,7 +1269,8 @@ FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const break; case eEnumerateDirectoryResultEnter: // Recurse into the current entry if it is a directory or symlink, or next if not - if (FileSpec::ForEachItemInDirectory(child_path, callback) == eEnumerateDirectoryResultQuit) + if (FileSpec::ForEachItemInDirectory(child_path.data(), callback) == + eEnumerateDirectoryResultQuit) { // The subdirectory returned Quit, which means to // stop all directory enumerations at all levels. @@ -1167,7 +1287,7 @@ FileSpec::ForEachItemInDirectory (const char *dir_path, DirectoryCallback const return eEnumerateDirectoryResultQuit; } } - } while (FindNextFile(hFind, &ffd) != 0); + } while (FindNextFileW(hFind, &ffd) != 0); FindClose(hFind); #else @@ -1313,17 +1433,9 @@ FileSpec::EnumerateDirectory FileSpec FileSpec::CopyByAppendingPathComponent (const char *new_path) const { - const bool resolve = false; - if (m_filename.IsEmpty() && m_directory.IsEmpty()) - return FileSpec(new_path,resolve); - StreamString stream; - if (m_filename.IsEmpty()) - stream.Printf("%s/%s",m_directory.GetCString(),new_path); - else if (m_directory.IsEmpty()) - stream.Printf("%s/%s",m_filename.GetCString(),new_path); - else - stream.Printf("%s/%s/%s",m_directory.GetCString(), m_filename.GetCString(),new_path); - return FileSpec(stream.GetData(),resolve); + FileSpec ret = *this; + ret.AppendPathComponent(new_path); + return ret; } FileSpec @@ -1424,20 +1536,26 @@ void FileSpec::AppendPathComponent(const char *new_path) { if (!new_path) return; - const bool resolve = false; - if (m_filename.IsEmpty() && m_directory.IsEmpty()) + + StreamString stream; + if (!m_directory.IsEmpty()) { - SetFile(new_path, resolve); - return; + stream.PutCString(m_directory.GetCString()); + if (!IsPathSeparator(m_directory.GetStringRef().back(), m_syntax)) + stream.PutChar(GetPrefferedPathSeparator(m_syntax)); } - StreamString stream; - if (m_filename.IsEmpty() || (m_filename.GetLength() == 1 && m_filename.GetCString()[0] == '.')) - stream.Printf("%s/%s", m_directory.GetCString(), new_path); - else if (m_directory.IsEmpty()) - stream.Printf("%s/%s", m_filename.GetCString(), new_path); - else - stream.Printf("%s/%s/%s", m_directory.GetCString(), m_filename.GetCString(), new_path); - SetFile(stream.GetData(), resolve); + + if (!m_filename.IsEmpty()) + { + stream.PutCString(m_filename.GetCString()); + if (!IsPathSeparator(m_filename.GetStringRef().back(), m_syntax)) + stream.PutChar(GetPrefferedPathSeparator(m_syntax)); + } + + stream.PutCString(new_path); + + const bool resolve = false; + SetFile(stream.GetData(), resolve, m_syntax); } void diff --git a/source/Host/common/Host.cpp b/source/Host/common/Host.cpp index e89f4def478c..656caa5e0d19 100644 --- a/source/Host/common/Host.cpp +++ b/source/Host/common/Host.cpp @@ -39,8 +39,10 @@ #include <pthread_np.h> #endif -// C++ includes -#include <limits> +// C++ Includes + +// Other libraries and framework includes +// Project includes #include "lldb/Host/FileSystem.h" #include "lldb/Host/Host.h" @@ -91,7 +93,6 @@ struct MonitorInfo { lldb::pid_t pid; // The process ID to monitor Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals - void *callback_baton; // The callback baton for the callback function bool monitor_signals; // If true, call the callback when "pid" gets signaled. }; @@ -99,13 +100,13 @@ static thread_result_t MonitorChildProcessThreadFunction (void *arg); HostThread -Host::StartMonitoringChildProcess(Host::MonitorChildProcessCallback callback, void *callback_baton, lldb::pid_t pid, bool monitor_signals) +Host::StartMonitoringChildProcess(const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid, + bool monitor_signals) { MonitorInfo * info_ptr = new MonitorInfo(); info_ptr->pid = pid; info_ptr->callback = callback; - info_ptr->callback_baton = callback_baton; info_ptr->monitor_signals = monitor_signals; char thread_name[256]; @@ -182,7 +183,6 @@ MonitorChildProcessThreadFunction (void *arg) MonitorInfo *info = (MonitorInfo *)arg; const Host::MonitorChildProcessCallback callback = info->callback; - void * const callback_baton = info->callback_baton; const bool monitor_signals = info->monitor_signals; assert (info->pid <= UINT32_MAX); @@ -283,8 +283,8 @@ MonitorChildProcessThreadFunction (void *arg) { bool callback_return = false; if (callback) - callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status); - + callback_return = callback(wait_pid, exited, signal, exit_status); + // If our process exited, then this thread should exit if (exited && wait_pid == abs(pid)) { @@ -498,7 +498,6 @@ struct ShellInfo { ShellInfo () : process_reaped (false), - can_delete (false), pid (LLDB_INVALID_PROCESS_ID), signo(-1), status(-1) @@ -506,33 +505,23 @@ struct ShellInfo } lldb_private::Predicate<bool> process_reaped; - lldb_private::Predicate<bool> can_delete; lldb::pid_t pid; int signo; int status; }; static bool -MonitorShellCommand (void *callback_baton, - lldb::pid_t pid, - bool exited, // True if the process did exit - int signo, // Zero for no signal - int status) // Exit value of process if signal is zero +MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid, + bool exited, // True if the process did exit + int signo, // Zero for no signal + int status) // Exit value of process if signal is zero { - ShellInfo *shell_info = (ShellInfo *)callback_baton; shell_info->pid = pid; shell_info->signo = signo; shell_info->status = status; // Let the thread running Host::RunShellCommand() know that the process // exited and that ShellInfo has been filled in by broadcasting to it - shell_info->process_reaped.SetValue(1, eBroadcastAlways); - // Now wait for a handshake back from that thread running Host::RunShellCommand - // so we know that we can delete shell_info_ptr - shell_info->can_delete.WaitForValueEqualTo(true); - // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete... - usleep(1000); - // Now delete the shell info that was passed into this function - delete shell_info; + shell_info->process_reaped.SetValue(true, eBroadcastAlways); return true; } @@ -615,13 +604,14 @@ Host::RunShellCommand(const Args &args, launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true); launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true); } - - // The process monitor callback will delete the 'shell_info_ptr' below... - std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo()); - + + std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo()); const bool monitor_signals = false; - launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals); - + launch_info.SetMonitorProcessCallback(std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3, + std::placeholders::_4), + monitor_signals); + error = LaunchProcess (launch_info); const lldb::pid_t pid = launch_info.GetProcessID(); @@ -630,11 +620,6 @@ Host::RunShellCommand(const Args &args, if (error.Success()) { - // The process successfully launched, so we can defer ownership of - // "shell_info" to the MonitorShellCommand callback function that will - // get called when the process dies. We release the unique pointer as it - // doesn't need to delete the ShellInfo anymore. - ShellInfo *shell_info = shell_info_ap.release(); TimeValue *timeout_ptr = nullptr; TimeValue timeout_time(TimeValue::Now()); if (timeout_sec > 0) { @@ -642,7 +627,7 @@ Host::RunShellCommand(const Args &args, timeout_ptr = &timeout_time; } bool timed_out = false; - shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out); + shell_info_sp->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out); if (timed_out) { error.SetErrorString("timed out waiting for shell command to complete"); @@ -653,16 +638,16 @@ Host::RunShellCommand(const Args &args, timeout_time = TimeValue::Now(); timeout_time.OffsetWithSeconds(1); timed_out = false; - shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out); + shell_info_sp->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out); } else { if (status_ptr) - *status_ptr = shell_info->status; - + *status_ptr = shell_info_sp->status; + if (signo_ptr) - *signo_ptr = shell_info->signo; - + *signo_ptr = shell_info_sp->signo; + if (command_output_ptr) { command_output_ptr->clear(); @@ -683,14 +668,10 @@ Host::RunShellCommand(const Args &args, } } } - shell_info->can_delete.SetValue(true, eBroadcastAlways); } if (FileSystem::GetFileExists(output_file_spec)) FileSystem::Unlink(output_file_spec); - // Handshake with the monitor thread, or just let it know in advance that - // it can delete "shell_info" in case we timed out and were not able to kill - // the process... return error; } diff --git a/source/Host/common/HostInfoBase.cpp b/source/Host/common/HostInfoBase.cpp index f7ba755b5bab..2bff4d9a670f 100644 --- a/source/Host/common/HostInfoBase.cpp +++ b/source/Host/common/HostInfoBase.cpp @@ -31,19 +31,6 @@ using namespace lldb_private; namespace { - void - CleanupProcessSpecificLLDBTempDir() - { - // Get the process specific LLDB temporary directory and delete it. - FileSpec tmpdir_file_spec; - if (!HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) - return; - - // Remove the LLDB temporary directory if we have one. Set "recurse" to - // true to all files that were created for the LLDB process can be cleaned up. - FileSystem::DeleteDirectory(tmpdir_file_spec, true); - } - //---------------------------------------------------------------------- // The HostInfoBaseFields is a work around for windows not supporting // static variables correctly in a thread safe way. Really each of the @@ -54,6 +41,16 @@ namespace struct HostInfoBaseFields { + ~HostInfoBaseFields() + { + if (m_lldb_process_tmp_dir.Exists()) + { + // Remove the LLDB temporary directory if we have one. Set "recurse" to + // true to all files that were created for the LLDB process can be cleaned up. + FileSystem::DeleteDirectory(m_lldb_process_tmp_dir, true); + } + } + uint32_t m_number_cpus; std::string m_vendor_string; std::string m_os_string; @@ -82,6 +79,13 @@ HostInfoBase::Initialize() g_fields = new HostInfoBaseFields(); } +void +HostInfoBase::Terminate() +{ + delete g_fields; + g_fields = nullptr; +} + uint32_t HostInfoBase::GetNumberCPUS() { @@ -335,9 +339,6 @@ HostInfoBase::ComputeProcessTempFileDirectory(FileSpec &file_spec) if (!FileSystem::MakeDirectory(temp_file_spec, eFilePermissionsDirectoryDefault).Success()) return false; - // Make an atexit handler to clean up the process specify LLDB temp dir - // and all of its contents. - ::atexit(CleanupProcessSpecificLLDBTempDir); file_spec.GetDirectory().SetCString(temp_file_spec.GetCString()); return true; } @@ -419,6 +420,7 @@ HostInfoBase::ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_6 case llvm::Triple::mips64: case llvm::Triple::mips64el: case llvm::Triple::sparcv9: + case llvm::Triple::systemz: arch_64.SetTriple(triple); break; } diff --git a/source/Host/common/HostProcess.cpp b/source/Host/common/HostProcess.cpp index 58a214693a52..0262e1c03c20 100644 --- a/source/Host/common/HostProcess.cpp +++ b/source/Host/common/HostProcess.cpp @@ -49,9 +49,9 @@ bool HostProcess::IsRunning() const } HostThread -HostProcess::StartMonitoring(HostProcess::MonitorCallback callback, void *callback_baton, bool monitor_signals) +HostProcess::StartMonitoring(const Host::MonitorChildProcessCallback &callback, bool monitor_signals) { - return m_native_process->StartMonitoring(callback, callback_baton, monitor_signals); + return m_native_process->StartMonitoring(callback, monitor_signals); } HostNativeProcessBase &HostProcess::GetNativeProcess() diff --git a/source/Host/common/MonitoringProcessLauncher.cpp b/source/Host/common/MonitoringProcessLauncher.cpp index 0fad44a9ec08..2845155987e3 100644 --- a/source/Host/common/MonitoringProcessLauncher.cpp +++ b/source/Host/common/MonitoringProcessLauncher.cpp @@ -75,12 +75,10 @@ MonitoringProcessLauncher::LaunchProcess(const ProcessLaunchInfo &launch_info, E Host::MonitorChildProcessCallback callback = launch_info.GetMonitorProcessCallback(); - void *baton = nullptr; bool monitor_signals = false; if (callback) { // If the ProcessLaunchInfo specified a callback, use that. - baton = launch_info.GetMonitorProcessBaton(); monitor_signals = launch_info.GetMonitorSignals(); } else @@ -88,7 +86,7 @@ MonitoringProcessLauncher::LaunchProcess(const ProcessLaunchInfo &launch_info, E callback = Process::SetProcessExitStatus; } - process.StartMonitoring(callback, baton, monitor_signals); + process.StartMonitoring(callback, monitor_signals); if (log) log->PutCString("started monitoring child process."); } diff --git a/source/Host/common/NativeBreakpointList.cpp b/source/Host/common/NativeBreakpointList.cpp index 52b9baf5f537..67873a06dd27 100644 --- a/source/Host/common/NativeBreakpointList.cpp +++ b/source/Host/common/NativeBreakpointList.cpp @@ -17,8 +17,7 @@ using namespace lldb; using namespace lldb_private; -NativeBreakpointList::NativeBreakpointList () : - m_mutex (Mutex::eMutexTypeRecursive) +NativeBreakpointList::NativeBreakpointList() : m_mutex() { } @@ -29,7 +28,7 @@ NativeBreakpointList::AddRef (lldb::addr_t addr, size_t size_hint, bool hardware if (log) log->Printf ("NativeBreakpointList::%s addr = 0x%" PRIx64 ", size_hint = %lu, hardware = %s", __FUNCTION__, addr, size_hint, hardware ? "true" : "false"); - Mutex::Locker locker (m_mutex); + std::lock_guard<std::recursive_mutex> guard(m_mutex); // Check if the breakpoint is already set. auto iter = m_breakpoints.find (addr); @@ -72,7 +71,7 @@ NativeBreakpointList::DecRef (lldb::addr_t addr) if (log) log->Printf ("NativeBreakpointList::%s addr = 0x%" PRIx64, __FUNCTION__, addr); - Mutex::Locker locker (m_mutex); + std::lock_guard<std::recursive_mutex> guard(m_mutex); // Check if the breakpoint is already set. auto iter = m_breakpoints.find (addr); @@ -136,7 +135,7 @@ NativeBreakpointList::EnableBreakpoint (lldb::addr_t addr) if (log) log->Printf ("NativeBreakpointList::%s addr = 0x%" PRIx64, __FUNCTION__, addr); - Mutex::Locker locker (m_mutex); + std::lock_guard<std::recursive_mutex> guard(m_mutex); // Ensure we have said breakpoint. auto iter = m_breakpoints.find (addr); @@ -159,7 +158,7 @@ NativeBreakpointList::DisableBreakpoint (lldb::addr_t addr) if (log) log->Printf ("NativeBreakpointList::%s addr = 0x%" PRIx64, __FUNCTION__, addr); - Mutex::Locker locker (m_mutex); + std::lock_guard<std::recursive_mutex> guard(m_mutex); // Ensure we have said breakpoint. auto iter = m_breakpoints.find (addr); @@ -182,7 +181,7 @@ NativeBreakpointList::GetBreakpoint (lldb::addr_t addr, NativeBreakpointSP &brea if (log) log->Printf ("NativeBreakpointList::%s addr = 0x%" PRIx64, __FUNCTION__, addr); - Mutex::Locker locker (m_mutex); + std::lock_guard<std::recursive_mutex> guard(m_mutex); // Ensure we have said breakpoint. auto iter = m_breakpoints.find (addr); diff --git a/source/Host/common/NativeProcessProtocol.cpp b/source/Host/common/NativeProcessProtocol.cpp index 7d2f4012bf85..dfac0cb5645c 100644 --- a/source/Host/common/NativeProcessProtocol.cpp +++ b/source/Host/common/NativeProcessProtocol.cpp @@ -26,22 +26,22 @@ using namespace lldb_private; // NativeProcessProtocol Members // ----------------------------------------------------------------------------- -NativeProcessProtocol::NativeProcessProtocol (lldb::pid_t pid) : - m_pid (pid), - m_threads (), - m_current_thread_id (LLDB_INVALID_THREAD_ID), - m_threads_mutex (Mutex::eMutexTypeRecursive), - m_state (lldb::eStateInvalid), - m_state_mutex (Mutex::eMutexTypeRecursive), - m_exit_type (eExitTypeInvalid), - m_exit_status (0), - m_exit_description (), - m_delegates_mutex (Mutex::eMutexTypeRecursive), - m_delegates (), - m_breakpoint_list (), - m_watchpoint_list (), - m_terminal_fd (-1), - m_stop_id (0) +NativeProcessProtocol::NativeProcessProtocol(lldb::pid_t pid) + : m_pid(pid), + m_threads(), + m_current_thread_id(LLDB_INVALID_THREAD_ID), + m_threads_mutex(), + m_state(lldb::eStateInvalid), + m_state_mutex(), + m_exit_type(eExitTypeInvalid), + m_exit_status(0), + m_exit_description(), + m_delegates_mutex(), + m_delegates(), + m_breakpoint_list(), + m_watchpoint_list(), + m_terminal_fd(-1), + m_stop_id(0) { } @@ -117,7 +117,7 @@ NativeProcessProtocol::SetExitStatus (ExitType exit_type, int status, const char NativeThreadProtocolSP NativeProcessProtocol::GetThreadAtIndex (uint32_t idx) { - Mutex::Locker locker (m_threads_mutex); + std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); if (idx < m_threads.size ()) return m_threads[idx]; return NativeThreadProtocolSP (); @@ -137,7 +137,7 @@ NativeProcessProtocol::GetThreadByIDUnlocked (lldb::tid_t tid) NativeThreadProtocolSP NativeProcessProtocol::GetThreadByID (lldb::tid_t tid) { - Mutex::Locker locker (m_threads_mutex); + std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); return GetThreadByIDUnlocked (tid); } @@ -221,7 +221,7 @@ NativeProcessProtocol::SetWatchpoint (lldb::addr_t addr, size_t size, uint32_t w // conceivable that if there are more threads than hardware // watchpoints available, some of the threads will fail to set // hardware watchpoints while software ones may be available. - Mutex::Locker locker (m_threads_mutex); + std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); for (auto thread_sp : m_threads) { assert (thread_sp && "thread list should not have a NULL thread!"); @@ -276,7 +276,7 @@ NativeProcessProtocol::RemoveWatchpoint (lldb::addr_t addr) Error overall_error; - Mutex::Locker locker (m_threads_mutex); + std::lock_guard<std::recursive_mutex> guard(m_threads_mutex); for (auto thread_sp : m_threads) { assert (thread_sp && "thread list should not have a NULL thread!"); @@ -300,7 +300,7 @@ NativeProcessProtocol::RemoveWatchpoint (lldb::addr_t addr) bool NativeProcessProtocol::RegisterNativeDelegate (NativeDelegate &native_delegate) { - Mutex::Locker locker (m_delegates_mutex); + std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex); if (std::find (m_delegates.begin (), m_delegates.end (), &native_delegate) != m_delegates.end ()) return false; @@ -312,7 +312,7 @@ NativeProcessProtocol::RegisterNativeDelegate (NativeDelegate &native_delegate) bool NativeProcessProtocol::UnregisterNativeDelegate (NativeDelegate &native_delegate) { - Mutex::Locker locker (m_delegates_mutex); + std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex); const auto initial_size = m_delegates.size (); m_delegates.erase (remove (m_delegates.begin (), m_delegates.end (), &native_delegate), m_delegates.end ()); @@ -327,7 +327,7 @@ NativeProcessProtocol::SynchronouslyNotifyProcessStateChanged (lldb::StateType s { Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); - Mutex::Locker locker (m_delegates_mutex); + std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex); for (auto native_delegate: m_delegates) native_delegate->ProcessStateChanged (this, state); @@ -354,7 +354,7 @@ NativeProcessProtocol::NotifyDidExec () log->Printf ("NativeProcessProtocol::%s - preparing to call delegates", __FUNCTION__); { - Mutex::Locker locker (m_delegates_mutex); + std::lock_guard<std::recursive_mutex> guard(m_delegates_mutex); for (auto native_delegate: m_delegates) native_delegate->DidExec (this); } @@ -394,14 +394,14 @@ NativeProcessProtocol::DisableBreakpoint (lldb::addr_t addr) lldb::StateType NativeProcessProtocol::GetState () const { - Mutex::Locker locker (m_state_mutex); + std::lock_guard<std::recursive_mutex> guard(m_state_mutex); return m_state; } void NativeProcessProtocol::SetState (lldb::StateType state, bool notify_delegates) { - Mutex::Locker locker (m_state_mutex); + std::lock_guard<std::recursive_mutex> guard(m_state_mutex); if (state == m_state) return; @@ -426,8 +426,8 @@ NativeProcessProtocol::SetState (lldb::StateType state, bool notify_delegates) uint32_t NativeProcessProtocol::GetStopID () const { - Mutex::Locker locker (m_state_mutex); - return m_stop_id; + std::lock_guard<std::recursive_mutex> guard(m_state_mutex); + return m_stop_id; } void diff --git a/source/Host/common/OptionParser.cpp b/source/Host/common/OptionParser.cpp index a9784592a738..16a29a1583d5 100644 --- a/source/Host/common/OptionParser.cpp +++ b/source/Host/common/OptionParser.cpp @@ -16,10 +16,10 @@ using namespace lldb_private; void -OptionParser::Prepare(Mutex::Locker &locker) +OptionParser::Prepare(std::unique_lock<std::mutex> &lock) { - static Mutex g_mutex(Mutex::eMutexTypeNormal); - locker.Lock(g_mutex); + static std::mutex g_mutex; + lock = std::unique_lock<std::mutex>(g_mutex); #ifdef __GLIBC__ optind = 0; #else diff --git a/source/Host/common/Socket.cpp b/source/Host/common/Socket.cpp index 91a5e37424e6..ea049ae6933e 100644 --- a/source/Host/common/Socket.cpp +++ b/source/Host/common/Socket.cpp @@ -268,7 +268,7 @@ Socket::DecodeHostAndPort(llvm::StringRef host_and_port, { bool ok = false; port = StringConvert::ToUInt32 (port_str.c_str(), UINT32_MAX, 10, &ok); - if (ok && port < UINT16_MAX) + if (ok && port <= UINT16_MAX) { if (error_ptr) error_ptr->Clear(); diff --git a/source/Host/common/SocketAddress.cpp b/source/Host/common/SocketAddress.cpp index c8b1687c378e..1dc43ea6294c 100644 --- a/source/Host/common/SocketAddress.cpp +++ b/source/Host/common/SocketAddress.cpp @@ -185,14 +185,12 @@ SocketAddress::GetIPAddress () const { case AF_INET: if (inet_ntop(GetFamily(), &m_socket_addr.sa_ipv4.sin_addr, str, sizeof(str))) - { return str; - } + break; case AF_INET6: if (inet_ntop(GetFamily(), &m_socket_addr.sa_ipv6.sin6_addr, str, sizeof(str))) - { return str; - } + break; } return ""; } diff --git a/source/Host/common/SoftwareBreakpoint.cpp b/source/Host/common/SoftwareBreakpoint.cpp index 5a6f78372b3f..51cb34ffe6dd 100644 --- a/source/Host/common/SoftwareBreakpoint.cpp +++ b/source/Host/common/SoftwareBreakpoint.cpp @@ -12,7 +12,6 @@ #include "lldb/Core/Error.h" #include "lldb/Core/Log.h" #include "lldb/Host/Debug.h" -#include "lldb/Host/Mutex.h" #include "lldb/Host/common/NativeProcessProtocol.h" diff --git a/source/Host/common/TCPSocket.cpp b/source/Host/common/TCPSocket.cpp index b23055ee7d87..07b0cdf908f5 100644 --- a/source/Host/common/TCPSocket.cpp +++ b/source/Host/common/TCPSocket.cpp @@ -112,9 +112,6 @@ TCPSocket::Connect(llvm::StringRef name) if (!DecodeHostAndPort (name, host_str, port_str, port, &error)) return error; - // Enable local address reuse - SetOptionReuseAddress(); - struct sockaddr_in sa; ::memset (&sa, 0, sizeof (sa)); sa.sin_family = kDomain; diff --git a/source/Host/common/UDPSocket.cpp b/source/Host/common/UDPSocket.cpp index 8297232ae723..9a2028e97a40 100644 --- a/source/Host/common/UDPSocket.cpp +++ b/source/Host/common/UDPSocket.cpp @@ -27,7 +27,7 @@ namespace { const int kDomain = AF_INET; const int kType = SOCK_DGRAM; -const Error kNotSupported("Not supported"); +static const char *g_not_supported_error = "Not supported"; } @@ -55,19 +55,19 @@ UDPSocket::Send(const void *buf, const size_t num_bytes) Error UDPSocket::Connect(llvm::StringRef name) { - return kNotSupported; + return Error("%s", g_not_supported_error); } Error UDPSocket::Listen(llvm::StringRef name, int backlog) { - return kNotSupported; + return Error("%s", g_not_supported_error); } Error UDPSocket::Accept(llvm::StringRef name, bool child_processes_inherit, Socket *&socket) { - return kNotSupported; + return Error("%s", g_not_supported_error); } Error |
