1 //===-- Host.cpp ----------------------------------------------------------===//
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__) || defined(__EMSCRIPTEN__)
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/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"
70 #include "lldb/Host/windows/ConnectionGenericFileWindows.h"
71 #include "lldb/Host/windows/ProcessLauncherWindows.h"
73 #include "lldb/Host/posix/ProcessLauncherPosixFork.h"
76 #if defined(__APPLE__)
77 #ifndef _POSIX_SPAWN_DISABLE_ASLR
78 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100
82 int __pthread_chdir(const char *path
);
83 int __pthread_fchdir(int fildes
);
89 using namespace lldb_private
;
91 #if !defined(__APPLE__)
92 void Host::SystemLog(llvm::StringRef message
) { llvm::errs() << message
; }
95 #if !defined(__APPLE__) && !defined(_WIN32)
96 static thread_result_t
97 MonitorChildProcessThreadFunction(::pid_t pid
,
98 Host::MonitorChildProcessCallback callback
);
100 llvm::Expected
<HostThread
> Host::StartMonitoringChildProcess(
101 const Host::MonitorChildProcessCallback
&callback
, lldb::pid_t pid
) {
102 char thread_name
[256];
103 ::snprintf(thread_name
, sizeof(thread_name
),
104 "<lldb.host.wait4(pid=%" PRIu64
")>", pid
);
105 assert(pid
<= UINT32_MAX
);
106 return ThreadLauncher::LaunchThread(thread_name
, [pid
, callback
] {
107 return MonitorChildProcessThreadFunction(pid
, callback
);
112 // Scoped class that will disable thread canceling when it is constructed, and
113 // exception safely restore the previous value it when it goes out of scope.
114 class ScopedPThreadCancelDisabler
{
116 ScopedPThreadCancelDisabler() {
117 // Disable the ability for this thread to be cancelled
118 int err
= ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE
, &m_old_state
);
123 ~ScopedPThreadCancelDisabler() {
124 // Restore the ability for this thread to be cancelled to what it
126 if (m_old_state
!= -1)
127 ::pthread_setcancelstate(m_old_state
, 0);
131 int m_old_state
; // Save the old cancelability state.
136 #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
137 static __thread
volatile sig_atomic_t g_usr1_called
;
139 static thread_local
volatile sig_atomic_t g_usr1_called
;
142 static void SigUsr1Handler(int) { g_usr1_called
= 1; }
145 static bool CheckForMonitorCancellation() {
152 ::pthread_testcancel();
157 static thread_result_t
158 MonitorChildProcessThreadFunction(::pid_t pid
,
159 Host::MonitorChildProcessCallback callback
) {
160 Log
*log
= GetLog(LLDBLog::Process
);
161 LLDB_LOG(log
, "pid = {0}", pid
);
166 // This signal is only used to interrupt the thread from waitpid
167 struct sigaction sigUsr1Action
;
168 memset(&sigUsr1Action
, 0, sizeof(sigUsr1Action
));
169 sigUsr1Action
.sa_handler
= SigUsr1Handler
;
170 ::sigaction(SIGUSR1
, &sigUsr1Action
, nullptr);
174 log
= GetLog(LLDBLog::Process
);
175 LLDB_LOG(log
, "::waitpid({0}, &status, 0)...", pid
);
177 if (CheckForMonitorCancellation())
180 const ::pid_t wait_pid
= ::waitpid(pid
, &status
, 0);
182 LLDB_LOG(log
, "::waitpid({0}, &status, 0) => pid = {1}, status = {2:x}", pid
,
185 if (CheckForMonitorCancellation())
190 if (errno
!= EINTR
) {
191 LLDB_LOG(log
, "pid = {0}, thread exiting because waitpid failed ({1})...",
192 pid
, llvm::sys::StrError());
199 if (WIFEXITED(status
)) {
200 exit_status
= WEXITSTATUS(status
);
201 } else if (WIFSIGNALED(status
)) {
202 signal
= WTERMSIG(status
);
205 llvm_unreachable("Unknown status");
208 // Scope for pthread_cancel_disabler
211 ScopedPThreadCancelDisabler pthread_cancel_disabler
;
215 callback(pid
, signal
, exit_status
);
218 LLDB_LOG(GetLog(LLDBLog::Process
), "pid = {0} thread exiting...", pid
);
222 #endif // #if !defined (__APPLE__) && !defined (_WIN32)
224 lldb::pid_t
Host::GetCurrentProcessID() { return ::getpid(); }
228 lldb::thread_t
Host::GetCurrentThread() {
229 return lldb::thread_t(pthread_self());
232 const char *Host::GetSignalAsCString(int signo
) {
235 return "SIGHUP"; // 1 hangup
237 return "SIGINT"; // 2 interrupt
239 return "SIGQUIT"; // 3 quit
241 return "SIGILL"; // 4 illegal instruction (not reset when caught)
243 return "SIGTRAP"; // 5 trace trap (not reset when caught)
245 return "SIGABRT"; // 6 abort()
247 #if !defined(SIGIO) || (SIGPOLL != SIGIO)
248 // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
249 // fail with 'multiple define cases with same value'
251 return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
256 return "SIGEMT"; // 7 EMT instruction
259 return "SIGFPE"; // 8 floating point exception
261 return "SIGKILL"; // 9 kill (cannot be caught or ignored)
263 return "SIGBUS"; // 10 bus error
265 return "SIGSEGV"; // 11 segmentation violation
267 return "SIGSYS"; // 12 bad argument to system call
269 return "SIGPIPE"; // 13 write on a pipe with no one to read it
271 return "SIGALRM"; // 14 alarm clock
273 return "SIGTERM"; // 15 software termination signal from kill
275 return "SIGURG"; // 16 urgent condition on IO channel
277 return "SIGSTOP"; // 17 sendable stop signal not from tty
279 return "SIGTSTP"; // 18 stop signal from tty
281 return "SIGCONT"; // 19 continue a stopped process
283 return "SIGCHLD"; // 20 to parent on child stop or exit
285 return "SIGTTIN"; // 21 to readers pgrp upon background tty read
287 return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local<OSTOP)
290 return "SIGIO"; // 23 input/output possible signal
293 return "SIGXCPU"; // 24 exceeded CPU time limit
295 return "SIGXFSZ"; // 25 exceeded file size limit
297 return "SIGVTALRM"; // 26 virtual time alarm
299 return "SIGPROF"; // 27 profiling time alarm
300 #if defined(SIGWINCH)
302 return "SIGWINCH"; // 28 window size changes
306 return "SIGINFO"; // 29 information request
309 return "SIGUSR1"; // 30 user defined signal 1
311 return "SIGUSR2"; // 31 user defined signal 2
320 #if !defined(__APPLE__) // see Host.mm
322 bool Host::GetBundleDirectory(const FileSpec
&file
, FileSpec
&bundle
) {
327 bool Host::ResolveExecutableInBundle(FileSpec
&file
) { return false; }
332 FileSpec
Host::GetModuleFileSpecForHostAddress(const void *host_addr
) {
333 FileSpec module_filespec
;
334 #if !defined(__ANDROID__)
336 if (::dladdr(host_addr
, &info
)) {
337 if (info
.dli_fname
) {
338 module_filespec
.SetFile(info
.dli_fname
, FileSpec::Style::native
);
339 FileSystem::Instance().Resolve(module_filespec
);
343 return module_filespec
;
348 #if !defined(__linux__)
349 bool Host::FindProcessThreads(const lldb::pid_t pid
, TidMap
&tids_to_attach
) {
355 ShellInfo() : process_reaped(false) {}
357 lldb_private::Predicate
<bool> process_reaped
;
358 lldb::pid_t pid
= LLDB_INVALID_PROCESS_ID
;
364 MonitorShellCommand(std::shared_ptr
<ShellInfo
> shell_info
, lldb::pid_t pid
,
365 int signo
, // Zero for no signal
366 int status
) // Exit value of process if signal is zero
368 shell_info
->pid
= pid
;
369 shell_info
->signo
= signo
;
370 shell_info
->status
= status
;
371 // Let the thread running Host::RunShellCommand() know that the process
372 // exited and that ShellInfo has been filled in by broadcasting to it
373 shell_info
->process_reaped
.SetValue(true, eBroadcastAlways
);
376 Status
Host::RunShellCommand(llvm::StringRef command
,
377 const FileSpec
&working_dir
, int *status_ptr
,
378 int *signo_ptr
, std::string
*command_output_ptr
,
379 const Timeout
<std::micro
> &timeout
,
380 bool run_in_shell
, bool hide_stderr
) {
381 return RunShellCommand(llvm::StringRef(), Args(command
), working_dir
,
382 status_ptr
, signo_ptr
, command_output_ptr
, timeout
,
383 run_in_shell
, hide_stderr
);
386 Status
Host::RunShellCommand(llvm::StringRef shell_path
,
387 llvm::StringRef command
,
388 const FileSpec
&working_dir
, int *status_ptr
,
389 int *signo_ptr
, std::string
*command_output_ptr
,
390 const Timeout
<std::micro
> &timeout
,
391 bool run_in_shell
, bool hide_stderr
) {
392 return RunShellCommand(shell_path
, Args(command
), working_dir
, status_ptr
,
393 signo_ptr
, command_output_ptr
, timeout
, run_in_shell
,
397 Status
Host::RunShellCommand(const Args
&args
, const FileSpec
&working_dir
,
398 int *status_ptr
, int *signo_ptr
,
399 std::string
*command_output_ptr
,
400 const Timeout
<std::micro
> &timeout
,
401 bool run_in_shell
, bool hide_stderr
) {
402 return RunShellCommand(llvm::StringRef(), args
, working_dir
, status_ptr
,
403 signo_ptr
, command_output_ptr
, timeout
, run_in_shell
,
407 Status
Host::RunShellCommand(llvm::StringRef shell_path
, const Args
&args
,
408 const FileSpec
&working_dir
, int *status_ptr
,
409 int *signo_ptr
, std::string
*command_output_ptr
,
410 const Timeout
<std::micro
> &timeout
,
411 bool run_in_shell
, bool hide_stderr
) {
413 ProcessLaunchInfo launch_info
;
414 launch_info
.SetArchitecture(HostInfo::GetArchitecture());
416 // Run the command in a shell
417 FileSpec shell
= HostInfo::GetDefaultShell();
418 if (!shell_path
.empty())
419 shell
.SetPath(shell_path
);
421 launch_info
.SetShell(shell
);
422 launch_info
.GetArguments().AppendArguments(args
);
423 const bool will_debug
= false;
424 const bool first_arg_is_full_shell_command
= false;
425 launch_info
.ConvertArgumentsForLaunchingInShell(
426 error
, will_debug
, first_arg_is_full_shell_command
, 0);
428 // No shell, just run it
429 const bool first_arg_is_executable
= true;
430 launch_info
.SetArguments(args
, first_arg_is_executable
);
433 launch_info
.GetEnvironment() = Host::GetEnvironment();
436 launch_info
.SetWorkingDirectory(working_dir
);
437 llvm::SmallString
<64> output_file_path
;
439 if (command_output_ptr
) {
440 // Create a temporary file to get the stdout/stderr and redirect the output
441 // of the command into this file. We will later read this file if all goes
442 // well and fill the data into "command_output_ptr"
443 if (FileSpec tmpdir_file_spec
= HostInfo::GetProcessTempDir()) {
444 tmpdir_file_spec
.AppendPathComponent("lldb-shell-output.%%%%%%");
445 llvm::sys::fs::createUniqueFile(tmpdir_file_spec
.GetPath(),
448 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "",
453 FileSpec
output_file_spec(output_file_path
.str());
454 // Set up file descriptors.
455 launch_info
.AppendSuppressFileAction(STDIN_FILENO
, true, false);
456 if (output_file_spec
)
457 launch_info
.AppendOpenFileAction(STDOUT_FILENO
, output_file_spec
, false,
460 launch_info
.AppendSuppressFileAction(STDOUT_FILENO
, false, true);
462 if (output_file_spec
&& !hide_stderr
)
463 launch_info
.AppendDuplicateFileAction(STDOUT_FILENO
, STDERR_FILENO
);
465 launch_info
.AppendSuppressFileAction(STDERR_FILENO
, false, true);
467 std::shared_ptr
<ShellInfo
> shell_info_sp(new ShellInfo());
468 launch_info
.SetMonitorProcessCallback(
469 std::bind(MonitorShellCommand
, shell_info_sp
, std::placeholders::_1
,
470 std::placeholders::_2
, std::placeholders::_3
));
472 error
= LaunchProcess(launch_info
);
473 const lldb::pid_t pid
= launch_info
.GetProcessID();
475 if (error
.Success() && pid
== LLDB_INVALID_PROCESS_ID
)
476 error
.SetErrorString("failed to get process ID");
478 if (error
.Success()) {
479 if (!shell_info_sp
->process_reaped
.WaitForValueEqualTo(true, timeout
)) {
480 error
.SetErrorString("timed out waiting for shell command to complete");
482 // Kill the process since it didn't complete within the timeout specified
484 // Wait for the monitor callback to get the message
485 shell_info_sp
->process_reaped
.WaitForValueEqualTo(
486 true, std::chrono::seconds(1));
489 *status_ptr
= shell_info_sp
->status
;
492 *signo_ptr
= shell_info_sp
->signo
;
494 if (command_output_ptr
) {
495 command_output_ptr
->clear();
497 FileSystem::Instance().GetByteSize(output_file_spec
);
499 if (file_size
> command_output_ptr
->max_size()) {
500 error
.SetErrorStringWithFormat(
501 "shell command output is too large to fit into a std::string");
503 WritableDataBufferSP Buffer
=
504 FileSystem::Instance().CreateWritableDataBuffer(
507 command_output_ptr
->assign(
508 reinterpret_cast<char *>(Buffer
->GetBytes()),
509 Buffer
->GetByteSize());
516 llvm::sys::fs::remove(output_file_spec
.GetPath());
520 // The functions below implement process launching for non-Apple-based
522 #if !defined(__APPLE__)
523 Status
Host::LaunchProcess(ProcessLaunchInfo
&launch_info
) {
524 std::unique_ptr
<ProcessLauncher
> delegate_launcher
;
526 delegate_launcher
.reset(new ProcessLauncherWindows());
528 delegate_launcher
.reset(new ProcessLauncherPosixFork());
530 MonitoringProcessLauncher
launcher(std::move(delegate_launcher
));
533 HostProcess process
= launcher
.LaunchProcess(launch_info
, error
);
535 // TODO(zturner): It would be better if the entire HostProcess were returned
536 // instead of writing it into this structure.
537 launch_info
.SetProcessID(process
.GetProcessId());
541 #endif // !defined(__APPLE__)
544 void Host::Kill(lldb::pid_t pid
, int signo
) { ::kill(pid
, signo
); }
548 #if !defined(__APPLE__)
549 llvm::Error
Host::OpenFileInExternalEditor(llvm::StringRef editor
,
550 const FileSpec
&file_spec
,
552 return llvm::errorCodeToError(
553 std::error_code(ENOTSUP
, std::system_category()));
556 bool Host::IsInteractiveGraphicSession() { return false; }
559 std::unique_ptr
<Connection
> Host::CreateDefaultConnection(llvm::StringRef url
) {
561 if (url
.startswith("file://"))
562 return std::unique_ptr
<Connection
>(new ConnectionGenericFile());
564 return std::unique_ptr
<Connection
>(new ConnectionFileDescriptor());
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");
579 void llvm::format_provider
<WaitStatus
>::format(const WaitStatus
&WS
,
582 if (Options
== "g") {
585 case WaitStatus::Exit
:
588 case WaitStatus::Signal
:
591 case WaitStatus::Stop
:
595 OS
<< formatv("{0}{1:x-2}", type
, WS
.status
);
599 assert(Options
.empty());
602 case WaitStatus::Exit
:
603 desc
= "Exited with status";
605 case WaitStatus::Signal
:
606 desc
= "Killed by signal";
608 case WaitStatus::Stop
:
609 desc
= "Stopped by signal";
612 OS
<< desc
<< " " << int(WS
.status
);
615 uint32_t Host::FindProcesses(const ProcessInstanceInfoMatch
&match_info
,
616 ProcessInstanceInfoList
&process_infos
) {
617 return FindProcessesImpl(match_info
, process_infos
);
620 char SystemLogHandler::ID
;
622 SystemLogHandler::SystemLogHandler() {}
624 void SystemLogHandler::Emit(llvm::StringRef message
) {
625 Host::SystemLog(message
);