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