1 //===-- source/Host/linux/Host.cpp ------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
17 #include <sys/types.h>
18 #include <sys/utsname.h>
21 // Other libraries and framework includes
23 #include "lldb/Core/Error.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Target/Process.h"
27 #include "lldb/Host/Host.h"
28 #include "lldb/Host/HostInfo.h"
29 #ifdef __ANDROID_NDK__
30 #include "lldb/Host/android/Android.h"
32 #include "lldb/Core/DataBufferHeap.h"
33 #include "lldb/Core/DataExtractor.h"
35 #include "lldb/Core/ModuleSpec.h"
36 #include "lldb/Symbol/ObjectFile.h"
37 #include "Plugins/Process/Linux/ProcFileReader.h"
40 using namespace lldb_private;
42 typedef enum ProcessStateFlags
44 eProcessStateRunning = (1u << 0), // Running
45 eProcessStateSleeping = (1u << 1), // Sleeping in an interruptible wait
46 eProcessStateWaiting = (1u << 2), // Waiting in an uninterruptible disk sleep
47 eProcessStateZombie = (1u << 3), // Zombie
48 eProcessStateTracedOrStopped = (1u << 4), // Traced or stopped (on a signal)
49 eProcessStatePaging = (1u << 5) // Paging
52 typedef struct ProcessStatInfo
54 lldb::pid_t ppid; // Parent Process ID
55 uint32_t fProcessState; // ProcessStateFlags
58 // Get the process info with additional information from /proc/$PID/stat (like process state, and tracer pid).
59 static bool GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid);
62 ReadProcPseudoFileStat (lldb::pid_t pid, ProcessStatInfo& stat_info)
64 // Read the /proc/$PID/stat file.
65 lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "stat");
67 // The filename of the executable is stored in parenthesis right after the pid. We look for the closing
68 // parenthesis for the filename and work from there in case the name has something funky like ')' in it.
69 const char *filename_end = strrchr ((const char *)buf_sp->GetBytes(), ')');
73 int ppid = LLDB_INVALID_PROCESS_ID;
75 // Read state and ppid.
76 sscanf (filename_end + 1, " %c %d", &state, &ppid);
78 stat_info.ppid = ppid;
83 stat_info.fProcessState |= eProcessStateRunning;
86 stat_info.fProcessState |= eProcessStateSleeping;
89 stat_info.fProcessState |= eProcessStateWaiting;
92 stat_info.fProcessState |= eProcessStateZombie;
95 stat_info.fProcessState |= eProcessStateTracedOrStopped;
98 stat_info.fProcessState |= eProcessStatePaging;
109 GetLinuxProcessUserAndGroup (lldb::pid_t pid, ProcessInstanceInfo &process_info, lldb::pid_t &tracerpid)
112 uint32_t rUid = UINT32_MAX; // Real User ID
113 uint32_t eUid = UINT32_MAX; // Effective User ID
114 uint32_t rGid = UINT32_MAX; // Real Group ID
115 uint32_t eGid = UINT32_MAX; // Effective Group ID
117 // Read the /proc/$PID/status file and parse the Uid:, Gid:, and TracerPid: fields.
118 lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "status");
120 static const char uid_token[] = "Uid:";
121 char *buf_uid = strstr ((char *)buf_sp->GetBytes(), uid_token);
124 // Real, effective, saved set, and file system UIDs. Read the first two.
125 buf_uid += sizeof(uid_token);
126 rUid = strtol (buf_uid, &buf_uid, 10);
127 eUid = strtol (buf_uid, &buf_uid, 10);
130 static const char gid_token[] = "Gid:";
131 char *buf_gid = strstr ((char *)buf_sp->GetBytes(), gid_token);
134 // Real, effective, saved set, and file system GIDs. Read the first two.
135 buf_gid += sizeof(gid_token);
136 rGid = strtol (buf_gid, &buf_gid, 10);
137 eGid = strtol (buf_gid, &buf_gid, 10);
140 static const char tracerpid_token[] = "TracerPid:";
141 char *buf_tracerpid = strstr((char *)buf_sp->GetBytes(), tracerpid_token);
144 // Tracer PID. 0 if we're not being debugged.
145 buf_tracerpid += sizeof(tracerpid_token);
146 tracerpid = strtol (buf_tracerpid, &buf_tracerpid, 10);
149 process_info.SetUserID (rUid);
150 process_info.SetEffectiveUserID (eUid);
151 process_info.SetGroupID (rGid);
152 process_info.SetEffectiveGroupID (eGid);
156 Host::GetAuxvData(lldb_private::Process *process)
158 return process_linux::ProcFileReader::ReadIntoDataBuffer (process->GetID(), "auxv");
162 Host::GetAuxvData (lldb::pid_t pid)
164 return process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "auxv");
168 IsDirNumeric(const char *dname)
170 for (; *dname; dname++)
172 if (!isdigit (*dname))
179 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
181 static const char procdir[] = "/proc/";
183 DIR *dirproc = opendir (procdir);
186 struct dirent *direntry = NULL;
187 const uid_t our_uid = getuid();
188 const lldb::pid_t our_pid = getpid();
189 bool all_users = match_info.GetMatchAllUsers();
191 while ((direntry = readdir (dirproc)) != NULL)
193 if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
196 lldb::pid_t pid = atoi (direntry->d_name);
198 // Skip this process.
202 lldb::pid_t tracerpid;
203 ProcessStatInfo stat_info;
204 ProcessInstanceInfo process_info;
206 if (!GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid))
209 // Skip if process is being debugged.
214 if (stat_info.fProcessState & eProcessStateZombie)
217 // Check for user match if we're not matching all users and not running as root.
218 if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid))
221 if (match_info.Matches (process_info))
223 process_infos.Append (process_info);
230 return process_infos.GetSize();
234 Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
236 bool tids_changed = false;
237 static const char procdir[] = "/proc/";
238 static const char taskdir[] = "/task/";
239 std::string process_task_dir = procdir + std::to_string(pid) + taskdir;
240 DIR *dirproc = opendir (process_task_dir.c_str());
244 struct dirent *direntry = NULL;
245 while ((direntry = readdir (dirproc)) != NULL)
247 if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
250 lldb::tid_t tid = atoi(direntry->d_name);
251 TidMap::iterator it = tids_to_attach.find(tid);
252 if (it == tids_to_attach.end())
254 tids_to_attach.insert(TidPair(tid, false));
265 GetELFProcessCPUType (const char *exe_path, ProcessInstanceInfo &process_info)
267 // Clear the architecture.
268 process_info.GetArchitecture().Clear();
270 ModuleSpecList specs;
271 FileSpec filespec (exe_path, false);
272 const size_t num_specs = ObjectFile::GetModuleSpecifications (filespec, 0, 0, specs);
273 // GetModuleSpecifications() could fail if the executable has been deleted or is locked.
274 // But it shouldn't return more than 1 architecture.
275 assert(num_specs <= 1 && "Linux plugin supports only a single architecture");
278 ModuleSpec module_spec;
279 if (specs.GetModuleSpecAtIndex (0, module_spec) && module_spec.GetArchitecture().IsValid())
281 process_info.GetArchitecture () = module_spec.GetArchitecture();
289 GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid)
292 process_info.Clear();
293 ::memset (&stat_info, 0, sizeof(stat_info));
294 stat_info.ppid = LLDB_INVALID_PROCESS_ID;
296 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
298 // Use special code here because proc/[pid]/exe is a symbolic link.
299 char link_path[PATH_MAX];
300 char exe_path[PATH_MAX] = "";
301 if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0)
304 log->Printf("%s: failed to sprintf pid %" PRIu64, __FUNCTION__, pid);
308 ssize_t len = readlink (link_path, exe_path, sizeof(exe_path) - 1);
312 log->Printf("%s: failed to read link %s: %s", __FUNCTION__, link_path, strerror(errno));
316 // readlink does not append a null byte.
319 // If the binary has been deleted, the link name has " (deleted)" appended.
321 static const ssize_t deleted_len = strlen(" (deleted)");
322 if (len > deleted_len &&
323 !strcmp(exe_path + len - deleted_len, " (deleted)"))
325 exe_path[len - deleted_len] = 0;
329 GetELFProcessCPUType (exe_path, process_info);
332 process_info.SetProcessID(pid);
333 process_info.GetExecutableFile().SetFile(exe_path, false);
334 process_info.GetArchitecture().MergeFrom(HostInfo::GetArchitecture());
336 lldb::DataBufferSP buf_sp;
338 // Get the process environment.
339 buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "environ");
340 Args &info_env = process_info.GetEnvironmentEntries();
341 char *next_var = (char *)buf_sp->GetBytes();
342 char *end_buf = next_var + buf_sp->GetByteSize();
343 while (next_var < end_buf && 0 != *next_var)
345 info_env.AppendArgument(next_var);
346 next_var += strlen(next_var) + 1;
349 // Get the command line used to start the process.
350 buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "cmdline");
352 // Grab Arg0 first, if there is one.
353 char *cmd = (char *)buf_sp->GetBytes();
356 process_info.SetArg0(cmd);
358 // Now process any remaining arguments.
359 Args &info_args = process_info.GetArguments();
360 char *next_arg = cmd + strlen(cmd) + 1;
361 end_buf = cmd + buf_sp->GetByteSize();
362 while (next_arg < end_buf && 0 != *next_arg)
364 info_args.AppendArgument(next_arg);
365 next_arg += strlen(next_arg) + 1;
369 // Read /proc/$PID/stat to get our parent pid.
370 if (ReadProcPseudoFileStat (pid, stat_info))
372 process_info.SetParentProcessID (stat_info.ppid);
375 // Get User and Group IDs and get tracer pid.
376 GetLinuxProcessUserAndGroup (pid, process_info, tracerpid);
382 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
384 lldb::pid_t tracerpid;
385 ProcessStatInfo stat_info;
387 return GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid);
391 Host::GetEnvironment (StringList &env)
393 char **host_env = environ;
396 for (i=0; (env_entry = host_env[i]) != NULL; ++i)
397 env.AppendString(env_entry);
402 Host::ShellExpandArguments (ProcessLaunchInfo &launch_info)
404 return Error("unimplemented");