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     return status == 3;
217 }
218 
219 lldb::DataBufferSP
220 Host::GetAuxvData(lldb_private::Process *process)
221 {
222     return ReadProcPseudoFile(process->GetID(), "auxv");
223 }
224 
225 static bool
226 IsDirNumeric(const char *dname)
227 {
228     for (; *dname; dname++)
229     {
230         if (!isdigit (*dname))
231             return false;
232     }
233     return true;
234 }
235 
236 uint32_t
237 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
238 {
239     static const char procdir[] = "/proc/";
240 
241     DIR *dirproc = opendir (procdir);
242     if (dirproc)
243     {
244         struct dirent *direntry = NULL;
245         const uid_t our_uid = getuid();
246         const lldb::pid_t our_pid = getpid();
247         bool all_users = match_info.GetMatchAllUsers();
248 
249         while ((direntry = readdir (dirproc)) != NULL)
250         {
251             if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
252                 continue;
253 
254             lldb::pid_t pid = atoi (direntry->d_name);
255 
256             // Skip this process.
257             if (pid == our_pid)
258                 continue;
259 
260             lldb::pid_t tracerpid;
261             ProcessStatInfo stat_info;
262             ProcessInstanceInfo process_info;
263 
264             if (!GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid))
265                 continue;
266 
267             // Skip if process is being debugged.
268             if (tracerpid != 0)
269                 continue;
270 
271             // Skip zombies.
272             if (stat_info.fProcessState & eProcessStateZombie)
273                 continue;
274 
275             // Check for user match if we're not matching all users and not running as root.
276             if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid))
277                 continue;
278 
279             if (match_info.Matches (process_info))
280             {
281                 process_infos.Append (process_info);
282             }
283         }
284 
285         closedir (dirproc);
286     }
287 
288     return process_infos.GetSize();
289 }
290 
291 bool
292 Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
293 {
294     bool tids_changed = false;
295     static const char procdir[] = "/proc/";
296     static const char taskdir[] = "/task/";
297     std::string process_task_dir = procdir + std::to_string(pid) + taskdir;
298     DIR *dirproc = opendir (process_task_dir.c_str());
299 
300     if (dirproc)
301     {
302         struct dirent *direntry = NULL;
303         while ((direntry = readdir (dirproc)) != NULL)
304         {
305             if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
306                 continue;
307 
308             lldb::tid_t tid = atoi(direntry->d_name);
309             TidMap::iterator it = tids_to_attach.find(tid);
310             if (it == tids_to_attach.end())
311             {
312                 tids_to_attach.insert(TidPair(tid, false));
313                 tids_changed = true;
314             }
315         }
316         closedir (dirproc);
317     }
318 
319     return tids_changed;
320 }
321 
322 static bool
323 GetELFProcessCPUType (const char *exe_path, ProcessInstanceInfo &process_info)
324 {
325     // Clear the architecture.
326     process_info.GetArchitecture().Clear();
327 
328     ModuleSpecList specs;
329     FileSpec filespec (exe_path, false);
330     const size_t num_specs = ObjectFile::GetModuleSpecifications (filespec, 0, 0, specs);
331     // GetModuleSpecifications() could fail if the executable has been deleted or is locked.
332     // But it shouldn't return more than 1 architecture.
333     assert(num_specs <= 1 && "Linux plugin supports only a single architecture");
334     if (num_specs == 1)
335     {
336         ModuleSpec module_spec;
337         if (specs.GetModuleSpecAtIndex (0, module_spec) && module_spec.GetArchitecture().IsValid())
338         {
339             process_info.GetArchitecture () = module_spec.GetArchitecture();
340             return true;
341         }
342     }
343     return false;
344 }
345 
346 static bool
347 GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid)
348 {
349     tracerpid = 0;
350     process_info.Clear();
351     ::memset (&stat_info, 0, sizeof(stat_info));
352     stat_info.ppid = LLDB_INVALID_PROCESS_ID;
353 
354     // Use special code here because proc/[pid]/exe is a symbolic link.
355     char link_path[PATH_MAX];
356     char exe_path[PATH_MAX] = "";
357     if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0)
358         return false;
359 
360     ssize_t len = readlink (link_path, exe_path, sizeof(exe_path) - 1);
361     if (len <= 0)
362         return false;
363 
364     // readlink does not append a null byte.
365     exe_path[len] = 0;
366 
367     // If the binary has been deleted, the link name has " (deleted)" appended.
368     //  Remove if there.
369     static const ssize_t deleted_len = strlen(" (deleted)");
370     if (len > deleted_len &&
371         !strcmp(exe_path + len - deleted_len, " (deleted)"))
372     {
373         exe_path[len - deleted_len] = 0;
374     }
375     else
376     {
377         GetELFProcessCPUType (exe_path, process_info);
378     }
379 
380     process_info.SetProcessID(pid);
381     process_info.GetExecutableFile().SetFile(exe_path, false);
382 
383     lldb::DataBufferSP buf_sp;
384 
385     // Get the process environment.
386     buf_sp = ReadProcPseudoFile(pid, "environ");
387     Args &info_env = process_info.GetEnvironmentEntries();
388     char *next_var = (char *)buf_sp->GetBytes();
389     char *end_buf = next_var + buf_sp->GetByteSize();
390     while (next_var < end_buf && 0 != *next_var)
391     {
392         info_env.AppendArgument(next_var);
393         next_var += strlen(next_var) + 1;
394     }
395 
396     // Get the commond line used to start the process.
397     buf_sp = ReadProcPseudoFile(pid, "cmdline");
398 
399     // Grab Arg0 first.
400     char *cmd = (char *)buf_sp->GetBytes();
401     process_info.SetArg0(cmd);
402 
403     // Now process any remaining arguments.
404     Args &info_args = process_info.GetArguments();
405     char *next_arg = cmd + strlen(cmd) + 1;
406     end_buf = cmd + buf_sp->GetByteSize();
407     while (next_arg < end_buf && 0 != *next_arg)
408     {
409         info_args.AppendArgument(next_arg);
410         next_arg += strlen(next_arg) + 1;
411     }
412 
413     // Read /proc/$PID/stat to get our parent pid.
414     if (ReadProcPseudoFileStat (pid, stat_info))
415     {
416         process_info.SetParentProcessID (stat_info.ppid);
417     }
418 
419     // Get User and Group IDs and get tracer pid.
420     GetLinuxProcessUserAndGroup (pid, process_info, tracerpid);
421 
422     return true;
423 }
424 
425 bool
426 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
427 {
428     lldb::pid_t tracerpid;
429     ProcessStatInfo stat_info;
430 
431     return GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid);
432 }
433 
434 void
435 Host::ThreadCreated (const char *thread_name)
436 {
437     if (!Host::SetThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, thread_name))
438     {
439         Host::SetShortThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, thread_name, 16);
440     }
441 }
442 
443 std::string
444 Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
445 {
446     assert(pid != LLDB_INVALID_PROCESS_ID);
447     assert(tid != LLDB_INVALID_THREAD_ID);
448 
449     // Read /proc/$TID/comm file.
450     lldb::DataBufferSP buf_sp = ReadProcPseudoFile (tid, "comm");
451     const char *comm_str = (const char *)buf_sp->GetBytes();
452     const char *cr_str = ::strchr(comm_str, '\n');
453     size_t length = cr_str ? (cr_str - comm_str) : strlen(comm_str);
454 
455     std::string thread_name(comm_str, length);
456     return thread_name;
457 }
458 
459 void
460 Host::Backtrace (Stream &strm, uint32_t max_frames)
461 {
462     if (max_frames > 0)
463     {
464         std::vector<void *> frame_buffer (max_frames, NULL);
465         int num_frames = ::backtrace (&frame_buffer[0], frame_buffer.size());
466         char** strs = ::backtrace_symbols (&frame_buffer[0], num_frames);
467         if (strs)
468         {
469             // Start at 1 to skip the "Host::Backtrace" frame
470             for (int i = 1; i < num_frames; ++i)
471                 strm.Printf("%s\n", strs[i]);
472             ::free (strs);
473         }
474     }
475 }
476 
477 size_t
478 Host::GetEnvironment (StringList &env)
479 {
480     char **host_env = environ;
481     char *env_entry;
482     size_t i;
483     for (i=0; (env_entry = host_env[i]) != NULL; ++i)
484         env.AppendString(env_entry);
485     return i;
486 }
487