1 //===-- Host.cpp ------------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
13 #include <sys/types.h>
23 #if defined(__APPLE__)
24 #include <mach-o/dyld.h>
25 #include <mach/mach_init.h>
26 #include <mach/mach_port.h>
29 #if defined(__linux__) || defined(__FreeBSD__) || \
30 defined(__FreeBSD_kernel__) || defined(__APPLE__) || \
31 defined(__NetBSD__) || defined(__OpenBSD__)
32 #if !defined(__ANDROID__)
35 #include <sys/syscall.h>
39 #if defined(__FreeBSD__)
40 #include <pthread_np.h>
43 #if defined(__NetBSD__)
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"
71 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
72 #include "lldb/Host/windows/ProcessLauncherWindows.h"
74 #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
77 #if defined(__APPLE__)
78 #ifndef _POSIX_SPAWN_DISABLE_ASLR
79 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
83 int __pthread_chdir(const char *path);
84 int __pthread_fchdir(int fildes);
90 using namespace lldb_private;
92 #if !defined(__APPLE__) && !defined(_WIN32)
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.
100 static thread_result_t MonitorChildProcessThreadFunction(void *arg);
102 llvm::Expected<HostThread> Host::StartMonitoringChildProcess(
103 const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid,
104 bool monitor_signals) {
105 MonitorInfo *info_ptr = new MonitorInfo();
108 info_ptr->callback = callback;
109 info_ptr->monitor_signals = monitor_signals;
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, 0);
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 {
123 ScopedPThreadCancelDisabler() {
124 // Disable the ability for this thread to be cancelled
125 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
130 ~ScopedPThreadCancelDisabler() {
131 // Restore the ability for this thread to be cancelled to what it
133 if (m_old_state != -1)
134 ::pthread_setcancelstate(m_old_state, 0);
138 int m_old_state; // Save the old cancelability state.
143 #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
144 static __thread volatile sig_atomic_t g_usr1_called;
146 static thread_local volatile sig_atomic_t g_usr1_called;
149 static void SigUsr1Handler(int) { g_usr1_called = 1; }
152 static bool CheckForMonitorCancellation() {
159 ::pthread_testcancel();
164 static thread_result_t MonitorChildProcessThreadFunction(void *arg) {
165 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
166 const char *function = __FUNCTION__;
168 log->Printf("%s (arg = %p) thread starting...", function, arg);
170 MonitorInfo *info = (MonitorInfo *)arg;
172 const Host::MonitorChildProcessCallback callback = info->callback;
173 const bool monitor_signals = info->monitor_signals;
175 assert(info->pid <= UINT32_MAX);
176 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
181 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
184 const int options = __WALL;
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);
195 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
197 log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...",
198 function, pid, options);
200 if (CheckForMonitorCancellation())
203 // Get signals from all children with same process group of pid
204 const ::pid_t wait_pid = ::waitpid(pid, &status, options);
206 if (CheckForMonitorCancellation())
209 if (wait_pid == -1) {
214 "arg = {0}, thread exiting because waitpid failed ({1})...",
215 arg, llvm::sys::StrError());
218 } else if (wait_pid > 0) {
222 const char *status_cstr = nullptr;
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";
230 } else if (WIFSIGNALED(status)) {
231 signal = WTERMSIG(status);
232 status_cstr = "SIGNALED";
233 if (wait_pid == abs(pid)) {
238 status_cstr = "(\?\?\?)";
241 // Scope for pthread_cancel_disabler
244 ScopedPThreadCancelDisabler pthread_cancel_disabler;
247 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
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);
255 if (exited || (signal != 0 && monitor_signals)) {
256 bool callback_return = false;
258 callback_return = callback(wait_pid, exited, signal, exit_status);
260 // If our process exited, then this thread should exit
261 if (exited && wait_pid == abs(pid)) {
263 log->Printf("%s (arg = %p) thread exiting because pid received "
268 // If the callback returns true, it means this process should exit
269 if (callback_return) {
271 log->Printf("%s (arg = %p) thread exiting because callback "
281 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
283 log->Printf("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
288 #endif // #if !defined (__APPLE__) && !defined (_WIN32)
290 #if !defined(__APPLE__)
292 void Host::SystemLog(SystemLogType type, const char *format, va_list args) {
293 vfprintf(stderr, format, args);
298 void Host::SystemLog(SystemLogType type, const char *format, ...) {
300 va_start(args, format);
301 SystemLog(type, format, args);
305 lldb::pid_t Host::GetCurrentProcessID() { return ::getpid(); }
309 lldb::thread_t Host::GetCurrentThread() {
310 return lldb::thread_t(pthread_self());
313 const char *Host::GetSignalAsCString(int signo) {
316 return "SIGHUP"; // 1 hangup
318 return "SIGINT"; // 2 interrupt
320 return "SIGQUIT"; // 3 quit
322 return "SIGILL"; // 4 illegal instruction (not reset when caught)
324 return "SIGTRAP"; // 5 trace trap (not reset when caught)
326 return "SIGABRT"; // 6 abort()
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'
332 return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
337 return "SIGEMT"; // 7 EMT instruction
340 return "SIGFPE"; // 8 floating point exception
342 return "SIGKILL"; // 9 kill (cannot be caught or ignored)
344 return "SIGBUS"; // 10 bus error
346 return "SIGSEGV"; // 11 segmentation violation
348 return "SIGSYS"; // 12 bad argument to system call
350 return "SIGPIPE"; // 13 write on a pipe with no one to read it
352 return "SIGALRM"; // 14 alarm clock
354 return "SIGTERM"; // 15 software termination signal from kill
356 return "SIGURG"; // 16 urgent condition on IO channel
358 return "SIGSTOP"; // 17 sendable stop signal not from tty
360 return "SIGTSTP"; // 18 stop signal from tty
362 return "SIGCONT"; // 19 continue a stopped process
364 return "SIGCHLD"; // 20 to parent on child stop or exit
366 return "SIGTTIN"; // 21 to readers pgrp upon background tty read
368 return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local<OSTOP)
371 return "SIGIO"; // 23 input/output possible signal
374 return "SIGXCPU"; // 24 exceeded CPU time limit
376 return "SIGXFSZ"; // 25 exceeded file size limit
378 return "SIGVTALRM"; // 26 virtual time alarm
380 return "SIGPROF"; // 27 profiling time alarm
381 #if defined(SIGWINCH)
383 return "SIGWINCH"; // 28 window size changes
387 return "SIGINFO"; // 29 information request
390 return "SIGUSR1"; // 30 user defined signal 1
392 return "SIGUSR2"; // 31 user defined signal 2
401 #if !defined(__APPLE__) // see Host.mm
403 bool Host::GetBundleDirectory(const FileSpec &file, FileSpec &bundle) {
408 bool Host::ResolveExecutableInBundle(FileSpec &file) { return false; }
413 FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) {
414 FileSpec module_filespec;
415 #if !defined(__ANDROID__)
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);
424 return module_filespec;
429 #if !defined(__linux__)
430 bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) {
437 : process_reaped(false), pid(LLDB_INVALID_PROCESS_ID), signo(-1),
440 lldb_private::Predicate<bool> process_reaped;
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
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);
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,
467 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr,
468 command_output_ptr, timeout, run_in_default_shell,
472 Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir,
473 int *status_ptr, int *signo_ptr,
474 std::string *command_output_ptr,
475 const Timeout<std::micro> &timeout,
476 bool run_in_default_shell,
479 ProcessLaunchInfo launch_info;
480 launch_info.SetArchitecture(HostInfo::GetArchitecture());
481 if (run_in_default_shell) {
482 // Run the command in a shell
483 launch_info.SetShell(HostInfo::GetDefaultShell());
484 launch_info.GetArguments().AppendArguments(args);
485 const bool localhost = true;
486 const bool will_debug = false;
487 const bool first_arg_is_full_shell_command = false;
488 launch_info.ConvertArgumentsForLaunchingInShell(
489 error, localhost, will_debug, first_arg_is_full_shell_command, 0);
491 // No shell, just run it
492 const bool first_arg_is_executable = true;
493 launch_info.SetArguments(args, first_arg_is_executable);
497 launch_info.SetWorkingDirectory(working_dir);
498 llvm::SmallString<64> output_file_path;
500 if (command_output_ptr) {
501 // Create a temporary file to get the stdout/stderr and redirect the output
502 // of the command into this file. We will later read this file if all goes
503 // well and fill the data into "command_output_ptr"
504 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
505 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
506 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
509 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "",
514 FileSpec output_file_spec(output_file_path.c_str());
515 // Set up file descriptors.
516 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
517 if (output_file_spec)
518 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false,
521 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
523 if (output_file_spec && !hide_stderr)
524 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
526 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
528 std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo());
529 const bool monitor_signals = false;
530 launch_info.SetMonitorProcessCallback(
531 std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1,
532 std::placeholders::_2, std::placeholders::_3,
533 std::placeholders::_4),
536 error = LaunchProcess(launch_info);
537 const lldb::pid_t pid = launch_info.GetProcessID();
539 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
540 error.SetErrorString("failed to get process ID");
542 if (error.Success()) {
543 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(true, timeout)) {
544 error.SetErrorString("timed out waiting for shell command to complete");
546 // Kill the process since it didn't complete within the timeout specified
548 // Wait for the monitor callback to get the message
549 shell_info_sp->process_reaped.WaitForValueEqualTo(
550 true, std::chrono::seconds(1));
553 *status_ptr = shell_info_sp->status;
556 *signo_ptr = shell_info_sp->signo;
558 if (command_output_ptr) {
559 command_output_ptr->clear();
561 FileSystem::Instance().GetByteSize(output_file_spec);
563 if (file_size > command_output_ptr->max_size()) {
564 error.SetErrorStringWithFormat(
565 "shell command output is too large to fit into a std::string");
568 FileSystem::Instance().CreateDataBuffer(output_file_spec);
570 command_output_ptr->assign(Buffer->GetChars(),
571 Buffer->GetByteSize());
578 llvm::sys::fs::remove(output_file_spec.GetPath());
582 // The functions below implement process launching for non-Apple-based
584 #if !defined(__APPLE__)
585 Status Host::LaunchProcess(ProcessLaunchInfo &launch_info) {
586 std::unique_ptr<ProcessLauncher> delegate_launcher;
588 delegate_launcher.reset(new ProcessLauncherWindows());
590 delegate_launcher.reset(new ProcessLauncherPosixFork());
592 MonitoringProcessLauncher launcher(std::move(delegate_launcher));
595 HostProcess process = launcher.LaunchProcess(launch_info, error);
597 // TODO(zturner): It would be better if the entire HostProcess were returned
598 // instead of writing it into this structure.
599 launch_info.SetProcessID(process.GetProcessId());
603 #endif // !defined(__APPLE__)
606 void Host::Kill(lldb::pid_t pid, int signo) { ::kill(pid, signo); }
610 #if !defined(__APPLE__)
611 bool Host::OpenFileInExternalEditor(const FileSpec &file_spec,
618 std::unique_ptr<Connection> Host::CreateDefaultConnection(llvm::StringRef url) {
620 if (url.startswith("file://"))
621 return std::unique_ptr<Connection>(new ConnectionGenericFile());
623 return std::unique_ptr<Connection>(new ConnectionFileDescriptor());
626 #if defined(LLVM_ON_UNIX)
627 WaitStatus WaitStatus::Decode(int wstatus) {
628 if (WIFEXITED(wstatus))
629 return {Exit, uint8_t(WEXITSTATUS(wstatus))};
630 else if (WIFSIGNALED(wstatus))
631 return {Signal, uint8_t(WTERMSIG(wstatus))};
632 else if (WIFSTOPPED(wstatus))
633 return {Stop, uint8_t(WSTOPSIG(wstatus))};
634 llvm_unreachable("Unknown wait status");
638 void llvm::format_provider<WaitStatus>::format(const WaitStatus &WS,
641 if (Options == "g") {
644 case WaitStatus::Exit:
647 case WaitStatus::Signal:
650 case WaitStatus::Stop:
654 OS << formatv("{0}{1:x-2}", type, WS.status);
658 assert(Options.empty());
661 case WaitStatus::Exit:
662 desc = "Exited with status";
664 case WaitStatus::Signal:
665 desc = "Killed by signal";
667 case WaitStatus::Stop:
668 desc = "Stopped by signal";
671 OS << desc << " " << int(WS.status);