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