diff options
author | Dimitry Andric <dim@FreeBSD.org> | 2020-07-26 19:36:28 +0000 |
---|---|---|
committer | Dimitry Andric <dim@FreeBSD.org> | 2020-07-26 19:36:28 +0000 |
commit | cfca06d7963fa0909f90483b42a6d7d194d01e08 (patch) | |
tree | 209fb2a2d68f8f277793fc8df46c753d31bc853b /lldb/source/Host/common | |
parent | 706b4fc47bbc608932d3b491ae19a3b9cde9497b (diff) |
Notes
Diffstat (limited to 'lldb/source/Host/common')
33 files changed, 325 insertions, 382 deletions
diff --git a/lldb/source/Host/common/Editline.cpp b/lldb/source/Host/common/Editline.cpp index 5fd5a0cfc7fc..226e638aba25 100644 --- a/lldb/source/Host/common/Editline.cpp +++ b/lldb/source/Host/common/Editline.cpp @@ -1,4 +1,4 @@ -//===-- Editline.cpp --------------------------------------------*- C++ -*-===// +//===-- Editline.cpp ------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -7,7 +7,6 @@ //===----------------------------------------------------------------------===// #include <iomanip> -#include <iostream> #include <limits.h> #include "lldb/Host/ConnectionFileDescriptor.h" @@ -35,7 +34,7 @@ using namespace lldb_private::line_editor; // with until TERM is set to VT100 where it stumbles over an implementation // assumption that may not exist on other platforms. The setupterm() function // would normally require headers that don't work gracefully in this context, -// so the function declaraction has been hoisted here. +// so the function declaration has been hoisted here. #if defined(__APPLE__) extern "C" { int setupterm(char *term, int fildes, int *errret); @@ -99,18 +98,24 @@ bool IsOnlySpaces(const EditLineStringType &content) { static int GetOperation(HistoryOperation op) { // The naming used by editline for the history operations is counter - // intuitive to how it's used here. + // intuitive to how it's used in LLDB's editline implementation. + // + // - The H_LAST returns the oldest entry in the history. // // - The H_PREV operation returns the previous element in the history, which // is newer than the current one. // + // - The H_CURR returns the current entry in the history. + // // - The H_NEXT operation returns the next element in the history, which is // older than the current one. // + // - The H_FIRST returns the most recent entry in the history. + // // The naming of the enum entries match the semantic meaning. switch(op) { case HistoryOperation::Oldest: - return H_FIRST; + return H_LAST; case HistoryOperation::Older: return H_NEXT; case HistoryOperation::Current: @@ -118,7 +123,7 @@ static int GetOperation(HistoryOperation op) { case HistoryOperation::Newer: return H_PREV; case HistoryOperation::Newest: - return H_LAST; + return H_FIRST; } llvm_unreachable("Fully covered switch!"); } @@ -138,10 +143,10 @@ std::vector<EditLineStringType> SplitLines(const EditLineStringType &input) { while (start < input.length()) { size_t end = input.find('\n', start); if (end == std::string::npos) { - result.insert(result.end(), input.substr(start)); + result.push_back(input.substr(start)); break; } - result.insert(result.end(), input.substr(start, end - start)); + result.push_back(input.substr(start, end - start)); start = end + 1; } return result; @@ -214,7 +219,7 @@ private: std::string filename = m_prefix + "-history"; #endif llvm::sys::path::append(lldb_history_file, filename); - m_path = lldb_history_file.str(); + m_path = std::string(lldb_history_file.str()); } } @@ -296,19 +301,16 @@ protected: // Editline private methods void Editline::SetBaseLineNumber(int line_number) { - std::stringstream line_number_stream; - line_number_stream << line_number; m_base_line_number = line_number; m_line_number_digits = - std::max(3, (int)line_number_stream.str().length() + 1); + std::max<int>(3, std::to_string(line_number).length() + 1); } std::string Editline::PromptForIndex(int line_index) { bool use_line_numbers = m_multiline_enabled && m_base_line_number > 0; std::string prompt = m_set_prompt; - if (use_line_numbers && prompt.length() == 0) { + if (use_line_numbers && prompt.length() == 0) prompt = ": "; - } std::string continuation_prompt = prompt; if (m_set_continuation_prompt.length() > 0) { continuation_prompt = m_set_continuation_prompt; @@ -327,7 +329,7 @@ std::string Editline::PromptForIndex(int line_index) { prompt_stream.Printf( "%*d%s", m_line_number_digits, m_base_line_number + line_index, (line_index == 0) ? prompt.c_str() : continuation_prompt.c_str()); - return std::move(prompt_stream.GetString()); + return std::string(std::move(prompt_stream.GetString())); } return (line_index == 0) ? prompt : continuation_prompt; } @@ -423,7 +425,7 @@ void Editline::DisplayInput(int firstIndex) { } int Editline::CountRowsForLine(const EditLineStringType &content) { - auto prompt = + std::string prompt = PromptForIndex(0); // Prompt width is constant during an edit session int line_length = (int)(content.length() + prompt.length()); return (line_length / m_terminal_width) + 1; @@ -557,6 +559,9 @@ int Editline::GetCharacter(EditLineGetCharType *c) { lldb::ConnectionStatus status = lldb::eConnectionStatusSuccess; char ch = 0; + if (m_terminal_size_has_changed) + ApplyTerminalSizeChange(); + // This mutex is locked by our caller (GetLine). Unlock it while we read a // character (blocking operation), so we do not hold the mutex // indefinitely. This gives a chance for someone to interrupt us. After @@ -1049,7 +1054,7 @@ void Editline::ConfigureEditor(bool multiline) { m_editline = el_init(m_editor_name.c_str(), m_input_file, m_output_file, m_error_file); - TerminalSizeChanged(); + ApplyTerminalSizeChange(); if (m_history_sp && m_history_sp->IsValid()) { if (!m_history_sp->Load()) { @@ -1302,28 +1307,32 @@ void Editline::SetContinuationPrompt(const char *continuation_prompt) { continuation_prompt == nullptr ? "" : continuation_prompt; } -void Editline::TerminalSizeChanged() { - if (m_editline != nullptr) { - el_resize(m_editline); - int columns; - // This function is documenting as taking (const char *, void *) for the - // vararg part, but in reality in was consuming arguments until the first - // null pointer. This was fixed in libedit in April 2019 - // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>, - // but we're keeping the workaround until a version with that fix is more - // widely available. - if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) { - m_terminal_width = columns; - if (m_current_line_rows != -1) { - const LineInfoW *info = el_wline(m_editline); - int lineLength = - (int)((info->lastchar - info->buffer) + GetPromptWidth()); - m_current_line_rows = (lineLength / columns) + 1; - } - } else { - m_terminal_width = INT_MAX; - m_current_line_rows = 1; +void Editline::TerminalSizeChanged() { m_terminal_size_has_changed = 1; } + +void Editline::ApplyTerminalSizeChange() { + if (!m_editline) + return; + + m_terminal_size_has_changed = 0; + el_resize(m_editline); + int columns; + // This function is documenting as taking (const char *, void *) for the + // vararg part, but in reality in was consuming arguments until the first + // null pointer. This was fixed in libedit in April 2019 + // <http://mail-index.netbsd.org/source-changes/2019/04/26/msg105454.html>, + // but we're keeping the workaround until a version with that fix is more + // widely available. + if (el_get(m_editline, EL_GETTC, "co", &columns, nullptr) == 0) { + m_terminal_width = columns; + if (m_current_line_rows != -1) { + const LineInfoW *info = el_wline(m_editline); + int lineLength = + (int)((info->lastchar - info->buffer) + GetPromptWidth()); + m_current_line_rows = (lineLength / columns) + 1; } + } else { + m_terminal_width = INT_MAX; + m_current_line_rows = 1; } } diff --git a/lldb/source/Host/common/File.cpp b/lldb/source/Host/common/File.cpp index 7850222376f7..a5b970907e64 100644 --- a/lldb/source/Host/common/File.cpp +++ b/lldb/source/Host/common/File.cpp @@ -1,4 +1,4 @@ -//===-- File.cpp ------------------------------------------------*- C++ -*-===// +//===-- File.cpp ----------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/FileAction.cpp b/lldb/source/Host/common/FileAction.cpp index 3268d952bcc9..8b4e7f4c2208 100644 --- a/lldb/source/Host/common/FileAction.cpp +++ b/lldb/source/Host/common/FileAction.cpp @@ -1,4 +1,4 @@ -//===-- FileAction.cpp ------------------------------------------*- C++ -*-===// +//===-- FileAction.cpp ----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/FileCache.cpp b/lldb/source/Host/common/FileCache.cpp index d9dcad992c33..da9a748e2f13 100644 --- a/lldb/source/Host/common/FileCache.cpp +++ b/lldb/source/Host/common/FileCache.cpp @@ -1,4 +1,4 @@ -//===-- FileCache.cpp -------------------------------------------*- C++ -*-===// +//===-- FileCache.cpp -----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/FileSystem.cpp b/lldb/source/Host/common/FileSystem.cpp index 2db5bff3207f..0fa27d131e1a 100644 --- a/lldb/source/Host/common/FileSystem.cpp +++ b/lldb/source/Host/common/FileSystem.cpp @@ -1,4 +1,4 @@ -//===-- FileSystem.cpp ------------------------------------------*- C++ -*-===// +//===-- FileSystem.cpp ----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -87,6 +87,11 @@ Optional<FileSystem> &FileSystem::InstanceImpl() { vfs::directory_iterator FileSystem::DirBegin(const FileSpec &file_spec, std::error_code &ec) { + if (!file_spec) { + ec = std::error_code(static_cast<int>(errc::no_such_file_or_directory), + std::system_category()); + return {}; + } return DirBegin(file_spec.GetPath(), ec); } @@ -97,6 +102,9 @@ vfs::directory_iterator FileSystem::DirBegin(const Twine &dir, llvm::ErrorOr<vfs::Status> FileSystem::GetStatus(const FileSpec &file_spec) const { + if (!file_spec) + return std::error_code(static_cast<int>(errc::no_such_file_or_directory), + std::system_category()); return GetStatus(file_spec.GetPath()); } @@ -106,6 +114,8 @@ llvm::ErrorOr<vfs::Status> FileSystem::GetStatus(const Twine &path) const { sys::TimePoint<> FileSystem::GetModificationTime(const FileSpec &file_spec) const { + if (!file_spec) + return sys::TimePoint<>(); return GetModificationTime(file_spec.GetPath()); } @@ -117,6 +127,8 @@ sys::TimePoint<> FileSystem::GetModificationTime(const Twine &path) const { } uint64_t FileSystem::GetByteSize(const FileSpec &file_spec) const { + if (!file_spec) + return 0; return GetByteSize(file_spec.GetPath()); } @@ -133,6 +145,8 @@ uint32_t FileSystem::GetPermissions(const FileSpec &file_spec) const { uint32_t FileSystem::GetPermissions(const FileSpec &file_spec, std::error_code &ec) const { + if (!file_spec) + return sys::fs::perms::perms_not_known; return GetPermissions(file_spec.GetPath(), ec); } @@ -154,7 +168,7 @@ uint32_t FileSystem::GetPermissions(const Twine &path, bool FileSystem::Exists(const Twine &path) const { return m_fs->exists(path); } bool FileSystem::Exists(const FileSpec &file_spec) const { - return Exists(file_spec.GetPath()); + return file_spec && Exists(file_spec.GetPath()); } bool FileSystem::Readable(const Twine &path) const { @@ -162,7 +176,7 @@ bool FileSystem::Readable(const Twine &path) const { } bool FileSystem::Readable(const FileSpec &file_spec) const { - return Readable(file_spec.GetPath()); + return file_spec && Readable(file_spec.GetPath()); } bool FileSystem::IsDirectory(const Twine &path) const { @@ -173,7 +187,7 @@ bool FileSystem::IsDirectory(const Twine &path) const { } bool FileSystem::IsDirectory(const FileSpec &file_spec) const { - return IsDirectory(file_spec.GetPath()); + return file_spec && IsDirectory(file_spec.GetPath()); } bool FileSystem::IsLocal(const Twine &path) const { @@ -183,7 +197,7 @@ bool FileSystem::IsLocal(const Twine &path) const { } bool FileSystem::IsLocal(const FileSpec &file_spec) const { - return IsLocal(file_spec.GetPath()); + return file_spec && IsLocal(file_spec.GetPath()); } void FileSystem::EnumerateDirectory(Twine path, bool find_directories, @@ -261,6 +275,9 @@ void FileSystem::Resolve(SmallVectorImpl<char> &path) { } void FileSystem::Resolve(FileSpec &file_spec) { + if (!file_spec) + return; + // Extract path from the FileSpec. SmallString<128> path; file_spec.GetPath(path); @@ -279,8 +296,7 @@ void FileSystem::Resolve(FileSpec &file_spec) { std::shared_ptr<DataBufferLLVM> FileSystem::CreateDataBuffer(const llvm::Twine &path, uint64_t size, uint64_t offset) { - if (m_collector) - m_collector->addFile(path); + Collect(path); const bool is_volatile = !IsLocal(path); const ErrorOr<std::string> external_path = GetExternalPath(path); @@ -418,8 +434,7 @@ static mode_t GetOpenMode(uint32_t permissions) { Expected<FileUP> FileSystem::Open(const FileSpec &file_spec, File::OpenOptions options, uint32_t permissions, bool should_close_fd) { - if (m_collector) - m_collector->addFile(file_spec.GetPath()); + Collect(file_spec.GetPath()); const int open_flags = GetOpenFlags(options); const mode_t open_mode = @@ -466,3 +481,17 @@ ErrorOr<std::string> FileSystem::GetExternalPath(const llvm::Twine &path) { ErrorOr<std::string> FileSystem::GetExternalPath(const FileSpec &file_spec) { return GetExternalPath(file_spec.GetPath()); } + +void FileSystem::Collect(const FileSpec &file_spec) { + Collect(file_spec.GetPath()); +} + +void FileSystem::Collect(const llvm::Twine &file) { + if (!m_collector) + return; + + if (llvm::sys::fs::is_directory(file)) + m_collector->addDirectory(file); + else + m_collector->addFile(file); +} diff --git a/lldb/source/Host/common/GetOptInc.cpp b/lldb/source/Host/common/GetOptInc.cpp index 95a68c5d3c76..62ce7428e8cc 100644 --- a/lldb/source/Host/common/GetOptInc.cpp +++ b/lldb/source/Host/common/GetOptInc.cpp @@ -1,4 +1,4 @@ -//===-- GetOptInc.cpp -------------------------------------------*- C++ -*-===// +//===-- GetOptInc.cpp -----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/Host.cpp b/lldb/source/Host/common/Host.cpp index 5fbb655fc793..4128fa19c142 100644 --- a/lldb/source/Host/common/Host.cpp +++ b/lldb/source/Host/common/Host.cpp @@ -1,4 +1,4 @@ -//===-- Host.cpp ------------------------------------------------*- C++ -*-===// +//===-- Host.cpp ----------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -28,7 +28,7 @@ #if defined(__linux__) || defined(__FreeBSD__) || \ defined(__FreeBSD_kernel__) || defined(__APPLE__) || \ - defined(__NetBSD__) || defined(__OpenBSD__) + defined(__NetBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__) #if !defined(__ANDROID__) #include <spawn.h> #endif @@ -501,6 +501,8 @@ Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir, launch_info.SetArguments(args, first_arg_is_executable); } + launch_info.GetEnvironment() = Host::GetEnvironment(); + if (working_dir) launch_info.SetWorkingDirectory(working_dir); llvm::SmallString<64> output_file_path; @@ -519,7 +521,7 @@ Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir, } } - FileSpec output_file_spec(output_file_path.c_str()); + FileSpec output_file_spec(output_file_path.str()); // Set up file descriptors. launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false); if (output_file_spec) @@ -678,3 +680,23 @@ void llvm::format_provider<WaitStatus>::format(const WaitStatus &WS, } OS << desc << " " << int(WS.status); } + +uint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info, + ProcessInstanceInfoList &process_infos) { + + if (llvm::Optional<ProcessInstanceInfoList> infos = + repro::GetReplayProcessInstanceInfoList()) { + process_infos = *infos; + return process_infos.size(); + } + + uint32_t result = FindProcessesImpl(match_info, process_infos); + + if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { + g->GetOrCreate<repro::ProcessInfoProvider>() + .GetNewProcessInfoRecorder() + ->Record(process_infos); + } + + return result; +} diff --git a/lldb/source/Host/common/HostInfoBase.cpp b/lldb/source/Host/common/HostInfoBase.cpp index 8f263e90d90f..333137a7fd25 100644 --- a/lldb/source/Host/common/HostInfoBase.cpp +++ b/lldb/source/Host/common/HostInfoBase.cpp @@ -1,4 +1,4 @@ -//===-- HostInfoBase.cpp ----------------------------------------*- C++ -*-===// +//===-- HostInfoBase.cpp --------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/HostNativeThreadBase.cpp b/lldb/source/Host/common/HostNativeThreadBase.cpp index fe7d85acaf11..a79431f61d88 100644 --- a/lldb/source/Host/common/HostNativeThreadBase.cpp +++ b/lldb/source/Host/common/HostNativeThreadBase.cpp @@ -1,4 +1,4 @@ -//===-- HostNativeThreadBase.cpp --------------------------------*- C++ -*-===// +//===-- HostNativeThreadBase.cpp ------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/HostProcess.cpp b/lldb/source/Host/common/HostProcess.cpp index e180687551f8..256a73bb6716 100644 --- a/lldb/source/Host/common/HostProcess.cpp +++ b/lldb/source/Host/common/HostProcess.cpp @@ -1,4 +1,4 @@ -//===-- HostProcess.cpp -----------------------------------------*- C++ -*-===// +//===-- HostProcess.cpp ---------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/HostThread.cpp b/lldb/source/Host/common/HostThread.cpp index 89cadce5b206..eec029be1c09 100644 --- a/lldb/source/Host/common/HostThread.cpp +++ b/lldb/source/Host/common/HostThread.cpp @@ -1,4 +1,4 @@ -//===-- HostThread.cpp ------------------------------------------*- C++ -*-===// +//===-- HostThread.cpp ----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/LZMA.cpp b/lldb/source/Host/common/LZMA.cpp index 02be8a09df66..5b457f07afca 100644 --- a/lldb/source/Host/common/LZMA.cpp +++ b/lldb/source/Host/common/LZMA.cpp @@ -1,4 +1,4 @@ -//===-- LZMA.cpp ------------------------------------------------*- C++ -*-===// +//===-- LZMA.cpp ----------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/LockFileBase.cpp b/lldb/source/Host/common/LockFileBase.cpp index 744b1eaabb4e..d4cd8f7ffed1 100644 --- a/lldb/source/Host/common/LockFileBase.cpp +++ b/lldb/source/Host/common/LockFileBase.cpp @@ -1,4 +1,4 @@ -//===-- LockFileBase.cpp ----------------------------------------*- C++ -*-===// +//===-- LockFileBase.cpp --------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/MainLoop.cpp b/lldb/source/Host/common/MainLoop.cpp index 240320f83242..02cabbc93550 100644 --- a/lldb/source/Host/common/MainLoop.cpp +++ b/lldb/source/Host/common/MainLoop.cpp @@ -1,4 +1,4 @@ -//===-- MainLoop.cpp --------------------------------------------*- C++ -*-===// +//===-- MainLoop.cpp ------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/MonitoringProcessLauncher.cpp b/lldb/source/Host/common/MonitoringProcessLauncher.cpp index 55e9f69a089a..1ef345cd5082 100644 --- a/lldb/source/Host/common/MonitoringProcessLauncher.cpp +++ b/lldb/source/Host/common/MonitoringProcessLauncher.cpp @@ -1,4 +1,4 @@ -//===-- MonitoringProcessLauncher.cpp ---------------------------*- C++ -*-===// +//===-- MonitoringProcessLauncher.cpp -------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/NativeProcessProtocol.cpp b/lldb/source/Host/common/NativeProcessProtocol.cpp index 712c448dc2c1..a4d0b4181d58 100644 --- a/lldb/source/Host/common/NativeProcessProtocol.cpp +++ b/lldb/source/Host/common/NativeProcessProtocol.cpp @@ -1,4 +1,4 @@ -//===-- NativeProcessProtocol.cpp -------------------------------*- C++ -*-===// +//===-- NativeProcessProtocol.cpp -----------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -650,7 +650,7 @@ Status NativeProcessProtocol::ReadMemoryWithoutTrap(lldb::addr_t addr, auto saved_opcodes = makeArrayRef(pair.second.saved_opcodes); if (bp_addr + saved_opcodes.size() < addr || addr + bytes_read <= bp_addr) - continue; // Breapoint not in range, ignore + continue; // Breakpoint not in range, ignore if (bp_addr < addr) { saved_opcodes = saved_opcodes.drop_front(addr - bp_addr); diff --git a/lldb/source/Host/common/NativeRegisterContext.cpp b/lldb/source/Host/common/NativeRegisterContext.cpp index fe40073eb59d..47548f90491d 100644 --- a/lldb/source/Host/common/NativeRegisterContext.cpp +++ b/lldb/source/Host/common/NativeRegisterContext.cpp @@ -1,4 +1,4 @@ -//===-- NativeRegisterContext.cpp -------------------------*- C++ -*-===// +//===-- NativeRegisterContext.cpp -----------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/NativeThreadProtocol.cpp b/lldb/source/Host/common/NativeThreadProtocol.cpp index e62b1425c891..16901bc9cf7b 100644 --- a/lldb/source/Host/common/NativeThreadProtocol.cpp +++ b/lldb/source/Host/common/NativeThreadProtocol.cpp @@ -1,4 +1,4 @@ -//===-- NativeThreadProtocol.cpp --------------------------------*- C++ -*-===// +//===-- NativeThreadProtocol.cpp ------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/NativeWatchpointList.cpp b/lldb/source/Host/common/NativeWatchpointList.cpp index c3db95fb252e..6d856202d147 100644 --- a/lldb/source/Host/common/NativeWatchpointList.cpp +++ b/lldb/source/Host/common/NativeWatchpointList.cpp @@ -1,4 +1,4 @@ -//===-- NativeWatchpointList.cpp --------------------------------*- C++ -*-===// +//===-- NativeWatchpointList.cpp ------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/OptionParser.cpp b/lldb/source/Host/common/OptionParser.cpp index 1e76f9b8f9f1..b5c7ea66732c 100644 --- a/lldb/source/Host/common/OptionParser.cpp +++ b/lldb/source/Host/common/OptionParser.cpp @@ -1,4 +1,4 @@ -//===-- source/Host/common/OptionParser.cpp ---------------------*- C++ -*-===// +//===-- source/Host/common/OptionParser.cpp -------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -41,7 +41,7 @@ int OptionParser::Parse(llvm::MutableArrayRef<char *> argv, ++longopts; } opts.push_back(option()); - std::string opt_cstr = optstring; + std::string opt_cstr = std::string(optstring); return getopt_long_only(argv.size() - 1, argv.data(), opt_cstr.c_str(), &opts[0], longindex); } diff --git a/lldb/source/Host/common/PipeBase.cpp b/lldb/source/Host/common/PipeBase.cpp index 2cbadf0c85f6..b3e0ab34a58d 100644 --- a/lldb/source/Host/common/PipeBase.cpp +++ b/lldb/source/Host/common/PipeBase.cpp @@ -1,4 +1,4 @@ -//===-- source/Host/common/PipeBase.cpp -------------------------*- C++ -*-===// +//===-- source/Host/common/PipeBase.cpp -----------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/ProcessLaunchInfo.cpp b/lldb/source/Host/common/ProcessLaunchInfo.cpp index 266b46763996..4bc8cda7a006 100644 --- a/lldb/source/Host/common/ProcessLaunchInfo.cpp +++ b/lldb/source/Host/common/ProcessLaunchInfo.cpp @@ -1,4 +1,4 @@ -//===-- ProcessLaunchInfo.cpp -----------------------------------*- C++ -*-===// +//===-- ProcessLaunchInfo.cpp ---------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -133,7 +133,7 @@ const char *ProcessLaunchInfo::GetProcessPluginName() const { } void ProcessLaunchInfo::SetProcessPluginName(llvm::StringRef plugin) { - m_plugin_name = plugin; + m_plugin_name = std::string(plugin); } const FileSpec &ProcessLaunchInfo::GetShell() const { return m_shell; } @@ -218,26 +218,26 @@ llvm::Error ProcessLaunchInfo::SetUpPtyRedirection() { // do for now. open_flags |= O_CLOEXEC; #endif - if (!m_pty->OpenFirstAvailableMaster(open_flags, nullptr, 0)) { + if (!m_pty->OpenFirstAvailablePrimary(open_flags, nullptr, 0)) { return llvm::createStringError(llvm::inconvertibleErrorCode(), - "PTY::OpenFirstAvailableMaster failed"); + "PTY::OpenFirstAvailablePrimary failed"); } - const FileSpec slave_file_spec(m_pty->GetSlaveName(nullptr, 0)); + const FileSpec secondary_file_spec(m_pty->GetSecondaryName(nullptr, 0)); - // Only use the slave tty if we don't have anything specified for + // Only use the secondary tty if we don't have anything specified for // input and don't have an action for stdin if (GetFileActionForFD(STDIN_FILENO) == nullptr) - AppendOpenFileAction(STDIN_FILENO, slave_file_spec, true, false); + AppendOpenFileAction(STDIN_FILENO, secondary_file_spec, true, false); - // Only use the slave tty if we don't have anything specified for + // Only use the secondary tty if we don't have anything specified for // output and don't have an action for stdout if (GetFileActionForFD(STDOUT_FILENO) == nullptr) - AppendOpenFileAction(STDOUT_FILENO, slave_file_spec, false, true); + AppendOpenFileAction(STDOUT_FILENO, secondary_file_spec, false, true); - // Only use the slave tty if we don't have anything specified for + // Only use the secondary tty if we don't have anything specified for // error and don't have an action for stderr if (GetFileActionForFD(STDERR_FILENO) == nullptr) - AppendOpenFileAction(STDERR_FILENO, slave_file_spec, false, true); + AppendOpenFileAction(STDERR_FILENO, secondary_file_spec, false, true); return llvm::Error::success(); } diff --git a/lldb/source/Host/common/ProcessRunLock.cpp b/lldb/source/Host/common/ProcessRunLock.cpp index a931da718766..3b6f033d33ab 100644 --- a/lldb/source/Host/common/ProcessRunLock.cpp +++ b/lldb/source/Host/common/ProcessRunLock.cpp @@ -1,4 +1,4 @@ -//===-- ProcessRunLock.cpp --------------------------------------*- C++ -*-===// +//===-- ProcessRunLock.cpp ------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/PseudoTerminal.cpp b/lldb/source/Host/common/PseudoTerminal.cpp index 85828283e210..72549f1c88ab 100644 --- a/lldb/source/Host/common/PseudoTerminal.cpp +++ b/lldb/source/Host/common/PseudoTerminal.cpp @@ -1,4 +1,4 @@ -//===-- PseudoTerminal.cpp --------------------------------------*- C++ -*-===// +//===-- PseudoTerminal.cpp ------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -34,73 +34,73 @@ static void ErrnoToStr(char *error_str, size_t error_len) { // PseudoTerminal constructor PseudoTerminal::PseudoTerminal() - : m_master_fd(invalid_fd), m_slave_fd(invalid_fd) {} + : m_primary_fd(invalid_fd), m_secondary_fd(invalid_fd) {} // Destructor // -// The destructor will close the master and slave file descriptors if they are -// valid and ownership has not been released using the -// ReleaseMasterFileDescriptor() or the ReleaseSaveFileDescriptor() member +// The destructor will close the primary and secondary file descriptors if they +// are valid and ownership has not been released using the +// ReleasePrimaryFileDescriptor() or the ReleaseSaveFileDescriptor() member // functions. PseudoTerminal::~PseudoTerminal() { - CloseMasterFileDescriptor(); - CloseSlaveFileDescriptor(); + ClosePrimaryFileDescriptor(); + CloseSecondaryFileDescriptor(); } -// Close the master file descriptor if it is valid. -void PseudoTerminal::CloseMasterFileDescriptor() { - if (m_master_fd >= 0) { - ::close(m_master_fd); - m_master_fd = invalid_fd; +// Close the primary file descriptor if it is valid. +void PseudoTerminal::ClosePrimaryFileDescriptor() { + if (m_primary_fd >= 0) { + ::close(m_primary_fd); + m_primary_fd = invalid_fd; } } -// Close the slave file descriptor if it is valid. -void PseudoTerminal::CloseSlaveFileDescriptor() { - if (m_slave_fd >= 0) { - ::close(m_slave_fd); - m_slave_fd = invalid_fd; +// Close the secondary file descriptor if it is valid. +void PseudoTerminal::CloseSecondaryFileDescriptor() { + if (m_secondary_fd >= 0) { + ::close(m_secondary_fd); + m_secondary_fd = invalid_fd; } } // Open the first available pseudo terminal with OFLAG as the permissions. The // file descriptor is stored in this object and can be accessed with the -// MasterFileDescriptor() accessor. The ownership of the master file descriptor -// can be released using the ReleaseMasterFileDescriptor() accessor. If this -// object has a valid master files descriptor when its destructor is called, it -// will close the master file descriptor, therefore clients must call -// ReleaseMasterFileDescriptor() if they wish to use the master file descriptor -// after this object is out of scope or destroyed. +// PrimaryFileDescriptor() accessor. The ownership of the primary file +// descriptor can be released using the ReleasePrimaryFileDescriptor() accessor. +// If this object has a valid primary files descriptor when its destructor is +// called, it will close the primary file descriptor, therefore clients must +// call ReleasePrimaryFileDescriptor() if they wish to use the primary file +// descriptor after this object is out of scope or destroyed. // // RETURNS: // True when successful, false indicating an error occurred. -bool PseudoTerminal::OpenFirstAvailableMaster(int oflag, char *error_str, - size_t error_len) { +bool PseudoTerminal::OpenFirstAvailablePrimary(int oflag, char *error_str, + size_t error_len) { if (error_str) error_str[0] = '\0'; #if LLDB_ENABLE_POSIX - // Open the master side of a pseudo terminal - m_master_fd = ::posix_openpt(oflag); - if (m_master_fd < 0) { + // Open the primary side of a pseudo terminal + m_primary_fd = ::posix_openpt(oflag); + if (m_primary_fd < 0) { if (error_str) ErrnoToStr(error_str, error_len); return false; } - // Grant access to the slave pseudo terminal - if (::grantpt(m_master_fd) < 0) { + // Grant access to the secondary pseudo terminal + if (::grantpt(m_primary_fd) < 0) { if (error_str) ErrnoToStr(error_str, error_len); - CloseMasterFileDescriptor(); + ClosePrimaryFileDescriptor(); return false; } - // Clear the lock flag on the slave pseudo terminal - if (::unlockpt(m_master_fd) < 0) { + // Clear the lock flag on the secondary pseudo terminal + if (::unlockpt(m_primary_fd) < 0) { if (error_str) ErrnoToStr(error_str, error_len); - CloseMasterFileDescriptor(); + ClosePrimaryFileDescriptor(); return false; } @@ -112,30 +112,32 @@ bool PseudoTerminal::OpenFirstAvailableMaster(int oflag, char *error_str, #endif } -// Open the slave pseudo terminal for the current master pseudo terminal. A -// master pseudo terminal should already be valid prior to calling this -// function (see OpenFirstAvailableMaster()). The file descriptor is stored +// Open the secondary pseudo terminal for the current primary pseudo terminal. A +// primary pseudo terminal should already be valid prior to calling this +// function (see OpenFirstAvailablePrimary()). The file descriptor is stored // this object's member variables and can be accessed via the -// GetSlaveFileDescriptor(), or released using the ReleaseSlaveFileDescriptor() -// member function. +// GetSecondaryFileDescriptor(), or released using the +// ReleaseSecondaryFileDescriptor() member function. // // RETURNS: // True when successful, false indicating an error occurred. -bool PseudoTerminal::OpenSlave(int oflag, char *error_str, size_t error_len) { +bool PseudoTerminal::OpenSecondary(int oflag, char *error_str, + size_t error_len) { if (error_str) error_str[0] = '\0'; - CloseSlaveFileDescriptor(); + CloseSecondaryFileDescriptor(); - // Open the master side of a pseudo terminal - const char *slave_name = GetSlaveName(error_str, error_len); + // Open the primary side of a pseudo terminal + const char *secondary_name = GetSecondaryName(error_str, error_len); - if (slave_name == nullptr) + if (secondary_name == nullptr) return false; - m_slave_fd = llvm::sys::RetryAfterSignal(-1, ::open, slave_name, oflag); + m_secondary_fd = + llvm::sys::RetryAfterSignal(-1, ::open, secondary_name, oflag); - if (m_slave_fd < 0) { + if (m_secondary_fd < 0) { if (error_str) ErrnoToStr(error_str, error_len); return false; @@ -144,46 +146,46 @@ bool PseudoTerminal::OpenSlave(int oflag, char *error_str, size_t error_len) { return true; } -// Get the name of the slave pseudo terminal. A master pseudo terminal should -// already be valid prior to calling this function (see -// OpenFirstAvailableMaster()). +// Get the name of the secondary pseudo terminal. A primary pseudo terminal +// should already be valid prior to calling this function (see +// OpenFirstAvailablePrimary()). // // RETURNS: -// NULL if no valid master pseudo terminal or if ptsname() fails. -// The name of the slave pseudo terminal as a NULL terminated C string +// NULL if no valid primary pseudo terminal or if ptsname() fails. +// The name of the secondary pseudo terminal as a NULL terminated C string // that comes from static memory, so a copy of the string should be // made as subsequent calls can change this value. -const char *PseudoTerminal::GetSlaveName(char *error_str, - size_t error_len) const { +const char *PseudoTerminal::GetSecondaryName(char *error_str, + size_t error_len) const { if (error_str) error_str[0] = '\0'; - if (m_master_fd < 0) { + if (m_primary_fd < 0) { if (error_str) ::snprintf(error_str, error_len, "%s", - "master file descriptor is invalid"); + "primary file descriptor is invalid"); return nullptr; } - const char *slave_name = ::ptsname(m_master_fd); + const char *secondary_name = ::ptsname(m_primary_fd); - if (error_str && slave_name == nullptr) + if (error_str && secondary_name == nullptr) ErrnoToStr(error_str, error_len); - return slave_name; + return secondary_name; } // Fork a child process and have its stdio routed to a pseudo terminal. // -// In the parent process when a valid pid is returned, the master file +// In the parent process when a valid pid is returned, the primary file // descriptor can be used as a read/write access to stdio of the child process. // // In the child process the stdin/stdout/stderr will already be routed to the -// slave pseudo terminal and the master file descriptor will be closed as it is -// no longer needed by the child process. +// secondary pseudo terminal and the primary file descriptor will be closed as +// it is no longer needed by the child process. // -// This class will close the file descriptors for the master/slave when the -// destructor is called, so be sure to call ReleaseMasterFileDescriptor() or -// ReleaseSlaveFileDescriptor() if any file descriptors are going to be used +// This class will close the file descriptors for the primary/secondary when the +// destructor is called, so be sure to call ReleasePrimaryFileDescriptor() or +// ReleaseSecondaryFileDescriptor() if any file descriptors are going to be used // past the lifespan of this object. // // RETURNS: @@ -196,8 +198,8 @@ lldb::pid_t PseudoTerminal::Fork(char *error_str, size_t error_len) { #if LLDB_ENABLE_POSIX int flags = O_RDWR; flags |= O_CLOEXEC; - if (OpenFirstAvailableMaster(flags, error_str, error_len)) { - // Successfully opened our master pseudo terminal + if (OpenFirstAvailablePrimary(flags, error_str, error_len)) { + // Successfully opened our primary pseudo terminal pid = ::fork(); if (pid < 0) { @@ -208,32 +210,32 @@ lldb::pid_t PseudoTerminal::Fork(char *error_str, size_t error_len) { // Child Process ::setsid(); - if (OpenSlave(O_RDWR, error_str, error_len)) { - // Successfully opened slave + if (OpenSecondary(O_RDWR, error_str, error_len)) { + // Successfully opened secondary - // Master FD should have O_CLOEXEC set, but let's close it just in + // Primary FD should have O_CLOEXEC set, but let's close it just in // case... - CloseMasterFileDescriptor(); + ClosePrimaryFileDescriptor(); #if defined(TIOCSCTTY) // Acquire the controlling terminal - if (::ioctl(m_slave_fd, TIOCSCTTY, (char *)0) < 0) { + if (::ioctl(m_secondary_fd, TIOCSCTTY, (char *)0) < 0) { if (error_str) ErrnoToStr(error_str, error_len); } #endif - // Duplicate all stdio file descriptors to the slave pseudo terminal - if (::dup2(m_slave_fd, STDIN_FILENO) != STDIN_FILENO) { + // Duplicate all stdio file descriptors to the secondary pseudo terminal + if (::dup2(m_secondary_fd, STDIN_FILENO) != STDIN_FILENO) { if (error_str && !error_str[0]) ErrnoToStr(error_str, error_len); } - if (::dup2(m_slave_fd, STDOUT_FILENO) != STDOUT_FILENO) { + if (::dup2(m_secondary_fd, STDOUT_FILENO) != STDOUT_FILENO) { if (error_str && !error_str[0]) ErrnoToStr(error_str, error_len); } - if (::dup2(m_slave_fd, STDERR_FILENO) != STDERR_FILENO) { + if (::dup2(m_secondary_fd, STDERR_FILENO) != STDERR_FILENO) { if (error_str && !error_str[0]) ErrnoToStr(error_str, error_len); } @@ -247,41 +249,43 @@ lldb::pid_t PseudoTerminal::Fork(char *error_str, size_t error_len) { return pid; } -// The master file descriptor accessor. This object retains ownership of the -// master file descriptor when this accessor is used. Use -// ReleaseMasterFileDescriptor() if you wish this object to release ownership -// of the master file descriptor. +// The primary file descriptor accessor. This object retains ownership of the +// primary file descriptor when this accessor is used. Use +// ReleasePrimaryFileDescriptor() if you wish this object to release ownership +// of the primary file descriptor. // -// Returns the master file descriptor, or -1 if the master file descriptor is +// Returns the primary file descriptor, or -1 if the primary file descriptor is // not currently valid. -int PseudoTerminal::GetMasterFileDescriptor() const { return m_master_fd; } +int PseudoTerminal::GetPrimaryFileDescriptor() const { return m_primary_fd; } -// The slave file descriptor accessor. +// The secondary file descriptor accessor. // -// Returns the slave file descriptor, or -1 if the slave file descriptor is not -// currently valid. -int PseudoTerminal::GetSlaveFileDescriptor() const { return m_slave_fd; } +// Returns the secondary file descriptor, or -1 if the secondary file descriptor +// is not currently valid. +int PseudoTerminal::GetSecondaryFileDescriptor() const { + return m_secondary_fd; +} -// Release ownership of the master pseudo terminal file descriptor without -// closing it. The destructor for this class will close the master file -// descriptor if the ownership isn't released using this call and the master +// Release ownership of the primary pseudo terminal file descriptor without +// closing it. The destructor for this class will close the primary file +// descriptor if the ownership isn't released using this call and the primary // file descriptor has been opened. -int PseudoTerminal::ReleaseMasterFileDescriptor() { - // Release ownership of the master pseudo terminal file descriptor without +int PseudoTerminal::ReleasePrimaryFileDescriptor() { + // Release ownership of the primary pseudo terminal file descriptor without // closing it. (the destructor for this class will close it otherwise!) - int fd = m_master_fd; - m_master_fd = invalid_fd; + int fd = m_primary_fd; + m_primary_fd = invalid_fd; return fd; } -// Release ownership of the slave pseudo terminal file descriptor without -// closing it. The destructor for this class will close the slave file -// descriptor if the ownership isn't released using this call and the slave +// Release ownership of the secondary pseudo terminal file descriptor without +// closing it. The destructor for this class will close the secondary file +// descriptor if the ownership isn't released using this call and the secondary // file descriptor has been opened. -int PseudoTerminal::ReleaseSlaveFileDescriptor() { - // Release ownership of the slave pseudo terminal file descriptor without +int PseudoTerminal::ReleaseSecondaryFileDescriptor() { + // Release ownership of the secondary pseudo terminal file descriptor without // closing it (the destructor for this class will close it otherwise!) - int fd = m_slave_fd; - m_slave_fd = invalid_fd; + int fd = m_secondary_fd; + m_secondary_fd = invalid_fd; return fd; } diff --git a/lldb/source/Host/common/Socket.cpp b/lldb/source/Host/common/Socket.cpp index 7fba1daff75f..4bcf34a6b456 100644 --- a/lldb/source/Host/common/Socket.cpp +++ b/lldb/source/Host/common/Socket.cpp @@ -1,4 +1,4 @@ -//===-- Socket.cpp ----------------------------------------------*- C++ -*-===// +//===-- Socket.cpp --------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -147,71 +147,65 @@ std::unique_ptr<Socket> Socket::Create(const SocketProtocol protocol, return socket_up; } -Status Socket::TcpConnect(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket) { - Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_COMMUNICATION)); - LLDB_LOGF(log, "Socket::%s (host/port = %s)", __FUNCTION__, - host_and_port.str().c_str()); +llvm::Expected<std::unique_ptr<Socket>> +Socket::TcpConnect(llvm::StringRef host_and_port, + bool child_processes_inherit) { + Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); + LLDB_LOG(log, "host_and_port = {0}", host_and_port); Status error; std::unique_ptr<Socket> connect_socket( Create(ProtocolTcp, child_processes_inherit, error)); if (error.Fail()) - return error; + return error.ToError(); error = connect_socket->Connect(host_and_port); if (error.Success()) - socket = connect_socket.release(); + return std::move(connect_socket); - return error; + return error.ToError(); } -Status Socket::TcpListen(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket, - Predicate<uint16_t> *predicate, int backlog) { +llvm::Expected<std::unique_ptr<TCPSocket>> +Socket::TcpListen(llvm::StringRef host_and_port, bool child_processes_inherit, + Predicate<uint16_t> *predicate, int backlog) { Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); - LLDB_LOGF(log, "Socket::%s (%s)", __FUNCTION__, host_and_port.str().c_str()); + LLDB_LOG(log, "host_and_port = {0}", host_and_port); Status error; std::string host_str; std::string port_str; int32_t port = INT32_MIN; if (!DecodeHostAndPort(host_and_port, host_str, port_str, port, &error)) - return error; + return error.ToError(); std::unique_ptr<TCPSocket> listen_socket( new TCPSocket(true, child_processes_inherit)); - if (error.Fail()) - return error; error = listen_socket->Listen(host_and_port, backlog); - if (error.Success()) { - // We were asked to listen on port zero which means we must now read the - // actual port that was given to us as port zero is a special code for - // "find an open port for me". - if (port == 0) - port = listen_socket->GetLocalPortNumber(); - - // Set the port predicate since when doing a listen://<host>:<port> it - // often needs to accept the incoming connection which is a blocking system - // call. Allowing access to the bound port using a predicate allows us to - // wait for the port predicate to be set to a non-zero value from another - // thread in an efficient manor. - if (predicate) - predicate->SetValue(port, eBroadcastAlways); - socket = listen_socket.release(); - } - - return error; + if (error.Fail()) + return error.ToError(); + + // We were asked to listen on port zero which means we must now read the + // actual port that was given to us as port zero is a special code for + // "find an open port for me". + if (port == 0) + port = listen_socket->GetLocalPortNumber(); + + // Set the port predicate since when doing a listen://<host>:<port> it + // often needs to accept the incoming connection which is a blocking system + // call. Allowing access to the bound port using a predicate allows us to + // wait for the port predicate to be set to a non-zero value from another + // thread in an efficient manor. + if (predicate) + predicate->SetValue(port, eBroadcastAlways); + return std::move(listen_socket); } -Status Socket::UdpConnect(llvm::StringRef host_and_port, - bool child_processes_inherit, Socket *&socket) { - Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); - LLDB_LOGF(log, "Socket::%s (host/port = %s)", __FUNCTION__, - host_and_port.str().c_str()); - - return UDPSocket::Connect(host_and_port, child_processes_inherit, socket); +llvm::Expected<std::unique_ptr<UDPSocket>> +Socket::UdpConnect(llvm::StringRef host_and_port, + bool child_processes_inherit) { + return UDPSocket::Connect(host_and_port, child_processes_inherit); } Status Socket::UnixDomainConnect(llvm::StringRef name, @@ -309,7 +303,7 @@ bool Socket::DecodeHostAndPort(llvm::StringRef host_and_port, host_str.clear(); port_str.clear(); if (to_integer(host_and_port, port, 10) && port < UINT16_MAX) { - port_str = host_and_port; + port_str = std::string(host_and_port); if (error_ptr) error_ptr->Clear(); return true; diff --git a/lldb/source/Host/common/SocketAddress.cpp b/lldb/source/Host/common/SocketAddress.cpp index 960ed18dc768..e98944d6cdc8 100644 --- a/lldb/source/Host/common/SocketAddress.cpp +++ b/lldb/source/Host/common/SocketAddress.cpp @@ -1,4 +1,4 @@ -//===-- SocketAddress.cpp ---------------------------------------*- C++ -*-===// +//===-- SocketAddress.cpp -------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/StringConvert.cpp b/lldb/source/Host/common/StringConvert.cpp index 8bf04f0a9ca3..e5f05e628c7c 100644 --- a/lldb/source/Host/common/StringConvert.cpp +++ b/lldb/source/Host/common/StringConvert.cpp @@ -1,4 +1,4 @@ -//===-- StringConvert.cpp ---------------------------------------*- C++ -*-===// +//===-- StringConvert.cpp -------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/TCPSocket.cpp b/lldb/source/Host/common/TCPSocket.cpp index b716935db6e6..047cb0e4c2bf 100644 --- a/lldb/source/Host/common/TCPSocket.cpp +++ b/lldb/source/Host/common/TCPSocket.cpp @@ -1,4 +1,4 @@ -//===-- TCPSocket.cpp -------------------------------------------*- C++ -*-===// +//===-- TCPSocket.cpp -----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -18,6 +18,7 @@ #include "llvm/Config/llvm-config.h" #include "llvm/Support/Errno.h" +#include "llvm/Support/WindowsError.h" #include "llvm/Support/raw_ostream.h" #if LLDB_ENABLE_POSIX @@ -42,6 +43,16 @@ typedef const void *set_socket_option_arg_type; using namespace lldb; using namespace lldb_private; +static Status GetLastSocketError() { + std::error_code EC; +#ifdef _WIN32 + EC = llvm::mapWindowsError(WSAGetLastError()); +#else + EC = std::error_code(errno, std::generic_category()); +#endif + return EC; +} + namespace { const int kType = SOCK_STREAM; } @@ -120,8 +131,8 @@ std::string TCPSocket::GetRemoteIPAddress() const { std::string TCPSocket::GetRemoteConnectionURI() const { if (m_socket != kInvalidSocketValue) { - return llvm::formatv("connect://[{0}]:{1}", GetRemoteIPAddress(), - GetRemotePortNumber()); + return std::string(llvm::formatv( + "connect://[{0}]:{1}", GetRemoteIPAddress(), GetRemotePortNumber())); } return ""; } @@ -192,10 +203,8 @@ Status TCPSocket::Listen(llvm::StringRef name, int backlog) { for (SocketAddress &address : addresses) { int fd = Socket::CreateSocket(address.GetFamily(), kType, IPPROTO_TCP, m_child_processes_inherit, error); - if (error.Fail()) { - error.Clear(); + if (error.Fail()) continue; - } // enable local address reuse int option_value = 1; @@ -216,6 +225,7 @@ Status TCPSocket::Listen(llvm::StringRef name, int backlog) { err = ::listen(fd, backlog); if (-1 == err) { + error = GetLastSocketError(); CLOSE_SOCKET(fd); continue; } @@ -228,9 +238,11 @@ Status TCPSocket::Listen(llvm::StringRef name, int backlog) { m_listen_sockets[fd] = address; } - if (m_listen_sockets.size() == 0) - error.SetErrorString("Failed to connect port"); - return error; + if (m_listen_sockets.empty()) { + assert(error.Fail()); + return error; + } + return Status(); } void TCPSocket::CloseListenSockets() { diff --git a/lldb/source/Host/common/TaskPool.cpp b/lldb/source/Host/common/TaskPool.cpp deleted file mode 100644 index 73f761b5cf63..000000000000 --- a/lldb/source/Host/common/TaskPool.cpp +++ /dev/null @@ -1,126 +0,0 @@ -//===--------------------- TaskPool.cpp -------------------------*- C++ -*-===// -// -// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. -// See https://llvm.org/LICENSE.txt for license information. -// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception -// -//===----------------------------------------------------------------------===// - -#include "lldb/Host/TaskPool.h" -#include "lldb/Host/ThreadLauncher.h" -#include "lldb/Utility/Log.h" - -#include <cstdint> -#include <queue> -#include <thread> - -namespace lldb_private { - -namespace { -class TaskPoolImpl { -public: - static TaskPoolImpl &GetInstance(); - - void AddTask(std::function<void()> &&task_fn); - -private: - TaskPoolImpl(); - - static lldb::thread_result_t WorkerPtr(void *pool); - - static void Worker(TaskPoolImpl *pool); - - std::queue<std::function<void()>> m_tasks; - std::mutex m_tasks_mutex; - uint32_t m_thread_count; -}; - -} // end of anonymous namespace - -TaskPoolImpl &TaskPoolImpl::GetInstance() { - static TaskPoolImpl g_task_pool_impl; - return g_task_pool_impl; -} - -void TaskPool::AddTaskImpl(std::function<void()> &&task_fn) { - TaskPoolImpl::GetInstance().AddTask(std::move(task_fn)); -} - -TaskPoolImpl::TaskPoolImpl() : m_thread_count(0) {} - -unsigned GetHardwareConcurrencyHint() { - // std::thread::hardware_concurrency may return 0 if the value is not well - // defined or not computable. - static const unsigned g_hardware_concurrency = - std::max(1u, std::thread::hardware_concurrency()); - return g_hardware_concurrency; -} - -void TaskPoolImpl::AddTask(std::function<void()> &&task_fn) { - const size_t min_stack_size = 8 * 1024 * 1024; - - std::unique_lock<std::mutex> lock(m_tasks_mutex); - m_tasks.emplace(std::move(task_fn)); - if (m_thread_count < GetHardwareConcurrencyHint()) { - m_thread_count++; - // Note that this detach call needs to happen with the m_tasks_mutex held. - // This prevents the thread from exiting prematurely and triggering a linux - // libc bug (https://sourceware.org/bugzilla/show_bug.cgi?id=19951). - llvm::Expected<HostThread> host_thread = - lldb_private::ThreadLauncher::LaunchThread( - "task-pool.worker", WorkerPtr, this, min_stack_size); - if (host_thread) { - host_thread->Release(); - } else { - LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), - "failed to launch host thread: {}", - llvm::toString(host_thread.takeError())); - } - } -} - -lldb::thread_result_t TaskPoolImpl::WorkerPtr(void *pool) { - Worker((TaskPoolImpl *)pool); - return {}; -} - -void TaskPoolImpl::Worker(TaskPoolImpl *pool) { - while (true) { - std::unique_lock<std::mutex> lock(pool->m_tasks_mutex); - if (pool->m_tasks.empty()) { - pool->m_thread_count--; - break; - } - - std::function<void()> f = std::move(pool->m_tasks.front()); - pool->m_tasks.pop(); - lock.unlock(); - - f(); - } -} - -void TaskMapOverInt(size_t begin, size_t end, - const llvm::function_ref<void(size_t)> &func) { - const size_t num_workers = std::min<size_t>(end, GetHardwareConcurrencyHint()); - std::atomic<size_t> idx{begin}; - - auto wrapper = [&idx, end, &func]() { - while (true) { - size_t i = idx.fetch_add(1); - if (i >= end) - break; - func(i); - } - }; - - std::vector<std::future<void>> futures; - futures.reserve(num_workers); - for (size_t i = 0; i < num_workers; i++) - futures.push_back(TaskPool::AddTask(wrapper)); - for (size_t i = 0; i < num_workers; i++) - futures[i].wait(); -} - -} // namespace lldb_private - diff --git a/lldb/source/Host/common/Terminal.cpp b/lldb/source/Host/common/Terminal.cpp index e1aea26eeb90..9990dbf74356 100644 --- a/lldb/source/Host/common/Terminal.cpp +++ b/lldb/source/Host/common/Terminal.cpp @@ -1,4 +1,4 @@ -//===-- Terminal.cpp --------------------------------------------*- C++ -*-===// +//===-- Terminal.cpp ------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/ThreadLauncher.cpp b/lldb/source/Host/common/ThreadLauncher.cpp index 6e3c8b6a13a4..bd104b3e4aed 100644 --- a/lldb/source/Host/common/ThreadLauncher.cpp +++ b/lldb/source/Host/common/ThreadLauncher.cpp @@ -1,4 +1,4 @@ -//===-- ThreadLauncher.cpp --------------------------------------*- C++ -*-===// +//===-- ThreadLauncher.cpp ------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. diff --git a/lldb/source/Host/common/UDPSocket.cpp b/lldb/source/Host/common/UDPSocket.cpp index 0a991c33645b..0b537b3a9b13 100644 --- a/lldb/source/Host/common/UDPSocket.cpp +++ b/lldb/source/Host/common/UDPSocket.cpp @@ -1,4 +1,4 @@ -//===-- UDPSocket.cpp -------------------------------------------*- C++ -*-===// +//===-- UDPSocket.cpp -----------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. @@ -53,19 +53,19 @@ Status UDPSocket::Accept(Socket *&socket) { return Status("%s", g_not_supported_error); } -Status UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit, - Socket *&socket) { - std::unique_ptr<UDPSocket> final_socket; +llvm::Expected<std::unique_ptr<UDPSocket>> +UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit) { + std::unique_ptr<UDPSocket> socket; Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_CONNECTION)); - LLDB_LOGF(log, "UDPSocket::%s (host/port = %s)", __FUNCTION__, name.data()); + LLDB_LOG(log, "host/port = {0}", name); Status error; std::string host_str; std::string port_str; int32_t port = INT32_MIN; if (!DecodeHostAndPort(name, host_str, port_str, port, &error)) - return error; + return error.ToError(); // At this point we have setup the receive port, now we need to setup the UDP // send socket @@ -86,7 +86,7 @@ Status UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit, "getaddrinfo(%s, %s, &hints, &info) returned error %i (%s)", #endif host_str.c_str(), port_str.c_str(), err, gai_strerror(err)); - return error; + return error.ToError(); } for (struct addrinfo *service_info_ptr = service_info_list; @@ -96,8 +96,8 @@ Status UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit, service_info_ptr->ai_family, service_info_ptr->ai_socktype, service_info_ptr->ai_protocol, child_processes_inherit, error); if (error.Success()) { - final_socket.reset(new UDPSocket(send_fd)); - final_socket->m_sockaddr = service_info_ptr; + socket.reset(new UDPSocket(send_fd)); + socket->m_sockaddr = service_info_ptr; break; } else continue; @@ -105,8 +105,8 @@ Status UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit, ::freeaddrinfo(service_info_list); - if (!final_socket) - return error; + if (!socket) + return error.ToError(); SocketAddress bind_addr; @@ -118,26 +118,25 @@ Status UDPSocket::Connect(llvm::StringRef name, bool child_processes_inherit, if (!bind_addr_success) { error.SetErrorString("Failed to get hostspec to bind for"); - return error; + return error.ToError(); } bind_addr.SetPort(0); // Let the source port # be determined dynamically - err = ::bind(final_socket->GetNativeSocket(), bind_addr, bind_addr.GetLength()); + err = ::bind(socket->GetNativeSocket(), bind_addr, bind_addr.GetLength()); struct sockaddr_in source_info; socklen_t address_len = sizeof (struct sockaddr_in); - err = ::getsockname(final_socket->GetNativeSocket(), (struct sockaddr *) &source_info, &address_len); + err = ::getsockname(socket->GetNativeSocket(), + (struct sockaddr *)&source_info, &address_len); - socket = final_socket.release(); - error.Clear(); - return error; + return std::move(socket); } std::string UDPSocket::GetRemoteConnectionURI() const { if (m_socket != kInvalidSocketValue) { - return llvm::formatv("udp://[{0}]:{1}", m_sockaddr.GetIPAddress(), - m_sockaddr.GetPort()); + return std::string(llvm::formatv( + "udp://[{0}]:{1}", m_sockaddr.GetIPAddress(), m_sockaddr.GetPort())); } return ""; } diff --git a/lldb/source/Host/common/XML.cpp b/lldb/source/Host/common/XML.cpp index 28d1f5a8eaf4..456c879b0148 100644 --- a/lldb/source/Host/common/XML.cpp +++ b/lldb/source/Host/common/XML.cpp @@ -1,4 +1,4 @@ -//===-- XML.cpp -------------------------------------------------*- C++ -*-===// +//===-- XML.cpp -----------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. |