1 //===-- source/Host/linux/Host.cpp ------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 #include <dirent.h>
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include <sys/stat.h>
17 #include <sys/types.h>
18 #include <sys/utsname.h>
19 
20 // C++ Includes
21 // Other libraries and framework includes
22 #include "llvm/Support/ScopedPrinter.h"
23 // Project includes
24 #include "lldb/Core/Error.h"
25 #include "lldb/Core/Log.h"
26 #include "lldb/Target/Process.h"
27 
28 #include "lldb/Host/Host.h"
29 #include "lldb/Host/HostInfo.h"
30 #include "lldb/Core/DataBufferHeap.h"
31 #include "lldb/Core/DataExtractor.h"
32 
33 #include "lldb/Core/ModuleSpec.h"
34 #include "lldb/Symbol/ObjectFile.h"
35 #include "Plugins/Process/Linux/ProcFileReader.h"
36 
37 using namespace lldb;
38 using namespace lldb_private;
39 
40 typedef enum ProcessStateFlags
41 {
42     eProcessStateRunning           = (1u << 0), // Running
43     eProcessStateSleeping          = (1u << 1), // Sleeping in an interruptible wait
44     eProcessStateWaiting           = (1u << 2), // Waiting in an uninterruptible disk sleep
45     eProcessStateZombie            = (1u << 3), // Zombie
46     eProcessStateTracedOrStopped   = (1u << 4), // Traced or stopped (on a signal)
47     eProcessStatePaging            = (1u << 5)  // Paging
48 } ProcessStateFlags;
49 
50 typedef struct ProcessStatInfo
51 {
52     lldb::pid_t ppid;           // Parent Process ID
53     uint32_t fProcessState;     // ProcessStateFlags
54 } ProcessStatInfo;
55 
56 // Get the process info with additional information from /proc/$PID/stat (like process state, and tracer pid).
57 static bool GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid);
58 
59 static bool
60 ReadProcPseudoFileStat (lldb::pid_t pid, ProcessStatInfo& stat_info)
61 {
62     // Read the /proc/$PID/stat file.
63     lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "stat");
64 
65     // The filename of the executable is stored in parenthesis right after the pid. We look for the closing
66     // parenthesis for the filename and work from there in case the name has something funky like ')' in it.
67     const char *filename_end = strrchr ((const char *)buf_sp->GetBytes(), ')');
68     if (filename_end)
69     {
70         char state = '\0';
71         int ppid = LLDB_INVALID_PROCESS_ID;
72 
73         // Read state and ppid.
74         sscanf (filename_end + 1, " %c %d", &state, &ppid);
75 
76         stat_info.ppid = ppid;
77 
78         switch (state)
79         {
80             case 'R':
81                 stat_info.fProcessState |= eProcessStateRunning;
82                 break;
83             case 'S':
84                 stat_info.fProcessState |= eProcessStateSleeping;
85                 break;
86             case 'D':
87                 stat_info.fProcessState |= eProcessStateWaiting;
88                 break;
89             case 'Z':
90                 stat_info.fProcessState |= eProcessStateZombie;
91                 break;
92             case 'T':
93                 stat_info.fProcessState |= eProcessStateTracedOrStopped;
94                 break;
95             case 'W':
96                 stat_info.fProcessState |= eProcessStatePaging;
97                 break;
98         }
99 
100         return true;
101     }
102 
103     return false;
104 }
105 
106 static void
107 GetLinuxProcessUserAndGroup (lldb::pid_t pid, ProcessInstanceInfo &process_info, lldb::pid_t &tracerpid)
108 {
109     tracerpid = 0;
110     uint32_t rUid = UINT32_MAX;     // Real User ID
111     uint32_t eUid = UINT32_MAX;     // Effective User ID
112     uint32_t rGid = UINT32_MAX;     // Real Group ID
113     uint32_t eGid = UINT32_MAX;     // Effective Group ID
114 
115     // Read the /proc/$PID/status file and parse the Uid:, Gid:, and TracerPid: fields.
116     lldb::DataBufferSP buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "status");
117 
118     static const char uid_token[] = "Uid:";
119     char *buf_uid = strstr ((char *)buf_sp->GetBytes(), uid_token);
120     if (buf_uid)
121     {
122         // Real, effective, saved set, and file system UIDs. Read the first two.
123         buf_uid += sizeof(uid_token);
124         rUid = strtol (buf_uid, &buf_uid, 10);
125         eUid = strtol (buf_uid, &buf_uid, 10);
126     }
127 
128     static const char gid_token[] = "Gid:";
129     char *buf_gid = strstr ((char *)buf_sp->GetBytes(), gid_token);
130     if (buf_gid)
131     {
132         // Real, effective, saved set, and file system GIDs. Read the first two.
133         buf_gid += sizeof(gid_token);
134         rGid = strtol (buf_gid, &buf_gid, 10);
135         eGid = strtol (buf_gid, &buf_gid, 10);
136     }
137 
138     static const char tracerpid_token[] = "TracerPid:";
139     char *buf_tracerpid = strstr((char *)buf_sp->GetBytes(), tracerpid_token);
140     if (buf_tracerpid)
141     {
142         // Tracer PID. 0 if we're not being debugged.
143         buf_tracerpid += sizeof(tracerpid_token);
144         tracerpid = strtol (buf_tracerpid, &buf_tracerpid, 10);
145     }
146 
147     process_info.SetUserID (rUid);
148     process_info.SetEffectiveUserID (eUid);
149     process_info.SetGroupID (rGid);
150     process_info.SetEffectiveGroupID (eGid);
151 }
152 
153 lldb::DataBufferSP
154 Host::GetAuxvData(lldb_private::Process *process)
155 {
156     return process_linux::ProcFileReader::ReadIntoDataBuffer (process->GetID(), "auxv");
157 }
158 
159 lldb::DataBufferSP
160 Host::GetAuxvData (lldb::pid_t pid)
161 {
162     return process_linux::ProcFileReader::ReadIntoDataBuffer (pid, "auxv");
163 }
164 
165 static bool
166 IsDirNumeric(const char *dname)
167 {
168     for (; *dname; dname++)
169     {
170         if (!isdigit (*dname))
171             return false;
172     }
173     return true;
174 }
175 
176 uint32_t
177 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
178 {
179     static const char procdir[] = "/proc/";
180 
181     DIR *dirproc = opendir (procdir);
182     if (dirproc)
183     {
184         struct dirent *direntry = NULL;
185         const uid_t our_uid = getuid();
186         const lldb::pid_t our_pid = getpid();
187         bool all_users = match_info.GetMatchAllUsers();
188 
189         while ((direntry = readdir (dirproc)) != NULL)
190         {
191             if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
192                 continue;
193 
194             lldb::pid_t pid = atoi (direntry->d_name);
195 
196             // Skip this process.
197             if (pid == our_pid)
198                 continue;
199 
200             lldb::pid_t tracerpid;
201             ProcessStatInfo stat_info;
202             ProcessInstanceInfo process_info;
203 
204             if (!GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid))
205                 continue;
206 
207             // Skip if process is being debugged.
208             if (tracerpid != 0)
209                 continue;
210 
211             // Skip zombies.
212             if (stat_info.fProcessState & eProcessStateZombie)
213                 continue;
214 
215             // Check for user match if we're not matching all users and not running as root.
216             if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid))
217                 continue;
218 
219             if (match_info.Matches (process_info))
220             {
221                 process_infos.Append (process_info);
222             }
223         }
224 
225         closedir (dirproc);
226     }
227 
228     return process_infos.GetSize();
229 }
230 
231 bool
232 Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
233 {
234     bool tids_changed = false;
235     static const char procdir[] = "/proc/";
236     static const char taskdir[] = "/task/";
237     std::string process_task_dir = procdir + llvm::to_string(pid) + taskdir;
238     DIR *dirproc = opendir (process_task_dir.c_str());
239 
240     if (dirproc)
241     {
242         struct dirent *direntry = NULL;
243         while ((direntry = readdir (dirproc)) != NULL)
244         {
245             if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
246                 continue;
247 
248             lldb::tid_t tid = atoi(direntry->d_name);
249             TidMap::iterator it = tids_to_attach.find(tid);
250             if (it == tids_to_attach.end())
251             {
252                 tids_to_attach.insert(TidPair(tid, false));
253                 tids_changed = true;
254             }
255         }
256         closedir (dirproc);
257     }
258 
259     return tids_changed;
260 }
261 
262 static bool
263 GetELFProcessCPUType (const char *exe_path, ProcessInstanceInfo &process_info)
264 {
265     // Clear the architecture.
266     process_info.GetArchitecture().Clear();
267 
268     ModuleSpecList specs;
269     FileSpec filespec (exe_path, false);
270     const size_t num_specs = ObjectFile::GetModuleSpecifications (filespec, 0, 0, specs);
271     // GetModuleSpecifications() could fail if the executable has been deleted or is locked.
272     // But it shouldn't return more than 1 architecture.
273     assert(num_specs <= 1 && "Linux plugin supports only a single architecture");
274     if (num_specs == 1)
275     {
276         ModuleSpec module_spec;
277         if (specs.GetModuleSpecAtIndex (0, module_spec) && module_spec.GetArchitecture().IsValid())
278         {
279             process_info.GetArchitecture () = module_spec.GetArchitecture();
280             return true;
281         }
282     }
283     return false;
284 }
285 
286 static bool
287 GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid)
288 {
289     tracerpid = 0;
290     process_info.Clear();
291     ::memset (&stat_info, 0, sizeof(stat_info));
292     stat_info.ppid = LLDB_INVALID_PROCESS_ID;
293 
294     Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
295 
296     // Use special code here because proc/[pid]/exe is a symbolic link.
297     char link_path[PATH_MAX];
298     char exe_path[PATH_MAX] = "";
299     if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0)
300     {
301         if (log)
302             log->Printf("%s: failed to sprintf pid %" PRIu64, __FUNCTION__, pid);
303         return false;
304     }
305 
306     ssize_t len = readlink (link_path, exe_path, sizeof(exe_path) - 1);
307     if (len <= 0)
308     {
309         if (log)
310             log->Printf("%s: failed to read link %s: %s", __FUNCTION__, link_path, strerror(errno));
311         return false;
312     }
313 
314     // readlink does not append a null byte.
315     exe_path[len] = 0;
316 
317     // If the binary has been deleted, the link name has " (deleted)" appended.
318     //  Remove if there.
319     static const ssize_t deleted_len = strlen(" (deleted)");
320     if (len > deleted_len &&
321         !strcmp(exe_path + len - deleted_len, " (deleted)"))
322     {
323         exe_path[len - deleted_len] = 0;
324     }
325     else
326     {
327         GetELFProcessCPUType (exe_path, process_info);
328     }
329 
330     process_info.SetProcessID(pid);
331     process_info.GetExecutableFile().SetFile(exe_path, false);
332     process_info.GetArchitecture().MergeFrom(HostInfo::GetArchitecture());
333 
334     lldb::DataBufferSP buf_sp;
335 
336     // Get the process environment.
337     buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "environ");
338     Args &info_env = process_info.GetEnvironmentEntries();
339     char *next_var = (char *)buf_sp->GetBytes();
340     char *end_buf = next_var + buf_sp->GetByteSize();
341     while (next_var < end_buf && 0 != *next_var)
342     {
343         info_env.AppendArgument(next_var);
344         next_var += strlen(next_var) + 1;
345     }
346 
347     // Get the command line used to start the process.
348     buf_sp = process_linux::ProcFileReader::ReadIntoDataBuffer(pid, "cmdline");
349 
350     // Grab Arg0 first, if there is one.
351     char *cmd = (char *)buf_sp->GetBytes();
352     if (cmd)
353     {
354         process_info.SetArg0(cmd);
355 
356         // Now process any remaining arguments.
357         Args &info_args = process_info.GetArguments();
358         char *next_arg = cmd + strlen(cmd) + 1;
359         end_buf = cmd + buf_sp->GetByteSize();
360         while (next_arg < end_buf && 0 != *next_arg)
361         {
362             info_args.AppendArgument(next_arg);
363             next_arg += strlen(next_arg) + 1;
364         }
365     }
366 
367     // Read /proc/$PID/stat to get our parent pid.
368     if (ReadProcPseudoFileStat (pid, stat_info))
369     {
370         process_info.SetParentProcessID (stat_info.ppid);
371     }
372 
373     // Get User and Group IDs and get tracer pid.
374     GetLinuxProcessUserAndGroup (pid, process_info, tracerpid);
375 
376     return true;
377 }
378 
379 bool
380 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
381 {
382     lldb::pid_t tracerpid;
383     ProcessStatInfo stat_info;
384 
385     return GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid);
386 }
387 
388 size_t
389 Host::GetEnvironment (StringList &env)
390 {
391     char **host_env = environ;
392     char *env_entry;
393     size_t i;
394     for (i=0; (env_entry = host_env[i]) != NULL; ++i)
395         env.AppendString(env_entry);
396     return i;
397 }
398 
399 Error
400 Host::ShellExpandArguments (ProcessLaunchInfo &launch_info)
401 {
402     return Error("unimplemented");
403 }
404