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