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