1 //===-- source/Host/linux/Host.cpp ----------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include <cerrno> 10 #include <cstdio> 11 #include <cstring> 12 #include <dirent.h> 13 #include <fcntl.h> 14 #include <sys/stat.h> 15 #include <sys/types.h> 16 #include <sys/utsname.h> 17 #include <unistd.h> 18 19 #include "llvm/ADT/StringSwitch.h" 20 #include "llvm/Object/ELF.h" 21 #include "llvm/Support/ScopedPrinter.h" 22 23 #include "lldb/Utility/LLDBLog.h" 24 #include "lldb/Utility/Log.h" 25 #include "lldb/Utility/ProcessInfo.h" 26 #include "lldb/Utility/Status.h" 27 28 #include "lldb/Host/FileSystem.h" 29 #include "lldb/Host/Host.h" 30 #include "lldb/Host/HostInfo.h" 31 #include "lldb/Host/linux/Host.h" 32 #include "lldb/Host/linux/Support.h" 33 #include "lldb/Utility/DataExtractor.h" 34 35 using namespace lldb; 36 using namespace lldb_private; 37 38 namespace { 39 enum class ProcessState { 40 Unknown, 41 Dead, 42 DiskSleep, 43 Idle, 44 Paging, 45 Parked, 46 Running, 47 Sleeping, 48 TracedOrStopped, 49 Zombie, 50 }; 51 } 52 53 namespace lldb_private { 54 class ProcessLaunchInfo; 55 } 56 57 static bool GetStatusInfo(::pid_t Pid, ProcessInstanceInfo &ProcessInfo, 58 ProcessState &State, ::pid_t &TracerPid, 59 ::pid_t &Tgid) { 60 Log *log = GetLog(LLDBLog::Host); 61 62 auto BufferOrError = getProcFile(Pid, "status"); 63 if (!BufferOrError) 64 return false; 65 66 llvm::StringRef Rest = BufferOrError.get()->getBuffer(); 67 while (!Rest.empty()) { 68 llvm::StringRef Line; 69 std::tie(Line, Rest) = Rest.split('\n'); 70 71 if (Line.consume_front("Gid:")) { 72 // Real, effective, saved set, and file system GIDs. Read the first two. 73 Line = Line.ltrim(); 74 uint32_t RGid, EGid; 75 Line.consumeInteger(10, RGid); 76 Line = Line.ltrim(); 77 Line.consumeInteger(10, EGid); 78 79 ProcessInfo.SetGroupID(RGid); 80 ProcessInfo.SetEffectiveGroupID(EGid); 81 } else if (Line.consume_front("Uid:")) { 82 // Real, effective, saved set, and file system UIDs. Read the first two. 83 Line = Line.ltrim(); 84 uint32_t RUid, EUid; 85 Line.consumeInteger(10, RUid); 86 Line = Line.ltrim(); 87 Line.consumeInteger(10, EUid); 88 89 ProcessInfo.SetUserID(RUid); 90 ProcessInfo.SetEffectiveUserID(EUid); 91 } else if (Line.consume_front("PPid:")) { 92 ::pid_t PPid; 93 Line.ltrim().consumeInteger(10, PPid); 94 ProcessInfo.SetParentProcessID(PPid); 95 } else if (Line.consume_front("State:")) { 96 State = llvm::StringSwitch<ProcessState>(Line.ltrim().take_front(1)) 97 .Case("D", ProcessState::DiskSleep) 98 .Case("I", ProcessState::Idle) 99 .Case("R", ProcessState::Running) 100 .Case("S", ProcessState::Sleeping) 101 .CaseLower("T", ProcessState::TracedOrStopped) 102 .Case("W", ProcessState::Paging) 103 .Case("P", ProcessState::Parked) 104 .Case("X", ProcessState::Dead) 105 .Case("Z", ProcessState::Zombie) 106 .Default(ProcessState::Unknown); 107 if (State == ProcessState::Unknown) { 108 LLDB_LOG(log, "Unknown process state {0}", Line); 109 } 110 } else if (Line.consume_front("TracerPid:")) { 111 Line = Line.ltrim(); 112 Line.consumeInteger(10, TracerPid); 113 } else if (Line.consume_front("Tgid:")) { 114 Line = Line.ltrim(); 115 Line.consumeInteger(10, Tgid); 116 } 117 } 118 return true; 119 } 120 121 static bool IsDirNumeric(const char *dname) { 122 for (; *dname; dname++) { 123 if (!isdigit(*dname)) 124 return false; 125 } 126 return true; 127 } 128 129 static ArchSpec GetELFProcessCPUType(llvm::StringRef exe_path) { 130 Log *log = GetLog(LLDBLog::Host); 131 132 auto buffer_sp = FileSystem::Instance().CreateDataBuffer(exe_path, 0x20, 0); 133 if (!buffer_sp) 134 return ArchSpec(); 135 136 uint8_t exe_class = 137 llvm::object::getElfArchType( 138 {buffer_sp->GetChars(), size_t(buffer_sp->GetByteSize())}) 139 .first; 140 141 switch (exe_class) { 142 case llvm::ELF::ELFCLASS32: 143 return HostInfo::GetArchitecture(HostInfo::eArchKind32); 144 case llvm::ELF::ELFCLASS64: 145 return HostInfo::GetArchitecture(HostInfo::eArchKind64); 146 default: 147 LLDB_LOG(log, "Unknown elf class ({0}) in file {1}", exe_class, exe_path); 148 return ArchSpec(); 149 } 150 } 151 152 static void GetProcessArgs(::pid_t pid, ProcessInstanceInfo &process_info) { 153 auto BufferOrError = getProcFile(pid, "cmdline"); 154 if (!BufferOrError) 155 return; 156 std::unique_ptr<llvm::MemoryBuffer> Cmdline = std::move(*BufferOrError); 157 158 llvm::StringRef Arg0, Rest; 159 std::tie(Arg0, Rest) = Cmdline->getBuffer().split('\0'); 160 process_info.SetArg0(Arg0); 161 while (!Rest.empty()) { 162 llvm::StringRef Arg; 163 std::tie(Arg, Rest) = Rest.split('\0'); 164 process_info.GetArguments().AppendArgument(Arg); 165 } 166 } 167 168 static void GetExePathAndArch(::pid_t pid, ProcessInstanceInfo &process_info) { 169 Log *log = GetLog(LLDBLog::Process); 170 std::string ExePath(PATH_MAX, '\0'); 171 172 // We can't use getProcFile here because proc/[pid]/exe is a symbolic link. 173 llvm::SmallString<64> ProcExe; 174 (llvm::Twine("/proc/") + llvm::Twine(pid) + "/exe").toVector(ProcExe); 175 176 ssize_t len = readlink(ProcExe.c_str(), &ExePath[0], PATH_MAX); 177 if (len > 0) { 178 ExePath.resize(len); 179 } else { 180 LLDB_LOG(log, "failed to read link exe link for {0}: {1}", pid, 181 Status(errno, eErrorTypePOSIX)); 182 ExePath.resize(0); 183 } 184 // If the binary has been deleted, the link name has " (deleted)" appended. 185 // Remove if there. 186 llvm::StringRef PathRef = ExePath; 187 PathRef.consume_back(" (deleted)"); 188 189 if (!PathRef.empty()) { 190 process_info.GetExecutableFile().SetFile(PathRef, FileSpec::Style::native); 191 process_info.SetArchitecture(GetELFProcessCPUType(PathRef)); 192 } 193 } 194 195 static void GetProcessEnviron(::pid_t pid, ProcessInstanceInfo &process_info) { 196 // Get the process environment. 197 auto BufferOrError = getProcFile(pid, "environ"); 198 if (!BufferOrError) 199 return; 200 201 std::unique_ptr<llvm::MemoryBuffer> Environ = std::move(*BufferOrError); 202 llvm::StringRef Rest = Environ->getBuffer(); 203 while (!Rest.empty()) { 204 llvm::StringRef Var; 205 std::tie(Var, Rest) = Rest.split('\0'); 206 process_info.GetEnvironment().insert(Var); 207 } 208 } 209 210 static bool GetProcessAndStatInfo(::pid_t pid, 211 ProcessInstanceInfo &process_info, 212 ProcessState &State, ::pid_t &tracerpid) { 213 ::pid_t tgid; 214 tracerpid = 0; 215 process_info.Clear(); 216 217 process_info.SetProcessID(pid); 218 219 GetExePathAndArch(pid, process_info); 220 GetProcessArgs(pid, process_info); 221 GetProcessEnviron(pid, process_info); 222 223 // Get User and Group IDs and get tracer pid. 224 if (!GetStatusInfo(pid, process_info, State, tracerpid, tgid)) 225 return false; 226 227 return true; 228 } 229 230 uint32_t Host::FindProcessesImpl(const ProcessInstanceInfoMatch &match_info, 231 ProcessInstanceInfoList &process_infos) { 232 static const char procdir[] = "/proc/"; 233 234 DIR *dirproc = opendir(procdir); 235 if (dirproc) { 236 struct dirent *direntry = nullptr; 237 const uid_t our_uid = getuid(); 238 const lldb::pid_t our_pid = getpid(); 239 bool all_users = match_info.GetMatchAllUsers(); 240 241 while ((direntry = readdir(dirproc)) != nullptr) { 242 if (direntry->d_type != DT_DIR || !IsDirNumeric(direntry->d_name)) 243 continue; 244 245 lldb::pid_t pid = atoi(direntry->d_name); 246 247 // Skip this process. 248 if (pid == our_pid) 249 continue; 250 251 ::pid_t tracerpid; 252 ProcessState State; 253 ProcessInstanceInfo process_info; 254 255 if (!GetProcessAndStatInfo(pid, process_info, State, tracerpid)) 256 continue; 257 258 // Skip if process is being debugged. 259 if (tracerpid != 0) 260 continue; 261 262 if (State == ProcessState::Zombie) 263 continue; 264 265 // Check for user match if we're not matching all users and not running 266 // as root. 267 if (!all_users && (our_uid != 0) && (process_info.GetUserID() != our_uid)) 268 continue; 269 270 if (match_info.Matches(process_info)) { 271 process_infos.push_back(process_info); 272 } 273 } 274 275 closedir(dirproc); 276 } 277 278 return process_infos.size(); 279 } 280 281 bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) { 282 bool tids_changed = false; 283 static const char procdir[] = "/proc/"; 284 static const char taskdir[] = "/task/"; 285 std::string process_task_dir = procdir + llvm::to_string(pid) + taskdir; 286 DIR *dirproc = opendir(process_task_dir.c_str()); 287 288 if (dirproc) { 289 struct dirent *direntry = nullptr; 290 while ((direntry = readdir(dirproc)) != nullptr) { 291 if (direntry->d_type != DT_DIR || !IsDirNumeric(direntry->d_name)) 292 continue; 293 294 lldb::tid_t tid = atoi(direntry->d_name); 295 TidMap::iterator it = tids_to_attach.find(tid); 296 if (it == tids_to_attach.end()) { 297 tids_to_attach.insert(TidPair(tid, false)); 298 tids_changed = true; 299 } 300 } 301 closedir(dirproc); 302 } 303 304 return tids_changed; 305 } 306 307 bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) { 308 ::pid_t tracerpid; 309 ProcessState State; 310 return GetProcessAndStatInfo(pid, process_info, State, tracerpid); 311 } 312 313 Environment Host::GetEnvironment() { return Environment(environ); } 314 315 Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { 316 return Status("unimplemented"); 317 } 318 319 llvm::Optional<lldb::pid_t> lldb_private::getPIDForTID(lldb::pid_t tid) { 320 ::pid_t tracerpid, tgid = LLDB_INVALID_PROCESS_ID; 321 ProcessInstanceInfo process_info; 322 ProcessState state; 323 324 if (!GetStatusInfo(tid, process_info, state, tracerpid, tgid) || 325 tgid == LLDB_INVALID_PROCESS_ID) 326 return llvm::None; 327 return tgid; 328 } 329