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