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