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 <dlfcn.h>
17 #include <grp.h>
18 #include <netdb.h>
19 #include <pwd.h>
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #endif
23 
24 #if defined(__APPLE__)
25 #include <mach-o/dyld.h>
26 #include <mach/mach_init.h>
27 #include <mach/mach_port.h>
28 #endif
29 
30 #if defined(__linux__) || defined(__FreeBSD__) ||                              \
31     defined(__FreeBSD_kernel__) || defined(__APPLE__) ||                       \
32     defined(__NetBSD__) || defined(__OpenBSD__)
33 #if !defined(__ANDROID__)
34 #include <spawn.h>
35 #endif
36 #include <sys/syscall.h>
37 #include <sys/wait.h>
38 #endif
39 
40 #if defined(__FreeBSD__)
41 #include <pthread_np.h>
42 #endif
43 
44 #if defined(__NetBSD__)
45 #include <lwp.h>
46 #endif
47 
48 // C++ Includes
49 
50 // Other libraries and framework includes
51 // Project includes
52 
53 #include "lldb/Core/ArchSpec.h"
54 #include "lldb/Host/Host.h"
55 #include "lldb/Host/HostInfo.h"
56 #include "lldb/Host/HostProcess.h"
57 #include "lldb/Host/MonitoringProcessLauncher.h"
58 #include "lldb/Host/Predicate.h"
59 #include "lldb/Host/ProcessLauncher.h"
60 #include "lldb/Host/ThreadLauncher.h"
61 #include "lldb/Target/FileAction.h"
62 #include "lldb/Target/ProcessLaunchInfo.h"
63 #include "lldb/Target/UnixSignals.h"
64 #include "lldb/Utility/CleanUp.h"
65 #include "lldb/Utility/DataBufferLLVM.h"
66 #include "lldb/Utility/FileSpec.h"
67 #include "lldb/Utility/Log.h"
68 #include "lldb/Utility/Status.h"
69 #include "lldb/lldb-private-forward.h"
70 #include "llvm/ADT/SmallString.h"
71 #include "llvm/ADT/StringSwitch.h"
72 #include "llvm/Support/Errno.h"
73 #include "llvm/Support/FileSystem.h"
74 
75 #if defined(_WIN32)
76 #include "lldb/Host/windows/ProcessLauncherWindows.h"
77 #else
78 #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
79 #endif
80 
81 #if defined(__APPLE__)
82 #ifndef _POSIX_SPAWN_DISABLE_ASLR
83 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
84 #endif
85 
86 extern "C" {
87 int __pthread_chdir(const char *path);
88 int __pthread_fchdir(int fildes);
89 }
90 
91 #endif
92 
93 using namespace lldb;
94 using namespace lldb_private;
95 
96 #if !defined(__APPLE__) && !defined(_WIN32)
97 struct MonitorInfo {
98   lldb::pid_t pid; // The process ID to monitor
99   Host::MonitorChildProcessCallback
100       callback; // The callback function to call when "pid" exits or signals
101   bool monitor_signals; // If true, call the callback when "pid" gets signaled.
102 };
103 
104 static thread_result_t MonitorChildProcessThreadFunction(void *arg);
105 
106 HostThread Host::StartMonitoringChildProcess(
107     const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid,
108     bool monitor_signals) {
109   MonitorInfo *info_ptr = new MonitorInfo();
110 
111   info_ptr->pid = pid;
112   info_ptr->callback = callback;
113   info_ptr->monitor_signals = monitor_signals;
114 
115   char thread_name[256];
116   ::snprintf(thread_name, sizeof(thread_name),
117              "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
118   return ThreadLauncher::LaunchThread(
119       thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL);
120 }
121 
122 #ifndef __linux__
123 //------------------------------------------------------------------
124 // Scoped class that will disable thread canceling when it is
125 // constructed, and exception safely restore the previous value it
126 // when it goes out of scope.
127 //------------------------------------------------------------------
128 class ScopedPThreadCancelDisabler {
129 public:
130   ScopedPThreadCancelDisabler() {
131     // Disable the ability for this thread to be cancelled
132     int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
133     if (err != 0)
134       m_old_state = -1;
135   }
136 
137   ~ScopedPThreadCancelDisabler() {
138     // Restore the ability for this thread to be cancelled to what it
139     // previously was.
140     if (m_old_state != -1)
141       ::pthread_setcancelstate(m_old_state, 0);
142   }
143 
144 private:
145   int m_old_state; // Save the old cancelability state.
146 };
147 #endif // __linux__
148 
149 #ifdef __linux__
150 #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
151 static __thread volatile sig_atomic_t g_usr1_called;
152 #else
153 static thread_local volatile sig_atomic_t g_usr1_called;
154 #endif
155 
156 static void SigUsr1Handler(int) { g_usr1_called = 1; }
157 #endif // __linux__
158 
159 static bool CheckForMonitorCancellation() {
160 #ifdef __linux__
161   if (g_usr1_called) {
162     g_usr1_called = 0;
163     return true;
164   }
165 #else
166   ::pthread_testcancel();
167 #endif
168   return false;
169 }
170 
171 static thread_result_t MonitorChildProcessThreadFunction(void *arg) {
172   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
173   const char *function = __FUNCTION__;
174   if (log)
175     log->Printf("%s (arg = %p) thread starting...", function, arg);
176 
177   MonitorInfo *info = (MonitorInfo *)arg;
178 
179   const Host::MonitorChildProcessCallback callback = info->callback;
180   const bool monitor_signals = info->monitor_signals;
181 
182   assert(info->pid <= UINT32_MAX);
183   const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
184 
185   delete info;
186 
187   int status = -1;
188 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
189 #define __WALL 0
190 #endif
191   const int options = __WALL;
192 
193 #ifdef __linux__
194   // This signal is only used to interrupt the thread from waitpid
195   struct sigaction sigUsr1Action;
196   memset(&sigUsr1Action, 0, sizeof(sigUsr1Action));
197   sigUsr1Action.sa_handler = SigUsr1Handler;
198   ::sigaction(SIGUSR1, &sigUsr1Action, nullptr);
199 #endif // __linux__
200 
201   while (1) {
202     log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
203     if (log)
204       log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...",
205                   function, pid, options);
206 
207     if (CheckForMonitorCancellation())
208       break;
209 
210     // Get signals from all children with same process group of pid
211     const ::pid_t wait_pid = ::waitpid(pid, &status, options);
212 
213     if (CheckForMonitorCancellation())
214       break;
215 
216     if (wait_pid == -1) {
217       if (errno == EINTR)
218         continue;
219       else {
220         LLDB_LOG(log,
221                  "arg = {0}, thread exiting because waitpid failed ({1})...",
222                  arg, llvm::sys::StrError());
223         break;
224       }
225     } else if (wait_pid > 0) {
226       bool exited = false;
227       int signal = 0;
228       int exit_status = 0;
229       const char *status_cstr = NULL;
230       if (WIFSTOPPED(status)) {
231         signal = WSTOPSIG(status);
232         status_cstr = "STOPPED";
233       } else if (WIFEXITED(status)) {
234         exit_status = WEXITSTATUS(status);
235         status_cstr = "EXITED";
236         exited = true;
237       } else if (WIFSIGNALED(status)) {
238         signal = WTERMSIG(status);
239         status_cstr = "SIGNALED";
240         if (wait_pid == abs(pid)) {
241           exited = true;
242           exit_status = -1;
243         }
244       } else {
245         status_cstr = "(\?\?\?)";
246       }
247 
248       // Scope for pthread_cancel_disabler
249       {
250 #ifndef __linux__
251         ScopedPThreadCancelDisabler pthread_cancel_disabler;
252 #endif
253 
254         log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
255         if (log)
256           log->Printf("%s ::waitpid (pid = %" PRIi32
257                       ", &status, options = %i) => pid = %" PRIi32
258                       ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
259                       function, pid, options, wait_pid, status, status_cstr,
260                       signal, exit_status);
261 
262         if (exited || (signal != 0 && monitor_signals)) {
263           bool callback_return = false;
264           if (callback)
265             callback_return = callback(wait_pid, exited, signal, exit_status);
266 
267           // If our process exited, then this thread should exit
268           if (exited && wait_pid == abs(pid)) {
269             if (log)
270               log->Printf("%s (arg = %p) thread exiting because pid received "
271                           "exit signal...",
272                           __FUNCTION__, arg);
273             break;
274           }
275           // If the callback returns true, it means this process should
276           // exit
277           if (callback_return) {
278             if (log)
279               log->Printf("%s (arg = %p) thread exiting because callback "
280                           "returned true...",
281                           __FUNCTION__, arg);
282             break;
283           }
284         }
285       }
286     }
287   }
288 
289   log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
290   if (log)
291     log->Printf("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
292 
293   return NULL;
294 }
295 
296 #endif // #if !defined (__APPLE__) && !defined (_WIN32)
297 
298 #if !defined(__APPLE__)
299 
300 void Host::SystemLog(SystemLogType type, const char *format, va_list args) {
301   vfprintf(stderr, format, args);
302 }
303 
304 #endif
305 
306 void Host::SystemLog(SystemLogType type, const char *format, ...) {
307   va_list args;
308   va_start(args, format);
309   SystemLog(type, format, args);
310   va_end(args);
311 }
312 
313 lldb::pid_t Host::GetCurrentProcessID() { return ::getpid(); }
314 
315 #ifndef _WIN32
316 
317 lldb::thread_t Host::GetCurrentThread() {
318   return lldb::thread_t(pthread_self());
319 }
320 
321 const char *Host::GetSignalAsCString(int signo) {
322   switch (signo) {
323   case SIGHUP:
324     return "SIGHUP"; // 1    hangup
325   case SIGINT:
326     return "SIGINT"; // 2    interrupt
327   case SIGQUIT:
328     return "SIGQUIT"; // 3    quit
329   case SIGILL:
330     return "SIGILL"; // 4    illegal instruction (not reset when caught)
331   case SIGTRAP:
332     return "SIGTRAP"; // 5    trace trap (not reset when caught)
333   case SIGABRT:
334     return "SIGABRT"; // 6    abort()
335 #if defined(SIGPOLL)
336 #if !defined(SIGIO) || (SIGPOLL != SIGIO)
337   // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
338   // fail with 'multiple define cases with same value'
339   case SIGPOLL:
340     return "SIGPOLL"; // 7    pollable event ([XSR] generated, not supported)
341 #endif
342 #endif
343 #if defined(SIGEMT)
344   case SIGEMT:
345     return "SIGEMT"; // 7    EMT instruction
346 #endif
347   case SIGFPE:
348     return "SIGFPE"; // 8    floating point exception
349   case SIGKILL:
350     return "SIGKILL"; // 9    kill (cannot be caught or ignored)
351   case SIGBUS:
352     return "SIGBUS"; // 10    bus error
353   case SIGSEGV:
354     return "SIGSEGV"; // 11    segmentation violation
355   case SIGSYS:
356     return "SIGSYS"; // 12    bad argument to system call
357   case SIGPIPE:
358     return "SIGPIPE"; // 13    write on a pipe with no one to read it
359   case SIGALRM:
360     return "SIGALRM"; // 14    alarm clock
361   case SIGTERM:
362     return "SIGTERM"; // 15    software termination signal from kill
363   case SIGURG:
364     return "SIGURG"; // 16    urgent condition on IO channel
365   case SIGSTOP:
366     return "SIGSTOP"; // 17    sendable stop signal not from tty
367   case SIGTSTP:
368     return "SIGTSTP"; // 18    stop signal from tty
369   case SIGCONT:
370     return "SIGCONT"; // 19    continue a stopped process
371   case SIGCHLD:
372     return "SIGCHLD"; // 20    to parent on child stop or exit
373   case SIGTTIN:
374     return "SIGTTIN"; // 21    to readers pgrp upon background tty read
375   case SIGTTOU:
376     return "SIGTTOU"; // 22    like TTIN for output if (tp->t_local&LTOSTOP)
377 #if defined(SIGIO)
378   case SIGIO:
379     return "SIGIO"; // 23    input/output possible signal
380 #endif
381   case SIGXCPU:
382     return "SIGXCPU"; // 24    exceeded CPU time limit
383   case SIGXFSZ:
384     return "SIGXFSZ"; // 25    exceeded file size limit
385   case SIGVTALRM:
386     return "SIGVTALRM"; // 26    virtual time alarm
387   case SIGPROF:
388     return "SIGPROF"; // 27    profiling time alarm
389 #if defined(SIGWINCH)
390   case SIGWINCH:
391     return "SIGWINCH"; // 28    window size changes
392 #endif
393 #if defined(SIGINFO)
394   case SIGINFO:
395     return "SIGINFO"; // 29    information request
396 #endif
397   case SIGUSR1:
398     return "SIGUSR1"; // 30    user defined signal 1
399   case SIGUSR2:
400     return "SIGUSR2"; // 31    user defined signal 2
401   default:
402     break;
403   }
404   return NULL;
405 }
406 
407 #endif
408 
409 #if !defined(__APPLE__) // see Host.mm
410 
411 bool Host::GetBundleDirectory(const FileSpec &file, FileSpec &bundle) {
412   bundle.Clear();
413   return false;
414 }
415 
416 bool Host::ResolveExecutableInBundle(FileSpec &file) { return false; }
417 #endif
418 
419 #ifndef _WIN32
420 
421 FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) {
422   FileSpec module_filespec;
423 #if !defined(__ANDROID__)
424   Dl_info info;
425   if (::dladdr(host_addr, &info)) {
426     if (info.dli_fname)
427       module_filespec.SetFile(info.dli_fname, true);
428   }
429 #endif
430   return module_filespec;
431 }
432 
433 #endif
434 
435 #if !defined(__linux__)
436 bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) {
437   return false;
438 }
439 #endif
440 
441 struct ShellInfo {
442   ShellInfo()
443       : process_reaped(false), pid(LLDB_INVALID_PROCESS_ID), signo(-1),
444         status(-1) {}
445 
446   lldb_private::Predicate<bool> process_reaped;
447   lldb::pid_t pid;
448   int signo;
449   int status;
450 };
451 
452 static bool
453 MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid,
454                     bool exited, // True if the process did exit
455                     int signo,   // Zero for no signal
456                     int status)  // Exit value of process if signal is zero
457 {
458   shell_info->pid = pid;
459   shell_info->signo = signo;
460   shell_info->status = status;
461   // Let the thread running Host::RunShellCommand() know that the process
462   // exited and that ShellInfo has been filled in by broadcasting to it
463   shell_info->process_reaped.SetValue(true, eBroadcastAlways);
464   return true;
465 }
466 
467 Status Host::RunShellCommand(const char *command, const FileSpec &working_dir,
468                              int *status_ptr, int *signo_ptr,
469                              std::string *command_output_ptr,
470                              uint32_t timeout_sec, bool run_in_default_shell) {
471   return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr,
472                          command_output_ptr, timeout_sec, run_in_default_shell);
473 }
474 
475 Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir,
476                              int *status_ptr, int *signo_ptr,
477                              std::string *command_output_ptr,
478                              uint32_t timeout_sec, bool run_in_default_shell) {
479   Status error;
480   ProcessLaunchInfo launch_info;
481   launch_info.SetArchitecture(HostInfo::GetArchitecture());
482   if (run_in_default_shell) {
483     // Run the command in a shell
484     launch_info.SetShell(HostInfo::GetDefaultShell());
485     launch_info.GetArguments().AppendArguments(args);
486     const bool localhost = true;
487     const bool will_debug = false;
488     const bool first_arg_is_full_shell_command = false;
489     launch_info.ConvertArgumentsForLaunchingInShell(
490         error, localhost, will_debug, first_arg_is_full_shell_command, 0);
491   } else {
492     // No shell, just run it
493     const bool first_arg_is_executable = true;
494     launch_info.SetArguments(args, first_arg_is_executable);
495   }
496 
497   if (working_dir)
498     launch_info.SetWorkingDirectory(working_dir);
499   llvm::SmallString<PATH_MAX> output_file_path;
500 
501   if (command_output_ptr) {
502     // Create a temporary file to get the stdout/stderr and redirect the
503     // output of the command into this file. We will later read this file
504     // if all goes well and fill the data into "command_output_ptr"
505     FileSpec tmpdir_file_spec;
506     if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) {
507       tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
508       llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
509                                       output_file_path);
510     } else {
511       llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "",
512                                          output_file_path);
513     }
514   }
515 
516   FileSpec output_file_spec{output_file_path.c_str(), false};
517 
518   launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
519   if (output_file_spec) {
520     launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false,
521                                      true);
522     launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
523   } else {
524     launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
525     launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
526   }
527 
528   std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo());
529   const bool monitor_signals = false;
530   launch_info.SetMonitorProcessCallback(
531       std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1,
532                 std::placeholders::_2, std::placeholders::_3,
533                 std::placeholders::_4),
534       monitor_signals);
535 
536   error = LaunchProcess(launch_info);
537   const lldb::pid_t pid = launch_info.GetProcessID();
538 
539   if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
540     error.SetErrorString("failed to get process ID");
541 
542   if (error.Success()) {
543     bool timed_out = false;
544     shell_info_sp->process_reaped.WaitForValueEqualTo(
545         true, std::chrono::seconds(timeout_sec), &timed_out);
546     if (timed_out) {
547       error.SetErrorString("timed out waiting for shell command to complete");
548 
549       // Kill the process since it didn't complete within the timeout specified
550       Kill(pid, SIGKILL);
551       // Wait for the monitor callback to get the message
552       timed_out = false;
553       shell_info_sp->process_reaped.WaitForValueEqualTo(
554           true, std::chrono::seconds(1), &timed_out);
555     } else {
556       if (status_ptr)
557         *status_ptr = shell_info_sp->status;
558 
559       if (signo_ptr)
560         *signo_ptr = shell_info_sp->signo;
561 
562       if (command_output_ptr) {
563         command_output_ptr->clear();
564         uint64_t file_size = output_file_spec.GetByteSize();
565         if (file_size > 0) {
566           if (file_size > command_output_ptr->max_size()) {
567             error.SetErrorStringWithFormat(
568                 "shell command output is too large to fit into a std::string");
569           } else {
570             auto Buffer =
571                 DataBufferLLVM::CreateFromPath(output_file_spec.GetPath());
572             if (error.Success())
573               command_output_ptr->assign(Buffer->GetChars(),
574                                          Buffer->GetByteSize());
575           }
576         }
577       }
578     }
579   }
580 
581   llvm::sys::fs::remove(output_file_spec.GetPath());
582   return error;
583 }
584 
585 // The functions below implement process launching for non-Apple-based platforms
586 #if !defined(__APPLE__)
587 Status Host::LaunchProcess(ProcessLaunchInfo &launch_info) {
588   std::unique_ptr<ProcessLauncher> delegate_launcher;
589 #if defined(_WIN32)
590   delegate_launcher.reset(new ProcessLauncherWindows());
591 #else
592   delegate_launcher.reset(new ProcessLauncherPosixFork());
593 #endif
594   MonitoringProcessLauncher launcher(std::move(delegate_launcher));
595 
596   Status error;
597   HostProcess process = launcher.LaunchProcess(launch_info, error);
598 
599   // TODO(zturner): It would be better if the entire HostProcess were returned
600   // instead of writing
601   // it into this structure.
602   launch_info.SetProcessID(process.GetProcessId());
603 
604   return error;
605 }
606 #endif // !defined(__APPLE__)
607 
608 #ifndef _WIN32
609 void Host::Kill(lldb::pid_t pid, int signo) { ::kill(pid, signo); }
610 
611 #endif
612 
613 #if !defined(__APPLE__)
614 bool Host::OpenFileInExternalEditor(const FileSpec &file_spec,
615                                     uint32_t line_no) {
616   return false;
617 }
618 
619 #endif
620 
621 const UnixSignalsSP &Host::GetUnixSignals() {
622   static const auto s_unix_signals_sp =
623       UnixSignals::Create(HostInfo::GetArchitecture());
624   return s_unix_signals_sp;
625 }
626 
627 #if defined(LLVM_ON_UNIX)
628 WaitStatus WaitStatus::Decode(int wstatus) {
629   if (WIFEXITED(wstatus))
630     return {Exit, uint8_t(WEXITSTATUS(wstatus))};
631   else if (WIFSIGNALED(wstatus))
632     return {Signal, uint8_t(WTERMSIG(wstatus))};
633   else if (WIFSTOPPED(wstatus))
634     return {Stop, uint8_t(WSTOPSIG(wstatus))};
635   llvm_unreachable("Unknown wait status");
636 }
637 #endif
638 
639 void llvm::format_provider<WaitStatus>::format(const WaitStatus &WS,
640                                                raw_ostream &OS,
641                                                StringRef Options) {
642   if (Options == "g") {
643     char type;
644     switch (WS.type) {
645     case WaitStatus::Exit:
646       type = 'W';
647       break;
648     case WaitStatus::Signal:
649       type = 'X';
650       break;
651     case WaitStatus::Stop:
652       type = 'S';
653       break;
654     }
655     OS << formatv("{0}{1:x-2}", type, WS.status);
656     return;
657   }
658 
659   assert(Options.empty());
660   const char *desc;
661   switch(WS.type) {
662   case WaitStatus::Exit:
663     desc = "Exited with status";
664     break;
665   case WaitStatus::Signal:
666     desc = "Killed by signal";
667     break;
668   case WaitStatus::Stop:
669     desc = "Stopped by signal";
670     break;
671   }
672   OS << desc << " " << int(WS.status);
673 }
674