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