1 //===-- 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 #include "lldb/lldb-python.h"
11 
12 // C includes
13 #include <errno.h>
14 #include <limits.h>
15 #include <stdlib.h>
16 #include <sys/types.h>
17 #ifdef _WIN32
18 #include "lldb/Host/windows/windows.h"
19 #include <winsock2.h>
20 #include <ws2tcpip.h>
21 #else
22 #include <unistd.h>
23 #include <dlfcn.h>
24 #include <grp.h>
25 #include <netdb.h>
26 #include <pwd.h>
27 #include <sys/stat.h>
28 #endif
29 
30 #if !defined (__GNU__) && !defined (_WIN32)
31 // Does not exist under GNU/HURD or Windows
32 #include <sys/sysctl.h>
33 #endif
34 
35 #if defined (__APPLE__)
36 #include <mach/mach_port.h>
37 #include <mach/mach_init.h>
38 #include <mach-o/dyld.h>
39 #include <AvailabilityMacros.h>
40 #ifndef CPU_SUBTYPE_X86_64_H
41 #define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8)
42 #endif
43 #endif
44 
45 #if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
46 #include <spawn.h>
47 #include <sys/wait.h>
48 #include <sys/syscall.h>
49 #endif
50 
51 #if defined (__FreeBSD__)
52 #include <pthread_np.h>
53 #endif
54 
55 // C++ includes
56 #include <limits>
57 
58 #include "lldb/Host/Host.h"
59 #include "lldb/Core/ArchSpec.h"
60 #include "lldb/Core/ConstString.h"
61 #include "lldb/Core/Debugger.h"
62 #include "lldb/Core/Error.h"
63 #include "lldb/Core/Log.h"
64 #include "lldb/Core/Module.h"
65 #include "lldb/Core/StreamString.h"
66 #include "lldb/Core/ThreadSafeSTLMap.h"
67 #include "lldb/Host/Config.h"
68 #include "lldb/Host/Endian.h"
69 #include "lldb/Host/FileSpec.h"
70 #include "lldb/Host/Mutex.h"
71 #include "lldb/Target/Process.h"
72 #include "lldb/Target/TargetList.h"
73 #include "lldb/Utility/CleanUp.h"
74 
75 #include "llvm/ADT/STLExtras.h"
76 #include "llvm/ADT/SmallString.h"
77 #include "llvm/Support/Host.h"
78 #include "llvm/Support/Path.h"
79 #include "llvm/Support/raw_ostream.h"
80 
81 #if defined (__APPLE__)
82 #ifndef _POSIX_SPAWN_DISABLE_ASLR
83 #define _POSIX_SPAWN_DISABLE_ASLR       0x0100
84 #endif
85 
86 extern "C"
87 {
88     int __pthread_chdir(const char *path);
89     int __pthread_fchdir (int fildes);
90 }
91 
92 #endif
93 
94 using namespace lldb;
95 using namespace lldb_private;
96 
97 // Define maximum thread name length
98 #if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
99 uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
100 #else
101 uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
102 #endif
103 
104 #if !defined (__APPLE__) && !defined (_WIN32)
105 struct MonitorInfo
106 {
107     lldb::pid_t pid;                            // The process ID to monitor
108     Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
109     void *callback_baton;                       // The callback baton for the callback function
110     bool monitor_signals;                       // If true, call the callback when "pid" gets signaled.
111 };
112 
113 static thread_result_t
114 MonitorChildProcessThreadFunction (void *arg);
115 
116 lldb::thread_t
117 Host::StartMonitoringChildProcess
118 (
119     Host::MonitorChildProcessCallback callback,
120     void *callback_baton,
121     lldb::pid_t pid,
122     bool monitor_signals
123 )
124 {
125     lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
126     MonitorInfo * info_ptr = new MonitorInfo();
127 
128     info_ptr->pid = pid;
129     info_ptr->callback = callback;
130     info_ptr->callback_baton = callback_baton;
131     info_ptr->monitor_signals = monitor_signals;
132 
133     char thread_name[256];
134     ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
135     thread = ThreadCreate (thread_name,
136                            MonitorChildProcessThreadFunction,
137                            info_ptr,
138                            NULL);
139 
140     return thread;
141 }
142 
143 //------------------------------------------------------------------
144 // Scoped class that will disable thread canceling when it is
145 // constructed, and exception safely restore the previous value it
146 // when it goes out of scope.
147 //------------------------------------------------------------------
148 class ScopedPThreadCancelDisabler
149 {
150 public:
151     ScopedPThreadCancelDisabler()
152     {
153         // Disable the ability for this thread to be cancelled
154         int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
155         if (err != 0)
156             m_old_state = -1;
157 
158     }
159 
160     ~ScopedPThreadCancelDisabler()
161     {
162         // Restore the ability for this thread to be cancelled to what it
163         // previously was.
164         if (m_old_state != -1)
165             ::pthread_setcancelstate (m_old_state, 0);
166     }
167 private:
168     int m_old_state;    // Save the old cancelability state.
169 };
170 
171 static thread_result_t
172 MonitorChildProcessThreadFunction (void *arg)
173 {
174     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
175     const char *function = __FUNCTION__;
176     if (log)
177         log->Printf ("%s (arg = %p) thread starting...", function, arg);
178 
179     MonitorInfo *info = (MonitorInfo *)arg;
180 
181     const Host::MonitorChildProcessCallback callback = info->callback;
182     void * const callback_baton = info->callback_baton;
183     const bool monitor_signals = info->monitor_signals;
184 
185     assert (info->pid <= UINT32_MAX);
186     const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
187 
188     delete info;
189 
190     int status = -1;
191 #if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
192     #define __WALL 0
193 #endif
194     const int options = __WALL;
195 
196     while (1)
197     {
198         log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
199         if (log)
200             log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
201 
202         // Wait for all child processes
203         ::pthread_testcancel ();
204         // Get signals from all children with same process group of pid
205         const ::pid_t wait_pid = ::waitpid (pid, &status, options);
206         ::pthread_testcancel ();
207 
208         if (wait_pid == -1)
209         {
210             if (errno == EINTR)
211                 continue;
212             else
213             {
214                 if (log)
215                     log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
216                 break;
217             }
218         }
219         else if (wait_pid > 0)
220         {
221             bool exited = false;
222             int signal = 0;
223             int exit_status = 0;
224             const char *status_cstr = NULL;
225             if (WIFSTOPPED(status))
226             {
227                 signal = WSTOPSIG(status);
228                 status_cstr = "STOPPED";
229             }
230             else if (WIFEXITED(status))
231             {
232                 exit_status = WEXITSTATUS(status);
233                 status_cstr = "EXITED";
234                 exited = true;
235             }
236             else if (WIFSIGNALED(status))
237             {
238                 signal = WTERMSIG(status);
239                 status_cstr = "SIGNALED";
240                 if (wait_pid == abs(pid)) {
241                     exited = true;
242                     exit_status = -1;
243                 }
244             }
245             else
246             {
247                 status_cstr = "(\?\?\?)";
248             }
249 
250             // Scope for pthread_cancel_disabler
251             {
252                 ScopedPThreadCancelDisabler pthread_cancel_disabler;
253 
254                 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
255                 if (log)
256                     log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
257                                  function,
258                                  wait_pid,
259                                  options,
260                                  pid,
261                                  status,
262                                  status_cstr,
263                                  signal,
264                                  exit_status);
265 
266                 if (exited || (signal != 0 && monitor_signals))
267                 {
268                     bool callback_return = false;
269                     if (callback)
270                         callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
271 
272                     // If our process exited, then this thread should exit
273                     if (exited && wait_pid == abs(pid))
274                     {
275                         if (log)
276                             log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
277                         break;
278                     }
279                     // If the callback returns true, it means this process should
280                     // exit
281                     if (callback_return)
282                     {
283                         if (log)
284                             log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
285                         break;
286                     }
287                 }
288             }
289         }
290     }
291 
292     log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
293     if (log)
294         log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
295 
296     return NULL;
297 }
298 
299 #endif // #if !defined (__APPLE__) && !defined (_WIN32)
300 
301 #if !defined (__APPLE__)
302 
303 void
304 Host::SystemLog (SystemLogType type, const char *format, va_list args)
305 {
306     vfprintf (stderr, format, args);
307 }
308 
309 #endif
310 
311 void
312 Host::SystemLog (SystemLogType type, const char *format, ...)
313 {
314     va_list args;
315     va_start (args, format);
316     SystemLog (type, format, args);
317     va_end (args);
318 }
319 
320 const ArchSpec &
321 Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
322 {
323     static bool g_supports_32 = false;
324     static bool g_supports_64 = false;
325     static ArchSpec g_host_arch_32;
326     static ArchSpec g_host_arch_64;
327 
328 #if defined (__APPLE__)
329 
330     // Apple is different in that it can support both 32 and 64 bit executables
331     // in the same operating system running concurrently. Here we detect the
332     // correct host architectures for both 32 and 64 bit including if 64 bit
333     // executables are supported on the system.
334 
335     if (g_supports_32 == false && g_supports_64 == false)
336     {
337         // All apple systems support 32 bit execution.
338         g_supports_32 = true;
339         uint32_t cputype, cpusubtype;
340         uint32_t is_64_bit_capable = false;
341         size_t len = sizeof(cputype);
342         ArchSpec host_arch;
343         // These will tell us about the kernel architecture, which even on a 64
344         // bit machine can be 32 bit...
345         if  (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
346         {
347             len = sizeof (cpusubtype);
348             if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
349                 cpusubtype = CPU_TYPE_ANY;
350 
351             len = sizeof (is_64_bit_capable);
352             if  (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
353             {
354                 if (is_64_bit_capable)
355                     g_supports_64 = true;
356             }
357 
358             if (is_64_bit_capable)
359             {
360                 if (cputype & CPU_ARCH_ABI64)
361                 {
362                     // We have a 64 bit kernel on a 64 bit system
363                     g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
364                 }
365                 else
366                 {
367                     // We have a 64 bit kernel that is returning a 32 bit cputype, the
368                     // cpusubtype will be correct as if it were for a 64 bit architecture
369                     g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype | CPU_ARCH_ABI64, cpusubtype);
370                 }
371 
372                 // Now we need modify the cpusubtype for the 32 bit slices.
373                 uint32_t cpusubtype32 = cpusubtype;
374 #if defined (__i386__) || defined (__x86_64__)
375                 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
376                     cpusubtype32 = CPU_SUBTYPE_I386_ALL;
377 #elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
378                 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
379                     cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
380 #endif
381                 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype & ~(CPU_ARCH_MASK), cpusubtype32);
382 
383                 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
384                 {
385                     g_host_arch_32.GetTriple().setOS(llvm::Triple::IOS);
386                     g_host_arch_64.GetTriple().setOS(llvm::Triple::IOS);
387                 }
388                 else
389                 {
390                     g_host_arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
391                     g_host_arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
392                 }
393             }
394             else
395             {
396                 // We have a 32 bit kernel on a 32 bit system
397                 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
398                 g_host_arch_64.Clear();
399             }
400         }
401     }
402 
403 #else // #if defined (__APPLE__)
404 
405     if (g_supports_32 == false && g_supports_64 == false)
406     {
407         llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
408 
409         g_host_arch_32.Clear();
410         g_host_arch_64.Clear();
411 
412         // If the OS is Linux, "unknown" in the vendor slot isn't what we want
413         // for the default triple.  It's probably an artifact of config.guess.
414         if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
415             triple.setVendorName ("");
416 
417         const char* distribution_id = GetDistributionId ().AsCString();
418 
419         switch (triple.getArch())
420         {
421         default:
422             g_host_arch_32.SetTriple(triple);
423             g_host_arch_32.SetDistributionId (distribution_id);
424             g_supports_32 = true;
425             break;
426 
427         case llvm::Triple::x86_64:
428             g_host_arch_64.SetTriple(triple);
429             g_host_arch_64.SetDistributionId (distribution_id);
430             g_supports_64 = true;
431             g_host_arch_32.SetTriple(triple.get32BitArchVariant());
432             g_host_arch_32.SetDistributionId (distribution_id);
433             g_supports_32 = true;
434             break;
435 
436         case llvm::Triple::mips64:
437         case llvm::Triple::sparcv9:
438         case llvm::Triple::ppc64:
439             g_host_arch_64.SetTriple(triple);
440             g_host_arch_64.SetDistributionId (distribution_id);
441             g_supports_64 = true;
442             break;
443         }
444 
445         g_supports_32 = g_host_arch_32.IsValid();
446         g_supports_64 = g_host_arch_64.IsValid();
447     }
448 
449 #endif // #else for #if defined (__APPLE__)
450 
451     if (arch_kind == eSystemDefaultArchitecture32)
452         return g_host_arch_32;
453     else if (arch_kind == eSystemDefaultArchitecture64)
454         return g_host_arch_64;
455 
456     if (g_supports_64)
457         return g_host_arch_64;
458 
459     return g_host_arch_32;
460 }
461 
462 const ConstString &
463 Host::GetVendorString()
464 {
465     static ConstString g_vendor;
466     if (!g_vendor)
467     {
468         const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
469         const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
470         g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
471     }
472     return g_vendor;
473 }
474 
475 const ConstString &
476 Host::GetOSString()
477 {
478     static ConstString g_os_string;
479     if (!g_os_string)
480     {
481         const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
482         const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
483         g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
484     }
485     return g_os_string;
486 }
487 
488 const ConstString &
489 Host::GetTargetTriple()
490 {
491     static ConstString g_host_triple;
492     if (!(g_host_triple))
493     {
494         const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
495         g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
496     }
497     return g_host_triple;
498 }
499 
500 // See linux/Host.cpp for Linux-based implementations of this.
501 // Add your platform-specific implementation to the appropriate host file.
502 #if !defined(__linux__)
503 
504 const ConstString &
505     Host::GetDistributionId ()
506 {
507     static ConstString s_distribution_id;
508     return s_distribution_id;
509 }
510 
511 #endif // #if !defined(__linux__)
512 
513 lldb::pid_t
514 Host::GetCurrentProcessID()
515 {
516     return ::getpid();
517 }
518 
519 #ifndef _WIN32
520 
521 lldb::tid_t
522 Host::GetCurrentThreadID()
523 {
524 #if defined (__APPLE__)
525     // Calling "mach_thread_self()" bumps the reference count on the thread
526     // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
527     // count.
528     thread_port_t thread_self = mach_thread_self();
529     mach_port_deallocate(mach_task_self(), thread_self);
530     return thread_self;
531 #elif defined(__FreeBSD__)
532     return lldb::tid_t(pthread_getthreadid_np());
533 #elif defined(__linux__)
534     return lldb::tid_t(syscall(SYS_gettid));
535 #else
536     return lldb::tid_t(pthread_self());
537 #endif
538 }
539 
540 lldb::thread_t
541 Host::GetCurrentThread ()
542 {
543     return lldb::thread_t(pthread_self());
544 }
545 
546 const char *
547 Host::GetSignalAsCString (int signo)
548 {
549     switch (signo)
550     {
551     case SIGHUP:    return "SIGHUP";    // 1    hangup
552     case SIGINT:    return "SIGINT";    // 2    interrupt
553     case SIGQUIT:   return "SIGQUIT";   // 3    quit
554     case SIGILL:    return "SIGILL";    // 4    illegal instruction (not reset when caught)
555     case SIGTRAP:   return "SIGTRAP";   // 5    trace trap (not reset when caught)
556     case SIGABRT:   return "SIGABRT";   // 6    abort()
557 #if  defined(SIGPOLL)
558 #if !defined(SIGIO) || (SIGPOLL != SIGIO)
559 // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
560 // fail with 'multiple define cases with same value'
561     case SIGPOLL:   return "SIGPOLL";   // 7    pollable event ([XSR] generated, not supported)
562 #endif
563 #endif
564 #if  defined(SIGEMT)
565     case SIGEMT:    return "SIGEMT";    // 7    EMT instruction
566 #endif
567     case SIGFPE:    return "SIGFPE";    // 8    floating point exception
568     case SIGKILL:   return "SIGKILL";   // 9    kill (cannot be caught or ignored)
569     case SIGBUS:    return "SIGBUS";    // 10    bus error
570     case SIGSEGV:   return "SIGSEGV";   // 11    segmentation violation
571     case SIGSYS:    return "SIGSYS";    // 12    bad argument to system call
572     case SIGPIPE:   return "SIGPIPE";   // 13    write on a pipe with no one to read it
573     case SIGALRM:   return "SIGALRM";   // 14    alarm clock
574     case SIGTERM:   return "SIGTERM";   // 15    software termination signal from kill
575     case SIGURG:    return "SIGURG";    // 16    urgent condition on IO channel
576     case SIGSTOP:   return "SIGSTOP";   // 17    sendable stop signal not from tty
577     case SIGTSTP:   return "SIGTSTP";   // 18    stop signal from tty
578     case SIGCONT:   return "SIGCONT";   // 19    continue a stopped process
579     case SIGCHLD:   return "SIGCHLD";   // 20    to parent on child stop or exit
580     case SIGTTIN:   return "SIGTTIN";   // 21    to readers pgrp upon background tty read
581     case SIGTTOU:   return "SIGTTOU";   // 22    like TTIN for output if (tp->t_local&LTOSTOP)
582 #if  defined(SIGIO)
583     case SIGIO:     return "SIGIO";     // 23    input/output possible signal
584 #endif
585     case SIGXCPU:   return "SIGXCPU";   // 24    exceeded CPU time limit
586     case SIGXFSZ:   return "SIGXFSZ";   // 25    exceeded file size limit
587     case SIGVTALRM: return "SIGVTALRM"; // 26    virtual time alarm
588     case SIGPROF:   return "SIGPROF";   // 27    profiling time alarm
589 #if  defined(SIGWINCH)
590     case SIGWINCH:  return "SIGWINCH";  // 28    window size changes
591 #endif
592 #if  defined(SIGINFO)
593     case SIGINFO:   return "SIGINFO";   // 29    information request
594 #endif
595     case SIGUSR1:   return "SIGUSR1";   // 30    user defined signal 1
596     case SIGUSR2:   return "SIGUSR2";   // 31    user defined signal 2
597     default:
598         break;
599     }
600     return NULL;
601 }
602 
603 #endif
604 
605 void
606 Host::WillTerminate ()
607 {
608 }
609 
610 #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
611 
612 void
613 Host::ThreadCreated (const char *thread_name)
614 {
615 }
616 
617 void
618 Host::Backtrace (Stream &strm, uint32_t max_frames)
619 {
620     // TODO: Is there a way to backtrace the current process on other systems?
621 }
622 
623 size_t
624 Host::GetEnvironment (StringList &env)
625 {
626     // TODO: Is there a way to the host environment for this process on other systems?
627     return 0;
628 }
629 
630 #endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
631 
632 struct HostThreadCreateInfo
633 {
634     std::string thread_name;
635     thread_func_t thread_fptr;
636     thread_arg_t thread_arg;
637 
638     HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
639         thread_name (name ? name : ""),
640         thread_fptr (fptr),
641         thread_arg (arg)
642     {
643     }
644 };
645 
646 static thread_result_t
647 #ifdef _WIN32
648 __stdcall
649 #endif
650 ThreadCreateTrampoline (thread_arg_t arg)
651 {
652     HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
653     Host::ThreadCreated (info->thread_name.c_str());
654     thread_func_t thread_fptr = info->thread_fptr;
655     thread_arg_t thread_arg = info->thread_arg;
656 
657     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
658     if (log)
659         log->Printf("thread created");
660 
661     delete info;
662     return thread_fptr (thread_arg);
663 }
664 
665 lldb::thread_t
666 Host::ThreadCreate
667 (
668     const char *thread_name,
669     thread_func_t thread_fptr,
670     thread_arg_t thread_arg,
671     Error *error
672 )
673 {
674     lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
675 
676     // Host::ThreadCreateTrampoline will delete this pointer for us.
677     HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
678 
679 #ifdef _WIN32
680     thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
681     int err = thread <= 0 ? GetLastError() : 0;
682 #else
683     int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
684 #endif
685     if (err == 0)
686     {
687         if (error)
688             error->Clear();
689         return thread;
690     }
691 
692     if (error)
693         error->SetError (err, eErrorTypePOSIX);
694 
695     return LLDB_INVALID_HOST_THREAD;
696 }
697 
698 #ifndef _WIN32
699 
700 bool
701 Host::ThreadCancel (lldb::thread_t thread, Error *error)
702 {
703     int err = ::pthread_cancel (thread);
704     if (error)
705         error->SetError(err, eErrorTypePOSIX);
706     return err == 0;
707 }
708 
709 bool
710 Host::ThreadDetach (lldb::thread_t thread, Error *error)
711 {
712     int err = ::pthread_detach (thread);
713     if (error)
714         error->SetError(err, eErrorTypePOSIX);
715     return err == 0;
716 }
717 
718 bool
719 Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
720 {
721     int err = ::pthread_join (thread, thread_result_ptr);
722     if (error)
723         error->SetError(err, eErrorTypePOSIX);
724     return err == 0;
725 }
726 
727 lldb::thread_key_t
728 Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
729 {
730     pthread_key_t key;
731     ::pthread_key_create (&key, callback);
732     return key;
733 }
734 
735 void*
736 Host::ThreadLocalStorageGet(lldb::thread_key_t key)
737 {
738     return ::pthread_getspecific (key);
739 }
740 
741 void
742 Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
743 {
744    ::pthread_setspecific (key, value);
745 }
746 
747 bool
748 Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
749 {
750 #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
751     lldb::pid_t curr_pid = Host::GetCurrentProcessID();
752     lldb::tid_t curr_tid = Host::GetCurrentThreadID();
753     if (pid == LLDB_INVALID_PROCESS_ID)
754         pid = curr_pid;
755 
756     if (tid == LLDB_INVALID_THREAD_ID)
757         tid = curr_tid;
758 
759     // Set the pthread name if possible
760     if (pid == curr_pid && tid == curr_tid)
761     {
762         if (::pthread_setname_np (name) == 0)
763             return true;
764     }
765     return false;
766 #elif defined (__FreeBSD__)
767     lldb::pid_t curr_pid = Host::GetCurrentProcessID();
768     lldb::tid_t curr_tid = Host::GetCurrentThreadID();
769     if (pid == LLDB_INVALID_PROCESS_ID)
770         pid = curr_pid;
771 
772     if (tid == LLDB_INVALID_THREAD_ID)
773         tid = curr_tid;
774 
775     // Set the pthread name if possible
776     if (pid == curr_pid && tid == curr_tid)
777     {
778         ::pthread_set_name_np (::pthread_self(), name);
779         return true;
780     }
781     return false;
782 #elif defined (__linux__) || defined (__GLIBC__)
783     void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
784     if (fn)
785     {
786         lldb::pid_t curr_pid = Host::GetCurrentProcessID();
787         lldb::tid_t curr_tid = Host::GetCurrentThreadID();
788         if (pid == LLDB_INVALID_PROCESS_ID)
789             pid = curr_pid;
790 
791         if (tid == LLDB_INVALID_THREAD_ID)
792             tid = curr_tid;
793 
794         if (pid == curr_pid && tid == curr_tid)
795         {
796             int (*pthread_setname_np_func)(pthread_t thread, const char *name);
797             *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
798 
799             if (pthread_setname_np_func (::pthread_self(), name) == 0)
800                 return true;
801         }
802     }
803     return false;
804 #else
805     return false;
806 #endif
807 }
808 
809 bool
810 Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
811                           const char *thread_name, size_t len)
812 {
813     std::unique_ptr<char[]> namebuf(new char[len+1]);
814 
815     // Thread names are coming in like '<lldb.comm.debugger.edit>' and
816     // '<lldb.comm.debugger.editline>'.  So just chopping the end of the string
817     // off leads to a lot of similar named threads.  Go through the thread name
818     // and search for the last dot and use that.
819     const char *lastdot = ::strrchr (thread_name, '.');
820 
821     if (lastdot && lastdot != thread_name)
822         thread_name = lastdot + 1;
823     ::strncpy (namebuf.get(), thread_name, len);
824     namebuf[len] = 0;
825 
826     int namebuflen = strlen(namebuf.get());
827     if (namebuflen > 0)
828     {
829         if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
830         {
831             // Trim off trailing '(' and '>' characters for a bit more cleanup.
832             namebuflen--;
833             namebuf[namebuflen] = 0;
834         }
835         return Host::SetThreadName (pid, tid, namebuf.get());
836     }
837     return false;
838 }
839 
840 #endif
841 
842 FileSpec::PathSyntax
843 Host::GetHostPathSyntax()
844 {
845 #if defined(_WIN32)
846     return FileSpec::ePathSyntaxWindows;
847 #else
848     return FileSpec::ePathSyntaxPosix;
849 #endif
850 }
851 
852 FileSpec
853 Host::GetUserProfileFileSpec ()
854 {
855     static FileSpec g_profile_filespec;
856     if (!g_profile_filespec)
857     {
858         llvm::SmallString<64> path;
859         llvm::sys::path::home_directory(path);
860         return FileSpec(path.c_str(), false);
861     }
862     return g_profile_filespec;
863 }
864 
865 FileSpec
866 Host::GetProgramFileSpec ()
867 {
868     static FileSpec g_program_filespec;
869     if (!g_program_filespec)
870     {
871 #if defined (__APPLE__)
872         char program_fullpath[PATH_MAX];
873         // If DST is NULL, then return the number of bytes needed.
874         uint32_t len = sizeof(program_fullpath);
875         int err = _NSGetExecutablePath (program_fullpath, &len);
876         if (err == 0)
877             g_program_filespec.SetFile (program_fullpath, false);
878         else if (err == -1)
879         {
880             char *large_program_fullpath = (char *)::malloc (len + 1);
881 
882             err = _NSGetExecutablePath (large_program_fullpath, &len);
883             if (err == 0)
884                 g_program_filespec.SetFile (large_program_fullpath, false);
885 
886             ::free (large_program_fullpath);
887         }
888 #elif defined (__linux__)
889         char exe_path[PATH_MAX];
890         ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
891         if (len > 0) {
892             exe_path[len] = 0;
893             g_program_filespec.SetFile(exe_path, false);
894         }
895 #elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
896         int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
897         size_t exe_path_size;
898         if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
899         {
900             char *exe_path = new char[exe_path_size];
901             if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
902                 g_program_filespec.SetFile(exe_path, false);
903             delete[] exe_path;
904         }
905 #elif defined(_WIN32)
906         std::vector<char> buffer(PATH_MAX);
907         ::GetModuleFileName(NULL, &buffer[0], buffer.size());
908         g_program_filespec.SetFile(&buffer[0], false);
909 #endif
910     }
911     return g_program_filespec;
912 }
913 
914 #if !defined (__APPLE__) // see Host.mm
915 
916 bool
917 Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
918 {
919     bundle.Clear();
920     return false;
921 }
922 
923 bool
924 Host::ResolveExecutableInBundle (FileSpec &file)
925 {
926     return false;
927 }
928 #endif
929 
930 #ifndef _WIN32
931 
932 // Opaque info that tracks a dynamic library that was loaded
933 struct DynamicLibraryInfo
934 {
935     DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
936         file_spec (fs),
937         open_options (o),
938         handle (h)
939     {
940     }
941 
942     const FileSpec file_spec;
943     uint32_t open_options;
944     void * handle;
945 };
946 
947 void *
948 Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
949 {
950     char path[PATH_MAX];
951     if (file_spec.GetPath(path, sizeof(path)))
952     {
953         int mode = 0;
954 
955         if (options & eDynamicLibraryOpenOptionLazy)
956             mode |= RTLD_LAZY;
957         else
958             mode |= RTLD_NOW;
959 
960 
961         if (options & eDynamicLibraryOpenOptionLocal)
962             mode |= RTLD_LOCAL;
963         else
964             mode |= RTLD_GLOBAL;
965 
966 #ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
967         if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
968             mode |= RTLD_FIRST;
969 #endif
970 
971         void * opaque = ::dlopen (path, mode);
972 
973         if (opaque)
974         {
975             error.Clear();
976             return new DynamicLibraryInfo (file_spec, options, opaque);
977         }
978         else
979         {
980             error.SetErrorString(::dlerror());
981         }
982     }
983     else
984     {
985         error.SetErrorString("failed to extract path");
986     }
987     return NULL;
988 }
989 
990 Error
991 Host::DynamicLibraryClose (void *opaque)
992 {
993     Error error;
994     if (opaque == NULL)
995     {
996         error.SetErrorString ("invalid dynamic library handle");
997     }
998     else
999     {
1000         DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1001         if (::dlclose (dylib_info->handle) != 0)
1002         {
1003             error.SetErrorString(::dlerror());
1004         }
1005 
1006         dylib_info->open_options = 0;
1007         dylib_info->handle = 0;
1008         delete dylib_info;
1009     }
1010     return error;
1011 }
1012 
1013 void *
1014 Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
1015 {
1016     if (opaque == NULL)
1017     {
1018         error.SetErrorString ("invalid dynamic library handle");
1019     }
1020     else
1021     {
1022         DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1023 
1024         void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
1025         if (symbol_addr)
1026         {
1027 #ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
1028             // This host doesn't support limiting searches to this shared library
1029             // so we need to verify that the match came from this shared library
1030             // if it was requested in the Host::DynamicLibraryOpen() function.
1031             if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
1032             {
1033                 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
1034                 if (match_dylib_spec != dylib_info->file_spec)
1035                 {
1036                     char dylib_path[PATH_MAX];
1037                     if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
1038                         error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
1039                     else
1040                         error.SetErrorString ("symbol not found");
1041                     return NULL;
1042                 }
1043             }
1044 #endif
1045             error.Clear();
1046             return symbol_addr;
1047         }
1048         else
1049         {
1050             error.SetErrorString(::dlerror());
1051         }
1052     }
1053     return NULL;
1054 }
1055 
1056 FileSpec
1057 Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1058 {
1059     FileSpec module_filespec;
1060     Dl_info info;
1061     if (::dladdr (host_addr, &info))
1062     {
1063         if (info.dli_fname)
1064             module_filespec.SetFile(info.dli_fname, true);
1065     }
1066     return module_filespec;
1067 }
1068 
1069 #endif
1070 
1071 
1072 static void CleanupProcessSpecificLLDBTempDir ()
1073 {
1074     // Get the process specific LLDB temporary directory and delete it.
1075     FileSpec tmpdir_file_spec;
1076     if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1077     {
1078         // Remove the LLDB temporary directory if we have one. Set "recurse" to
1079         // true to all files that were created for the LLDB process can be cleaned up.
1080         const bool recurse = true;
1081         Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1082     }
1083 }
1084 
1085 bool
1086 Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1087 {
1088     // To get paths related to LLDB we get the path to the executable that
1089     // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1090     // on linux this is assumed to be the "lldb" main executable. If LLDB on
1091     // linux is actually in a shared library (liblldb.so) then this function will
1092     // need to be modified to "do the right thing".
1093     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
1094 
1095     switch (path_type)
1096     {
1097     case ePathTypeLLDBShlibDir:
1098         {
1099             static ConstString g_lldb_so_dir;
1100             if (!g_lldb_so_dir)
1101             {
1102                 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1103                     reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
1104                 g_lldb_so_dir = lldb_file_spec.GetDirectory();
1105                 if (log)
1106                     log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
1107             }
1108             file_spec.GetDirectory() = g_lldb_so_dir;
1109             return (bool)file_spec.GetDirectory();
1110         }
1111         break;
1112 
1113     case ePathTypeSupportExecutableDir:
1114         {
1115             static ConstString g_lldb_support_exe_dir;
1116             if (!g_lldb_support_exe_dir)
1117             {
1118                 FileSpec lldb_file_spec;
1119                 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1120                 {
1121                     char raw_path[PATH_MAX];
1122                     lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1123 
1124 #if defined (__APPLE__)
1125                     char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1126                     if (framework_pos)
1127                     {
1128                         framework_pos += strlen("LLDB.framework");
1129 #if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
1130                         // Shallow bundle
1131                         *framework_pos = '\0';
1132 #else
1133                         // Normal bundle
1134                         ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
1135 #endif
1136                     }
1137 #elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1138                     // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1139                     // helper exe programs.  This will fail if the /lib and /bin directories are rooted in entirely
1140                     // different trees.
1141                     if (log)
1142                         log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1143                     char *lib_pos = ::strstr (raw_path, "/lib");
1144                     if (lib_pos != nullptr)
1145                     {
1146                         // First terminate the raw path at the start of lib.
1147                         *lib_pos = '\0';
1148 
1149                         // Now write in bin in place of lib.
1150                         ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1151 
1152                         if (log)
1153                             log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1154                     }
1155                     else
1156                     {
1157                         if (log)
1158                             log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1159                     }
1160 #endif  // #if defined (__APPLE__)
1161                     llvm::SmallString<64> resolved_path(raw_path);
1162                     FileSpec::Resolve (resolved_path);
1163                     g_lldb_support_exe_dir.SetCString(resolved_path.c_str());
1164                 }
1165                 if (log)
1166                     log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
1167             }
1168             file_spec.GetDirectory() = g_lldb_support_exe_dir;
1169             return (bool)file_spec.GetDirectory();
1170         }
1171         break;
1172 
1173     case ePathTypeHeaderDir:
1174         {
1175             static ConstString g_lldb_headers_dir;
1176             if (!g_lldb_headers_dir)
1177             {
1178 #if defined (__APPLE__)
1179                 FileSpec lldb_file_spec;
1180                 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1181                 {
1182                     char raw_path[PATH_MAX];
1183                     lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1184 
1185                     char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1186                     if (framework_pos)
1187                     {
1188                         framework_pos += strlen("LLDB.framework");
1189                         ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1190                     }
1191                     llvm::SmallString<64> resolved_path(raw_path);
1192                     FileSpec::Resolve (resolved_path);
1193                     g_lldb_headers_dir.SetCString(resolved_path.c_str());
1194                 }
1195 #else
1196                 // TODO: Anyone know how we can determine this for linux? Other systems??
1197                 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1198 #endif
1199                 if (log)
1200                     log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
1201             }
1202             file_spec.GetDirectory() = g_lldb_headers_dir;
1203             return (bool)file_spec.GetDirectory();
1204         }
1205         break;
1206 
1207 #ifdef LLDB_DISABLE_PYTHON
1208     case ePathTypePythonDir:
1209         return false;
1210 #else
1211     case ePathTypePythonDir:
1212         {
1213             static ConstString g_lldb_python_dir;
1214             if (!g_lldb_python_dir)
1215             {
1216                 FileSpec lldb_file_spec;
1217                 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1218                 {
1219                     char raw_path[PATH_MAX];
1220 #if defined(_WIN32)
1221                     lldb_file_spec.AppendPathComponent("../lib/site-packages");
1222                     lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1223 #else
1224                     lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1225 
1226 #if defined (__APPLE__)
1227                     char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1228                     if (framework_pos)
1229                     {
1230                         framework_pos += strlen("LLDB.framework");
1231                         ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1232                     }
1233                     else
1234                     {
1235 #endif
1236                         llvm::SmallString<256> python_version_dir;
1237                         llvm::raw_svector_ostream os(python_version_dir);
1238                         os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1239                         os.flush();
1240 
1241                         // We may get our string truncated. Should we protect
1242                         // this with an assert?
1243 
1244                         ::strncat(raw_path, python_version_dir.c_str(),
1245                                   sizeof(raw_path) - strlen(raw_path) - 1);
1246 #endif
1247 #if defined (__APPLE__)
1248                     }
1249 #endif
1250                     llvm::SmallString<64> resolved_path(raw_path);
1251                     FileSpec::Resolve (resolved_path);
1252                     g_lldb_python_dir.SetCString(resolved_path.c_str());
1253                 }
1254 
1255                 if (log)
1256                     log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1257 
1258             }
1259             file_spec.GetDirectory() = g_lldb_python_dir;
1260             return (bool)file_spec.GetDirectory();
1261         }
1262         break;
1263 #endif
1264 
1265     case ePathTypeLLDBSystemPlugins:    // System plug-ins directory
1266         {
1267 #if defined (__APPLE__) || defined(__linux__)
1268             static ConstString g_lldb_system_plugin_dir;
1269             static bool g_lldb_system_plugin_dir_located = false;
1270             if (!g_lldb_system_plugin_dir_located)
1271             {
1272                 g_lldb_system_plugin_dir_located = true;
1273 #if defined (__APPLE__)
1274                 FileSpec lldb_file_spec;
1275                 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1276                 {
1277                     char raw_path[PATH_MAX];
1278                     lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1279 
1280                     char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1281                     if (framework_pos)
1282                     {
1283                         framework_pos += strlen("LLDB.framework");
1284                         ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
1285                         llvm::SmallString<64> resolved_path(raw_path);
1286                         FileSpec::Resolve (resolved_path);
1287                         g_lldb_system_plugin_dir.SetCString(resolved_path.c_str());
1288                     }
1289                     return false;
1290                 }
1291 #elif defined (__linux__)
1292                 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1293                 if (lldb_file_spec.Exists())
1294                 {
1295                     g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1296                 }
1297 #endif // __APPLE__ || __linux__
1298 
1299                 if (log)
1300                     log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1301 
1302             }
1303 
1304             if (g_lldb_system_plugin_dir)
1305             {
1306                 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1307                 return true;
1308             }
1309 #else
1310             // TODO: where would system LLDB plug-ins be located on other systems?
1311             return false;
1312 #endif
1313         }
1314         break;
1315 
1316     case ePathTypeLLDBUserPlugins:      // User plug-ins directory
1317         {
1318 #if defined (__APPLE__)
1319             static ConstString g_lldb_user_plugin_dir;
1320             if (!g_lldb_user_plugin_dir)
1321             {
1322                     llvm::SmallString<64> user_plugin_path("~/Library/Application Support/LLDB/PlugIns");
1323                     FileSpec::Resolve (user_plugin_path);
1324                 if (user_plugin_path.size())
1325                 {
1326                     g_lldb_user_plugin_dir.SetCString(user_plugin_path.c_str());
1327                 }
1328             }
1329             file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1330             return (bool)file_spec.GetDirectory();
1331 #elif defined (__linux__)
1332             static ConstString g_lldb_user_plugin_dir;
1333             if (!g_lldb_user_plugin_dir)
1334             {
1335                 // XDG Base Directory Specification
1336                 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1337                 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1338                 FileSpec lldb_file_spec;
1339                 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1340                 if (xdg_data_home && xdg_data_home[0])
1341                 {
1342                     std::string user_plugin_dir (xdg_data_home);
1343                     user_plugin_dir += "/lldb";
1344                     lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1345                 }
1346                 else
1347                 {
1348                     const char *home_dir = getenv("HOME");
1349                     if (home_dir && home_dir[0])
1350                     {
1351                         std::string user_plugin_dir (home_dir);
1352                         user_plugin_dir += "/.local/share/lldb";
1353                         lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1354                     }
1355                 }
1356 
1357                 if (lldb_file_spec.Exists())
1358                     g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1359                 if (log)
1360                     log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
1361             }
1362             file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1363             return (bool)file_spec.GetDirectory();
1364 #endif
1365             // TODO: where would user LLDB plug-ins be located on other systems?
1366             return false;
1367         }
1368 
1369     case ePathTypeLLDBTempSystemDir:
1370         {
1371             static ConstString g_lldb_tmp_dir;
1372             if (!g_lldb_tmp_dir)
1373             {
1374                 const char *tmpdir_cstr = getenv("TMPDIR");
1375                 if (tmpdir_cstr == NULL)
1376                 {
1377                     tmpdir_cstr = getenv("TMP");
1378                     if (tmpdir_cstr == NULL)
1379                         tmpdir_cstr = getenv("TEMP");
1380                 }
1381                 if (tmpdir_cstr)
1382                 {
1383                     StreamString pid_tmpdir;
1384                     pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1385                     if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1386                     {
1387                         pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1388                         if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1389                         {
1390                             // Make an atexit handler to clean up the process specify LLDB temp dir
1391                             // and all of its contents.
1392                             ::atexit (CleanupProcessSpecificLLDBTempDir);
1393                             g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1394                             if (log)
1395                                 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1396 
1397                         }
1398                     }
1399                 }
1400             }
1401             file_spec.GetDirectory() = g_lldb_tmp_dir;
1402             return (bool)file_spec.GetDirectory();
1403         }
1404     }
1405 
1406     return false;
1407 }
1408 
1409 
1410 bool
1411 Host::GetHostname (std::string &s)
1412 {
1413     char hostname[PATH_MAX];
1414     hostname[sizeof(hostname) - 1] = '\0';
1415     if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1416     {
1417         struct hostent* h = ::gethostbyname (hostname);
1418         if (h)
1419             s.assign (h->h_name);
1420         else
1421             s.assign (hostname);
1422         return true;
1423     }
1424     return false;
1425 }
1426 
1427 #ifndef _WIN32
1428 
1429 const char *
1430 Host::GetUserName (uint32_t uid, std::string &user_name)
1431 {
1432     struct passwd user_info;
1433     struct passwd *user_info_ptr = &user_info;
1434     char user_buffer[PATH_MAX];
1435     size_t user_buffer_size = sizeof(user_buffer);
1436     if (::getpwuid_r (uid,
1437                       &user_info,
1438                       user_buffer,
1439                       user_buffer_size,
1440                       &user_info_ptr) == 0)
1441     {
1442         if (user_info_ptr)
1443         {
1444             user_name.assign (user_info_ptr->pw_name);
1445             return user_name.c_str();
1446         }
1447     }
1448     user_name.clear();
1449     return NULL;
1450 }
1451 
1452 const char *
1453 Host::GetGroupName (uint32_t gid, std::string &group_name)
1454 {
1455     char group_buffer[PATH_MAX];
1456     size_t group_buffer_size = sizeof(group_buffer);
1457     struct group group_info;
1458     struct group *group_info_ptr = &group_info;
1459     // Try the threadsafe version first
1460     if (::getgrgid_r (gid,
1461                       &group_info,
1462                       group_buffer,
1463                       group_buffer_size,
1464                       &group_info_ptr) == 0)
1465     {
1466         if (group_info_ptr)
1467         {
1468             group_name.assign (group_info_ptr->gr_name);
1469             return group_name.c_str();
1470         }
1471     }
1472     else
1473     {
1474         // The threadsafe version isn't currently working
1475         // for me on darwin, but the non-threadsafe version
1476         // is, so I am calling it below.
1477         group_info_ptr = ::getgrgid (gid);
1478         if (group_info_ptr)
1479         {
1480             group_name.assign (group_info_ptr->gr_name);
1481             return group_name.c_str();
1482         }
1483     }
1484     group_name.clear();
1485     return NULL;
1486 }
1487 
1488 uint32_t
1489 Host::GetUserID ()
1490 {
1491     return getuid();
1492 }
1493 
1494 uint32_t
1495 Host::GetGroupID ()
1496 {
1497     return getgid();
1498 }
1499 
1500 uint32_t
1501 Host::GetEffectiveUserID ()
1502 {
1503     return geteuid();
1504 }
1505 
1506 uint32_t
1507 Host::GetEffectiveGroupID ()
1508 {
1509     return getegid();
1510 }
1511 
1512 #endif
1513 
1514 #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1515 bool
1516 Host::GetOSBuildString (std::string &s)
1517 {
1518     s.clear();
1519     return false;
1520 }
1521 
1522 bool
1523 Host::GetOSKernelDescription (std::string &s)
1524 {
1525     s.clear();
1526     return false;
1527 }
1528 #endif
1529 
1530 #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1531     && !defined(__linux__) && !defined(_WIN32)
1532 uint32_t
1533 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
1534 {
1535     process_infos.Clear();
1536     return process_infos.GetSize();
1537 }
1538 
1539 bool
1540 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
1541 {
1542     process_info.Clear();
1543     return false;
1544 }
1545 #endif
1546 
1547 #if !defined(__linux__)
1548 bool
1549 Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1550 {
1551     return false;
1552 }
1553 #endif
1554 
1555 lldb::TargetSP
1556 Host::GetDummyTarget (lldb_private::Debugger &debugger)
1557 {
1558     static TargetSP g_dummy_target_sp;
1559 
1560     // FIXME: Maybe the dummy target should be per-Debugger
1561     if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1562     {
1563         ArchSpec arch(Target::GetDefaultArchitecture());
1564         if (!arch.IsValid())
1565             arch = Host::GetArchitecture ();
1566         Error err = debugger.GetTargetList().CreateTarget(debugger,
1567                                                           NULL,
1568                                                           arch.GetTriple().getTriple().c_str(),
1569                                                           false,
1570                                                           NULL,
1571                                                           g_dummy_target_sp);
1572     }
1573 
1574     return g_dummy_target_sp;
1575 }
1576 
1577 struct ShellInfo
1578 {
1579     ShellInfo () :
1580         process_reaped (false),
1581         can_delete (false),
1582         pid (LLDB_INVALID_PROCESS_ID),
1583         signo(-1),
1584         status(-1)
1585     {
1586     }
1587 
1588     lldb_private::Predicate<bool> process_reaped;
1589     lldb_private::Predicate<bool> can_delete;
1590     lldb::pid_t pid;
1591     int signo;
1592     int status;
1593 };
1594 
1595 static bool
1596 MonitorShellCommand (void *callback_baton,
1597                      lldb::pid_t pid,
1598                      bool exited,       // True if the process did exit
1599                      int signo,         // Zero for no signal
1600                      int status)   // Exit value of process if signal is zero
1601 {
1602     ShellInfo *shell_info = (ShellInfo *)callback_baton;
1603     shell_info->pid = pid;
1604     shell_info->signo = signo;
1605     shell_info->status = status;
1606     // Let the thread running Host::RunShellCommand() know that the process
1607     // exited and that ShellInfo has been filled in by broadcasting to it
1608     shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1609     // Now wait for a handshake back from that thread running Host::RunShellCommand
1610     // so we know that we can delete shell_info_ptr
1611     shell_info->can_delete.WaitForValueEqualTo(true);
1612     // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1613     usleep(1000);
1614     // Now delete the shell info that was passed into this function
1615     delete shell_info;
1616     return true;
1617 }
1618 
1619 Error
1620 Host::RunShellCommand (const char *command,
1621                        const char *working_dir,
1622                        int *status_ptr,
1623                        int *signo_ptr,
1624                        std::string *command_output_ptr,
1625                        uint32_t timeout_sec,
1626                        const char *shell)
1627 {
1628     Error error;
1629     ProcessLaunchInfo launch_info;
1630     if (shell && shell[0])
1631     {
1632         // Run the command in a shell
1633         launch_info.SetShell(shell);
1634         launch_info.GetArguments().AppendArgument(command);
1635         const bool localhost = true;
1636         const bool will_debug = false;
1637         const bool first_arg_is_full_shell_command = true;
1638         launch_info.ConvertArgumentsForLaunchingInShell (error,
1639                                                          localhost,
1640                                                          will_debug,
1641                                                          first_arg_is_full_shell_command,
1642                                                          0);
1643     }
1644     else
1645     {
1646         // No shell, just run it
1647         Args args (command);
1648         const bool first_arg_is_executable = true;
1649         launch_info.SetArguments(args, first_arg_is_executable);
1650     }
1651 
1652     if (working_dir)
1653         launch_info.SetWorkingDirectory(working_dir);
1654     char output_file_path_buffer[PATH_MAX];
1655     const char *output_file_path = NULL;
1656 
1657     if (command_output_ptr)
1658     {
1659         // Create a temporary file to get the stdout/stderr and redirect the
1660         // output of the command into this file. We will later read this file
1661         // if all goes well and fill the data into "command_output_ptr"
1662         FileSpec tmpdir_file_spec;
1663         if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1664         {
1665             tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1666             strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1667         }
1668         else
1669         {
1670             strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1671         }
1672 
1673         output_file_path = ::mktemp(output_file_path_buffer);
1674     }
1675 
1676     launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1677     if (output_file_path)
1678     {
1679         launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
1680         launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
1681     }
1682     else
1683     {
1684         launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1685         launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1686     }
1687 
1688     // The process monitor callback will delete the 'shell_info_ptr' below...
1689     std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
1690 
1691     const bool monitor_signals = false;
1692     launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1693 
1694     error = LaunchProcess (launch_info);
1695     const lldb::pid_t pid = launch_info.GetProcessID();
1696 
1697     if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1698         error.SetErrorString("failed to get process ID");
1699 
1700     if (error.Success())
1701     {
1702         // The process successfully launched, so we can defer ownership of
1703         // "shell_info" to the MonitorShellCommand callback function that will
1704         // get called when the process dies. We release the unique pointer as it
1705         // doesn't need to delete the ShellInfo anymore.
1706         ShellInfo *shell_info = shell_info_ap.release();
1707         TimeValue *timeout_ptr = nullptr;
1708         TimeValue timeout_time(TimeValue::Now());
1709         if (timeout_sec > 0) {
1710             timeout_time.OffsetWithSeconds(timeout_sec);
1711             timeout_ptr = &timeout_time;
1712         }
1713         bool timed_out = false;
1714         shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
1715         if (timed_out)
1716         {
1717             error.SetErrorString("timed out waiting for shell command to complete");
1718 
1719             // Kill the process since it didn't complete within the timeout specified
1720             Kill (pid, SIGKILL);
1721             // Wait for the monitor callback to get the message
1722             timeout_time = TimeValue::Now();
1723             timeout_time.OffsetWithSeconds(1);
1724             timed_out = false;
1725             shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1726         }
1727         else
1728         {
1729             if (status_ptr)
1730                 *status_ptr = shell_info->status;
1731 
1732             if (signo_ptr)
1733                 *signo_ptr = shell_info->signo;
1734 
1735             if (command_output_ptr)
1736             {
1737                 command_output_ptr->clear();
1738                 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1739                 uint64_t file_size = file_spec.GetByteSize();
1740                 if (file_size > 0)
1741                 {
1742                     if (file_size > command_output_ptr->max_size())
1743                     {
1744                         error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1745                     }
1746                     else
1747                     {
1748                         command_output_ptr->resize(file_size);
1749                         file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1750                     }
1751                 }
1752             }
1753         }
1754         shell_info->can_delete.SetValue(true, eBroadcastAlways);
1755     }
1756 
1757     if (output_file_path)
1758         ::unlink (output_file_path);
1759     // Handshake with the monitor thread, or just let it know in advance that
1760     // it can delete "shell_info" in case we timed out and were not able to kill
1761     // the process...
1762     return error;
1763 }
1764 
1765 
1766 // LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1767 // systems
1768 
1769 #if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
1770 
1771 // this method needs to be visible to macosx/Host.cpp and
1772 // common/Host.cpp.
1773 
1774 short
1775 Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1776 {
1777     short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1778 
1779 #if defined (__APPLE__)
1780     if (launch_info.GetFlags().Test (eLaunchFlagExec))
1781         flags |= POSIX_SPAWN_SETEXEC;           // Darwin specific posix_spawn flag
1782 
1783     if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1784         flags |= POSIX_SPAWN_START_SUSPENDED;   // Darwin specific posix_spawn flag
1785 
1786     if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1787         flags |= _POSIX_SPAWN_DISABLE_ASLR;     // Darwin specific posix_spawn flag
1788 
1789     if (launch_info.GetLaunchInSeparateProcessGroup())
1790         flags |= POSIX_SPAWN_SETPGROUP;
1791 
1792 #ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1793 #if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1794     static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1795     if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1796     {
1797         g_use_close_on_exec_flag = eLazyBoolNo;
1798 
1799         uint32_t major, minor, update;
1800         if (Host::GetOSVersion(major, minor, update))
1801         {
1802             // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1803             if (major > 10 || (major == 10 && minor > 7))
1804             {
1805                 // Only enable for 10.8 and later OS versions
1806                 g_use_close_on_exec_flag = eLazyBoolYes;
1807             }
1808         }
1809     }
1810 #else
1811     static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1812 #endif
1813     // Close all files exception those with file actions if this is supported.
1814     if (g_use_close_on_exec_flag == eLazyBoolYes)
1815         flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1816 #endif
1817 #endif // #if defined (__APPLE__)
1818     return flags;
1819 }
1820 
1821 Error
1822 Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1823 {
1824     Error error;
1825     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1826 
1827     posix_spawnattr_t attr;
1828     error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1829 
1830     if (error.Fail() || log)
1831         error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
1832     if (error.Fail())
1833         return error;
1834 
1835     // Make a quick class that will cleanup the posix spawn attributes in case
1836     // we return in the middle of this function.
1837     lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1838 
1839     sigset_t no_signals;
1840     sigset_t all_signals;
1841     sigemptyset (&no_signals);
1842     sigfillset (&all_signals);
1843     ::posix_spawnattr_setsigmask(&attr, &no_signals);
1844 #if defined (__linux__)  || defined (__FreeBSD__)
1845     ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1846 #else
1847     ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1848 #endif
1849 
1850     short flags = GetPosixspawnFlags(launch_info);
1851 
1852     error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1853     if (error.Fail() || log)
1854         error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1855     if (error.Fail())
1856         return error;
1857 
1858     // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1859     // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1860 #if defined (__APPLE__) && !defined (__arm__)
1861 
1862     // Don't set the binpref if a shell was provided.  After all, that's only going to affect what version of the shell
1863     // is launched, not what fork of the binary is launched.  We insert "arch --arch <ARCH> as part of the shell invocation
1864     // to do that job on OSX.
1865 
1866     if (launch_info.GetShell() == nullptr)
1867     {
1868         // We don't need to do this for ARM, and we really shouldn't now that we
1869         // have multiple CPU subtypes and no posix_spawnattr call that allows us
1870         // to set which CPU subtype to launch...
1871         const ArchSpec &arch_spec = launch_info.GetArchitecture();
1872         cpu_type_t cpu = arch_spec.GetMachOCPUType();
1873         cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1874         if (cpu != 0 &&
1875             cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1876             cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
1877             !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1878         {
1879             size_t ocount = 0;
1880             error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1881             if (error.Fail() || log)
1882                 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu, (uint64_t)ocount);
1883 
1884             if (error.Fail() || ocount != 1)
1885                 return error;
1886         }
1887     }
1888 
1889 #endif
1890 
1891     const char *tmp_argv[2];
1892     char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1893     char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1894     if (argv == NULL)
1895     {
1896         // posix_spawn gets very unhappy if it doesn't have at least the program
1897         // name in argv[0]. One of the side affects I have noticed is the environment
1898         // variables don't make it into the child process if "argv == NULL"!!!
1899         tmp_argv[0] = exe_path;
1900         tmp_argv[1] = NULL;
1901         argv = (char * const*)tmp_argv;
1902     }
1903 
1904 #if !defined (__APPLE__)
1905     // manage the working directory
1906     char current_dir[PATH_MAX];
1907     current_dir[0] = '\0';
1908 #endif
1909 
1910     const char *working_dir = launch_info.GetWorkingDirectory();
1911     if (working_dir)
1912     {
1913 #if defined (__APPLE__)
1914         // Set the working directory on this thread only
1915         if (__pthread_chdir (working_dir) < 0) {
1916             if (errno == ENOENT) {
1917                 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1918             } else if (errno == ENOTDIR) {
1919                 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1920             } else {
1921                 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1922             }
1923             return error;
1924         }
1925 #else
1926         if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1927         {
1928             error.SetError(errno, eErrorTypePOSIX);
1929             error.LogIfError(log, "unable to save the current directory");
1930             return error;
1931         }
1932 
1933         if (::chdir(working_dir) == -1)
1934         {
1935             error.SetError(errno, eErrorTypePOSIX);
1936             error.LogIfError(log, "unable to change working directory to %s", working_dir);
1937             return error;
1938         }
1939 #endif
1940     }
1941 
1942     const size_t num_file_actions = launch_info.GetNumFileActions ();
1943     if (num_file_actions > 0)
1944     {
1945         posix_spawn_file_actions_t file_actions;
1946         error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1947         if (error.Fail() || log)
1948             error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1949         if (error.Fail())
1950             return error;
1951 
1952         // Make a quick class that will cleanup the posix spawn attributes in case
1953         // we return in the middle of this function.
1954         lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1955 
1956         for (size_t i=0; i<num_file_actions; ++i)
1957         {
1958             const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1959             if (launch_file_action)
1960             {
1961                 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1962                                                                              launch_file_action,
1963                                                                              log,
1964                                                                              error))
1965                     return error;
1966             }
1967         }
1968 
1969         error.SetError (::posix_spawnp (&pid,
1970                                         exe_path,
1971                                         &file_actions,
1972                                         &attr,
1973                                         argv,
1974                                         envp),
1975                         eErrorTypePOSIX);
1976 
1977         if (error.Fail() || log)
1978         {
1979             error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1980                            pid, exe_path, static_cast<void*>(&file_actions),
1981                            static_cast<void*>(&attr),
1982                            reinterpret_cast<const void*>(argv),
1983                            reinterpret_cast<const void*>(envp));
1984             if (log)
1985             {
1986                 for (int ii=0; argv[ii]; ++ii)
1987                     log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1988             }
1989         }
1990 
1991     }
1992     else
1993     {
1994         error.SetError (::posix_spawnp (&pid,
1995                                         exe_path,
1996                                         NULL,
1997                                         &attr,
1998                                         argv,
1999                                         envp),
2000                         eErrorTypePOSIX);
2001 
2002         if (error.Fail() || log)
2003         {
2004             error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
2005                            pid, exe_path, static_cast<void*>(&attr),
2006                            reinterpret_cast<const void*>(argv),
2007                            reinterpret_cast<const void*>(envp));
2008             if (log)
2009             {
2010                 for (int ii=0; argv[ii]; ++ii)
2011                     log->Printf("argv[%i] = '%s'", ii, argv[ii]);
2012             }
2013         }
2014     }
2015 
2016     if (working_dir)
2017     {
2018 #if defined (__APPLE__)
2019         // No more thread specific current working directory
2020         __pthread_fchdir (-1);
2021 #else
2022         if (::chdir(current_dir) == -1 && error.Success())
2023         {
2024             error.SetError(errno, eErrorTypePOSIX);
2025             error.LogIfError(log, "unable to change current directory back to %s",
2026                     current_dir);
2027         }
2028 #endif
2029     }
2030 
2031     return error;
2032 }
2033 
2034 #endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2035 
2036 
2037 #if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2038 // The functions below implement process launching via posix_spawn() for Linux,
2039 // FreeBSD and NetBSD.
2040 
2041 Error
2042 Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2043 {
2044     Error error;
2045     char exe_path[PATH_MAX];
2046 
2047     PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2048 
2049     const ArchSpec &arch_spec = launch_info.GetArchitecture();
2050 
2051     FileSpec exe_spec(launch_info.GetExecutableFile());
2052 
2053     FileSpec::FileType file_type = exe_spec.GetFileType();
2054     if (file_type != FileSpec::eFileTypeRegular)
2055     {
2056         lldb::ModuleSP exe_module_sp;
2057         error = host_platform_sp->ResolveExecutable (exe_spec,
2058                                                      arch_spec,
2059                                                      exe_module_sp,
2060                                                      NULL);
2061 
2062         if (error.Fail())
2063             return error;
2064 
2065         if (exe_module_sp)
2066             exe_spec = exe_module_sp->GetFileSpec();
2067     }
2068 
2069     if (exe_spec.Exists())
2070     {
2071         exe_spec.GetPath (exe_path, sizeof(exe_path));
2072     }
2073     else
2074     {
2075         launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2076         error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2077         return error;
2078     }
2079 
2080     assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2081 
2082     ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2083 
2084     error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2085 
2086     if (pid != LLDB_INVALID_PROCESS_ID)
2087     {
2088         // If all went well, then set the process ID into the launch info
2089         launch_info.SetProcessID(pid);
2090 
2091         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2092 
2093         // Make sure we reap any processes we spawn or we will have zombies.
2094         if (!launch_info.MonitorProcess())
2095         {
2096             const bool monitor_signals = false;
2097             StartMonitoringChildProcess (Process::SetProcessExitStatus,
2098                                          NULL,
2099                                          pid,
2100                                          monitor_signals);
2101             if (log)
2102                 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2103         }
2104         else
2105         {
2106             if (log)
2107                 log->PutCString ("monitored child process with user-specified process monitor.");
2108         }
2109     }
2110     else
2111     {
2112         // Invalid process ID, something didn't go well
2113         if (error.Success())
2114             error.SetErrorString ("process launch failed for unknown reasons");
2115     }
2116     return error;
2117 }
2118 
2119 #endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
2120 
2121 #ifndef _WIN32
2122 
2123 size_t
2124 Host::GetPageSize()
2125 {
2126     return ::getpagesize();
2127 }
2128 
2129 uint32_t
2130 Host::GetNumberCPUS ()
2131 {
2132     static uint32_t g_num_cores = UINT32_MAX;
2133     if (g_num_cores == UINT32_MAX)
2134     {
2135 #if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
2136 
2137         g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
2138 
2139 #else
2140 
2141         // Assume POSIX support if a host specific case has not been supplied above
2142         g_num_cores = 0;
2143         int num_cores = 0;
2144         size_t num_cores_len = sizeof(num_cores);
2145 #ifdef HW_AVAILCPU
2146         int mib[] = { CTL_HW, HW_AVAILCPU };
2147 #else
2148         int mib[] = { CTL_HW, HW_NCPU };
2149 #endif
2150 
2151         /* get the number of CPUs from the system */
2152         if (sysctl(mib, llvm::array_lengthof(mib), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
2153         {
2154             g_num_cores = num_cores;
2155         }
2156         else
2157         {
2158             mib[1] = HW_NCPU;
2159             num_cores_len = sizeof(num_cores);
2160             if (sysctl(mib, llvm::array_lengthof(mib), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
2161             {
2162                 if (num_cores > 0)
2163                     g_num_cores = num_cores;
2164             }
2165         }
2166 #endif
2167     }
2168     return g_num_cores;
2169 }
2170 
2171 void
2172 Host::Kill(lldb::pid_t pid, int signo)
2173 {
2174     ::kill(pid, signo);
2175 }
2176 
2177 #endif
2178 
2179 #if !defined (__APPLE__)
2180 bool
2181 Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
2182 {
2183     return false;
2184 }
2185 
2186 void
2187 Host::SetCrashDescriptionWithFormat (const char *format, ...)
2188 {
2189 }
2190 
2191 void
2192 Host::SetCrashDescription (const char *description)
2193 {
2194 }
2195 
2196 lldb::pid_t
2197 Host::LaunchApplication (const FileSpec &app_file_spec)
2198 {
2199     return LLDB_INVALID_PROCESS_ID;
2200 }
2201 
2202 #endif
2203 
2204 
2205 #if !defined(_WIN32)
2206 Error
2207 Host::MakeDirectory (const char* path, uint32_t file_permissions)
2208 {
2209     Error error;
2210     if (path && path[0])
2211     {
2212         if (::mkdir(path, file_permissions) != 0)
2213         {
2214             error.SetErrorToErrno();
2215             switch (error.GetError())
2216             {
2217             case ENOENT:
2218                 {
2219                     // Parent directory doesn't exist, so lets make it if we can
2220                     FileSpec spec(path, false);
2221                     if (spec.GetDirectory() && spec.GetFilename())
2222                     {
2223                         // Make the parent directory and try again
2224                         Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2225                         if (error2.Success())
2226                         {
2227                             // Try and make the directory again now that the parent directory was made successfully
2228                             if (::mkdir(path, file_permissions) == 0)
2229                                 error.Clear();
2230                             else
2231                                 error.SetErrorToErrno();
2232                         }
2233                     }
2234                 }
2235                 break;
2236             case EEXIST:
2237                 {
2238                     FileSpec path_spec(path, false);
2239                     if (path_spec.IsDirectory())
2240                         error.Clear(); // It is a directory and it already exists
2241                 }
2242                 break;
2243             }
2244         }
2245     }
2246     else
2247     {
2248         error.SetErrorString("empty path");
2249     }
2250     return error;
2251 }
2252 
2253 Error
2254 Host::RemoveDirectory (const char* path, bool recurse)
2255 {
2256     Error error;
2257     if (path && path[0])
2258     {
2259         if (recurse)
2260         {
2261             StreamString command;
2262             command.Printf("rm -rf \"%s\"", path);
2263             int status = ::system(command.GetString().c_str());
2264             if (status != 0)
2265                 error.SetError(status, eErrorTypeGeneric);
2266         }
2267         else
2268         {
2269             if (::rmdir(path) != 0)
2270                 error.SetErrorToErrno();
2271         }
2272     }
2273     else
2274     {
2275         error.SetErrorString("empty path");
2276     }
2277     return error;
2278 }
2279 
2280 Error
2281 Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2282 {
2283     Error error;
2284     struct stat file_stats;
2285     if (::stat (path, &file_stats) == 0)
2286     {
2287         // The bits in "st_mode" currently match the definitions
2288         // for the file mode bits in unix.
2289         file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2290     }
2291     else
2292     {
2293         error.SetErrorToErrno();
2294     }
2295     return error;
2296 }
2297 
2298 Error
2299 Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2300 {
2301     Error error;
2302     if (::chmod(path, file_permissions) != 0)
2303         error.SetErrorToErrno();
2304     return error;
2305 }
2306 
2307 Error
2308 Host::Symlink (const char *src, const char *dst)
2309 {
2310     Error error;
2311     if (::symlink(dst, src) == -1)
2312         error.SetErrorToErrno();
2313     return error;
2314 }
2315 
2316 Error
2317 Host::Unlink (const char *path)
2318 {
2319     Error error;
2320     if (::unlink(path) == -1)
2321         error.SetErrorToErrno();
2322     return error;
2323 }
2324 
2325 Error
2326 Host::Readlink (const char *path, char *buf, size_t buf_len)
2327 {
2328     Error error;
2329     ssize_t count = ::readlink(path, buf, buf_len);
2330     if (count < 0)
2331         error.SetErrorToErrno();
2332     else if (static_cast<size_t>(count) < (buf_len-1))
2333         buf[count] = '\0'; // Success
2334     else
2335         error.SetErrorString("'buf' buffer is too small to contain link contents");
2336     return error;
2337 }
2338 
2339 
2340 #endif
2341 
2342 typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2343 FDToFileMap& GetFDToFileMap()
2344 {
2345     static FDToFileMap g_fd2filemap;
2346     return g_fd2filemap;
2347 }
2348 
2349 lldb::user_id_t
2350 Host::OpenFile (const FileSpec& file_spec,
2351                 uint32_t flags,
2352                 uint32_t mode,
2353                 Error &error)
2354 {
2355     std::string path (file_spec.GetPath());
2356     if (path.empty())
2357     {
2358         error.SetErrorString("empty path");
2359         return UINT64_MAX;
2360     }
2361     FileSP file_sp(new File());
2362     error = file_sp->Open(path.c_str(),flags,mode);
2363     if (file_sp->IsValid() == false)
2364         return UINT64_MAX;
2365     lldb::user_id_t fd = file_sp->GetDescriptor();
2366     GetFDToFileMap()[fd] = file_sp;
2367     return fd;
2368 }
2369 
2370 bool
2371 Host::CloseFile (lldb::user_id_t fd, Error &error)
2372 {
2373     if (fd == UINT64_MAX)
2374     {
2375         error.SetErrorString ("invalid file descriptor");
2376         return false;
2377     }
2378     FDToFileMap& file_map = GetFDToFileMap();
2379     FDToFileMap::iterator pos = file_map.find(fd);
2380     if (pos == file_map.end())
2381     {
2382         error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2383         return false;
2384     }
2385     FileSP file_sp = pos->second;
2386     if (!file_sp)
2387     {
2388         error.SetErrorString ("invalid host backing file");
2389         return false;
2390     }
2391     error = file_sp->Close();
2392     file_map.erase(pos);
2393     return error.Success();
2394 }
2395 
2396 uint64_t
2397 Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2398 {
2399     if (fd == UINT64_MAX)
2400     {
2401         error.SetErrorString ("invalid file descriptor");
2402         return UINT64_MAX;
2403     }
2404     FDToFileMap& file_map = GetFDToFileMap();
2405     FDToFileMap::iterator pos = file_map.find(fd);
2406     if (pos == file_map.end())
2407     {
2408         error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2409         return false;
2410     }
2411     FileSP file_sp = pos->second;
2412     if (!file_sp)
2413     {
2414         error.SetErrorString ("invalid host backing file");
2415         return UINT64_MAX;
2416     }
2417     if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2418         error.Fail())
2419         return UINT64_MAX;
2420     size_t bytes_written = src_len;
2421     error = file_sp->Write(src, bytes_written);
2422     if (error.Fail())
2423         return UINT64_MAX;
2424     return bytes_written;
2425 }
2426 
2427 uint64_t
2428 Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2429 {
2430     if (fd == UINT64_MAX)
2431     {
2432         error.SetErrorString ("invalid file descriptor");
2433         return UINT64_MAX;
2434     }
2435     FDToFileMap& file_map = GetFDToFileMap();
2436     FDToFileMap::iterator pos = file_map.find(fd);
2437     if (pos == file_map.end())
2438     {
2439         error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2440         return false;
2441     }
2442     FileSP file_sp = pos->second;
2443     if (!file_sp)
2444     {
2445         error.SetErrorString ("invalid host backing file");
2446         return UINT64_MAX;
2447     }
2448     if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2449         error.Fail())
2450         return UINT64_MAX;
2451     size_t bytes_read = dst_len;
2452     error = file_sp->Read(dst ,bytes_read);
2453     if (error.Fail())
2454         return UINT64_MAX;
2455     return bytes_read;
2456 }
2457 
2458 lldb::user_id_t
2459 Host::GetFileSize (const FileSpec& file_spec)
2460 {
2461     return file_spec.GetByteSize();
2462 }
2463 
2464 bool
2465 Host::GetFileExists (const FileSpec& file_spec)
2466 {
2467     return file_spec.Exists();
2468 }
2469 
2470 bool
2471 Host::CalculateMD5 (const FileSpec& file_spec,
2472                     uint64_t &low,
2473                     uint64_t &high)
2474 {
2475 #if defined (__APPLE__)
2476     StreamString md5_cmd_line;
2477     md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2478     std::string hash_string;
2479     Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2480     if (err.Fail())
2481         return false;
2482     // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2483     // if the output is any other length it is probably wrong
2484     if (hash_string.size() != 32)
2485         return false;
2486     std::string part1(hash_string,0,16);
2487     std::string part2(hash_string,16);
2488     const char* part1_cstr = part1.c_str();
2489     const char* part2_cstr = part2.c_str();
2490     high = ::strtoull(part1_cstr, NULL, 16);
2491     low = ::strtoull(part2_cstr, NULL, 16);
2492     return true;
2493 #else
2494     // your own MD5 implementation here
2495     return false;
2496 #endif
2497 }
2498