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 // C includes
11 #include <errno.h>
12 #include <limits.h>
13 #include <stdlib.h>
14 #include <sys/types.h>
15 #ifndef _WIN32
16 #include <unistd.h>
17 #include <dlfcn.h>
18 #include <grp.h>
19 #include <netdb.h>
20 #include <pwd.h>
21 #include <sys/stat.h>
22 #endif
23 
24 #if defined (__APPLE__)
25 #include <mach/mach_port.h>
26 #include <mach/mach_init.h>
27 #include <mach-o/dyld.h>
28 #endif
29 
30 #if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
31 #if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
32 #include <spawn.h>
33 #endif
34 #include <sys/wait.h>
35 #include <sys/syscall.h>
36 #endif
37 
38 #if defined (__FreeBSD__)
39 #include <pthread_np.h>
40 #endif
41 
42 // C++ includes
43 #include <limits>
44 
45 #include "lldb/Host/FileSystem.h"
46 #include "lldb/Host/Host.h"
47 #include "lldb/Host/HostInfo.h"
48 #include "lldb/Core/ArchSpec.h"
49 #include "lldb/Core/Error.h"
50 #include "lldb/Core/Log.h"
51 #include "lldb/Host/FileSpec.h"
52 #include "lldb/Host/HostProcess.h"
53 #include "lldb/Host/MonitoringProcessLauncher.h"
54 #include "lldb/Host/Predicate.h"
55 #include "lldb/Host/ProcessLauncher.h"
56 #include "lldb/Host/ThreadLauncher.h"
57 #include "lldb/lldb-private-forward.h"
58 #include "llvm/Support/FileSystem.h"
59 #include "lldb/Target/FileAction.h"
60 #include "lldb/Target/ProcessLaunchInfo.h"
61 #include "lldb/Target/UnixSignals.h"
62 #include "lldb/Utility/CleanUp.h"
63 #include "llvm/ADT/SmallString.h"
64 
65 #if defined(_WIN32)
66 #include "lldb/Host/windows/ProcessLauncherWindows.h"
67 #elif defined(__ANDROID__) || defined(__ANDROID_NDK__)
68 #include "lldb/Host/android/ProcessLauncherAndroid.h"
69 #else
70 #include "lldb/Host/posix/ProcessLauncherPosix.h"
71 #endif
72 
73 #if defined (__APPLE__)
74 #ifndef _POSIX_SPAWN_DISABLE_ASLR
75 #define _POSIX_SPAWN_DISABLE_ASLR       0x0100
76 #endif
77 
78 extern "C"
79 {
80     int __pthread_chdir(const char *path);
81     int __pthread_fchdir (int fildes);
82 }
83 
84 #endif
85 
86 using namespace lldb;
87 using namespace lldb_private;
88 
89 #if !defined (__APPLE__) && !defined (_WIN32)
90 struct MonitorInfo
91 {
92     lldb::pid_t pid;                            // The process ID to monitor
93     Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
94     void *callback_baton;                       // The callback baton for the callback function
95     bool monitor_signals;                       // If true, call the callback when "pid" gets signaled.
96 };
97 
98 static thread_result_t
99 MonitorChildProcessThreadFunction (void *arg);
100 
101 HostThread
102 Host::StartMonitoringChildProcess(Host::MonitorChildProcessCallback callback, void *callback_baton, lldb::pid_t pid, bool monitor_signals)
103 {
104     MonitorInfo * info_ptr = new MonitorInfo();
105 
106     info_ptr->pid = pid;
107     info_ptr->callback = callback;
108     info_ptr->callback_baton = callback_baton;
109     info_ptr->monitor_signals = monitor_signals;
110 
111     char thread_name[256];
112     ::snprintf(thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
113     return ThreadLauncher::LaunchThread(thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL);
114 }
115 
116 #ifndef __linux__
117 //------------------------------------------------------------------
118 // Scoped class that will disable thread canceling when it is
119 // constructed, and exception safely restore the previous value it
120 // when it goes out of scope.
121 //------------------------------------------------------------------
122 class ScopedPThreadCancelDisabler
123 {
124 public:
125     ScopedPThreadCancelDisabler()
126     {
127         // Disable the ability for this thread to be cancelled
128         int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
129         if (err != 0)
130             m_old_state = -1;
131     }
132 
133     ~ScopedPThreadCancelDisabler()
134     {
135         // Restore the ability for this thread to be cancelled to what it
136         // previously was.
137         if (m_old_state != -1)
138             ::pthread_setcancelstate (m_old_state, 0);
139     }
140 private:
141     int m_old_state;    // Save the old cancelability state.
142 };
143 #endif // __linux__
144 
145 #ifdef __linux__
146 static thread_local volatile sig_atomic_t g_usr1_called;
147 
148 static void
149 SigUsr1Handler (int)
150 {
151     g_usr1_called = 1;
152 }
153 #endif // __linux__
154 
155 static bool
156 CheckForMonitorCancellation()
157 {
158 #ifdef __linux__
159     if (g_usr1_called)
160     {
161         g_usr1_called = 0;
162         return true;
163     }
164 #else
165     ::pthread_testcancel ();
166 #endif
167     return false;
168 }
169 
170 static thread_result_t
171 MonitorChildProcessThreadFunction (void *arg)
172 {
173     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
174     const char *function = __FUNCTION__;
175     if (log)
176         log->Printf ("%s (arg = %p) thread starting...", function, arg);
177 
178     MonitorInfo *info = (MonitorInfo *)arg;
179 
180     const Host::MonitorChildProcessCallback callback = info->callback;
181     void * const callback_baton = info->callback_baton;
182     const bool monitor_signals = info->monitor_signals;
183 
184     assert (info->pid <= UINT32_MAX);
185     const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
186 
187     delete info;
188 
189     int status = -1;
190 #if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
191     #define __WALL 0
192 #endif
193     const int options = __WALL;
194 
195 #ifdef __linux__
196     // This signal is only used to interrupt the thread from waitpid
197     struct sigaction sigUsr1Action;
198     memset(&sigUsr1Action, 0, sizeof(sigUsr1Action));
199     sigUsr1Action.sa_handler = SigUsr1Handler;
200     ::sigaction(SIGUSR1, &sigUsr1Action, nullptr);
201 #endif // __linux__
202 
203     while (1)
204     {
205         log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
206         if (log)
207             log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
208 
209         if (CheckForMonitorCancellation ())
210             break;
211 
212         // Get signals from all children with same process group of pid
213         const ::pid_t wait_pid = ::waitpid (pid, &status, options);
214 
215         if (CheckForMonitorCancellation ())
216             break;
217 
218         if (wait_pid == -1)
219         {
220             if (errno == EINTR)
221                 continue;
222             else
223             {
224                 if (log)
225                     log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
226                 break;
227             }
228         }
229         else if (wait_pid > 0)
230         {
231             bool exited = false;
232             int signal = 0;
233             int exit_status = 0;
234             const char *status_cstr = NULL;
235             if (WIFSTOPPED(status))
236             {
237                 signal = WSTOPSIG(status);
238                 status_cstr = "STOPPED";
239             }
240             else if (WIFEXITED(status))
241             {
242                 exit_status = WEXITSTATUS(status);
243                 status_cstr = "EXITED";
244                 exited = true;
245             }
246             else if (WIFSIGNALED(status))
247             {
248                 signal = WTERMSIG(status);
249                 status_cstr = "SIGNALED";
250                 if (wait_pid == abs(pid)) {
251                     exited = true;
252                     exit_status = -1;
253                 }
254             }
255             else
256             {
257                 status_cstr = "(\?\?\?)";
258             }
259 
260             // Scope for pthread_cancel_disabler
261             {
262 #ifndef __linux__
263                 ScopedPThreadCancelDisabler pthread_cancel_disabler;
264 #endif
265 
266                 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
267                 if (log)
268                     log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
269                                  function,
270                                  pid,
271                                  options,
272                                  wait_pid,
273                                  status,
274                                  status_cstr,
275                                  signal,
276                                  exit_status);
277 
278                 if (exited || (signal != 0 && monitor_signals))
279                 {
280                     bool callback_return = false;
281                     if (callback)
282                         callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
283 
284                     // If our process exited, then this thread should exit
285                     if (exited && wait_pid == abs(pid))
286                     {
287                         if (log)
288                             log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
289                         break;
290                     }
291                     // If the callback returns true, it means this process should
292                     // exit
293                     if (callback_return)
294                     {
295                         if (log)
296                             log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
297                         break;
298                     }
299                 }
300             }
301         }
302     }
303 
304     log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
305     if (log)
306         log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
307 
308     return NULL;
309 }
310 
311 #endif // #if !defined (__APPLE__) && !defined (_WIN32)
312 
313 #if !defined (__APPLE__)
314 
315 void
316 Host::SystemLog (SystemLogType type, const char *format, va_list args)
317 {
318     vfprintf (stderr, format, args);
319 }
320 
321 #endif
322 
323 void
324 Host::SystemLog (SystemLogType type, const char *format, ...)
325 {
326     va_list args;
327     va_start (args, format);
328     SystemLog (type, format, args);
329     va_end (args);
330 }
331 
332 lldb::pid_t
333 Host::GetCurrentProcessID()
334 {
335     return ::getpid();
336 }
337 
338 #ifndef _WIN32
339 
340 lldb::tid_t
341 Host::GetCurrentThreadID()
342 {
343 #if defined (__APPLE__)
344     // Calling "mach_thread_self()" bumps the reference count on the thread
345     // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
346     // count.
347     thread_port_t thread_self = mach_thread_self();
348     mach_port_deallocate(mach_task_self(), thread_self);
349     return thread_self;
350 #elif defined(__FreeBSD__)
351     return lldb::tid_t(pthread_getthreadid_np());
352 #elif defined(__ANDROID_NDK__)
353     return lldb::tid_t(gettid());
354 #elif defined(__linux__)
355     return lldb::tid_t(syscall(SYS_gettid));
356 #else
357     return lldb::tid_t(pthread_self());
358 #endif
359 }
360 
361 lldb::thread_t
362 Host::GetCurrentThread ()
363 {
364     return lldb::thread_t(pthread_self());
365 }
366 
367 const char *
368 Host::GetSignalAsCString (int signo)
369 {
370     switch (signo)
371     {
372     case SIGHUP:    return "SIGHUP";    // 1    hangup
373     case SIGINT:    return "SIGINT";    // 2    interrupt
374     case SIGQUIT:   return "SIGQUIT";   // 3    quit
375     case SIGILL:    return "SIGILL";    // 4    illegal instruction (not reset when caught)
376     case SIGTRAP:   return "SIGTRAP";   // 5    trace trap (not reset when caught)
377     case SIGABRT:   return "SIGABRT";   // 6    abort()
378 #if  defined(SIGPOLL)
379 #if !defined(SIGIO) || (SIGPOLL != SIGIO)
380 // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
381 // fail with 'multiple define cases with same value'
382     case SIGPOLL:   return "SIGPOLL";   // 7    pollable event ([XSR] generated, not supported)
383 #endif
384 #endif
385 #if  defined(SIGEMT)
386     case SIGEMT:    return "SIGEMT";    // 7    EMT instruction
387 #endif
388     case SIGFPE:    return "SIGFPE";    // 8    floating point exception
389     case SIGKILL:   return "SIGKILL";   // 9    kill (cannot be caught or ignored)
390     case SIGBUS:    return "SIGBUS";    // 10    bus error
391     case SIGSEGV:   return "SIGSEGV";   // 11    segmentation violation
392     case SIGSYS:    return "SIGSYS";    // 12    bad argument to system call
393     case SIGPIPE:   return "SIGPIPE";   // 13    write on a pipe with no one to read it
394     case SIGALRM:   return "SIGALRM";   // 14    alarm clock
395     case SIGTERM:   return "SIGTERM";   // 15    software termination signal from kill
396     case SIGURG:    return "SIGURG";    // 16    urgent condition on IO channel
397     case SIGSTOP:   return "SIGSTOP";   // 17    sendable stop signal not from tty
398     case SIGTSTP:   return "SIGTSTP";   // 18    stop signal from tty
399     case SIGCONT:   return "SIGCONT";   // 19    continue a stopped process
400     case SIGCHLD:   return "SIGCHLD";   // 20    to parent on child stop or exit
401     case SIGTTIN:   return "SIGTTIN";   // 21    to readers pgrp upon background tty read
402     case SIGTTOU:   return "SIGTTOU";   // 22    like TTIN for output if (tp->t_local&LTOSTOP)
403 #if  defined(SIGIO)
404     case SIGIO:     return "SIGIO";     // 23    input/output possible signal
405 #endif
406     case SIGXCPU:   return "SIGXCPU";   // 24    exceeded CPU time limit
407     case SIGXFSZ:   return "SIGXFSZ";   // 25    exceeded file size limit
408     case SIGVTALRM: return "SIGVTALRM"; // 26    virtual time alarm
409     case SIGPROF:   return "SIGPROF";   // 27    profiling time alarm
410 #if  defined(SIGWINCH)
411     case SIGWINCH:  return "SIGWINCH";  // 28    window size changes
412 #endif
413 #if  defined(SIGINFO)
414     case SIGINFO:   return "SIGINFO";   // 29    information request
415 #endif
416     case SIGUSR1:   return "SIGUSR1";   // 30    user defined signal 1
417     case SIGUSR2:   return "SIGUSR2";   // 31    user defined signal 2
418     default:
419         break;
420     }
421     return NULL;
422 }
423 
424 #endif
425 
426 #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
427 
428 size_t
429 Host::GetEnvironment (StringList &env)
430 {
431     // TODO: Is there a way to the host environment for this process on other systems?
432     return 0;
433 }
434 
435 #endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
436 
437 #ifndef _WIN32
438 
439 lldb::thread_key_t
440 Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
441 {
442     pthread_key_t key;
443     ::pthread_key_create (&key, callback);
444     return key;
445 }
446 
447 void*
448 Host::ThreadLocalStorageGet(lldb::thread_key_t key)
449 {
450     return ::pthread_getspecific (key);
451 }
452 
453 void
454 Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
455 {
456    ::pthread_setspecific (key, value);
457 }
458 
459 #endif
460 
461 #if !defined (__APPLE__) // see Host.mm
462 
463 bool
464 Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
465 {
466     bundle.Clear();
467     return false;
468 }
469 
470 bool
471 Host::ResolveExecutableInBundle (FileSpec &file)
472 {
473     return false;
474 }
475 #endif
476 
477 #ifndef _WIN32
478 
479 FileSpec
480 Host::GetModuleFileSpecForHostAddress (const void *host_addr)
481 {
482     FileSpec module_filespec;
483 #if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
484     Dl_info info;
485     if (::dladdr (host_addr, &info))
486     {
487         if (info.dli_fname)
488             module_filespec.SetFile(info.dli_fname, true);
489     }
490 #endif
491     return module_filespec;
492 }
493 
494 #endif
495 
496 #if !defined(__linux__)
497 bool
498 Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
499 {
500     return false;
501 }
502 #endif
503 
504 struct ShellInfo
505 {
506     ShellInfo () :
507         process_reaped (false),
508         can_delete (false),
509         pid (LLDB_INVALID_PROCESS_ID),
510         signo(-1),
511         status(-1)
512     {
513     }
514 
515     lldb_private::Predicate<bool> process_reaped;
516     lldb_private::Predicate<bool> can_delete;
517     lldb::pid_t pid;
518     int signo;
519     int status;
520 };
521 
522 static bool
523 MonitorShellCommand (void *callback_baton,
524                      lldb::pid_t pid,
525                      bool exited,       // True if the process did exit
526                      int signo,         // Zero for no signal
527                      int status)   // Exit value of process if signal is zero
528 {
529     ShellInfo *shell_info = (ShellInfo *)callback_baton;
530     shell_info->pid = pid;
531     shell_info->signo = signo;
532     shell_info->status = status;
533     // Let the thread running Host::RunShellCommand() know that the process
534     // exited and that ShellInfo has been filled in by broadcasting to it
535     shell_info->process_reaped.SetValue(1, eBroadcastAlways);
536     // Now wait for a handshake back from that thread running Host::RunShellCommand
537     // so we know that we can delete shell_info_ptr
538     shell_info->can_delete.WaitForValueEqualTo(true);
539     // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
540     usleep(1000);
541     // Now delete the shell info that was passed into this function
542     delete shell_info;
543     return true;
544 }
545 
546 Error
547 Host::RunShellCommand (const char *command,
548                        const char *working_dir,
549                        int *status_ptr,
550                        int *signo_ptr,
551                        std::string *command_output_ptr,
552                        uint32_t timeout_sec,
553                        bool run_in_default_shell)
554 {
555     return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, command_output_ptr, timeout_sec, run_in_default_shell);
556 }
557 
558 Error
559 Host::RunShellCommand (const Args &args,
560                        const char *working_dir,
561                        int *status_ptr,
562                        int *signo_ptr,
563                        std::string *command_output_ptr,
564                        uint32_t timeout_sec,
565                        bool run_in_default_shell)
566 {
567     Error error;
568     ProcessLaunchInfo launch_info;
569     launch_info.SetArchitecture(HostInfo::GetArchitecture());
570     if (run_in_default_shell)
571     {
572         // Run the command in a shell
573         launch_info.SetShell(HostInfo::GetDefaultShell());
574         launch_info.GetArguments().AppendArguments(args);
575         const bool localhost = true;
576         const bool will_debug = false;
577         const bool first_arg_is_full_shell_command = false;
578         launch_info.ConvertArgumentsForLaunchingInShell (error,
579                                                          localhost,
580                                                          will_debug,
581                                                          first_arg_is_full_shell_command,
582                                                          0);
583     }
584     else
585     {
586         // No shell, just run it
587         const bool first_arg_is_executable = true;
588         launch_info.SetArguments(args, first_arg_is_executable);
589     }
590 
591     if (working_dir)
592         launch_info.SetWorkingDirectory(working_dir);
593     llvm::SmallString<PATH_MAX> output_file_path;
594 
595     if (command_output_ptr)
596     {
597         // Create a temporary file to get the stdout/stderr and redirect the
598         // output of the command into this file. We will later read this file
599         // if all goes well and fill the data into "command_output_ptr"
600         FileSpec tmpdir_file_spec;
601         if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
602         {
603             tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
604             llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), output_file_path);
605         }
606         else
607         {
608             llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "", output_file_path);
609         }
610     }
611 
612     launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
613     if (!output_file_path.empty())
614     {
615         launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path.c_str(), false, true);
616         launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
617     }
618     else
619     {
620         launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
621         launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
622     }
623 
624     // The process monitor callback will delete the 'shell_info_ptr' below...
625     std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
626 
627     const bool monitor_signals = false;
628     launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
629 
630     error = LaunchProcess (launch_info);
631     const lldb::pid_t pid = launch_info.GetProcessID();
632 
633     if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
634         error.SetErrorString("failed to get process ID");
635 
636     if (error.Success())
637     {
638         // The process successfully launched, so we can defer ownership of
639         // "shell_info" to the MonitorShellCommand callback function that will
640         // get called when the process dies. We release the unique pointer as it
641         // doesn't need to delete the ShellInfo anymore.
642         ShellInfo *shell_info = shell_info_ap.release();
643         TimeValue *timeout_ptr = nullptr;
644         TimeValue timeout_time(TimeValue::Now());
645         if (timeout_sec > 0) {
646             timeout_time.OffsetWithSeconds(timeout_sec);
647             timeout_ptr = &timeout_time;
648         }
649         bool timed_out = false;
650         shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
651         if (timed_out)
652         {
653             error.SetErrorString("timed out waiting for shell command to complete");
654 
655             // Kill the process since it didn't complete within the timeout specified
656             Kill (pid, SIGKILL);
657             // Wait for the monitor callback to get the message
658             timeout_time = TimeValue::Now();
659             timeout_time.OffsetWithSeconds(1);
660             timed_out = false;
661             shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
662         }
663         else
664         {
665             if (status_ptr)
666                 *status_ptr = shell_info->status;
667 
668             if (signo_ptr)
669                 *signo_ptr = shell_info->signo;
670 
671             if (command_output_ptr)
672             {
673                 command_output_ptr->clear();
674                 FileSpec file_spec(output_file_path.c_str(), File::eOpenOptionRead);
675                 uint64_t file_size = file_spec.GetByteSize();
676                 if (file_size > 0)
677                 {
678                     if (file_size > command_output_ptr->max_size())
679                     {
680                         error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
681                     }
682                     else
683                     {
684                         command_output_ptr->resize(file_size);
685                         file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
686                     }
687                 }
688             }
689         }
690         shell_info->can_delete.SetValue(true, eBroadcastAlways);
691     }
692 
693     FileSpec output_file_spec(output_file_path.c_str(), false);
694     if (FileSystem::GetFileExists(output_file_spec))
695         FileSystem::Unlink(output_file_path.c_str());
696     // Handshake with the monitor thread, or just let it know in advance that
697     // it can delete "shell_info" in case we timed out and were not able to kill
698     // the process...
699     return error;
700 }
701 
702 // LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
703 // systems
704 
705 #if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
706 #if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
707 // this method needs to be visible to macosx/Host.cpp and
708 // common/Host.cpp.
709 
710 short
711 Host::GetPosixspawnFlags(const ProcessLaunchInfo &launch_info)
712 {
713     short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
714 
715 #if defined (__APPLE__)
716     if (launch_info.GetFlags().Test (eLaunchFlagExec))
717         flags |= POSIX_SPAWN_SETEXEC;           // Darwin specific posix_spawn flag
718 
719     if (launch_info.GetFlags().Test (eLaunchFlagDebug))
720         flags |= POSIX_SPAWN_START_SUSPENDED;   // Darwin specific posix_spawn flag
721 
722     if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
723         flags |= _POSIX_SPAWN_DISABLE_ASLR;     // Darwin specific posix_spawn flag
724 
725     if (launch_info.GetLaunchInSeparateProcessGroup())
726         flags |= POSIX_SPAWN_SETPGROUP;
727 
728 #ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
729 #if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
730     static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
731     if (g_use_close_on_exec_flag == eLazyBoolCalculate)
732     {
733         g_use_close_on_exec_flag = eLazyBoolNo;
734 
735         uint32_t major, minor, update;
736         if (HostInfo::GetOSVersion(major, minor, update))
737         {
738             // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
739             if (major > 10 || (major == 10 && minor > 7))
740             {
741                 // Only enable for 10.8 and later OS versions
742                 g_use_close_on_exec_flag = eLazyBoolYes;
743             }
744         }
745     }
746 #else
747     static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
748 #endif
749     // Close all files exception those with file actions if this is supported.
750     if (g_use_close_on_exec_flag == eLazyBoolYes)
751         flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
752 #endif
753 #endif // #if defined (__APPLE__)
754     return flags;
755 }
756 
757 Error
758 Host::LaunchProcessPosixSpawn(const char *exe_path, const ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
759 {
760     Error error;
761     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
762 
763     posix_spawnattr_t attr;
764     error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
765 
766     if (error.Fail() || log)
767         error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
768     if (error.Fail())
769         return error;
770 
771     // Make a quick class that will cleanup the posix spawn attributes in case
772     // we return in the middle of this function.
773     lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
774 
775     sigset_t no_signals;
776     sigset_t all_signals;
777     sigemptyset (&no_signals);
778     sigfillset (&all_signals);
779     ::posix_spawnattr_setsigmask(&attr, &no_signals);
780 #if defined (__linux__)  || defined (__FreeBSD__)
781     ::posix_spawnattr_setsigdefault(&attr, &no_signals);
782 #else
783     ::posix_spawnattr_setsigdefault(&attr, &all_signals);
784 #endif
785 
786     short flags = GetPosixspawnFlags(launch_info);
787 
788     error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
789     if (error.Fail() || log)
790         error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
791     if (error.Fail())
792         return error;
793 
794     // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
795     // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
796 #if defined (__APPLE__) && !defined (__arm__)
797 
798     // Don't set the binpref if a shell was provided.  After all, that's only going to affect what version of the shell
799     // is launched, not what fork of the binary is launched.  We insert "arch --arch <ARCH> as part of the shell invocation
800     // to do that job on OSX.
801 
802     if (launch_info.GetShell() == nullptr)
803     {
804         // We don't need to do this for ARM, and we really shouldn't now that we
805         // have multiple CPU subtypes and no posix_spawnattr call that allows us
806         // to set which CPU subtype to launch...
807         const ArchSpec &arch_spec = launch_info.GetArchitecture();
808         cpu_type_t cpu = arch_spec.GetMachOCPUType();
809         cpu_type_t sub = arch_spec.GetMachOCPUSubType();
810         if (cpu != 0 &&
811             cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
812             cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
813             !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
814         {
815             size_t ocount = 0;
816             error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
817             if (error.Fail() || log)
818                 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu, (uint64_t)ocount);
819 
820             if (error.Fail() || ocount != 1)
821                 return error;
822         }
823     }
824 
825 #endif
826 
827     const char *tmp_argv[2];
828     char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
829     char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
830     if (argv == NULL)
831     {
832         // posix_spawn gets very unhappy if it doesn't have at least the program
833         // name in argv[0]. One of the side affects I have noticed is the environment
834         // variables don't make it into the child process if "argv == NULL"!!!
835         tmp_argv[0] = exe_path;
836         tmp_argv[1] = NULL;
837         argv = (char * const*)tmp_argv;
838     }
839 
840 #if !defined (__APPLE__)
841     // manage the working directory
842     char current_dir[PATH_MAX];
843     current_dir[0] = '\0';
844 #endif
845 
846     const char *working_dir = launch_info.GetWorkingDirectory();
847     if (working_dir)
848     {
849 #if defined (__APPLE__)
850         // Set the working directory on this thread only
851         if (__pthread_chdir (working_dir) < 0) {
852             if (errno == ENOENT) {
853                 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
854             } else if (errno == ENOTDIR) {
855                 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
856             } else {
857                 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
858             }
859             return error;
860         }
861 #else
862         if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
863         {
864             error.SetError(errno, eErrorTypePOSIX);
865             error.LogIfError(log, "unable to save the current directory");
866             return error;
867         }
868 
869         if (::chdir(working_dir) == -1)
870         {
871             error.SetError(errno, eErrorTypePOSIX);
872             error.LogIfError(log, "unable to change working directory to %s", working_dir);
873             return error;
874         }
875 #endif
876     }
877 
878     ::pid_t result_pid = LLDB_INVALID_PROCESS_ID;
879     const size_t num_file_actions = launch_info.GetNumFileActions ();
880     if (num_file_actions > 0)
881     {
882         posix_spawn_file_actions_t file_actions;
883         error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
884         if (error.Fail() || log)
885             error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
886         if (error.Fail())
887             return error;
888 
889         // Make a quick class that will cleanup the posix spawn attributes in case
890         // we return in the middle of this function.
891         lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
892 
893         for (size_t i=0; i<num_file_actions; ++i)
894         {
895             const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
896             if (launch_file_action)
897             {
898                 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
899                     return error;
900             }
901         }
902 
903         error.SetError(::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp), eErrorTypePOSIX);
904 
905         if (error.Fail() || log)
906         {
907             error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", result_pid,
908                            exe_path, static_cast<void *>(&file_actions), static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
909                            reinterpret_cast<const void *>(envp));
910             if (log)
911             {
912                 for (int ii=0; argv[ii]; ++ii)
913                     log->Printf("argv[%i] = '%s'", ii, argv[ii]);
914             }
915         }
916 
917     }
918     else
919     {
920         error.SetError(::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp), eErrorTypePOSIX);
921 
922         if (error.Fail() || log)
923         {
924             error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
925                            result_pid, exe_path, static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
926                            reinterpret_cast<const void *>(envp));
927             if (log)
928             {
929                 for (int ii=0; argv[ii]; ++ii)
930                     log->Printf("argv[%i] = '%s'", ii, argv[ii]);
931             }
932         }
933     }
934     pid = result_pid;
935 
936     if (working_dir)
937     {
938 #if defined (__APPLE__)
939         // No more thread specific current working directory
940         __pthread_fchdir (-1);
941 #else
942         if (::chdir(current_dir) == -1 && error.Success())
943         {
944             error.SetError(errno, eErrorTypePOSIX);
945             error.LogIfError(log, "unable to change current directory back to %s",
946                     current_dir);
947         }
948 #endif
949     }
950 
951     return error;
952 }
953 
954 bool
955 Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
956 {
957     if (info == NULL)
958         return false;
959 
960     posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
961 
962     switch (info->GetAction())
963     {
964         case FileAction::eFileActionNone:
965             error.Clear();
966             break;
967 
968         case FileAction::eFileActionClose:
969             if (info->GetFD() == -1)
970                 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
971             else
972             {
973                 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
974                 if (log && (error.Fail() || log))
975                     error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
976                                    static_cast<void *>(file_actions), info->GetFD());
977             }
978             break;
979 
980         case FileAction::eFileActionDuplicate:
981             if (info->GetFD() == -1)
982                 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
983             else if (info->GetActionArgument() == -1)
984                 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
985             else
986             {
987                 error.SetError(
988                     ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
989                     eErrorTypePOSIX);
990                 if (log && (error.Fail() || log))
991                     error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
992                                    static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
993             }
994             break;
995 
996         case FileAction::eFileActionOpen:
997             if (info->GetFD() == -1)
998                 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
999             else
1000             {
1001                 int oflag = info->GetActionArgument();
1002 
1003                 mode_t mode = 0;
1004 
1005                 if (oflag & O_CREAT)
1006                     mode = 0640;
1007 
1008                 error.SetError(
1009                     ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
1010                     eErrorTypePOSIX);
1011                 if (error.Fail() || log)
1012                     error.PutToLog(log,
1013                                    "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
1014                                    static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
1015             }
1016             break;
1017     }
1018     return error.Success();
1019 }
1020 #endif // !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
1021 #endif // defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
1022 
1023 #if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__) || defined(_WIN32)
1024 // The functions below implement process launching via posix_spawn() for Linux,
1025 // FreeBSD and NetBSD.
1026 
1027 Error
1028 Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1029 {
1030     std::unique_ptr<ProcessLauncher> delegate_launcher;
1031 #if defined(_WIN32)
1032     delegate_launcher.reset(new ProcessLauncherWindows());
1033 #elif defined(__ANDROID__) || defined(__ANDROID_NDK__)
1034     delegate_launcher.reset(new ProcessLauncherAndroid());
1035 #else
1036     delegate_launcher.reset(new ProcessLauncherPosix());
1037 #endif
1038     MonitoringProcessLauncher launcher(std::move(delegate_launcher));
1039 
1040     Error error;
1041     HostProcess process = launcher.LaunchProcess(launch_info, error);
1042 
1043     // TODO(zturner): It would be better if the entire HostProcess were returned instead of writing
1044     // it into this structure.
1045     launch_info.SetProcessID(process.GetProcessId());
1046 
1047     return error;
1048 }
1049 #endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
1050 
1051 #ifndef _WIN32
1052 void
1053 Host::Kill(lldb::pid_t pid, int signo)
1054 {
1055     ::kill(pid, signo);
1056 }
1057 
1058 #endif
1059 
1060 #if !defined (__APPLE__)
1061 bool
1062 Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
1063 {
1064     return false;
1065 }
1066 
1067 void
1068 Host::SetCrashDescriptionWithFormat (const char *format, ...)
1069 {
1070 }
1071 
1072 void
1073 Host::SetCrashDescription (const char *description)
1074 {
1075 }
1076 
1077 #endif
1078 
1079 #if !defined (__linux__) && !defined (__FreeBSD__) && !defined(__FreeBSD_kernel__) && !defined (__NetBSD__)
1080 
1081 const lldb_private::UnixSignalsSP&
1082 Host::GetUnixSignals ()
1083 {
1084     static UnixSignalsSP s_unix_signals_sp (new UnixSignals ());
1085     return s_unix_signals_sp;
1086 }
1087 
1088 #endif
1089