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