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