diff options
Diffstat (limited to 'lldb/source/Host/linux')
-rw-r--r-- | lldb/source/Host/linux/AbstractSocket.cpp | 15 | ||||
-rw-r--r-- | lldb/source/Host/linux/Host.cpp | 608 | ||||
-rw-r--r-- | lldb/source/Host/linux/HostInfoLinux.cpp | 403 | ||||
-rw-r--r-- | lldb/source/Host/linux/HostThreadLinux.cpp | 43 | ||||
-rw-r--r-- | lldb/source/Host/linux/LibcGlue.cpp | 27 | ||||
-rw-r--r-- | lldb/source/Host/linux/ProcessLauncherLinux.cpp | 330 | ||||
-rw-r--r-- | lldb/source/Host/linux/ThisThread.cpp | 14 |
7 files changed, 680 insertions, 760 deletions
diff --git a/lldb/source/Host/linux/AbstractSocket.cpp b/lldb/source/Host/linux/AbstractSocket.cpp index 8ac0107..b6b59ae 100644 --- a/lldb/source/Host/linux/AbstractSocket.cpp +++ b/lldb/source/Host/linux/AbstractSocket.cpp @@ -15,17 +15,8 @@ using namespace lldb; using namespace lldb_private; AbstractSocket::AbstractSocket(bool child_processes_inherit, Error &error) - : DomainSocket(ProtocolUnixAbstract, child_processes_inherit, error) -{ -} + : DomainSocket(ProtocolUnixAbstract, child_processes_inherit, error) {} -size_t -AbstractSocket::GetNameOffset() const -{ - return 1; -} +size_t AbstractSocket::GetNameOffset() const { return 1; } -void -AbstractSocket::DeleteSocketFile(llvm::StringRef name) -{ -} +void AbstractSocket::DeleteSocketFile(llvm::StringRef name) {} diff --git a/lldb/source/Host/linux/Host.cpp b/lldb/source/Host/linux/Host.cpp index 53d74d5..ca2084d 100644 --- a/lldb/source/Host/linux/Host.cpp +++ b/lldb/source/Host/linux/Host.cpp @@ -25,379 +25,353 @@ #include "lldb/Core/Log.h" #include "lldb/Target/Process.h" -#include "lldb/Host/Host.h" -#include "lldb/Host/HostInfo.h" #include "lldb/Core/DataBufferHeap.h" #include "lldb/Core/DataExtractor.h" +#include "lldb/Host/Host.h" +#include "lldb/Host/HostInfo.h" +#include "Plugins/Process/Linux/ProcFileReader.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Symbol/ObjectFile.h" -#include "Plugins/Process/Linux/ProcFileReader.h" using namespace lldb; using namespace lldb_private; -typedef enum ProcessStateFlags -{ - eProcessStateRunning = (1u << 0), // Running - eProcessStateSleeping = (1u << 1), // Sleeping in an interruptible wait - eProcessStateWaiting = (1u << 2), // Waiting in an uninterruptible disk sleep - eProcessStateZombie = (1u << 3), // Zombie - eProcessStateTracedOrStopped = (1u << 4), // Traced or stopped (on a signal) - eProcessStatePaging = (1u << 5) // Paging +typedef enum ProcessStateFlags { + eProcessStateRunning = (1u << 0), // Running + eProcessStateSleeping = (1u << 1), // Sleeping in an interruptible wait + eProcessStateWaiting = (1u << 2), // Waiting in an uninterruptible disk sleep + eProcessStateZombie = (1u << 3), // Zombie + eProcessStateTracedOrStopped = (1u << 4), // Traced or stopped (on a signal) + eProcessStatePaging = (1u << 5) // Paging } ProcessStateFlags; -typedef struct ProcessStatInfo -{ - lldb::pid_t ppid; // Parent Process ID - uint32_t fProcessState; // ProcessStateFlags +typedef struct ProcessStatInfo { + lldb::pid_t ppid; // Parent Process ID + uint32_t fProcessState; // ProcessStateFlags } ProcessStatInfo; -// Get the process info with additional information from /proc/$PID/stat (like process state, and tracer pid). -static bool GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid); - -static bool -ReadProcPseudoFileStat (lldb::pid_t pid, ProcessStatInfo& stat_info) -{ - // Read the /proc/$PID/stat file. - lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "stat"); - - // The filename of the executable is stored in parenthesis right after the pid. We look for the closing - // parenthesis for the filename and work from there in case the name has something funky like ')' in it. - const char *filename_end = strrchr ((const char *)buf_sp->GetBytes(), ')'); - if (filename_end) - { - char state = '\0'; - int ppid = LLDB_INVALID_PROCESS_ID; - - // Read state and ppid. - sscanf (filename_end + 1, " %c %d", &state, &ppid); - - stat_info.ppid = ppid; - - switch (state) - { - case 'R': - stat_info.fProcessState |= eProcessStateRunning; - break; - case 'S': - stat_info.fProcessState |= eProcessStateSleeping; - break; - case 'D': - stat_info.fProcessState |= eProcessStateWaiting; - break; - case 'Z': - stat_info.fProcessState |= eProcessStateZombie; - break; - case 'T': - stat_info.fProcessState |= eProcessStateTracedOrStopped; - break; - case 'W': - stat_info.fProcessState |= eProcessStatePaging; - break; - } - - return true; +// Get the process info with additional information from /proc/$PID/stat (like +// process state, and tracer pid). +static bool GetProcessAndStatInfo(lldb::pid_t pid, + ProcessInstanceInfo &process_info, + ProcessStatInfo &stat_info, + lldb::pid_t &tracerpid); + +static bool ReadProcPseudoFileStat(lldb::pid_t pid, + ProcessStatInfo &stat_info) { + // Read the /proc/$PID/stat file. + lldb::DataBufferSP buf_sp = + process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "stat"); + + // The filename of the executable is stored in parenthesis right after the + // pid. We look for the closing + // parenthesis for the filename and work from there in case the name has + // something funky like ')' in it. + const char *filename_end = strrchr((const char *)buf_sp->GetBytes(), ')'); + if (filename_end) { + char state = '\0'; + int ppid = LLDB_INVALID_PROCESS_ID; + + // Read state and ppid. + sscanf(filename_end + 1, " %c %d", &state, &ppid); + + stat_info.ppid = ppid; + + switch (state) { + case 'R': + stat_info.fProcessState |= eProcessStateRunning; + break; + case 'S': + stat_info.fProcessState |= eProcessStateSleeping; + break; + case 'D': + stat_info.fProcessState |= eProcessStateWaiting; + break; + case 'Z': + stat_info.fProcessState |= eProcessStateZombie; + break; + case 'T': + stat_info.fProcessState |= eProcessStateTracedOrStopped; + break; + case 'W': + stat_info.fProcessState |= eProcessStatePaging; + break; } - return false; -} - -static void -GetLinuxProcessUserAndGroup (lldb::pid_t pid, ProcessInstanceInfo &process_info, lldb::pid_t &tracerpid) -{ - tracerpid = 0; - uint32_t rUid = UINT32_MAX; // Real User ID - uint32_t eUid = UINT32_MAX; // Effective User ID - uint32_t rGid = UINT32_MAX; // Real Group ID - uint32_t eGid = UINT32_MAX; // Effective Group ID - - // Read the /proc/$PID/status file and parse the Uid:, Gid:, and TracerPid: fields. - lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "status"); - - static const char uid_token[] = "Uid:"; - char *buf_uid = strstr ((char *)buf_sp->GetBytes(), uid_token); - if (buf_uid) - { - // Real, effective, saved set, and file system UIDs. Read the first two. - buf_uid += sizeof(uid_token); - rUid = strtol (buf_uid, &buf_uid, 10); - eUid = strtol (buf_uid, &buf_uid, 10); - } - - static const char gid_token[] = "Gid:"; - char *buf_gid = strstr ((char *)buf_sp->GetBytes(), gid_token); - if (buf_gid) - { - // Real, effective, saved set, and file system GIDs. Read the first two. - buf_gid += sizeof(gid_token); - rGid = strtol (buf_gid, &buf_gid, 10); - eGid = strtol (buf_gid, &buf_gid, 10); - } - - static const char tracerpid_token[] = "TracerPid:"; - char *buf_tracerpid = strstr((char *)buf_sp->GetBytes(), tracerpid_token); - if (buf_tracerpid) - { - // Tracer PID. 0 if we're not being debugged. - buf_tracerpid += sizeof(tracerpid_token); - tracerpid = strtol (buf_tracerpid, &buf_tracerpid, 10); - } + return true; + } - process_info.SetUserID (rUid); - process_info.SetEffectiveUserID (eUid); - process_info.SetGroupID (rGid); - process_info.SetEffectiveGroupID (eGid); + return false; } -lldb::DataBufferSP -Host::GetAuxvData(lldb_private::Process *process) -{ - return process_linux::ProcFileReader::ReadIntoDataBuffer (process->GetID(), "auxv"); +static void GetLinuxProcessUserAndGroup(lldb::pid_t pid, + ProcessInstanceInfo &process_info, + lldb::pid_t &tracerpid) { + tracerpid = 0; + uint32_t rUid = UINT32_MAX; // Real User ID + uint32_t eUid = UINT32_MAX; // Effective User ID + uint32_t rGid = UINT32_MAX; // Real Group ID + uint32_t eGid = UINT32_MAX; // Effective Group ID + + // Read the /proc/$PID/status file and parse the Uid:, Gid:, and TracerPid: + // fields. + lldb::DataBufferSP buf_sp = + process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "status"); + + static const char uid_token[] = "Uid:"; + char *buf_uid = strstr((char *)buf_sp->GetBytes(), uid_token); + if (buf_uid) { + // Real, effective, saved set, and file system UIDs. Read the first two. + buf_uid += sizeof(uid_token); + rUid = strtol(buf_uid, &buf_uid, 10); + eUid = strtol(buf_uid, &buf_uid, 10); + } + + static const char gid_token[] = "Gid:"; + char *buf_gid = strstr((char *)buf_sp->GetBytes(), gid_token); + if (buf_gid) { + // Real, effective, saved set, and file system GIDs. Read the first two. + buf_gid += sizeof(gid_token); + rGid = strtol(buf_gid, &buf_gid, 10); + eGid = strtol(buf_gid, &buf_gid, 10); + } + + static const char tracerpid_token[] = "TracerPid:"; + char *buf_tracerpid = strstr((char *)buf_sp->GetBytes(), tracerpid_token); + if (buf_tracerpid) { + // Tracer PID. 0 if we're not being debugged. + buf_tracerpid += sizeof(tracerpid_token); + tracerpid = strtol(buf_tracerpid, &buf_tracerpid, 10); + } + + process_info.SetUserID(rUid); + process_info.SetEffectiveUserID(eUid); + process_info.SetGroupID(rGid); + process_info.SetEffectiveGroupID(eGid); } -lldb::DataBufferSP -Host::GetAuxvData (lldb::pid_t pid) -{ - return process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "auxv"); +lldb::DataBufferSP Host::GetAuxvData(lldb_private::Process *process) { + return process_linux::ProcFileReader::ReadIntoDataBuffer(process->GetID(), + "auxv"); } -static bool -IsDirNumeric(const char *dname) -{ - for (; *dname; dname++) - { - if (!isdigit (*dname)) - return false; - } - return true; +lldb::DataBufferSP Host::GetAuxvData(lldb::pid_t pid) { + return process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "auxv"); } -uint32_t -Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) -{ - static const char procdir[] = "/proc/"; +static bool IsDirNumeric(const char *dname) { + for (; *dname; dname++) { + if (!isdigit(*dname)) + return false; + } + return true; +} - DIR *dirproc = opendir (procdir); - if (dirproc) - { - struct dirent *direntry = NULL; - const uid_t our_uid = getuid(); - const lldb::pid_t our_pid = getpid(); - bool all_users = match_info.GetMatchAllUsers(); +uint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info, + ProcessInstanceInfoList &process_infos) { + static const char procdir[] = "/proc/"; - while ((direntry = readdir (dirproc)) != NULL) - { - if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name)) - continue; + DIR *dirproc = opendir(procdir); + if (dirproc) { + struct dirent *direntry = NULL; + const uid_t our_uid = getuid(); + const lldb::pid_t our_pid = getpid(); + bool all_users = match_info.GetMatchAllUsers(); - lldb::pid_t pid = atoi (direntry->d_name); + while ((direntry = readdir(dirproc)) != NULL) { + if (direntry->d_type != DT_DIR || !IsDirNumeric(direntry->d_name)) + continue; - // Skip this process. - if (pid == our_pid) - continue; + lldb::pid_t pid = atoi(direntry->d_name); - lldb::pid_t tracerpid; - ProcessStatInfo stat_info; - ProcessInstanceInfo process_info; + // Skip this process. + if (pid == our_pid) + continue; - if (!GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid)) - continue; + lldb::pid_t tracerpid; + ProcessStatInfo stat_info; + ProcessInstanceInfo process_info; - // Skip if process is being debugged. - if (tracerpid != 0) - continue; + if (!GetProcessAndStatInfo(pid, process_info, stat_info, tracerpid)) + continue; - // Skip zombies. - if (stat_info.fProcessState & eProcessStateZombie) - continue; + // Skip if process is being debugged. + if (tracerpid != 0) + continue; - // Check for user match if we're not matching all users and not running as root. - if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid)) - continue; + // Skip zombies. + if (stat_info.fProcessState & eProcessStateZombie) + continue; - if (match_info.Matches (process_info)) - { - process_infos.Append (process_info); - } - } + // Check for user match if we're not matching all users and not running as + // root. + if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid)) + continue; - closedir (dirproc); + if (match_info.Matches(process_info)) { + process_infos.Append(process_info); + } } - return process_infos.GetSize(); + closedir(dirproc); + } + + return process_infos.GetSize(); } -bool -Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach) -{ - bool tids_changed = false; - static const char procdir[] = "/proc/"; - static const char taskdir[] = "/task/"; - std::string process_task_dir = procdir + llvm::to_string(pid) + taskdir; - DIR *dirproc = opendir (process_task_dir.c_str()); - - if (dirproc) - { - struct dirent *direntry = NULL; - while ((direntry = readdir (dirproc)) != NULL) - { - if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name)) - continue; - - lldb::tid_t tid = atoi(direntry->d_name); - TidMap::iterator it = tids_to_attach.find(tid); - if (it == tids_to_attach.end()) - { - tids_to_attach.insert(TidPair(tid, false)); - tids_changed = true; - } - } - closedir (dirproc); +bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) { + bool tids_changed = false; + static const char procdir[] = "/proc/"; + static const char taskdir[] = "/task/"; + std::string process_task_dir = procdir + llvm::to_string(pid) + taskdir; + DIR *dirproc = opendir(process_task_dir.c_str()); + + if (dirproc) { + struct dirent *direntry = NULL; + while ((direntry = readdir(dirproc)) != NULL) { + if (direntry->d_type != DT_DIR || !IsDirNumeric(direntry->d_name)) + continue; + + lldb::tid_t tid = atoi(direntry->d_name); + TidMap::iterator it = tids_to_attach.find(tid); + if (it == tids_to_attach.end()) { + tids_to_attach.insert(TidPair(tid, false)); + tids_changed = true; + } } + closedir(dirproc); + } - return tids_changed; + return tids_changed; } -static bool -GetELFProcessCPUType (const char *exe_path, ProcessInstanceInfo &process_info) -{ - // Clear the architecture. - process_info.GetArchitecture().Clear(); - - ModuleSpecList specs; - FileSpec filespec (exe_path, false); - const size_t num_specs = ObjectFile::GetModuleSpecifications (filespec, 0, 0, specs); - // GetModuleSpecifications() could fail if the executable has been deleted or is locked. - // But it shouldn't return more than 1 architecture. - assert(num_specs <= 1 && "Linux plugin supports only a single architecture"); - if (num_specs == 1) - { - ModuleSpec module_spec; - if (specs.GetModuleSpecAtIndex (0, module_spec) && module_spec.GetArchitecture().IsValid()) - { - process_info.GetArchitecture () = module_spec.GetArchitecture(); - return true; - } +static bool GetELFProcessCPUType(const char *exe_path, + ProcessInstanceInfo &process_info) { + // Clear the architecture. + process_info.GetArchitecture().Clear(); + + ModuleSpecList specs; + FileSpec filespec(exe_path, false); + const size_t num_specs = + ObjectFile::GetModuleSpecifications(filespec, 0, 0, specs); + // GetModuleSpecifications() could fail if the executable has been deleted or + // is locked. + // But it shouldn't return more than 1 architecture. + assert(num_specs <= 1 && "Linux plugin supports only a single architecture"); + if (num_specs == 1) { + ModuleSpec module_spec; + if (specs.GetModuleSpecAtIndex(0, module_spec) && + module_spec.GetArchitecture().IsValid()) { + process_info.GetArchitecture() = module_spec.GetArchitecture(); + return true; } - return false; + } + return false; } -static bool -GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid) -{ - tracerpid = 0; - process_info.Clear(); - ::memset (&stat_info, 0, sizeof(stat_info)); - stat_info.ppid = LLDB_INVALID_PROCESS_ID; - - Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); - - // Use special code here because proc/[pid]/exe is a symbolic link. - char link_path[PATH_MAX]; - char exe_path[PATH_MAX] = ""; - if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0) - { - if (log) - log->Printf("%s: failed to sprintf pid %" PRIu64, __FUNCTION__, pid); - return false; - } - - ssize_t len = readlink (link_path, exe_path, sizeof(exe_path) - 1); - if (len <= 0) - { - if (log) - log->Printf("%s: failed to read link %s: %s", __FUNCTION__, link_path, strerror(errno)); - return false; - } - - // readlink does not append a null byte. - exe_path[len] = 0; - - // If the binary has been deleted, the link name has " (deleted)" appended. - // Remove if there. - static const ssize_t deleted_len = strlen(" (deleted)"); - if (len > deleted_len && - !strcmp(exe_path + len - deleted_len, " (deleted)")) - { - exe_path[len - deleted_len] = 0; - } - else - { - GetELFProcessCPUType (exe_path, process_info); - } - - process_info.SetProcessID(pid); - process_info.GetExecutableFile().SetFile(exe_path, false); - process_info.GetArchitecture().MergeFrom(HostInfo::GetArchitecture()); - - lldb::DataBufferSP buf_sp; - - // Get the process environment. - buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "environ"); - Args &info_env = process_info.GetEnvironmentEntries(); - char *next_var = (char *)buf_sp->GetBytes(); - char *end_buf = next_var + buf_sp->GetByteSize(); - while (next_var < end_buf && 0 != *next_var) - { - info_env.AppendArgument(next_var); - next_var += strlen(next_var) + 1; - } +static bool GetProcessAndStatInfo(lldb::pid_t pid, + ProcessInstanceInfo &process_info, + ProcessStatInfo &stat_info, + lldb::pid_t &tracerpid) { + tracerpid = 0; + process_info.Clear(); + ::memset(&stat_info, 0, sizeof(stat_info)); + stat_info.ppid = LLDB_INVALID_PROCESS_ID; + + Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); + + // Use special code here because proc/[pid]/exe is a symbolic link. + char link_path[PATH_MAX]; + char exe_path[PATH_MAX] = ""; + if (snprintf(link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0) { + if (log) + log->Printf("%s: failed to sprintf pid %" PRIu64, __FUNCTION__, pid); + return false; + } - // Get the command line used to start the process. - buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "cmdline"); - - // Grab Arg0 first, if there is one. - char *cmd = (char *)buf_sp->GetBytes(); - if (cmd) - { - process_info.SetArg0(cmd); - - // Now process any remaining arguments. - Args &info_args = process_info.GetArguments(); - char *next_arg = cmd + strlen(cmd) + 1; - end_buf = cmd + buf_sp->GetByteSize(); - while (next_arg < end_buf && 0 != *next_arg) - { - info_args.AppendArgument(next_arg); - next_arg += strlen(next_arg) + 1; - } + ssize_t len = readlink(link_path, exe_path, sizeof(exe_path) - 1); + if (len <= 0) { + if (log) + log->Printf("%s: failed to read link %s: %s", __FUNCTION__, link_path, + strerror(errno)); + return false; + } + + // readlink does not append a null byte. + exe_path[len] = 0; + + // If the binary has been deleted, the link name has " (deleted)" appended. + // Remove if there. + static const ssize_t deleted_len = strlen(" (deleted)"); + if (len > deleted_len && + !strcmp(exe_path + len - deleted_len, " (deleted)")) { + exe_path[len - deleted_len] = 0; + } else { + GetELFProcessCPUType(exe_path, process_info); + } + + process_info.SetProcessID(pid); + process_info.GetExecutableFile().SetFile(exe_path, false); + process_info.GetArchitecture().MergeFrom(HostInfo::GetArchitecture()); + + lldb::DataBufferSP buf_sp; + + // Get the process environment. + buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "environ"); + Args &info_env = process_info.GetEnvironmentEntries(); + char *next_var = (char *)buf_sp->GetBytes(); + char *end_buf = next_var + buf_sp->GetByteSize(); + while (next_var < end_buf && 0 != *next_var) { + info_env.AppendArgument(next_var); + next_var += strlen(next_var) + 1; + } + + // Get the command line used to start the process. + buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "cmdline"); + + // Grab Arg0 first, if there is one. + char *cmd = (char *)buf_sp->GetBytes(); + if (cmd) { + process_info.SetArg0(cmd); + + // Now process any remaining arguments. + Args &info_args = process_info.GetArguments(); + char *next_arg = cmd + strlen(cmd) + 1; + end_buf = cmd + buf_sp->GetByteSize(); + while (next_arg < end_buf && 0 != *next_arg) { + info_args.AppendArgument(next_arg); + next_arg += strlen(next_arg) + 1; } + } - // Read /proc/$PID/stat to get our parent pid. - if (ReadProcPseudoFileStat (pid, stat_info)) - { - process_info.SetParentProcessID (stat_info.ppid); - } + // Read /proc/$PID/stat to get our parent pid. + if (ReadProcPseudoFileStat(pid, stat_info)) { + process_info.SetParentProcessID(stat_info.ppid); + } - // Get User and Group IDs and get tracer pid. - GetLinuxProcessUserAndGroup (pid, process_info, tracerpid); + // Get User and Group IDs and get tracer pid. + GetLinuxProcessUserAndGroup(pid, process_info, tracerpid); - return true; + return true; } -bool -Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) -{ - lldb::pid_t tracerpid; - ProcessStatInfo stat_info; +bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) { + lldb::pid_t tracerpid; + ProcessStatInfo stat_info; - return GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid); + return GetProcessAndStatInfo(pid, process_info, stat_info, tracerpid); } -size_t -Host::GetEnvironment (StringList &env) -{ - char **host_env = environ; - char *env_entry; - size_t i; - for (i=0; (env_entry = host_env[i]) != NULL; ++i) - env.AppendString(env_entry); - return i; +size_t Host::GetEnvironment(StringList &env) { + char **host_env = environ; + char *env_entry; + size_t i; + for (i = 0; (env_entry = host_env[i]) != NULL; ++i) + env.AppendString(env_entry); + return i; } -Error -Host::ShellExpandArguments (ProcessLaunchInfo &launch_info) -{ - return Error("unimplemented"); +Error Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { + return Error("unimplemented"); } diff --git a/lldb/source/Host/linux/HostInfoLinux.cpp b/lldb/source/Host/linux/HostInfoLinux.cpp index 0d0ba33..0f2ab7922 100644 --- a/lldb/source/Host/linux/HostInfoLinux.cpp +++ b/lldb/source/Host/linux/HostInfoLinux.cpp @@ -7,8 +7,8 @@ // //===----------------------------------------------------------------------===// -#include "lldb/Core/Log.h" #include "lldb/Host/linux/HostInfoLinux.h" +#include "lldb/Core/Log.h" #include <limits.h> #include <stdio.h> @@ -20,263 +20,224 @@ using namespace lldb_private; -namespace -{ -struct HostInfoLinuxFields -{ - HostInfoLinuxFields() - : m_os_major(0) - , m_os_minor(0) - , m_os_update(0) - { - } +namespace { +struct HostInfoLinuxFields { + HostInfoLinuxFields() : m_os_major(0), m_os_minor(0), m_os_update(0) {} - std::string m_distribution_id; - uint32_t m_os_major; - uint32_t m_os_minor; - uint32_t m_os_update; + std::string m_distribution_id; + uint32_t m_os_major; + uint32_t m_os_minor; + uint32_t m_os_update; }; HostInfoLinuxFields *g_fields = nullptr; } -void -HostInfoLinux::Initialize() -{ - HostInfoPosix::Initialize(); +void HostInfoLinux::Initialize() { + HostInfoPosix::Initialize(); - g_fields = new HostInfoLinuxFields(); + g_fields = new HostInfoLinuxFields(); } -uint32_t -HostInfoLinux::GetMaxThreadNameLength() -{ - return 16; -} +uint32_t HostInfoLinux::GetMaxThreadNameLength() { return 16; } -bool -HostInfoLinux::GetOSVersion(uint32_t &major, uint32_t &minor, uint32_t &update) -{ - static bool success = false; - static std::once_flag g_once_flag; - std::call_once(g_once_flag, []() { - - struct utsname un; - if (uname(&un) == 0) - { - int status = sscanf(un.release, "%u.%u.%u", &g_fields->m_os_major, &g_fields->m_os_minor, &g_fields->m_os_update); - if (status == 3) - success = true; - else - { - // Some kernels omit the update version, so try looking for just "X.Y" and - // set update to 0. - g_fields->m_os_update = 0; - status = sscanf(un.release, "%u.%u", &g_fields->m_os_major, &g_fields->m_os_minor); - if (status == 2) - success = true; - } - } - }); +bool HostInfoLinux::GetOSVersion(uint32_t &major, uint32_t &minor, + uint32_t &update) { + static bool success = false; + static std::once_flag g_once_flag; + std::call_once(g_once_flag, []() { + struct utsname un; + if (uname(&un) == 0) { + int status = sscanf(un.release, "%u.%u.%u", &g_fields->m_os_major, + &g_fields->m_os_minor, &g_fields->m_os_update); + if (status == 3) + success = true; + else { + // Some kernels omit the update version, so try looking for just "X.Y" + // and + // set update to 0. + g_fields->m_os_update = 0; + status = sscanf(un.release, "%u.%u", &g_fields->m_os_major, + &g_fields->m_os_minor); + if (status == 2) + success = true; + } + } + }); - major = g_fields->m_os_major; - minor = g_fields->m_os_minor; - update = g_fields->m_os_update; - return success; + major = g_fields->m_os_major; + minor = g_fields->m_os_minor; + update = g_fields->m_os_update; + return success; } -bool -HostInfoLinux::GetOSBuildString(std::string &s) -{ - struct utsname un; - ::memset(&un, 0, sizeof(utsname)); - s.clear(); +bool HostInfoLinux::GetOSBuildString(std::string &s) { + struct utsname un; + ::memset(&un, 0, sizeof(utsname)); + s.clear(); - if (uname(&un) < 0) - return false; + if (uname(&un) < 0) + return false; - s.assign(un.release); - return true; + s.assign(un.release); + return true; } -bool -HostInfoLinux::GetOSKernelDescription(std::string &s) -{ - struct utsname un; +bool HostInfoLinux::GetOSKernelDescription(std::string &s) { + struct utsname un; - ::memset(&un, 0, sizeof(utsname)); - s.clear(); + ::memset(&un, 0, sizeof(utsname)); + s.clear(); - if (uname(&un) < 0) - return false; + if (uname(&un) < 0) + return false; - s.assign(un.version); - return true; + s.assign(un.version); + return true; } -llvm::StringRef -HostInfoLinux::GetDistributionId() -{ - // Try to run 'lbs_release -i', and use that response - // for the distribution id. - static std::once_flag g_once_flag; - std::call_once(g_once_flag, []() { - - Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST)); +llvm::StringRef HostInfoLinux::GetDistributionId() { + // Try to run 'lbs_release -i', and use that response + // for the distribution id. + static std::once_flag g_once_flag; + std::call_once(g_once_flag, []() { + + Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST)); + if (log) + log->Printf("attempting to determine Linux distribution..."); + + // check if the lsb_release command exists at one of the + // following paths + const char *const exe_paths[] = {"/bin/lsb_release", + "/usr/bin/lsb_release"}; + + for (size_t exe_index = 0; + exe_index < sizeof(exe_paths) / sizeof(exe_paths[0]); ++exe_index) { + const char *const get_distribution_info_exe = exe_paths[exe_index]; + if (access(get_distribution_info_exe, F_OK)) { + // this exe doesn't exist, move on to next exe if (log) - log->Printf("attempting to determine Linux distribution..."); - - // check if the lsb_release command exists at one of the - // following paths - const char *const exe_paths[] = {"/bin/lsb_release", "/usr/bin/lsb_release"}; - - for (size_t exe_index = 0; exe_index < sizeof(exe_paths) / sizeof(exe_paths[0]); ++exe_index) - { - const char *const get_distribution_info_exe = exe_paths[exe_index]; - if (access(get_distribution_info_exe, F_OK)) - { - // this exe doesn't exist, move on to next exe - if (log) - log->Printf("executable doesn't exist: %s", get_distribution_info_exe); - continue; - } - - // execute the distribution-retrieval command, read output - std::string get_distribution_id_command(get_distribution_info_exe); - get_distribution_id_command += " -i"; - - FILE *file = popen(get_distribution_id_command.c_str(), "r"); - if (!file) - { - if (log) - log->Printf("failed to run command: \"%s\", cannot retrieve " - "platform information", - get_distribution_id_command.c_str()); - break; - } - - // retrieve the distribution id string. - char distribution_id[256] = {'\0'}; - if (fgets(distribution_id, sizeof(distribution_id) - 1, file) != NULL) - { - if (log) - log->Printf("distribution id command returned \"%s\"", distribution_id); - - const char *const distributor_id_key = "Distributor ID:\t"; - if (strstr(distribution_id, distributor_id_key)) - { - // strip newlines - std::string id_string(distribution_id + strlen(distributor_id_key)); - id_string.erase(std::remove(id_string.begin(), id_string.end(), '\n'), id_string.end()); - - // lower case it and convert whitespace to underscores - std::transform(id_string.begin(), id_string.end(), id_string.begin(), [](char ch) - { - return tolower(isspace(ch) ? '_' : ch); - }); - - g_fields->m_distribution_id = id_string; - if (log) - log->Printf("distribution id set to \"%s\"", g_fields->m_distribution_id.c_str()); - } - else - { - if (log) - log->Printf("failed to find \"%s\" field in \"%s\"", distributor_id_key, distribution_id); - } - } - else - { - if (log) - log->Printf("failed to retrieve distribution id, \"%s\" returned no" - " lines", - get_distribution_id_command.c_str()); - } - - // clean up the file - pclose(file); - } - }); + log->Printf("executable doesn't exist: %s", + get_distribution_info_exe); + continue; + } - return g_fields->m_distribution_id.c_str(); -} + // execute the distribution-retrieval command, read output + std::string get_distribution_id_command(get_distribution_info_exe); + get_distribution_id_command += " -i"; -FileSpec -HostInfoLinux::GetProgramFileSpec() -{ - static FileSpec g_program_filespec; - - if (!g_program_filespec) - { - char exe_path[PATH_MAX]; - ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1); - if (len > 0) - { - exe_path[len] = 0; - g_program_filespec.SetFile(exe_path, false); + FILE *file = popen(get_distribution_id_command.c_str(), "r"); + if (!file) { + if (log) + log->Printf("failed to run command: \"%s\", cannot retrieve " + "platform information", + get_distribution_id_command.c_str()); + break; + } + + // retrieve the distribution id string. + char distribution_id[256] = {'\0'}; + if (fgets(distribution_id, sizeof(distribution_id) - 1, file) != NULL) { + if (log) + log->Printf("distribution id command returned \"%s\"", + distribution_id); + + const char *const distributor_id_key = "Distributor ID:\t"; + if (strstr(distribution_id, distributor_id_key)) { + // strip newlines + std::string id_string(distribution_id + strlen(distributor_id_key)); + id_string.erase(std::remove(id_string.begin(), id_string.end(), '\n'), + id_string.end()); + + // lower case it and convert whitespace to underscores + std::transform( + id_string.begin(), id_string.end(), id_string.begin(), + [](char ch) { return tolower(isspace(ch) ? '_' : ch); }); + + g_fields->m_distribution_id = id_string; + if (log) + log->Printf("distribution id set to \"%s\"", + g_fields->m_distribution_id.c_str()); + } else { + if (log) + log->Printf("failed to find \"%s\" field in \"%s\"", + distributor_id_key, distribution_id); } + } else { + if (log) + log->Printf("failed to retrieve distribution id, \"%s\" returned no" + " lines", + get_distribution_id_command.c_str()); + } + + // clean up the file + pclose(file); } + }); - return g_program_filespec; + return g_fields->m_distribution_id.c_str(); } -bool -HostInfoLinux::ComputeSupportExeDirectory(FileSpec &file_spec) -{ - if (HostInfoPosix::ComputeSupportExeDirectory(file_spec) && - file_spec.IsAbsolute() && - file_spec.Exists()) - return true; - file_spec.GetDirectory() = GetProgramFileSpec().GetDirectory(); - return !file_spec.GetDirectory().IsEmpty(); -} +FileSpec HostInfoLinux::GetProgramFileSpec() { + static FileSpec g_program_filespec; -bool -HostInfoLinux::ComputeSystemPluginsDirectory(FileSpec &file_spec) -{ - FileSpec temp_file("/usr/lib/lldb/plugins", true); - file_spec.GetDirectory().SetCString(temp_file.GetPath().c_str()); - return true; + if (!g_program_filespec) { + char exe_path[PATH_MAX]; + ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1); + if (len > 0) { + exe_path[len] = 0; + g_program_filespec.SetFile(exe_path, false); + } + } + + return g_program_filespec; } -bool -HostInfoLinux::ComputeUserPluginsDirectory(FileSpec &file_spec) -{ - // XDG Base Directory Specification - // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html - // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb. - const char *xdg_data_home = getenv("XDG_DATA_HOME"); - if (xdg_data_home && xdg_data_home[0]) - { - std::string user_plugin_dir(xdg_data_home); - user_plugin_dir += "/lldb"; - file_spec.GetDirectory().SetCString(user_plugin_dir.c_str()); - } - else - file_spec.GetDirectory().SetCString("~/.local/share/lldb"); +bool HostInfoLinux::ComputeSupportExeDirectory(FileSpec &file_spec) { + if (HostInfoPosix::ComputeSupportExeDirectory(file_spec) && + file_spec.IsAbsolute() && file_spec.Exists()) return true; + file_spec.GetDirectory() = GetProgramFileSpec().GetDirectory(); + return !file_spec.GetDirectory().IsEmpty(); } -void -HostInfoLinux::ComputeHostArchitectureSupport(ArchSpec &arch_32, ArchSpec &arch_64) -{ - HostInfoPosix::ComputeHostArchitectureSupport(arch_32, arch_64); +bool HostInfoLinux::ComputeSystemPluginsDirectory(FileSpec &file_spec) { + FileSpec temp_file("/usr/lib/lldb/plugins", true); + file_spec.GetDirectory().SetCString(temp_file.GetPath().c_str()); + return true; +} - const char *distribution_id = GetDistributionId().data(); +bool HostInfoLinux::ComputeUserPluginsDirectory(FileSpec &file_spec) { + // XDG Base Directory Specification + // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html + // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb. + const char *xdg_data_home = getenv("XDG_DATA_HOME"); + if (xdg_data_home && xdg_data_home[0]) { + std::string user_plugin_dir(xdg_data_home); + user_plugin_dir += "/lldb"; + file_spec.GetDirectory().SetCString(user_plugin_dir.c_str()); + } else + file_spec.GetDirectory().SetCString("~/.local/share/lldb"); + return true; +} - // On Linux, "unknown" in the vendor slot isn't what we want for the default - // triple. It's probably an artifact of config.guess. - if (arch_32.IsValid()) - { - arch_32.SetDistributionId(distribution_id); - if (arch_32.GetTriple().getVendor() == llvm::Triple::UnknownVendor) - arch_32.GetTriple().setVendorName(llvm::StringRef()); - } - if (arch_64.IsValid()) - { - arch_64.SetDistributionId(distribution_id); - if (arch_64.GetTriple().getVendor() == llvm::Triple::UnknownVendor) - arch_64.GetTriple().setVendorName(llvm::StringRef()); - } +void HostInfoLinux::ComputeHostArchitectureSupport(ArchSpec &arch_32, + ArchSpec &arch_64) { + HostInfoPosix::ComputeHostArchitectureSupport(arch_32, arch_64); + + const char *distribution_id = GetDistributionId().data(); + + // On Linux, "unknown" in the vendor slot isn't what we want for the default + // triple. It's probably an artifact of config.guess. + if (arch_32.IsValid()) { + arch_32.SetDistributionId(distribution_id); + if (arch_32.GetTriple().getVendor() == llvm::Triple::UnknownVendor) + arch_32.GetTriple().setVendorName(llvm::StringRef()); + } + if (arch_64.IsValid()) { + arch_64.SetDistributionId(distribution_id); + if (arch_64.GetTriple().getVendor() == llvm::Triple::UnknownVendor) + arch_64.GetTriple().setVendorName(llvm::StringRef()); + } } diff --git a/lldb/source/Host/linux/HostThreadLinux.cpp b/lldb/source/Host/linux/HostThreadLinux.cpp index 2312ced..625f05d 100644 --- a/lldb/source/Host/linux/HostThreadLinux.cpp +++ b/lldb/source/Host/linux/HostThreadLinux.cpp @@ -7,9 +7,9 @@ // //===----------------------------------------------------------------------===// -#include "lldb/Core/DataBuffer.h" #include "lldb/Host/linux/HostThreadLinux.h" #include "Plugins/Process/Linux/ProcFileReader.h" +#include "lldb/Core/DataBuffer.h" #include "llvm/ADT/SmallVector.h" @@ -17,36 +17,29 @@ using namespace lldb_private; -HostThreadLinux::HostThreadLinux() - : HostThreadPosix() -{ -} +HostThreadLinux::HostThreadLinux() : HostThreadPosix() {} HostThreadLinux::HostThreadLinux(lldb::thread_t thread) - : HostThreadPosix(thread) -{ -} + : HostThreadPosix(thread) {} -void -HostThreadLinux::SetName(lldb::thread_t thread, llvm::StringRef name) -{ +void HostThreadLinux::SetName(lldb::thread_t thread, llvm::StringRef name) { #if (defined(__GLIBC__) && defined(_GNU_SOURCE)) || defined(__ANDROID__) - ::pthread_setname_np(thread, name.data()); + ::pthread_setname_np(thread, name.data()); #else - (void) thread; - (void) name; + (void)thread; + (void)name; #endif } -void -HostThreadLinux::GetName(lldb::thread_t thread, llvm::SmallVectorImpl<char> &name) -{ - // Read /proc/$TID/comm file. - lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(thread, "comm"); - const char *comm_str = (const char *)buf_sp->GetBytes(); - const char *cr_str = ::strchr(comm_str, '\n'); - size_t length = cr_str ? (cr_str - comm_str) : strlen(comm_str); - - name.clear(); - name.append(comm_str, comm_str + length); +void HostThreadLinux::GetName(lldb::thread_t thread, + llvm::SmallVectorImpl<char> &name) { + // Read /proc/$TID/comm file. + lldb::DataBufferSP buf_sp = + process_linux::ProcFileReader::ReadIntoDataBuffer(thread, "comm"); + const char *comm_str = (const char *)buf_sp->GetBytes(); + const char *cr_str = ::strchr(comm_str, '\n'); + size_t length = cr_str ? (cr_str - comm_str) : strlen(comm_str); + + name.clear(); + name.append(comm_str, comm_str + length); } diff --git a/lldb/source/Host/linux/LibcGlue.cpp b/lldb/source/Host/linux/LibcGlue.cpp index 63d026f..c036bb2 100644 --- a/lldb/source/Host/linux/LibcGlue.cpp +++ b/lldb/source/Host/linux/LibcGlue.cpp @@ -9,22 +9,23 @@ // This file adds functions missing from libc on older versions of linux -#include <unistd.h> -#include <sys/syscall.h> -#include <lldb/Host/linux/Uio.h> #include <cerrno> +#include <lldb/Host/linux/Uio.h> +#include <sys/syscall.h> +#include <unistd.h> -#ifndef HAVE_PROCESS_VM_READV // If the syscall wrapper is not available, provide one. -ssize_t process_vm_readv(::pid_t pid, - const struct iovec *local_iov, unsigned long liovcnt, - const struct iovec *remote_iov, unsigned long riovcnt, - unsigned long flags) -{ -#ifdef HAVE_NR_PROCESS_VM_READV // If we have the syscall number, we can issue the syscall ourselves. - return syscall(__NR_process_vm_readv, pid, local_iov, liovcnt, remote_iov, riovcnt, flags); +#ifndef HAVE_PROCESS_VM_READV // If the syscall wrapper is not available, + // provide one. +ssize_t process_vm_readv(::pid_t pid, const struct iovec *local_iov, + unsigned long liovcnt, const struct iovec *remote_iov, + unsigned long riovcnt, unsigned long flags) { +#ifdef HAVE_NR_PROCESS_VM_READV // If we have the syscall number, we can issue + // the syscall ourselves. + return syscall(__NR_process_vm_readv, pid, local_iov, liovcnt, remote_iov, + riovcnt, flags); #else // If not, let's pretend the syscall is not present. - errno = ENOSYS; - return -1; + errno = ENOSYS; + return -1; #endif } #endif diff --git a/lldb/source/Host/linux/ProcessLauncherLinux.cpp b/lldb/source/Host/linux/ProcessLauncherLinux.cpp index 2e5f4e5..444a8fd 100644 --- a/lldb/source/Host/linux/ProcessLauncherLinux.cpp +++ b/lldb/source/Host/linux/ProcessLauncherLinux.cpp @@ -25,189 +25,193 @@ using namespace lldb; using namespace lldb_private; -static void -FixupEnvironment(Args &env) -{ +static void FixupEnvironment(Args &env) { #ifdef __ANDROID_NDK__ - // If there is no PATH variable specified inside the environment then set the path to /system/bin. - // It is required because the default path used by execve() is wrong on android. - static const char *path = "PATH="; - static const int path_len = ::strlen(path); - for (const char **args = env.GetConstArgumentVector(); *args; ++args) - if (::strncmp(path, *args, path_len) == 0) - return; - env.AppendArgument("PATH=/system/bin"); + // If there is no PATH variable specified inside the environment then set the + // path to /system/bin. + // It is required because the default path used by execve() is wrong on + // android. + static const char *path = "PATH="; + static const int path_len = ::strlen(path); + for (const char **args = env.GetConstArgumentVector(); *args; ++args) + if (::strncmp(path, *args, path_len) == 0) + return; + env.AppendArgument("PATH=/system/bin"); #endif } -static void LLVM_ATTRIBUTE_NORETURN -ExitWithError(int error_fd, const char *operation) -{ - std::ostringstream os; - os << operation << " failed: " << strerror(errno); - write(error_fd, os.str().data(), os.str().size()); - close(error_fd); - _exit(1); +static void LLVM_ATTRIBUTE_NORETURN ExitWithError(int error_fd, + const char *operation) { + std::ostringstream os; + os << operation << " failed: " << strerror(errno); + write(error_fd, os.str().data(), os.str().size()); + close(error_fd); + _exit(1); } -static void -DupDescriptor(int error_fd, const FileSpec &file_spec, int fd, int flags) -{ - int target_fd = ::open(file_spec.GetCString(), flags, 0666); +static void DupDescriptor(int error_fd, const FileSpec &file_spec, int fd, + int flags) { + int target_fd = ::open(file_spec.GetCString(), flags, 0666); - if (target_fd == -1) - ExitWithError(error_fd, "DupDescriptor-open"); + if (target_fd == -1) + ExitWithError(error_fd, "DupDescriptor-open"); - if (target_fd == fd) - return; - - if (::dup2(target_fd, fd) == -1) - ExitWithError(error_fd, "DupDescriptor-dup2"); - - ::close(target_fd); + if (target_fd == fd) return; -} - -static void LLVM_ATTRIBUTE_NORETURN -ChildFunc(int error_fd, const ProcessLaunchInfo &info) -{ - // First, make sure we disable all logging. If we are logging to stdout, our logs can be - // mistaken for inferior output. - Log::DisableAllLogChannels(nullptr); - - // Do not inherit setgid powers. - if (setgid(getgid()) != 0) - ExitWithError(error_fd, "setgid"); - - if (info.GetFlags().Test(eLaunchFlagLaunchInSeparateProcessGroup)) - { - if (setpgid(0, 0) != 0) - ExitWithError(error_fd, "setpgid"); - } - for (size_t i = 0; i < info.GetNumFileActions(); ++i) - { - const FileAction &action = *info.GetFileActionAtIndex(i); - switch (action.GetAction()) - { - case FileAction::eFileActionClose: - if (close(action.GetFD()) != 0) - ExitWithError(error_fd, "close"); - break; - case FileAction::eFileActionDuplicate: - if (dup2(action.GetFD(), action.GetActionArgument()) == -1) - ExitWithError(error_fd, "dup2"); - break; - case FileAction::eFileActionOpen: - DupDescriptor(error_fd, action.GetFileSpec(), action.GetFD(), action.GetActionArgument()); - break; - case FileAction::eFileActionNone: - break; - } - } - - const char **argv = info.GetArguments().GetConstArgumentVector(); - - // Change working directory - if (info.GetWorkingDirectory() && 0 != ::chdir(info.GetWorkingDirectory().GetCString())) - ExitWithError(error_fd, "chdir"); + if (::dup2(target_fd, fd) == -1) + ExitWithError(error_fd, "DupDescriptor-dup2"); - // Disable ASLR if requested. - if (info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)) - { - const unsigned long personality_get_current = 0xffffffff; - int value = personality(personality_get_current); - if (value == -1) - ExitWithError(error_fd, "personality get"); - - value = personality(ADDR_NO_RANDOMIZE | value); - if (value == -1) - ExitWithError(error_fd, "personality set"); - } - - Args env = info.GetEnvironmentEntries(); - FixupEnvironment(env); - const char **envp = env.GetConstArgumentVector(); - - // Clear the signal mask to prevent the child from being affected by - // any masking done by the parent. - sigset_t set; - if (sigemptyset(&set) != 0 || pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0) - ExitWithError(error_fd, "pthread_sigmask"); - - if (info.GetFlags().Test(eLaunchFlagDebug)) - { - // HACK: - // Close everything besides stdin, stdout, and stderr that has no file - // action to avoid leaking. Only do this when debugging, as elsewhere we actually rely on - // passing open descriptors to child processes. - for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd) - if (!info.GetFileActionForFD(fd) && fd != error_fd) - close(fd); - - // Start tracing this child that is about to exec. - if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) - ExitWithError(error_fd, "ptrace"); - } + ::close(target_fd); + return; +} - // Execute. We should never return... - execve(argv[0], const_cast<char *const *>(argv), const_cast<char *const *>(envp)); - - if (errno == ETXTBSY) - { - // On android M and earlier we can get this error because the adb deamon can hold a write - // handle on the executable even after it has finished uploading it. This state lasts - // only a short time and happens only when there are many concurrent adb commands being - // issued, such as when running the test suite. (The file remains open when someone does - // an "adb shell" command in the fork() child before it has had a chance to exec.) Since - // this state should clear up quickly, wait a while and then give it one more go. - usleep(50000); - execve(argv[0], const_cast<char *const *>(argv), const_cast<char *const *>(envp)); +static void LLVM_ATTRIBUTE_NORETURN ChildFunc(int error_fd, + const ProcessLaunchInfo &info) { + // First, make sure we disable all logging. If we are logging to stdout, our + // logs can be + // mistaken for inferior output. + Log::DisableAllLogChannels(nullptr); + + // Do not inherit setgid powers. + if (setgid(getgid()) != 0) + ExitWithError(error_fd, "setgid"); + + if (info.GetFlags().Test(eLaunchFlagLaunchInSeparateProcessGroup)) { + if (setpgid(0, 0) != 0) + ExitWithError(error_fd, "setpgid"); + } + + for (size_t i = 0; i < info.GetNumFileActions(); ++i) { + const FileAction &action = *info.GetFileActionAtIndex(i); + switch (action.GetAction()) { + case FileAction::eFileActionClose: + if (close(action.GetFD()) != 0) + ExitWithError(error_fd, "close"); + break; + case FileAction::eFileActionDuplicate: + if (dup2(action.GetFD(), action.GetActionArgument()) == -1) + ExitWithError(error_fd, "dup2"); + break; + case FileAction::eFileActionOpen: + DupDescriptor(error_fd, action.GetFileSpec(), action.GetFD(), + action.GetActionArgument()); + break; + case FileAction::eFileActionNone: + break; } - - // ...unless exec fails. In which case we definitely need to end the child here. - ExitWithError(error_fd, "execve"); + } + + const char **argv = info.GetArguments().GetConstArgumentVector(); + + // Change working directory + if (info.GetWorkingDirectory() && + 0 != ::chdir(info.GetWorkingDirectory().GetCString())) + ExitWithError(error_fd, "chdir"); + + // Disable ASLR if requested. + if (info.GetFlags().Test(lldb::eLaunchFlagDisableASLR)) { + const unsigned long personality_get_current = 0xffffffff; + int value = personality(personality_get_current); + if (value == -1) + ExitWithError(error_fd, "personality get"); + + value = personality(ADDR_NO_RANDOMIZE | value); + if (value == -1) + ExitWithError(error_fd, "personality set"); + } + + Args env = info.GetEnvironmentEntries(); + FixupEnvironment(env); + const char **envp = env.GetConstArgumentVector(); + + // Clear the signal mask to prevent the child from being affected by + // any masking done by the parent. + sigset_t set; + if (sigemptyset(&set) != 0 || + pthread_sigmask(SIG_SETMASK, &set, nullptr) != 0) + ExitWithError(error_fd, "pthread_sigmask"); + + if (info.GetFlags().Test(eLaunchFlagDebug)) { + // HACK: + // Close everything besides stdin, stdout, and stderr that has no file + // action to avoid leaking. Only do this when debugging, as elsewhere we + // actually rely on + // passing open descriptors to child processes. + for (int fd = 3; fd < sysconf(_SC_OPEN_MAX); ++fd) + if (!info.GetFileActionForFD(fd) && fd != error_fd) + close(fd); + + // Start tracing this child that is about to exec. + if (ptrace(PTRACE_TRACEME, 0, nullptr, nullptr) == -1) + ExitWithError(error_fd, "ptrace"); + } + + // Execute. We should never return... + execve(argv[0], const_cast<char *const *>(argv), + const_cast<char *const *>(envp)); + + if (errno == ETXTBSY) { + // On android M and earlier we can get this error because the adb deamon can + // hold a write + // handle on the executable even after it has finished uploading it. This + // state lasts + // only a short time and happens only when there are many concurrent adb + // commands being + // issued, such as when running the test suite. (The file remains open when + // someone does + // an "adb shell" command in the fork() child before it has had a chance to + // exec.) Since + // this state should clear up quickly, wait a while and then give it one + // more go. + usleep(50000); + execve(argv[0], const_cast<char *const *>(argv), + const_cast<char *const *>(envp)); + } + + // ...unless exec fails. In which case we definitely need to end the child + // here. + ExitWithError(error_fd, "execve"); } HostProcess -ProcessLauncherLinux::LaunchProcess(const ProcessLaunchInfo &launch_info, Error &error) -{ - char exe_path[PATH_MAX]; - launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path)); - - // A pipe used by the child process to report errors. - PipePosix pipe; - const bool child_processes_inherit = false; - error = pipe.CreateNew(child_processes_inherit); - if (error.Fail()) - return HostProcess(); - - ::pid_t pid = ::fork(); - if (pid == -1) - { - // Fork failed - error.SetErrorStringWithFormat("Fork failed with error message: %s", strerror(errno)); - return HostProcess(LLDB_INVALID_PROCESS_ID); - } - if (pid == 0) - { - // child process - pipe.CloseReadFileDescriptor(); - ChildFunc(pipe.ReleaseWriteFileDescriptor(), launch_info); - } +ProcessLauncherLinux::LaunchProcess(const ProcessLaunchInfo &launch_info, + Error &error) { + char exe_path[PATH_MAX]; + launch_info.GetExecutableFile().GetPath(exe_path, sizeof(exe_path)); + + // A pipe used by the child process to report errors. + PipePosix pipe; + const bool child_processes_inherit = false; + error = pipe.CreateNew(child_processes_inherit); + if (error.Fail()) + return HostProcess(); - // parent process + ::pid_t pid = ::fork(); + if (pid == -1) { + // Fork failed + error.SetErrorStringWithFormat("Fork failed with error message: %s", + strerror(errno)); + return HostProcess(LLDB_INVALID_PROCESS_ID); + } + if (pid == 0) { + // child process + pipe.CloseReadFileDescriptor(); + ChildFunc(pipe.ReleaseWriteFileDescriptor(), launch_info); + } - pipe.CloseWriteFileDescriptor(); - char buf[1000]; - int r = read(pipe.GetReadFileDescriptor(), buf, sizeof buf); + // parent process - if (r == 0) - return HostProcess(pid); // No error. We're done. + pipe.CloseWriteFileDescriptor(); + char buf[1000]; + int r = read(pipe.GetReadFileDescriptor(), buf, sizeof buf); - error.SetErrorString(buf); + if (r == 0) + return HostProcess(pid); // No error. We're done. - waitpid(pid, nullptr, 0); + error.SetErrorString(buf); - return HostProcess(); + waitpid(pid, nullptr, 0); + + return HostProcess(); } diff --git a/lldb/source/Host/linux/ThisThread.cpp b/lldb/source/Host/linux/ThisThread.cpp index 1c68c8b..f65440b 100644 --- a/lldb/source/Host/linux/ThisThread.cpp +++ b/lldb/source/Host/linux/ThisThread.cpp @@ -7,8 +7,8 @@ // //===----------------------------------------------------------------------===// -#include "lldb/Host/HostNativeThread.h" #include "lldb/Host/ThisThread.h" +#include "lldb/Host/HostNativeThread.h" #include "llvm/ADT/SmallVector.h" @@ -16,14 +16,10 @@ using namespace lldb_private; -void -ThisThread::SetName(llvm::StringRef name) -{ - HostNativeThread::SetName(::pthread_self(), name); +void ThisThread::SetName(llvm::StringRef name) { + HostNativeThread::SetName(::pthread_self(), name); } -void -ThisThread::GetName(llvm::SmallVectorImpl<char> &name) -{ - HostNativeThread::GetName(::pthread_self(), name); +void ThisThread::GetName(llvm::SmallVectorImpl<char> &name) { + HostNativeThread::GetName(::pthread_self(), name); } |