1 //===-- source/Host/freebsd/Host.cpp ------------------------------*- C++
2 //-*-===//
3 //
4 //                     The LLVM Compiler Infrastructure
5 //
6 // This file is distributed under the University of Illinois Open Source
7 // License. See LICENSE.TXT for details.
8 //
9 //===----------------------------------------------------------------------===//
10 
11 // C Includes
12 #include <sys/types.h>
13 
14 #include <sys/exec.h>
15 #include <sys/proc.h>
16 #include <sys/ptrace.h>
17 #include <sys/sysctl.h>
18 #include <sys/user.h>
19 
20 #include <machine/elf.h>
21 
22 #include <dlfcn.h>
23 #include <execinfo.h>
24 #include <stdio.h>
25 
26 // C++ Includes
27 // Other libraries and framework includes
28 // Project includes
29 #include "lldb/Core/Module.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Target/Platform.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Utility/CleanUp.h"
35 #include "lldb/Utility/DataBufferHeap.h"
36 #include "lldb/Utility/DataExtractor.h"
37 #include "lldb/Utility/Endian.h"
38 #include "lldb/Utility/Log.h"
39 #include "lldb/Utility/NameMatches.h"
40 #include "lldb/Utility/Status.h"
41 #include "lldb/Utility/StreamString.h"
42 
43 #include "llvm/Support/Host.h"
44 
45 extern "C" {
46 extern char **environ;
47 }
48 
49 using namespace lldb;
50 using namespace lldb_private;
51 
52 static bool
53 GetFreeBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr,
54                       ProcessInstanceInfo &process_info) {
55   if (!process_info.ProcessIDIsValid())
56     return false;
57 
58   int pid = process_info.GetProcessID();
59 
60   int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, pid};
61 
62   char arg_data[8192];
63   size_t arg_data_size = sizeof(arg_data);
64   if (::sysctl(mib, 4, arg_data, &arg_data_size, NULL, 0) != 0)
65     return false;
66 
67   DataExtractor data(arg_data, arg_data_size, endian::InlHostByteOrder(),
68                      sizeof(void *));
69   lldb::offset_t offset = 0;
70   const char *cstr;
71 
72   cstr = data.GetCStr(&offset);
73   if (!cstr)
74     return false;
75 
76   // Get pathname for pid. If that fails fall back to argv[0].
77   char pathname[MAXPATHLEN];
78   size_t pathname_len = sizeof(pathname);
79   mib[2] = KERN_PROC_PATHNAME;
80   if (::sysctl(mib, 4, pathname, &pathname_len, NULL, 0) == 0)
81     process_info.GetExecutableFile().SetFile(pathname, false);
82   else
83     process_info.GetExecutableFile().SetFile(cstr, false);
84 
85   if (!(match_info_ptr == NULL ||
86         NameMatches(process_info.GetExecutableFile().GetFilename().GetCString(),
87                     match_info_ptr->GetNameMatchType(),
88                     match_info_ptr->GetProcessInfo().GetName())))
89     return false;
90 
91   Args &proc_args = process_info.GetArguments();
92   while (1) {
93     const uint8_t *p = data.PeekData(offset, 1);
94     while ((p != NULL) && (*p == '\0') && offset < arg_data_size) {
95       ++offset;
96       p = data.PeekData(offset, 1);
97     }
98     if (p == NULL || offset >= arg_data_size)
99       break;
100 
101     cstr = data.GetCStr(&offset);
102     if (!cstr)
103       break;
104 
105     proc_args.AppendArgument(llvm::StringRef(cstr));
106   }
107 
108   return true;
109 }
110 
111 static bool GetFreeBSDProcessCPUType(ProcessInstanceInfo &process_info) {
112   if (process_info.ProcessIDIsValid()) {
113     process_info.GetArchitecture() =
114         HostInfo::GetArchitecture(HostInfo::eArchKindDefault);
115     return true;
116   }
117   process_info.GetArchitecture().Clear();
118   return false;
119 }
120 
121 static bool GetFreeBSDProcessUserAndGroup(ProcessInstanceInfo &process_info) {
122   struct kinfo_proc proc_kinfo;
123   size_t proc_kinfo_size;
124   const int pid = process_info.GetProcessID();
125   int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
126 
127   if (!process_info.ProcessIDIsValid())
128     goto error;
129 
130   proc_kinfo_size = sizeof(struct kinfo_proc);
131 
132   if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) != 0)
133     goto error;
134 
135   if (proc_kinfo_size == 0)
136     goto error;
137 
138   process_info.SetParentProcessID(proc_kinfo.ki_ppid);
139   process_info.SetUserID(proc_kinfo.ki_ruid);
140   process_info.SetGroupID(proc_kinfo.ki_rgid);
141   process_info.SetEffectiveUserID(proc_kinfo.ki_uid);
142   if (proc_kinfo.ki_ngroups > 0)
143     process_info.SetEffectiveGroupID(proc_kinfo.ki_groups[0]);
144   else
145     process_info.SetEffectiveGroupID(UINT32_MAX);
146   return true;
147 
148 error:
149   process_info.SetParentProcessID(LLDB_INVALID_PROCESS_ID);
150   process_info.SetUserID(UINT32_MAX);
151   process_info.SetGroupID(UINT32_MAX);
152   process_info.SetEffectiveUserID(UINT32_MAX);
153   process_info.SetEffectiveGroupID(UINT32_MAX);
154   return false;
155 }
156 
157 uint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info,
158                              ProcessInstanceInfoList &process_infos) {
159   const ::pid_t our_pid = ::getpid();
160   const ::uid_t our_uid = ::getuid();
161   std::vector<struct kinfo_proc> kinfos;
162   // Special case, if lldb is being run as root we can attach to anything.
163   bool all_users = match_info.GetMatchAllUsers() || (our_uid == 0);
164 
165   int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL};
166 
167   size_t pid_data_size = 0;
168   if (::sysctl(mib, 3, NULL, &pid_data_size, NULL, 0) != 0)
169     return 0;
170 
171   // Add a few extra in case a few more show up
172   const size_t estimated_pid_count =
173       (pid_data_size / sizeof(struct kinfo_proc)) + 10;
174 
175   kinfos.resize(estimated_pid_count);
176   pid_data_size = kinfos.size() * sizeof(struct kinfo_proc);
177 
178   if (::sysctl(mib, 3, &kinfos[0], &pid_data_size, NULL, 0) != 0)
179     return 0;
180 
181   const size_t actual_pid_count = (pid_data_size / sizeof(struct kinfo_proc));
182 
183   for (size_t i = 0; i < actual_pid_count; i++) {
184     const struct kinfo_proc &kinfo = kinfos[i];
185 
186     /* Make sure the user is acceptable */
187     if (!all_users && kinfo.ki_ruid != our_uid)
188       continue;
189 
190     if (kinfo.ki_pid == our_pid ||  // Skip this process
191         kinfo.ki_pid == 0 ||        // Skip kernel (kernel pid is 0)
192         kinfo.ki_stat == SZOMB ||   // Zombies are bad
193         kinfo.ki_flag & P_TRACED || // Being debugged?
194         kinfo.ki_flag & P_WEXIT)    // Working on exiting
195       continue;
196 
197     // Every thread is a process in FreeBSD, but all the threads of a single
198     // process have the same pid. Do not store the process info in the
199     // result list if a process with given identifier is already registered
200     // there.
201     bool already_registered = false;
202     for (uint32_t pi = 0;
203          !already_registered && (const int)kinfo.ki_numthreads > 1 &&
204          pi < (const uint32_t)process_infos.GetSize();
205          pi++)
206       already_registered =
207           (process_infos.GetProcessIDAtIndex(pi) == (uint32_t)kinfo.ki_pid);
208 
209     if (already_registered)
210       continue;
211 
212     ProcessInstanceInfo process_info;
213     process_info.SetProcessID(kinfo.ki_pid);
214     process_info.SetParentProcessID(kinfo.ki_ppid);
215     process_info.SetUserID(kinfo.ki_ruid);
216     process_info.SetGroupID(kinfo.ki_rgid);
217     process_info.SetEffectiveUserID(kinfo.ki_svuid);
218     process_info.SetEffectiveGroupID(kinfo.ki_svgid);
219 
220     // Make sure our info matches before we go fetch the name and cpu type
221     if (match_info.Matches(process_info) &&
222         GetFreeBSDProcessArgs(&match_info, process_info)) {
223       GetFreeBSDProcessCPUType(process_info);
224       if (match_info.Matches(process_info))
225         process_infos.Append(process_info);
226     }
227   }
228 
229   return process_infos.GetSize();
230 }
231 
232 bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) {
233   process_info.SetProcessID(pid);
234 
235   if (GetFreeBSDProcessArgs(NULL, process_info)) {
236     // should use libprocstat instead of going right into sysctl?
237     GetFreeBSDProcessCPUType(process_info);
238     GetFreeBSDProcessUserAndGroup(process_info);
239     return true;
240   }
241 
242   process_info.Clear();
243   return false;
244 }
245 
246 size_t Host::GetEnvironment(StringList &env) {
247   char **host_env = environ;
248   char *env_entry;
249   size_t i;
250   for (i = 0; (env_entry = host_env[i]) != NULL; ++i)
251     env.AppendString(env_entry);
252   return i;
253 }
254 
255 Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
256   return Status("unimplemented");
257 }
258