blob: ef3c9fbf06f1ad11bb6e521951414c90d6b6d172 [file] [log] [blame]
Stephen Wilson3e2a18f2011-03-23 01:58:26 +00001//===-- 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>
Johnny Chen30213ff2012-01-05 19:17:38 +000013#include <sys/types.h>
14#include <sys/stat.h>
Daniel Malea25d7eb02013-05-15 17:54:07 +000015#include <dirent.h>
Johnny Chen30213ff2012-01-05 19:17:38 +000016#include <fcntl.h>
17
Stephen Wilson3e2a18f2011-03-23 01:58:26 +000018// C++ Includes
19// Other libraries and framework includes
20// Project includes
Johnny Chenc18a5382011-05-19 23:07:19 +000021#include "lldb/Core/Error.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000022#include "lldb/Target/Process.h"
23
Stephen Wilson3e2a18f2011-03-23 01:58:26 +000024#include "lldb/Host/Host.h"
Johnny Chen30213ff2012-01-05 19:17:38 +000025#include "lldb/Core/DataBufferHeap.h"
26#include "lldb/Core/DataExtractor.h"
Stephen Wilson3e2a18f2011-03-23 01:58:26 +000027
Michael Sartainc836ae72013-05-23 20:57:03 +000028#include "lldb/Core/ModuleSpec.h"
29#include "lldb/Symbol/ObjectFile.h"
30
Stephen Wilson3e2a18f2011-03-23 01:58:26 +000031using namespace lldb;
32using namespace lldb_private;
33
Daniel Malea25d7eb02013-05-15 17:54:07 +000034typedef 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
44typedef 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).
51static bool GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid);
52
Michael Sartainb9931492013-05-17 00:08:09 +000053
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +000054namespace
Stephen Wilson3e2a18f2011-03-23 01:58:26 +000055{
Johnny Chenc18a5382011-05-19 23:07:19 +000056
Johnny Chen30213ff2012-01-05 19:17:38 +000057lldb::DataBufferSP
Daniel Malea25d7eb02013-05-15 17:54:07 +000058ReadProcPseudoFile (lldb::pid_t pid, const char *name)
Johnny Chen30213ff2012-01-05 19:17:38 +000059{
Johnny Chen30213ff2012-01-05 19:17:38 +000060 int fd;
Daniel Malea25d7eb02013-05-15 17:54:07 +000061 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));
Johnny Chen30213ff2012-01-05 19:17:38 +000066
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
Daniel Malea25d7eb02013-05-15 17:54:07 +000070 // current ReadFileContents implementation. Therefore we simply stream the
Johnny Chen30213ff2012-01-05 19:17:38 +000071 // data into a DataBuffer ourselves.
Daniel Malea25d7eb02013-05-15 17:54:07 +000072 if (snprintf (path, PATH_MAX, "/proc/%" PRIu64 "/%s", pid, name) > 0)
Johnny Chen30213ff2012-01-05 19:17:38 +000073 {
Daniel Malea25d7eb02013-05-15 17:54:07 +000074 if ((fd = open (path, O_RDONLY, 0)) >= 0)
Johnny Chen30213ff2012-01-05 19:17:38 +000075 {
Daniel Malea25d7eb02013-05-15 17:54:07 +000076 size_t bytes_read = 0;
77 std::unique_ptr<DataBufferHeap> buf_ap(new DataBufferHeap(1024, 0));
Johnny Chen30213ff2012-01-05 19:17:38 +000078
Daniel Malea25d7eb02013-05-15 17:54:07 +000079 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 }
Johnny Chen30213ff2012-01-05 19:17:38 +0000102 }
103
104 return buf_sp;
105}
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000106
Matt Kopecfb6ab542013-07-10 20:53:11 +0000107lldb::DataBufferSP
108ReadProcPseudoFile (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
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000114} // anonymous namespace
115
Daniel Malea25d7eb02013-05-15 17:54:07 +0000116static bool
117ReadProcPseudoFileStat (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
163static void
164GetLinuxProcessUserAndGroup (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
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000210bool
211Host::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
225Error
226Host::LaunchProcess (ProcessLaunchInfo &launch_info)
227{
228 Error error;
229 assert(!"Not implemented yet!!!");
230 return error;
231}
232
233lldb::DataBufferSP
234Host::GetAuxvData(lldb_private::Process *process)
235{
236 return ReadProcPseudoFile(process->GetID(), "auxv");
237}
238
Daniel Malea25d7eb02013-05-15 17:54:07 +0000239static bool
240IsDirNumeric(const char *dname)
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000241{
Daniel Malea25d7eb02013-05-15 17:54:07 +0000242 for (; *dname; dname++)
243 {
244 if (!isdigit (*dname))
245 return false;
246 }
247 return true;
248}
249
250uint32_t
251Host::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
Matt Kopec085d6ce2013-05-31 22:00:07 +0000305bool
306Host::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
Daniel Malea25d7eb02013-05-15 17:54:07 +0000336static bool
Michael Sartainc836ae72013-05-23 20:57:03 +0000337GetELFProcessCPUType (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);
Jason Molendad6cfc162013-07-15 03:25:21 +0000344 const size_t num_specs = ObjectFile::GetModuleSpecifications (filespec, 0, 0, specs);
Michael Sartainc836ae72013-05-23 20:57:03 +0000345 // 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
360static bool
Daniel Malea25d7eb02013-05-15 17:54:07 +0000361GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid)
362{
363 tracerpid = 0;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000364 process_info.Clear();
Daniel Malea25d7eb02013-05-15 17:54:07 +0000365 ::memset (&stat_info, 0, sizeof(stat_info));
366 stat_info.ppid = LLDB_INVALID_PROCESS_ID;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000367
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000368 // Use special code here because proc/[pid]/exe is a symbolic link.
369 char link_path[PATH_MAX];
370 char exe_path[PATH_MAX] = "";
Daniel Malea25d7eb02013-05-15 17:54:07 +0000371 if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0)
372 return false;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000373
Daniel Malea25d7eb02013-05-15 17:54:07 +0000374 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;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000388 }
Michael Sartainc836ae72013-05-23 20:57:03 +0000389 else
390 {
391 GetELFProcessCPUType (exe_path, process_info);
392 }
Daniel Malea25d7eb02013-05-15 17:54:07 +0000393
394 process_info.SetProcessID(pid);
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000395 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
Daniel Malea25d7eb02013-05-15 17:54:07 +0000427 // 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);
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000435
436 return true;
Matt Kopec62502c62013-05-13 19:33:58 +0000437}
438
Daniel Malea25d7eb02013-05-15 17:54:07 +0000439bool
440Host::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
Matt Kopec62502c62013-05-13 19:33:58 +0000448void
449Host::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
Matt Kopecfb6ab542013-07-10 20:53:11 +0000482std::string
483Host::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
Matt Kopec62502c62013-05-13 19:33:58 +0000509void
510Host::Backtrace (Stream &strm, uint32_t max_frames)
511{
512 // TODO: Is there a way to backtrace the current process on linux?
513}
514
515size_t
516Host::GetEnvironment (StringList &env)
517{
518 // TODO: Is there a way to the host environment for this process on linux?
519 return 0;
520}