blob: f1adf405fe1252ad384c0f99e0f04fefe9630d8f [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
28using namespace lldb;
29using namespace lldb_private;
30
Daniel Malea25d7eb02013-05-15 17:54:07 +000031typedef enum ProcessStateFlags
32{
33 eProcessStateRunning = (1u << 0), // Running
34 eProcessStateSleeping = (1u << 1), // Sleeping in an interruptible wait
35 eProcessStateWaiting = (1u << 2), // Waiting in an uninterruptible disk sleep
36 eProcessStateZombie = (1u << 3), // Zombie
37 eProcessStateTracedOrStopped = (1u << 4), // Traced or stopped (on a signal)
38 eProcessStatePaging = (1u << 5) // Paging
39} ProcessStateFlags;
40
41typedef struct ProcessStatInfo
42{
43 lldb::pid_t ppid; // Parent Process ID
44 uint32_t fProcessState; // ProcessStateFlags
45} ProcessStatInfo;
46
47// Get the process info with additional information from /proc/$PID/stat (like process state, and tracer pid).
48static bool GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid);
49
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +000050namespace
Stephen Wilson3e2a18f2011-03-23 01:58:26 +000051{
Johnny Chenc18a5382011-05-19 23:07:19 +000052
Johnny Chen30213ff2012-01-05 19:17:38 +000053lldb::DataBufferSP
Daniel Malea25d7eb02013-05-15 17:54:07 +000054ReadProcPseudoFile (lldb::pid_t pid, const char *name)
Johnny Chen30213ff2012-01-05 19:17:38 +000055{
Johnny Chen30213ff2012-01-05 19:17:38 +000056 int fd;
Daniel Malea25d7eb02013-05-15 17:54:07 +000057 char path[PATH_MAX];
58
59 // Make sure we've got a nil terminated buffer for all the folks calling
60 // GetBytes() directly off our returned DataBufferSP if we hit an error.
61 lldb::DataBufferSP buf_sp (new DataBufferHeap(1, 0));
Johnny Chen30213ff2012-01-05 19:17:38 +000062
63 // Ideally, we would simply create a FileSpec and call ReadFileContents.
64 // However, files in procfs have zero size (since they are, in general,
65 // dynamically generated by the kernel) which is incompatible with the
Daniel Malea25d7eb02013-05-15 17:54:07 +000066 // current ReadFileContents implementation. Therefore we simply stream the
Johnny Chen30213ff2012-01-05 19:17:38 +000067 // data into a DataBuffer ourselves.
Daniel Malea25d7eb02013-05-15 17:54:07 +000068 if (snprintf (path, PATH_MAX, "/proc/%" PRIu64 "/%s", pid, name) > 0)
Johnny Chen30213ff2012-01-05 19:17:38 +000069 {
Daniel Malea25d7eb02013-05-15 17:54:07 +000070 if ((fd = open (path, O_RDONLY, 0)) >= 0)
Johnny Chen30213ff2012-01-05 19:17:38 +000071 {
Daniel Malea25d7eb02013-05-15 17:54:07 +000072 size_t bytes_read = 0;
73 std::unique_ptr<DataBufferHeap> buf_ap(new DataBufferHeap(1024, 0));
Johnny Chen30213ff2012-01-05 19:17:38 +000074
Daniel Malea25d7eb02013-05-15 17:54:07 +000075 for (;;)
76 {
77 size_t avail = buf_ap->GetByteSize() - bytes_read;
78 ssize_t status = read (fd, buf_ap->GetBytes() + bytes_read, avail);
79
80 if (status < 0)
81 break;
82
83 if (status == 0)
84 {
85 buf_ap->SetByteSize (bytes_read);
86 buf_sp.reset (buf_ap.release());
87 break;
88 }
89
90 bytes_read += status;
91
92 if (avail - status == 0)
93 buf_ap->SetByteSize (2 * buf_ap->GetByteSize());
94 }
95
96 close (fd);
97 }
Johnny Chen30213ff2012-01-05 19:17:38 +000098 }
99
100 return buf_sp;
101}
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000102
103} // anonymous namespace
104
Daniel Malea25d7eb02013-05-15 17:54:07 +0000105static bool
106ReadProcPseudoFileStat (lldb::pid_t pid, ProcessStatInfo& stat_info)
107{
108 // Read the /proc/$PID/stat file.
109 lldb::DataBufferSP buf_sp = ReadProcPseudoFile (pid, "stat");
110
111 // The filename of the executable is stored in parenthesis right after the pid. We look for the closing
112 // parenthesis for the filename and work from there in case the name has something funky like ')' in it.
113 const char *filename_end = strrchr ((const char *)buf_sp->GetBytes(), ')');
114 if (filename_end)
115 {
116 char state = '\0';
117 int ppid = LLDB_INVALID_PROCESS_ID;
118
119 // Read state and ppid.
120 sscanf (filename_end + 1, " %c %d", &state, &ppid);
121
122 stat_info.ppid = ppid;
123
124 switch (state)
125 {
126 case 'R':
127 stat_info.fProcessState |= eProcessStateRunning;
128 break;
129 case 'S':
130 stat_info.fProcessState |= eProcessStateSleeping;
131 break;
132 case 'D':
133 stat_info.fProcessState |= eProcessStateWaiting;
134 break;
135 case 'Z':
136 stat_info.fProcessState |= eProcessStateZombie;
137 break;
138 case 'T':
139 stat_info.fProcessState |= eProcessStateTracedOrStopped;
140 break;
141 case 'W':
142 stat_info.fProcessState |= eProcessStatePaging;
143 break;
144 }
145
146 return true;
147 }
148
149 return false;
150}
151
152static void
153GetLinuxProcessUserAndGroup (lldb::pid_t pid, ProcessInstanceInfo &process_info, lldb::pid_t &tracerpid)
154{
155 tracerpid = 0;
156 uint32_t rUid = UINT32_MAX; // Real User ID
157 uint32_t eUid = UINT32_MAX; // Effective User ID
158 uint32_t rGid = UINT32_MAX; // Real Group ID
159 uint32_t eGid = UINT32_MAX; // Effective Group ID
160
161 // Read the /proc/$PID/status file and parse the Uid:, Gid:, and TracerPid: fields.
162 lldb::DataBufferSP buf_sp = ReadProcPseudoFile (pid, "status");
163
164 static const char uid_token[] = "Uid:";
165 char *buf_uid = strstr ((char *)buf_sp->GetBytes(), uid_token);
166 if (buf_uid)
167 {
168 // Real, effective, saved set, and file system UIDs. Read the first two.
169 buf_uid += sizeof(uid_token);
170 rUid = strtol (buf_uid, &buf_uid, 10);
171 eUid = strtol (buf_uid, &buf_uid, 10);
172 }
173
174 static const char gid_token[] = "Gid:";
175 char *buf_gid = strstr ((char *)buf_sp->GetBytes(), gid_token);
176 if (buf_gid)
177 {
178 // Real, effective, saved set, and file system GIDs. Read the first two.
179 buf_gid += sizeof(gid_token);
180 rGid = strtol (buf_gid, &buf_gid, 10);
181 eGid = strtol (buf_gid, &buf_gid, 10);
182 }
183
184 static const char tracerpid_token[] = "TracerPid:";
185 char *buf_tracerpid = strstr((char *)buf_sp->GetBytes(), tracerpid_token);
186 if (buf_tracerpid)
187 {
188 // Tracer PID. 0 if we're not being debugged.
189 buf_tracerpid += sizeof(tracerpid_token);
190 tracerpid = strtol (buf_tracerpid, &buf_tracerpid, 10);
191 }
192
193 process_info.SetUserID (rUid);
194 process_info.SetEffectiveUserID (eUid);
195 process_info.SetGroupID (rGid);
196 process_info.SetEffectiveGroupID (eGid);
197}
198
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000199bool
200Host::GetOSVersion(uint32_t &major,
201 uint32_t &minor,
202 uint32_t &update)
203{
204 struct utsname un;
205 int status;
206
207 if (uname(&un))
208 return false;
209
210 status = sscanf(un.release, "%u.%u.%u", &major, &minor, &update);
211 return status == 3;
212}
213
214Error
215Host::LaunchProcess (ProcessLaunchInfo &launch_info)
216{
217 Error error;
218 assert(!"Not implemented yet!!!");
219 return error;
220}
221
222lldb::DataBufferSP
223Host::GetAuxvData(lldb_private::Process *process)
224{
225 return ReadProcPseudoFile(process->GetID(), "auxv");
226}
227
Daniel Malea25d7eb02013-05-15 17:54:07 +0000228static bool
229IsDirNumeric(const char *dname)
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000230{
Daniel Malea25d7eb02013-05-15 17:54:07 +0000231 for (; *dname; dname++)
232 {
233 if (!isdigit (*dname))
234 return false;
235 }
236 return true;
237}
238
239uint32_t
240Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
241{
242 static const char procdir[] = "/proc/";
243
244 DIR *dirproc = opendir (procdir);
245 if (dirproc)
246 {
247 struct dirent *direntry = NULL;
248 const uid_t our_uid = getuid();
249 const lldb::pid_t our_pid = getpid();
250 bool all_users = match_info.GetMatchAllUsers();
251
252 while ((direntry = readdir (dirproc)) != NULL)
253 {
254 if (direntry->d_type != DT_DIR || !IsDirNumeric (direntry->d_name))
255 continue;
256
257 lldb::pid_t pid = atoi (direntry->d_name);
258
259 // Skip this process.
260 if (pid == our_pid)
261 continue;
262
263 lldb::pid_t tracerpid;
264 ProcessStatInfo stat_info;
265 ProcessInstanceInfo process_info;
266
267 if (!GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid))
268 continue;
269
270 // Skip if process is being debugged.
271 if (tracerpid != 0)
272 continue;
273
274 // Skip zombies.
275 if (stat_info.fProcessState & eProcessStateZombie)
276 continue;
277
278 // Check for user match if we're not matching all users and not running as root.
279 if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid))
280 continue;
281
282 if (match_info.Matches (process_info))
283 {
284 process_infos.Append (process_info);
285 }
286 }
287
288 closedir (dirproc);
289 }
290
291 return process_infos.GetSize();
292}
293
294static bool
295GetProcessAndStatInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info, ProcessStatInfo &stat_info, lldb::pid_t &tracerpid)
296{
297 tracerpid = 0;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000298 process_info.Clear();
Daniel Malea25d7eb02013-05-15 17:54:07 +0000299 ::memset (&stat_info, 0, sizeof(stat_info));
300 stat_info.ppid = LLDB_INVALID_PROCESS_ID;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000301
302 // Architecture is intentionally omitted because that's better resolved
303 // in other places (see ProcessPOSIX::DoAttachWithID().
304
305 // Use special code here because proc/[pid]/exe is a symbolic link.
306 char link_path[PATH_MAX];
307 char exe_path[PATH_MAX] = "";
Daniel Malea25d7eb02013-05-15 17:54:07 +0000308 if (snprintf (link_path, PATH_MAX, "/proc/%" PRIu64 "/exe", pid) <= 0)
309 return false;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000310
Daniel Malea25d7eb02013-05-15 17:54:07 +0000311 ssize_t len = readlink (link_path, exe_path, sizeof(exe_path) - 1);
312 if (len <= 0)
313 return false;
314
315 // readlink does not append a null byte.
316 exe_path[len] = 0;
317
318 // If the binary has been deleted, the link name has " (deleted)" appended.
319 // Remove if there.
320 static const ssize_t deleted_len = strlen(" (deleted)");
321 if (len > deleted_len &&
322 !strcmp(exe_path + len - deleted_len, " (deleted)"))
323 {
324 exe_path[len - deleted_len] = 0;
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000325 }
Daniel Malea25d7eb02013-05-15 17:54:07 +0000326
327 process_info.SetProcessID(pid);
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000328 process_info.GetExecutableFile().SetFile(exe_path, false);
329
330 lldb::DataBufferSP buf_sp;
331
332 // Get the process environment.
333 buf_sp = ReadProcPseudoFile(pid, "environ");
334 Args &info_env = process_info.GetEnvironmentEntries();
335 char *next_var = (char *)buf_sp->GetBytes();
336 char *end_buf = next_var + buf_sp->GetByteSize();
337 while (next_var < end_buf && 0 != *next_var)
338 {
339 info_env.AppendArgument(next_var);
340 next_var += strlen(next_var) + 1;
341 }
342
343 // Get the commond line used to start the process.
344 buf_sp = ReadProcPseudoFile(pid, "cmdline");
345
346 // Grab Arg0 first.
347 char *cmd = (char *)buf_sp->GetBytes();
348 process_info.SetArg0(cmd);
349
350 // Now process any remaining arguments.
351 Args &info_args = process_info.GetArguments();
352 char *next_arg = cmd + strlen(cmd) + 1;
353 end_buf = cmd + buf_sp->GetByteSize();
354 while (next_arg < end_buf && 0 != *next_arg)
355 {
356 info_args.AppendArgument(next_arg);
357 next_arg += strlen(next_arg) + 1;
358 }
359
Daniel Malea25d7eb02013-05-15 17:54:07 +0000360 // Read /proc/$PID/stat to get our parent pid.
361 if (ReadProcPseudoFileStat (pid, stat_info))
362 {
363 process_info.SetParentProcessID (stat_info.ppid);
364 }
365
366 // Get User and Group IDs and get tracer pid.
367 GetLinuxProcessUserAndGroup (pid, process_info, tracerpid);
Andrew Kaylorbf9b4c12013-05-07 22:46:38 +0000368
369 return true;
Matt Kopec62502c62013-05-13 19:33:58 +0000370}
371
Daniel Malea25d7eb02013-05-15 17:54:07 +0000372bool
373Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
374{
375 lldb::pid_t tracerpid;
376 ProcessStatInfo stat_info;
377
378 return GetProcessAndStatInfo (pid, process_info, stat_info, tracerpid);
379}
380
Matt Kopec62502c62013-05-13 19:33:58 +0000381void
382Host::ThreadCreated (const char *thread_name)
383{
384 if (!Host::SetThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, thread_name))
385 {
386 // pthread_setname_np_func can fail if the thread name is longer than
387 // the supported limit on Linux. When this occurs, the error ERANGE is returned
388 // and SetThreadName will fail. Let's drop it down to 16 characters and try again.
389 char namebuf[16];
390
391 // Thread names are coming in like '<lldb.comm.debugger.edit>' and '<lldb.comm.debugger.editline>'
392 // So just chopping the end of the string off leads to a lot of similar named threads.
393 // Go through the thread name and search for the last dot and use that.
394 const char *lastdot = ::strrchr( thread_name, '.' );
395
396 if (lastdot && lastdot != thread_name)
397 thread_name = lastdot + 1;
398 ::strncpy (namebuf, thread_name, sizeof(namebuf));
399 namebuf[ sizeof(namebuf) - 1 ] = 0;
400
401 int namebuflen = strlen(namebuf);
402 if (namebuflen > 0)
403 {
404 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
405 {
406 // Trim off trailing '(' and '>' characters for a bit more cleanup.
407 namebuflen--;
408 namebuf[namebuflen] = 0;
409 }
410 Host::SetThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, namebuf);
411 }
412 }
413}
414
415void
416Host::Backtrace (Stream &strm, uint32_t max_frames)
417{
418 // TODO: Is there a way to backtrace the current process on linux?
419}
420
421size_t
422Host::GetEnvironment (StringList &env)
423{
424 // TODO: Is there a way to the host environment for this process on linux?
425 return 0;
426}