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