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