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