1 //===-- source/Host/freebsd/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 <dlfcn.h>
13 #include <execinfo.h>
14 #include <sys/types.h>
15 #include <sys/user.h>
16 #include <sys/utsname.h>
17 #include <sys/sysctl.h>
18 #include <sys/proc.h>
19 
20 #include <sys/ptrace.h>
21 #include <sys/exec.h>
22 #include <machine/elf.h>
23 
24 // C++ Includes
25 // Other libraries and framework includes
26 // Project includes
27 #include "lldb/Core/Error.h"
28 #include "lldb/Host/Endian.h"
29 #include "lldb/Host/Host.h"
30 #include "lldb/Core/Module.h"
31 #include "lldb/Core/DataExtractor.h"
32 #include "lldb/Core/StreamFile.h"
33 #include "lldb/Core/StreamString.h"
34 #include "lldb/Core/Log.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/Platform.h"
37 
38 #include "lldb/Core/DataBufferHeap.h"
39 #include "lldb/Core/DataExtractor.h"
40 #include "lldb/Utility/CleanUp.h"
41 
42 #include "llvm/Support/Host.h"
43 
44 
45 extern "C" {
46     extern char **environ;
47 }
48 
49 using namespace lldb;
50 using namespace lldb_private;
51 
52 class FreeBSDThread
53 {
54 public:
55     FreeBSDThread(const char *thread_name)
56     {
57         Host::SetThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, thread_name);
58     }
59     static void PThreadDestructor (void *v)
60     {
61         delete (FreeBSDThread*)v;
62     }
63 };
64 
65 static pthread_once_t g_thread_create_once = PTHREAD_ONCE_INIT;
66 static pthread_key_t g_thread_create_key = 0;
67 
68 static void
69 InitThreadCreated()
70 {
71     ::pthread_key_create (&g_thread_create_key, FreeBSDThread::PThreadDestructor);
72 }
73 
74 void
75 Host::ThreadCreated (const char *thread_name)
76 {
77     ::pthread_once (&g_thread_create_once, InitThreadCreated);
78     if (g_thread_create_key)
79     {
80         ::pthread_setspecific (g_thread_create_key, new FreeBSDThread(thread_name));
81     }
82 
83     Host::SetShortThreadName (LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID, thread_name, 16);
84 }
85 
86 std::string
87 Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
88 {
89     struct kinfo_proc *kp = nullptr;
90     size_t len = 0;
91     int error;
92     int name[4] = {
93         CTL_KERN, KERN_PROC, KERN_PROC_PID | KERN_PROC_INC_THREAD, (int)pid
94     };
95 
96     while (1) {
97         error = sysctl(name, 4, kp, &len, nullptr, 0);
98         if (kp == nullptr || (error != 0 && errno == ENOMEM)) {
99             // Add extra space in case threads are added before next call.
100             len += sizeof(*kp) + len / 10;
101             kp = (struct kinfo_proc *)reallocf(kp, len);
102             if (kp == nullptr)
103                 return std::string();
104             continue;
105         }
106         if (error != 0)
107             len = 0;
108         break;
109     }
110 
111     std::string thread_name;
112     for (size_t i = 0; i < len / sizeof(*kp); i++) {
113         if (kp[i].ki_tid == (int)tid) {
114             thread_name = kp[i].ki_tdname;
115             break;
116         }
117     }
118     free(kp);
119     return thread_name;
120 }
121 
122 void
123 Host::Backtrace (Stream &strm, uint32_t max_frames)
124 {
125     char backtrace_path[] = "/tmp/lldb-backtrace-tmp-XXXXXX";
126     int backtrace_fd = ::mkstemp (backtrace_path);
127     if (backtrace_fd != -1)
128     {
129         std::vector<void *> frame_buffer (max_frames, NULL);
130         int count = ::backtrace (&frame_buffer[0], frame_buffer.size());
131         ::backtrace_symbols_fd (&frame_buffer[0], count, backtrace_fd);
132 
133         const off_t buffer_size = ::lseek(backtrace_fd, 0, SEEK_CUR);
134 
135         if (::lseek(backtrace_fd, 0, SEEK_SET) == 0)
136         {
137             char *buffer = (char *)::malloc (buffer_size);
138             if (buffer)
139             {
140                 ssize_t bytes_read = ::read (backtrace_fd, buffer, buffer_size);
141                 if (bytes_read > 0)
142                     strm.Write(buffer, bytes_read);
143                 ::free (buffer);
144             }
145         }
146         ::close (backtrace_fd);
147         ::unlink (backtrace_path);
148     }
149 }
150 
151 size_t
152 Host::GetEnvironment (StringList &env)
153 {
154     char *v;
155     char **var = environ;
156     for (; var != NULL && *var != NULL; ++var)
157     {
158         v = strchr(*var, (int)'-');
159         if (v == NULL)
160             continue;
161         env.AppendString(v);
162     }
163     return env.GetSize();
164 }
165 
166 bool
167 Host::GetOSVersion(uint32_t &major,
168                    uint32_t &minor,
169                    uint32_t &update)
170 {
171     struct utsname un;
172 
173     ::memset(&un, 0, sizeof(utsname));
174     if (uname(&un) < 0)
175         return false;
176 
177     int status = sscanf(un.release, "%u.%u", &major, &minor);
178     return status == 2;
179 }
180 
181 bool
182 Host::GetOSBuildString (std::string &s)
183 {
184     int mib[2] = { CTL_KERN, KERN_OSREV };
185     char osrev_str[12];
186     uint32_t osrev = 0;
187     size_t osrev_len = sizeof(osrev);
188 
189     if (::sysctl (mib, 2, &osrev, &osrev_len, NULL, 0) == 0)
190     {
191         ::snprintf(osrev_str, sizeof(osrev_str), "%-8.8u", osrev);
192         s.assign (osrev_str);
193         return true;
194     }
195 
196     s.clear();
197     return false;
198 }
199 
200 bool
201 Host::GetOSKernelDescription (std::string &s)
202 {
203     struct utsname un;
204 
205     ::memset(&un, 0, sizeof(utsname));
206     s.clear();
207 
208     if (uname(&un) < 0)
209     return false;
210 
211     s.assign (un.version);
212 
213     return true;
214 }
215 
216 static bool
217 GetFreeBSDProcessArgs (const ProcessInstanceInfoMatch *match_info_ptr,
218                       ProcessInstanceInfo &process_info)
219 {
220     if (process_info.ProcessIDIsValid())
221     {
222         int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ARGS, (int)process_info.GetProcessID() };
223 
224         char arg_data[8192];
225         size_t arg_data_size = sizeof(arg_data);
226         if (::sysctl (mib, 4, arg_data, &arg_data_size , NULL, 0) == 0)
227         {
228             DataExtractor data (arg_data, arg_data_size, lldb::endian::InlHostByteOrder(), sizeof(void *));
229             lldb::offset_t offset = 0;
230             const char *cstr;
231 
232             cstr = data.GetCStr (&offset);
233             if (cstr)
234             {
235                 process_info.GetExecutableFile().SetFile(cstr, false);
236 
237                 if (!(match_info_ptr == NULL ||
238                     NameMatches (process_info.GetExecutableFile().GetFilename().GetCString(),
239                                  match_info_ptr->GetNameMatchType(),
240                                  match_info_ptr->GetProcessInfo().GetName())))
241                     return false;
242 
243                 Args &proc_args = process_info.GetArguments();
244                 while (1)
245                 {
246                     const uint8_t *p = data.PeekData(offset, 1);
247                     while ((p != NULL) && (*p == '\0') && offset < arg_data_size)
248                     {
249                         ++offset;
250                         p = data.PeekData(offset, 1);
251                     }
252                     if (p == NULL || offset >= arg_data_size)
253                         return true;
254 
255                     cstr = data.GetCStr(&offset);
256                     if (cstr)
257                         proc_args.AppendArgument(cstr);
258                     else
259                         return true;
260                 }
261             }
262         }
263     }
264     return false;
265 }
266 
267 static bool
268 GetFreeBSDProcessCPUType (ProcessInstanceInfo &process_info)
269 {
270     if (process_info.ProcessIDIsValid())
271     {
272         process_info.GetArchitecture() = Host::GetArchitecture (Host::eSystemDefaultArchitecture);
273         return true;
274     }
275     process_info.GetArchitecture().Clear();
276     return false;
277 }
278 
279 static bool
280 GetFreeBSDProcessUserAndGroup(ProcessInstanceInfo &process_info)
281 {
282     struct kinfo_proc proc_kinfo;
283     size_t proc_kinfo_size;
284 
285     if (process_info.ProcessIDIsValid())
286     {
287         int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
288             (int)process_info.GetProcessID() };
289         proc_kinfo_size = sizeof(struct kinfo_proc);
290 
291         if (::sysctl (mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) == 0)
292         {
293             if (proc_kinfo_size > 0)
294             {
295                 process_info.SetParentProcessID (proc_kinfo.ki_ppid);
296                 process_info.SetUserID (proc_kinfo.ki_ruid);
297                 process_info.SetGroupID (proc_kinfo.ki_rgid);
298                 process_info.SetEffectiveUserID (proc_kinfo.ki_uid);
299                 if (proc_kinfo.ki_ngroups > 0)
300                     process_info.SetEffectiveGroupID (proc_kinfo.ki_groups[0]);
301                 else
302                     process_info.SetEffectiveGroupID (UINT32_MAX);
303                 return true;
304             }
305         }
306     }
307     process_info.SetParentProcessID (LLDB_INVALID_PROCESS_ID);
308     process_info.SetUserID (UINT32_MAX);
309     process_info.SetGroupID (UINT32_MAX);
310     process_info.SetEffectiveUserID (UINT32_MAX);
311     process_info.SetEffectiveGroupID (UINT32_MAX);
312     return false;
313 }
314 
315 uint32_t
316 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
317 {
318     std::vector<struct kinfo_proc> kinfos;
319 
320     int mib[3] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL };
321 
322     size_t pid_data_size = 0;
323     if (::sysctl (mib, 3, NULL, &pid_data_size, NULL, 0) != 0)
324         return 0;
325 
326     // Add a few extra in case a few more show up
327     const size_t estimated_pid_count = (pid_data_size / sizeof(struct kinfo_proc)) + 10;
328 
329     kinfos.resize (estimated_pid_count);
330     pid_data_size = kinfos.size() * sizeof(struct kinfo_proc);
331 
332     if (::sysctl (mib, 3, &kinfos[0], &pid_data_size, NULL, 0) != 0)
333         return 0;
334 
335     const size_t actual_pid_count = (pid_data_size / sizeof(struct kinfo_proc));
336 
337     bool all_users = match_info.GetMatchAllUsers();
338     const ::pid_t our_pid = getpid();
339     const uid_t our_uid = getuid();
340     for (size_t i = 0; i < actual_pid_count; i++)
341     {
342         const struct kinfo_proc &kinfo = kinfos[i];
343         const bool kinfo_user_matches = (all_users ||
344                                          (kinfo.ki_ruid == our_uid) ||
345                                          // Special case, if lldb is being run as root we can attach to anything.
346                                          (our_uid == 0)
347                                          );
348 
349         if (kinfo_user_matches == false      || // Make sure the user is acceptable
350             kinfo.ki_pid == our_pid          || // Skip this process
351             kinfo.ki_pid == 0                || // Skip kernel (kernel pid is zero)
352             kinfo.ki_stat == SZOMB    || // Zombies are bad, they like brains...
353             kinfo.ki_flag & P_TRACED  || // Being debugged?
354             kinfo.ki_flag & P_WEXIT)     // Working on exiting
355             continue;
356 
357         // Every thread is a process in FreeBSD, but all the threads of a single process
358         // have the same pid. Do not store the process info in the result list if a process
359         // with given identifier is already registered there.
360         bool already_registered = false;
361         for (uint32_t pi = 0;
362              !already_registered &&
363              (const int)kinfo.ki_numthreads > 1 &&
364              pi < (const uint32_t)process_infos.GetSize(); pi++)
365             already_registered = (process_infos.GetProcessIDAtIndex(pi) == (uint32_t)kinfo.ki_pid);
366 
367         if (already_registered)
368             continue;
369 
370         ProcessInstanceInfo process_info;
371         process_info.SetProcessID (kinfo.ki_pid);
372         process_info.SetParentProcessID (kinfo.ki_ppid);
373         process_info.SetUserID (kinfo.ki_ruid);
374         process_info.SetGroupID (kinfo.ki_rgid);
375         process_info.SetEffectiveUserID (kinfo.ki_svuid);
376         process_info.SetEffectiveGroupID (kinfo.ki_svgid);
377 
378         // Make sure our info matches before we go fetch the name and cpu type
379         if (match_info.Matches (process_info) &&
380             GetFreeBSDProcessArgs (&match_info, process_info))
381         {
382             GetFreeBSDProcessCPUType (process_info);
383             if (match_info.Matches (process_info))
384                 process_infos.Append (process_info);
385         }
386     }
387 
388     return process_infos.GetSize();
389 }
390 
391 bool
392 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
393 {
394     process_info.SetProcessID(pid);
395 
396     if (GetFreeBSDProcessArgs(NULL, process_info))
397     {
398         // should use libprocstat instead of going right into sysctl?
399         GetFreeBSDProcessCPUType(process_info);
400         GetFreeBSDProcessUserAndGroup(process_info);
401         return true;
402     }
403 
404     process_info.Clear();
405     return false;
406 }
407 
408 lldb::DataBufferSP
409 Host::GetAuxvData(lldb_private::Process *process)
410 {
411    int mib[2] = { CTL_KERN, KERN_PS_STRINGS };
412    void *ps_strings_addr, *auxv_addr;
413    size_t ps_strings_size = sizeof(void *);
414    Elf_Auxinfo aux_info[AT_COUNT];
415    struct ps_strings ps_strings;
416    struct ptrace_io_desc pid;
417    DataBufferSP buf_sp;
418    std::unique_ptr<DataBufferHeap> buf_ap(new DataBufferHeap(1024, 0));
419 
420    if (::sysctl(mib, 2, &ps_strings_addr, &ps_strings_size, NULL, 0) == 0) {
421            pid.piod_op = PIOD_READ_D;
422            pid.piod_addr = &ps_strings;
423            pid.piod_offs = ps_strings_addr;
424            pid.piod_len = sizeof(ps_strings);
425            if (::ptrace(PT_IO, process->GetID(), (caddr_t)&pid, 0)) {
426                    perror("failed to fetch ps_strings");
427                    buf_ap.release();
428                    goto done;
429            }
430 
431            auxv_addr = ps_strings.ps_envstr + ps_strings.ps_nenvstr + 1;
432 
433            pid.piod_addr = aux_info;
434            pid.piod_offs = auxv_addr;
435            pid.piod_len = sizeof(aux_info);
436            if (::ptrace(PT_IO, process->GetID(), (caddr_t)&pid, 0)) {
437                    perror("failed to fetch aux_info");
438                    buf_ap.release();
439                    goto done;
440            }
441            memcpy(buf_ap->GetBytes(), aux_info, pid.piod_len);
442            buf_sp.reset(buf_ap.release());
443    } else {
444            perror("sysctl failed on ps_strings");
445    }
446 
447    done:
448    return buf_sp;
449 }
450