1 //===-- Host.cpp ------------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
14 #include <sys/types.h>
24 #if defined(__APPLE__)
25 #include <mach-o/dyld.h>
26 #include <mach/mach_init.h>
27 #include <mach/mach_port.h>
30 #if defined(__linux__) || defined(__FreeBSD__) || \
31 defined(__FreeBSD_kernel__) || defined(__APPLE__) || \
32 defined(__NetBSD__) || defined(__OpenBSD__)
33 #if !defined(__ANDROID__)
36 #include <sys/syscall.h>
40 #if defined(__FreeBSD__)
41 #include <pthread_np.h>
44 #if defined(__NetBSD__)
51 // Other libraries and framework includes
54 #include "lldb/Core/ArchSpec.h"
55 #include "lldb/Host/Host.h"
56 #include "lldb/Host/HostInfo.h"
57 #include "lldb/Host/HostProcess.h"
58 #include "lldb/Host/MonitoringProcessLauncher.h"
59 #include "lldb/Host/Predicate.h"
60 #include "lldb/Host/ProcessLauncher.h"
61 #include "lldb/Host/ThreadLauncher.h"
62 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
63 #include "lldb/Target/FileAction.h"
64 #include "lldb/Target/ProcessLaunchInfo.h"
65 #include "lldb/Target/UnixSignals.h"
66 #include "lldb/Utility/CleanUp.h"
67 #include "lldb/Utility/DataBufferLLVM.h"
68 #include "lldb/Utility/FileSpec.h"
69 #include "lldb/Utility/Log.h"
70 #include "lldb/Utility/Status.h"
71 #include "lldb/lldb-private-forward.h"
72 #include "llvm/ADT/SmallString.h"
73 #include "llvm/ADT/StringSwitch.h"
74 #include "llvm/Support/Errno.h"
75 #include "llvm/Support/FileSystem.h"
78 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
79 #include "lldb/Host/windows/ProcessLauncherWindows.h"
81 #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
84 #if defined(__APPLE__)
85 #ifndef _POSIX_SPAWN_DISABLE_ASLR
86 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
90 int __pthread_chdir(const char *path);
91 int __pthread_fchdir(int fildes);
97 using namespace lldb_private;
99 #if !defined(__APPLE__) && !defined(_WIN32)
101 lldb::pid_t pid; // The process ID to monitor
102 Host::MonitorChildProcessCallback
103 callback; // The callback function to call when "pid" exits or signals
104 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
107 static thread_result_t MonitorChildProcessThreadFunction(void *arg);
109 HostThread Host::StartMonitoringChildProcess(
110 const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid,
111 bool monitor_signals) {
112 MonitorInfo *info_ptr = new MonitorInfo();
115 info_ptr->callback = callback;
116 info_ptr->monitor_signals = monitor_signals;
118 char thread_name[256];
119 ::snprintf(thread_name, sizeof(thread_name),
120 "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
121 return ThreadLauncher::LaunchThread(
122 thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL);
126 //------------------------------------------------------------------
127 // Scoped class that will disable thread canceling when it is
128 // constructed, and exception safely restore the previous value it
129 // when it goes out of scope.
130 //------------------------------------------------------------------
131 class ScopedPThreadCancelDisabler {
133 ScopedPThreadCancelDisabler() {
134 // Disable the ability for this thread to be cancelled
135 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
140 ~ScopedPThreadCancelDisabler() {
141 // Restore the ability for this thread to be cancelled to what it
143 if (m_old_state != -1)
144 ::pthread_setcancelstate(m_old_state, 0);
148 int m_old_state; // Save the old cancelability state.
153 #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
154 static __thread volatile sig_atomic_t g_usr1_called;
156 static thread_local volatile sig_atomic_t g_usr1_called;
159 static void SigUsr1Handler(int) { g_usr1_called = 1; }
162 static bool CheckForMonitorCancellation() {
169 ::pthread_testcancel();
174 static thread_result_t MonitorChildProcessThreadFunction(void *arg) {
175 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
176 const char *function = __FUNCTION__;
178 log->Printf("%s (arg = %p) thread starting...", function, arg);
180 MonitorInfo *info = (MonitorInfo *)arg;
182 const Host::MonitorChildProcessCallback callback = info->callback;
183 const bool monitor_signals = info->monitor_signals;
185 assert(info->pid <= UINT32_MAX);
186 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
191 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__)
194 const int options = __WALL;
197 // This signal is only used to interrupt the thread from waitpid
198 struct sigaction sigUsr1Action;
199 memset(&sigUsr1Action, 0, sizeof(sigUsr1Action));
200 sigUsr1Action.sa_handler = SigUsr1Handler;
201 ::sigaction(SIGUSR1, &sigUsr1Action, nullptr);
205 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
207 log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...",
208 function, pid, options);
210 if (CheckForMonitorCancellation())
213 // Get signals from all children with same process group of pid
214 const ::pid_t wait_pid = ::waitpid(pid, &status, options);
216 if (CheckForMonitorCancellation())
219 if (wait_pid == -1) {
224 "arg = {0}, thread exiting because waitpid failed ({1})...",
225 arg, llvm::sys::StrError());
228 } else if (wait_pid > 0) {
232 const char *status_cstr = NULL;
233 if (WIFSTOPPED(status)) {
234 signal = WSTOPSIG(status);
235 status_cstr = "STOPPED";
236 } else if (WIFEXITED(status)) {
237 exit_status = WEXITSTATUS(status);
238 status_cstr = "EXITED";
240 } else if (WIFSIGNALED(status)) {
241 signal = WTERMSIG(status);
242 status_cstr = "SIGNALED";
243 if (wait_pid == abs(pid)) {
248 status_cstr = "(\?\?\?)";
251 // Scope for pthread_cancel_disabler
254 ScopedPThreadCancelDisabler pthread_cancel_disabler;
257 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
259 log->Printf("%s ::waitpid (pid = %" PRIi32
260 ", &status, options = %i) => pid = %" PRIi32
261 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
262 function, pid, options, wait_pid, status, status_cstr,
263 signal, exit_status);
265 if (exited || (signal != 0 && monitor_signals)) {
266 bool callback_return = false;
268 callback_return = callback(wait_pid, exited, signal, exit_status);
270 // If our process exited, then this thread should exit
271 if (exited && wait_pid == abs(pid)) {
273 log->Printf("%s (arg = %p) thread exiting because pid received "
278 // If the callback returns true, it means this process should
280 if (callback_return) {
282 log->Printf("%s (arg = %p) thread exiting because callback "
292 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
294 log->Printf("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
299 #endif // #if !defined (__APPLE__) && !defined (_WIN32)
301 #if !defined(__APPLE__)
303 void Host::SystemLog(SystemLogType type, const char *format, va_list args) {
304 vfprintf(stderr, format, args);
309 void Host::SystemLog(SystemLogType type, const char *format, ...) {
311 va_start(args, format);
312 SystemLog(type, format, args);
316 lldb::pid_t Host::GetCurrentProcessID() { return ::getpid(); }
320 lldb::thread_t Host::GetCurrentThread() {
321 return lldb::thread_t(pthread_self());
324 const char *Host::GetSignalAsCString(int signo) {
327 return "SIGHUP"; // 1 hangup
329 return "SIGINT"; // 2 interrupt
331 return "SIGQUIT"; // 3 quit
333 return "SIGILL"; // 4 illegal instruction (not reset when caught)
335 return "SIGTRAP"; // 5 trace trap (not reset when caught)
337 return "SIGABRT"; // 6 abort()
339 #if !defined(SIGIO) || (SIGPOLL != SIGIO)
340 // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
341 // fail with 'multiple define cases with same value'
343 return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
348 return "SIGEMT"; // 7 EMT instruction
351 return "SIGFPE"; // 8 floating point exception
353 return "SIGKILL"; // 9 kill (cannot be caught or ignored)
355 return "SIGBUS"; // 10 bus error
357 return "SIGSEGV"; // 11 segmentation violation
359 return "SIGSYS"; // 12 bad argument to system call
361 return "SIGPIPE"; // 13 write on a pipe with no one to read it
363 return "SIGALRM"; // 14 alarm clock
365 return "SIGTERM"; // 15 software termination signal from kill
367 return "SIGURG"; // 16 urgent condition on IO channel
369 return "SIGSTOP"; // 17 sendable stop signal not from tty
371 return "SIGTSTP"; // 18 stop signal from tty
373 return "SIGCONT"; // 19 continue a stopped process
375 return "SIGCHLD"; // 20 to parent on child stop or exit
377 return "SIGTTIN"; // 21 to readers pgrp upon background tty read
379 return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local<OSTOP)
382 return "SIGIO"; // 23 input/output possible signal
385 return "SIGXCPU"; // 24 exceeded CPU time limit
387 return "SIGXFSZ"; // 25 exceeded file size limit
389 return "SIGVTALRM"; // 26 virtual time alarm
391 return "SIGPROF"; // 27 profiling time alarm
392 #if defined(SIGWINCH)
394 return "SIGWINCH"; // 28 window size changes
398 return "SIGINFO"; // 29 information request
401 return "SIGUSR1"; // 30 user defined signal 1
403 return "SIGUSR2"; // 31 user defined signal 2
412 #if !defined(__APPLE__) // see Host.mm
414 bool Host::GetBundleDirectory(const FileSpec &file, FileSpec &bundle) {
419 bool Host::ResolveExecutableInBundle(FileSpec &file) { return false; }
424 FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) {
425 FileSpec module_filespec;
426 #if !defined(__ANDROID__)
428 if (::dladdr(host_addr, &info)) {
430 module_filespec.SetFile(info.dli_fname, true);
433 return module_filespec;
438 #if !defined(__linux__)
439 bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) {
446 : process_reaped(false), pid(LLDB_INVALID_PROCESS_ID), signo(-1),
449 lldb_private::Predicate<bool> process_reaped;
456 MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid,
457 bool exited, // True if the process did exit
458 int signo, // Zero for no signal
459 int status) // Exit value of process if signal is zero
461 shell_info->pid = pid;
462 shell_info->signo = signo;
463 shell_info->status = status;
464 // Let the thread running Host::RunShellCommand() know that the process
465 // exited and that ShellInfo has been filled in by broadcasting to it
466 shell_info->process_reaped.SetValue(true, eBroadcastAlways);
470 Status Host::RunShellCommand(const char *command, const FileSpec &working_dir,
471 int *status_ptr, int *signo_ptr,
472 std::string *command_output_ptr,
473 uint32_t timeout_sec, bool run_in_default_shell) {
474 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr,
475 command_output_ptr, timeout_sec, run_in_default_shell);
478 Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir,
479 int *status_ptr, int *signo_ptr,
480 std::string *command_output_ptr,
481 uint32_t timeout_sec, bool run_in_default_shell) {
483 ProcessLaunchInfo launch_info;
484 launch_info.SetArchitecture(HostInfo::GetArchitecture());
485 if (run_in_default_shell) {
486 // Run the command in a shell
487 launch_info.SetShell(HostInfo::GetDefaultShell());
488 launch_info.GetArguments().AppendArguments(args);
489 const bool localhost = true;
490 const bool will_debug = false;
491 const bool first_arg_is_full_shell_command = false;
492 launch_info.ConvertArgumentsForLaunchingInShell(
493 error, localhost, will_debug, first_arg_is_full_shell_command, 0);
495 // No shell, just run it
496 const bool first_arg_is_executable = true;
497 launch_info.SetArguments(args, first_arg_is_executable);
501 launch_info.SetWorkingDirectory(working_dir);
502 llvm::SmallString<PATH_MAX> output_file_path;
504 if (command_output_ptr) {
505 // Create a temporary file to get the stdout/stderr and redirect the
506 // output of the command into this file. We will later read this file
507 // if all goes well and fill the data into "command_output_ptr"
508 FileSpec tmpdir_file_spec;
509 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) {
510 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
511 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
514 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "",
519 FileSpec output_file_spec{output_file_path.c_str(), false};
521 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
522 if (output_file_spec) {
523 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false,
525 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
527 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
528 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
531 std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo());
532 const bool monitor_signals = false;
533 launch_info.SetMonitorProcessCallback(
534 std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1,
535 std::placeholders::_2, std::placeholders::_3,
536 std::placeholders::_4),
539 error = LaunchProcess(launch_info);
540 const lldb::pid_t pid = launch_info.GetProcessID();
542 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
543 error.SetErrorString("failed to get process ID");
545 if (error.Success()) {
546 bool timed_out = false;
547 shell_info_sp->process_reaped.WaitForValueEqualTo(
548 true, std::chrono::seconds(timeout_sec), &timed_out);
550 error.SetErrorString("timed out waiting for shell command to complete");
552 // Kill the process since it didn't complete within the timeout specified
554 // Wait for the monitor callback to get the message
556 shell_info_sp->process_reaped.WaitForValueEqualTo(
557 true, std::chrono::seconds(1), &timed_out);
560 *status_ptr = shell_info_sp->status;
563 *signo_ptr = shell_info_sp->signo;
565 if (command_output_ptr) {
566 command_output_ptr->clear();
567 uint64_t file_size = output_file_spec.GetByteSize();
569 if (file_size > command_output_ptr->max_size()) {
570 error.SetErrorStringWithFormat(
571 "shell command output is too large to fit into a std::string");
574 DataBufferLLVM::CreateFromPath(output_file_spec.GetPath());
576 command_output_ptr->assign(Buffer->GetChars(),
577 Buffer->GetByteSize());
584 llvm::sys::fs::remove(output_file_spec.GetPath());
588 // The functions below implement process launching for non-Apple-based platforms
589 #if !defined(__APPLE__)
590 Status Host::LaunchProcess(ProcessLaunchInfo &launch_info) {
591 std::unique_ptr<ProcessLauncher> delegate_launcher;
593 delegate_launcher.reset(new ProcessLauncherWindows());
595 delegate_launcher.reset(new ProcessLauncherPosixFork());
597 MonitoringProcessLauncher launcher(std::move(delegate_launcher));
600 HostProcess process = launcher.LaunchProcess(launch_info, error);
602 // TODO(zturner): It would be better if the entire HostProcess were returned
603 // instead of writing
604 // it into this structure.
605 launch_info.SetProcessID(process.GetProcessId());
609 #endif // !defined(__APPLE__)
612 void Host::Kill(lldb::pid_t pid, int signo) { ::kill(pid, signo); }
616 #if !defined(__APPLE__)
617 bool Host::OpenFileInExternalEditor(const FileSpec &file_spec,
624 const UnixSignalsSP &Host::GetUnixSignals() {
625 static const auto s_unix_signals_sp =
626 UnixSignals::Create(HostInfo::GetArchitecture());
627 return s_unix_signals_sp;
630 std::unique_ptr<Connection> Host::CreateDefaultConnection(llvm::StringRef url) {
632 if (url.startswith("file://"))
633 return std::unique_ptr<Connection>(new ConnectionGenericFile());
635 return std::unique_ptr<Connection>(new ConnectionFileDescriptor());
638 #if defined(LLVM_ON_UNIX)
639 WaitStatus WaitStatus::Decode(int wstatus) {
640 if (WIFEXITED(wstatus))
641 return {Exit, uint8_t(WEXITSTATUS(wstatus))};
642 else if (WIFSIGNALED(wstatus))
643 return {Signal, uint8_t(WTERMSIG(wstatus))};
644 else if (WIFSTOPPED(wstatus))
645 return {Stop, uint8_t(WSTOPSIG(wstatus))};
646 llvm_unreachable("Unknown wait status");
650 void llvm::format_provider<WaitStatus>::format(const WaitStatus &WS,
653 if (Options == "g") {
656 case WaitStatus::Exit:
659 case WaitStatus::Signal:
662 case WaitStatus::Stop:
666 OS << formatv("{0}{1:x-2}", type, WS.status);
670 assert(Options.empty());
673 case WaitStatus::Exit:
674 desc = "Exited with status";
676 case WaitStatus::Signal:
677 desc = "Killed by signal";
679 case WaitStatus::Stop:
680 desc = "Stopped by signal";
683 OS << desc << " " << int(WS.status);