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 <stdio.h>
12 #include <sys/utsname.h>
13 #include <sys/types.h>
14 #include <sys/stat.h>
15 #include <dirent.h>
16 #include <fcntl.h>
17 #include <execinfo.h>
18 
19 // C++ Includes
20 // Other libraries and framework includes
21 // Project includes
22 #include "lldb/Core/Error.h"
23 #include "lldb/Target/Process.h"
24 
25 #include "lldb/Host/Host.h"
26 #include "lldb/Core/DataBufferHeap.h"
27 #include "lldb/Core/DataExtractor.h"
28 
29 #include "lldb/Core/ModuleSpec.h"
30 #include "lldb/Symbol/ObjectFile.h"
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 
35 typedef enum ProcessStateFlags
36 {
37     eProcessStateRunning           = (1u << 0), // Running
38     eProcessStateSleeping          = (1u << 1), // Sleeping in an interruptible wait
39     eProcessStateWaiting           = (1u << 2), // Waiting in an uninterruptible disk sleep
40     eProcessStateZombie            = (1u << 3), // Zombie
41     eProcessStateTracedOrStopped   = (1u << 4), // Traced or stopped (on a signal)
42     eProcessStatePaging            = (1u << 5)  // Paging
43 } ProcessStateFlags;
44 
45 typedef struct ProcessStatInfo
46 {
47     lldb::pid_t ppid;           // Parent Process ID
48     uint32_t fProcessState;     // ProcessStateFlags
49 } ProcessStatInfo;
50 
51 // Get the process info with additional information from /proc/$PID/stat (like process state, and tracer pid).
52 static bool GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid);
53 
54 
55 namespace
56 {
57 
58 lldb::DataBufferSP
59 ReadProcPseudoFile (lldb::pid_t pid, const char *name)
60 {
61     int fd;
62     char path[PATH_MAX];
63 
64     // Make sure we've got a nil terminated buffer for all the folks calling
65     // GetBytes() directly off our returned DataBufferSP if we hit an error.
66     lldb::DataBufferSP buf_sp (new DataBufferHeap(1, 0));
67 
68     // Ideally, we would simply create a FileSpec and call ReadFileContents.
69     // However, files in procfs have zero size (since they are, in general,
70     // dynamically generated by the kernel) which is incompatible with the
71     // current ReadFileContents implementation. Therefore we simply stream the
72     // data into a DataBuffer ourselves.
73     if (snprintf (path, PATH_MAX, "/proc/%" PRIu64 "/%s", pid, name) > 0)
74     {
75         if ((fd = open (path, O_RDONLY, 0)) >= 0)
76         {
77             size_t bytes_read = 0;
78             std::unique_ptr<DataBufferHeap> buf_ap(new DataBufferHeap(1024, 0));
79 
80             for (;;)
81             {
82                 size_t avail = buf_ap->GetByteSize() - bytes_read;
83                 ssize_t status = read (fd, buf_ap->GetBytes() + bytes_read, avail);
84 
85                 if (status < 0)
86                     break;
87 
88                 if (status == 0)
89                 {
90                     buf_ap->SetByteSize (bytes_read);
91                     buf_sp.reset (buf_ap.release());
92                     break;
93                 }
94 
95                 bytes_read += status;
96 
97                 if (avail - status == 0)
98                     buf_ap->SetByteSize (2 * buf_ap->GetByteSize());
99             }
100 
101             close (fd);
102         }
103     }
104 
105     return buf_sp;
106 }
107 
108 } // anonymous namespace
109 
110 static bool
111 ReadProcPseudoFileStat (lldb::pid_t pid, ProcessStatInfo& stat_info)
112 {
113     // Read the /proc/$PID/stat file.
114     lldb::DataBufferSP buf_sp = ReadProcPseudoFile (pid, "stat");
115 
116     // The filename of the executable is stored in parenthesis right after the pid. We look for the closing
117     // parenthesis for the filename and work from there in case the name has something funky like ')' in it.
118     const char *filename_end = strrchr ((const char *)buf_sp->GetBytes(), ')');
119     if (filename_end)
120     {
121         char state = '\0';
122         int ppid = LLDB_INVALID_PROCESS_ID;
123 
124         // Read state and ppid.
125         sscanf (filename_end + 1, " %c %d", &state, &ppid);
126 
127         stat_info.ppid = ppid;
128 
129         switch (state)
130         {
131             case 'R':
132                 stat_info.fProcessState |= eProcessStateRunning;
133                 break;
134             case 'S':
135                 stat_info.fProcessState |= eProcessStateSleeping;
136                 break;
137             case 'D':
138                 stat_info.fProcessState |= eProcessStateWaiting;
139                 break;
140             case 'Z':
141                 stat_info.fProcessState |= eProcessStateZombie;
142                 break;
143             case 'T':
144                 stat_info.fProcessState |= eProcessStateTracedOrStopped;
145                 break;
146             case 'W':
147                 stat_info.fProcessState |= eProcessStatePaging;
148                 break;
149         }
150 
151         return true;
152     }
153 
154     return false;
155 }
156 
157 static void
158 GetLinuxProcessUserAndGroup (lldb::pid_t pid, ProcessInstanceInfo &process_info, lldb::pid_t &tracerpid)
159 {
160     tracerpid = 0;
161     uint32_t rUid = UINT32_MAX;     // Real User ID
162     uint32_t eUid = UINT32_MAX;     // Effective User ID
163     uint32_t rGid = UINT32_MAX;     // Real Group ID
164     uint32_t eGid = UINT32_MAX;     // Effective Group ID
165 
166     // Read the /proc/$PID/status file and parse the Uid:, Gid:, and TracerPid: fields.
167     lldb::DataBufferSP buf_sp = ReadProcPseudoFile (pid, "status");
168 
169     static const char uid_token[] = "Uid:";
170     char *buf_uid = strstr ((char *)buf_sp->GetBytes(), uid_token);
171     if (buf_uid)
172     {
173         // Real, effective, saved set, and file system UIDs. Read the first two.
174         buf_uid += sizeof(uid_token);
175         rUid = strtol (buf_uid, &buf_uid, 10);
176         eUid = strtol (buf_uid, &buf_uid, 10);
177     }
178 
179     static const char gid_token[] = "Gid:";
180     char *buf_gid = strstr ((char *)buf_sp->GetBytes(), gid_token);
181     if (buf_gid)
182     {
183         // Real, effective, saved set, and file system GIDs. Read the first two.
184         buf_gid += sizeof(gid_token);
185         rGid = strtol (buf_gid, &buf_gid, 10);
186         eGid = strtol (buf_gid, &buf_gid, 10);
187     }
188 
189     static const char tracerpid_token[] = "TracerPid:";
190     char *buf_tracerpid = strstr((char *)buf_sp->GetBytes(), tracerpid_token);
191     if (buf_tracerpid)
192     {
193         // Tracer PID. 0 if we're not being debugged.
194         buf_tracerpid += sizeof(tracerpid_token);
195         tracerpid = strtol (buf_tracerpid, &buf_tracerpid, 10);
196     }
197 
198     process_info.SetUserID (rUid);
199     process_info.SetEffectiveUserID (eUid);
200     process_info.SetGroupID (rGid);
201     process_info.SetEffectiveGroupID (eGid);
202 }
203 
204 bool
205 Host::GetOSVersion(uint32_t &major,
206                    uint32_t &minor,
207                    uint32_t &update)
208 {
209     struct utsname un;
210     int status;
211 
212     if (uname(&un))
213         return false;
214 
215     status = sscanf(un.release, "%u.%u.%u", &major, &minor, &update);
216     if (status == 3)
217         return true;
218 
219     // Some kernels omit the update version, so try looking for just "X.Y" and
220     // set update to 0.
221     update = 0;
222     status = sscanf(un.release, "%u.%u", &major, &minor);
223     return status == 2;
224 }
225 
226 lldb::DataBufferSP
227 Host::GetAuxvData(lldb_private::Process *process)
228 {
229     return ReadProcPseudoFile(process->GetID(), "auxv");
230 }
231 
232 static bool
233 IsDirNumeric(const char *dname)
234 {
235     for (; *dname; dname++)
236     {
237         if (!isdigit (*dname))
238             return false;
239     }
240     return true;
241 }
242 
243 uint32_t
244 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
245 {
246     static const char procdir[] = "/proc/";
247 
248     DIR *dirproc = opendir (procdir);
249     if (dirproc)
250     {
251         struct dirent *direntry = NULL;
252         const uid_t our_uid = getuid();
253         const lldb::pid_t our_pid = getpid();
254         bool all_users = match_info.GetMatchAllUsers();
255 
256         while ((direntry = readdir (dirproc)) != NULL)
257         {
258             if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
259                 continue;
260 
261             lldb::pid_t pid = atoi (direntry->d_name);
262 
263             // Skip this process.
264             if (pid == our_pid)
265                 continue;
266 
267             lldb::pid_t tracerpid;
268             ProcessStatInfo stat_info;
269             ProcessInstanceInfo process_info;
270 
271             if (!GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid))
272                 continue;
273 
274             // Skip if process is being debugged.
275             if (tracerpid != 0)
276                 continue;
277 
278             // Skip zombies.
279             if (stat_info.fProcessState & eProcessStateZombie)
280                 continue;
281 
282             // Check for user match if we're not matching all users and not running as root.
283             if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid))
284                 continue;
285 
286             if (match_info.Matches (process_info))
287             {
288                 process_infos.Append (process_info);
289             }
290         }
291 
292         closedir (dirproc);
293     }
294 
295     return process_infos.GetSize();
296 }
297 
298 bool
299 Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
300 {
301     bool tids_changed = false;
302     static const char procdir[] = "/proc/";
303     static const char taskdir[] = "/task/";
304     std::string process_task_dir = procdir + std::to_string(pid) + taskdir;
305     DIR *dirproc = opendir (process_task_dir.c_str());
306 
307     if (dirproc)
308     {
309         struct dirent *direntry = NULL;
310         while ((direntry = readdir (dirproc)) != NULL)
311         {
312             if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
313                 continue;
314 
315             lldb::tid_t tid = atoi(direntry->d_name);
316             TidMap::iterator it = tids_to_attach.find(tid);
317             if (it == tids_to_attach.end())
318             {
319                 tids_to_attach.insert(TidPair(tid, false));
320                 tids_changed = true;
321             }
322         }
323         closedir (dirproc);
324     }
325 
326     return tids_changed;
327 }
328 
329 static bool
330 GetELFProcessCPUType (const char *exe_path, ProcessInstanceInfo &process_info)
331 {
332     // Clear the architecture.
333     process_info.GetArchitecture().Clear();
334 
335     ModuleSpecList specs;
336     FileSpec filespec (exe_path, false);
337     const size_t num_specs = ObjectFile::GetModuleSpecifications (filespec, 0, 0, specs);
338     // GetModuleSpecifications() could fail if the executable has been deleted or is locked.
339     // But it shouldn't return more than 1 architecture.
340     assert(num_specs <= 1 && "Linux plugin supports only a single architecture");
341     if (num_specs == 1)
342     {
343         ModuleSpec module_spec;
344         if (specs.GetModuleSpecAtIndex (0, module_spec) && module_spec.GetArchitecture().IsValid())
345         {
346             process_info.GetArchitecture () = module_spec.GetArchitecture();
347             return true;
348         }
349     }
350     return false;
351 }
352 
353 static bool
354 GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid)
355 {
356     tracerpid = 0;
357     process_info.Clear();
358     ::memset (&stat_info, 0, sizeof(stat_info));
359     stat_info.ppid = LLDB_INVALID_PROCESS_ID;
360 
361     // Use special code here because proc/[pid]/exe is a symbolic link.
362     char link_path[PATH_MAX];
363     char exe_path[PATH_MAX] = "";
364     if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0)
365         return false;
366 
367     ssize_t len = readlink (link_path, exe_path, sizeof(exe_path) - 1);
368     if (len <= 0)
369         return false;
370 
371     // readlink does not append a null byte.
372     exe_path[len] = 0;
373 
374     // If the binary has been deleted, the link name has " (deleted)" appended.
375     //  Remove if there.
376     static const ssize_t deleted_len = strlen(" (deleted)");
377     if (len > deleted_len &&
378         !strcmp(exe_path + len - deleted_len, " (deleted)"))
379     {
380         exe_path[len - deleted_len] = 0;
381     }
382     else
383     {
384         GetELFProcessCPUType (exe_path, process_info);
385     }
386 
387     process_info.SetProcessID(pid);
388     process_info.GetExecutableFile().SetFile(exe_path, false);
389 
390     lldb::DataBufferSP buf_sp;
391 
392     // Get the process environment.
393     buf_sp = ReadProcPseudoFile(pid, "environ");
394     Args &info_env = process_info.GetEnvironmentEntries();
395     char *next_var = (char *)buf_sp->GetBytes();
396     char *end_buf = next_var + buf_sp->GetByteSize();
397     while (next_var < end_buf && 0 != *next_var)
398     {
399         info_env.AppendArgument(next_var);
400         next_var += strlen(next_var) + 1;
401     }
402 
403     // Get the commond line used to start the process.
404     buf_sp = ReadProcPseudoFile(pid, "cmdline");
405 
406     // Grab Arg0 first, if there is one.
407     char *cmd = (char *)buf_sp->GetBytes();
408     if (cmd)
409     {
410         process_info.SetArg0(cmd);
411 
412         // Now process any remaining arguments.
413         Args &info_args = process_info.GetArguments();
414         char *next_arg = cmd + strlen(cmd) + 1;
415         end_buf = cmd + buf_sp->GetByteSize();
416         while (next_arg < end_buf && 0 != *next_arg)
417         {
418             info_args.AppendArgument(next_arg);
419             next_arg += strlen(next_arg) + 1;
420         }
421     }
422 
423     // Read /proc/$PID/stat to get our parent pid.
424     if (ReadProcPseudoFileStat (pid, stat_info))
425     {
426         process_info.SetParentProcessID (stat_info.ppid);
427     }
428 
429     // Get User and Group IDs and get tracer pid.
430     GetLinuxProcessUserAndGroup (pid, process_info, tracerpid);
431 
432     return true;
433 }
434 
435 bool
436 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
437 {
438     lldb::pid_t tracerpid;
439     ProcessStatInfo stat_info;
440 
441     return GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid);
442 }
443 
444 void
445 Host::ThreadCreated (const char *thread_name)
446 {
447     if (!Host::SetThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, thread_name))
448     {
449         Host::SetShortThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, thread_name, 16);
450     }
451 }
452 
453 std::string
454 Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
455 {
456     assert(pid != LLDB_INVALID_PROCESS_ID);
457     assert(tid != LLDB_INVALID_THREAD_ID);
458 
459     // Read /proc/$TID/comm file.
460     lldb::DataBufferSP buf_sp = ReadProcPseudoFile (tid, "comm");
461     const char *comm_str = (const char *)buf_sp->GetBytes();
462     const char *cr_str = ::strchr(comm_str, '\n');
463     size_t length = cr_str ? (cr_str - comm_str) : strlen(comm_str);
464 
465     std::string thread_name(comm_str, length);
466     return thread_name;
467 }
468 
469 void
470 Host::Backtrace (Stream &strm, uint32_t max_frames)
471 {
472     if (max_frames > 0)
473     {
474         std::vector<void *> frame_buffer (max_frames, NULL);
475         int num_frames = ::backtrace (&frame_buffer[0], frame_buffer.size());
476         char** strs = ::backtrace_symbols (&frame_buffer[0], num_frames);
477         if (strs)
478         {
479             // Start at 1 to skip the "Host::Backtrace" frame
480             for (int i = 1; i < num_frames; ++i)
481                 strm.Printf("%s\n", strs[i]);
482             ::free (strs);
483         }
484     }
485 }
486 
487 size_t
488 Host::GetEnvironment (StringList &env)
489 {
490     char **host_env = environ;
491     char *env_entry;
492     size_t i;
493     for (i=0; (env_entry = host_env[i]) != NULL; ++i)
494         env.AppendString(env_entry);
495     return i;
496 }
497