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__)
65#include "llvm/ADT/SmallString.h"
66#include "llvm/Support/Errno.h"
67#include "llvm/Support/FileSystem.h"
77#ifndef _POSIX_SPAWN_DISABLE_ASLR
78#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
91#if !defined(__APPLE__)
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);
99 syslog(LOG_INFO,
"%s", message.data());
102void Host::SystemLog(llvm::StringRef message) { llvm::errs() << message; }
106#if !defined(__APPLE__) && !defined(_WIN32)
113 char thread_name[256];
114 ::snprintf(thread_name,
sizeof(thread_name),
115 "<lldb.host.wait4(pid=%" PRIu64
")>", pid);
129 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
137 if (m_old_state != -1)
138 ::pthread_setcancelstate(m_old_state, 0);
147static thread_local volatile sig_atomic_t g_usr1_called;
149static void SigUsr1Handler(
int) { g_usr1_called = 1; }
159 ::pthread_testcancel();
174 struct sigaction sigUsr1Action;
175 memset(&sigUsr1Action, 0,
sizeof(sigUsr1Action));
176 sigUsr1Action.sa_handler = SigUsr1Handler;
177 ::sigaction(SIGUSR1, &sigUsr1Action,
nullptr);
182 LLDB_LOG(log,
"::waitpid({0}, &status, 0)...", pid);
187 const ::pid_t wait_pid = ::waitpid(pid, &status, 0);
189 LLDB_LOG(log,
"::waitpid({0}, &status, 0) => pid = {1}, status = {2:x}", pid,
197 if (errno != EINTR) {
198 LLDB_LOG(log,
"pid = {0}, thread exiting because waitpid failed ({1})...",
199 pid, llvm::sys::StrError());
206 if (WIFEXITED(status)) {
207 exit_status = WEXITSTATUS(status);
208 }
else if (WIFSIGNALED(status)) {
209 signal = WTERMSIG(status);
212 llvm_unreachable(
"Unknown status");
222 callback(pid, signal, exit_status);
254#if !defined(SIGIO) || (SIGPOLL != SIGIO)
327#if !defined(__APPLE__)
341#if !defined(__ANDROID__)
343 if (::dladdr(host_addr, &info)) {
344 if (info.dli_fname) {
345 module_filespec.
SetFile(info.dli_fname, FileSpec::Style::native);
350 return module_filespec;
355#if !defined(__linux__)
375 shell_info->pid = pid;
376 shell_info->signo = signo;
377 shell_info->status = status;
384 const FileSpec &working_dir,
int *status_ptr,
385 int *signo_ptr, std::string *command_output_ptr,
387 bool run_in_shell,
bool hide_stderr) {
389 status_ptr, signo_ptr, command_output_ptr, timeout,
390 run_in_shell, hide_stderr);
394 llvm::StringRef command,
395 const FileSpec &working_dir,
int *status_ptr,
396 int *signo_ptr, std::string *command_output_ptr,
398 bool run_in_shell,
bool hide_stderr) {
400 signo_ptr, command_output_ptr, timeout, run_in_shell,
405 int *status_ptr,
int *signo_ptr,
406 std::string *command_output_ptr,
408 bool run_in_shell,
bool hide_stderr) {
409 return RunShellCommand(llvm::StringRef(), args, working_dir, status_ptr,
410 signo_ptr, command_output_ptr, timeout, run_in_shell,
415 const FileSpec &working_dir,
int *status_ptr,
416 int *signo_ptr, std::string *command_output_ptr,
418 bool run_in_shell,
bool hide_stderr) {
424 FileSpec shell = HostInfo::GetDefaultShell();
425 if (!shell_path.empty())
430 const bool will_debug =
false;
431 const bool first_arg_is_full_shell_command =
false;
433 error, will_debug, first_arg_is_full_shell_command, 0);
436 const bool first_arg_is_executable =
true;
437 launch_info.
SetArguments(args, first_arg_is_executable);
444 llvm::SmallString<64> output_file_path;
446 if (command_output_ptr) {
450 if (
FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
451 tmpdir_file_spec.AppendPathComponent(
"lldb-shell-output.%%%%%%");
452 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
455 llvm::sys::fs::createTemporaryFile(
"lldb-shell-output.%%%%%%",
"",
460 FileSpec output_file_spec(output_file_path.str());
463 if (output_file_spec)
469 if (output_file_spec && !hide_stderr)
474 std::shared_ptr<ShellInfo> shell_info_sp(
new ShellInfo());
477 std::placeholders::_2, std::placeholders::_3));
483 error.SetErrorString(
"failed to get process ID");
485 if (
error.Success()) {
486 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(
true, timeout)) {
487 error.SetErrorString(
"timed out waiting for shell command to complete");
492 shell_info_sp->process_reaped.WaitForValueEqualTo(
493 true, std::chrono::seconds(1));
496 *status_ptr = shell_info_sp->status;
499 *signo_ptr = shell_info_sp->signo;
501 if (command_output_ptr) {
502 command_output_ptr->clear();
506 if (file_size > command_output_ptr->max_size()) {
507 error.SetErrorStringWithFormat(
508 "shell command output is too large to fit into a std::string");
514 command_output_ptr->assign(
515 reinterpret_cast<char *
>(Buffer->GetBytes()),
516 Buffer->GetByteSize());
523 llvm::sys::fs::remove(output_file_spec.
GetPath());
529#if !defined(__APPLE__)
531 std::unique_ptr<ProcessLauncher> delegate_launcher;
555#if !defined(__APPLE__)
559 return llvm::errorCodeToError(
560 std::error_code(ENOTSUP, std::system_category()));
568 if (url.starts_with(
"file://"))
574#if defined(LLVM_ON_UNIX)
576 if (WIFEXITED(wstatus))
577 return {
Exit, uint8_t(WEXITSTATUS(wstatus))};
578 else if (WIFSIGNALED(wstatus))
579 return {
Signal, uint8_t(WTERMSIG(wstatus))};
580 else if (WIFSTOPPED(wstatus))
581 return {
Stop, uint8_t(WSTOPSIG(wstatus))};
582 llvm_unreachable(
"Unknown wait status");
586void llvm::format_provider<WaitStatus>::format(
const WaitStatus &WS,
602 OS << formatv(
"{0}{1:x-2}", type, WS.
status);
610 desc =
"Exited with status";
613 desc =
"Killed by signal";
616 desc =
"Stopped by signal";
619 OS << desc <<
" " << int(WS.
status);
static llvm::raw_ostream & error(Stream &strm)
int __pthread_chdir(const char *path)
int __pthread_fchdir(int fildes)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
ScopedPThreadCancelDisabler()
~ScopedPThreadCancelDisabler()
A command line argument class.
void AppendArguments(const Args &rhs)
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
void Clear()
Clears the object state.
uint64_t GetByteSize(const FileSpec &file_spec) const
Returns the on-disk size of the given file in bytes.
void Resolve(llvm::SmallVectorImpl< char > &path)
Resolve path to make it canonical.
std::shared_ptr< WritableDataBuffer > CreateWritableDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
static FileSystem & Instance()
lldb::pid_t GetProcessId() const
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
static bool FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach)
static bool ResolveExecutableInBundle(FileSpec &file)
When executable files may live within a directory, where the directory represents an executable bundl...
std::map< lldb::pid_t, bool > TidMap
static Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, const Timeout< std::micro > &timeout, bool run_in_shell=true, bool hide_stderr=false)
Run a shell command.
static lldb::thread_t GetCurrentThread()
Get the thread token (the one returned by ThreadCreate when the thread was created) for the calling t...
static Environment GetEnvironment()
static lldb::pid_t GetCurrentProcessID()
Get the process ID for the calling process.
static void SystemLog(llvm::StringRef message)
Emit the given message to the operating system log.
static uint32_t FindProcessesImpl(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
static FileSpec GetModuleFileSpecForHostAddress(const void *host_addr)
Given an address in the current process (the process that is running the LLDB code),...
std::function< void(lldb::pid_t pid, int signal, int status)> MonitorChildProcessCallback
static uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
static std::unique_ptr< Connection > CreateDefaultConnection(llvm::StringRef url)
static llvm::Expected< HostThread > StartMonitoringChildProcess(const MonitorChildProcessCallback &callback, lldb::pid_t pid)
Start monitoring a child process.
static void Kill(lldb::pid_t pid, int signo)
static const char * GetSignalAsCString(int signo)
static bool IsInteractiveGraphicSession()
Check if we're running in an interactive graphical session.
static bool GetBundleDirectory(const FileSpec &file, FileSpec &bundle_directory)
If you have an executable that is in a bundle and want to get back to the bundle directory from the p...
static llvm::Error OpenFileInExternalEditor(llvm::StringRef editor, const FileSpec &file_spec, uint32_t line_no)
HostProcess LaunchProcess(const ProcessLaunchInfo &launch_info, Status &error) override
Launch the process specified in launch_info.
A command line option parsing protocol class.
A C++ wrapper class for providing threaded access to a value of type T.
void SetArchitecture(const ArchSpec &arch)
lldb::pid_t GetProcessID() const
void SetArguments(const Args &args, bool first_arg_is_executable)
void SetProcessID(lldb::pid_t pid)
Environment & GetEnvironment()
bool AppendOpenFileAction(int fd, const FileSpec &file_spec, bool read, bool write)
bool AppendSuppressFileAction(int fd, bool read, bool write)
void SetShell(const FileSpec &shell)
void SetMonitorProcessCallback(Host::MonitorChildProcessCallback callback)
bool ConvertArgumentsForLaunchingInShell(Status &error, bool will_debug, bool first_arg_is_full_shell_command, uint32_t num_resumes)
bool AppendDuplicateFileAction(int fd, int dup_fd)
void SetWorkingDirectory(const FileSpec &working_dir)
void Emit(llvm::StringRef message) override
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
static bool CheckForMonitorCancellation()
static void MonitorShellCommand(std::shared_ptr< ShellInfo > shell_info, lldb::pid_t pid, int signo, int status)
static thread_result_t MonitorChildProcessThreadFunction(::pid_t pid, Host::MonitorChildProcessCallback callback)
#define LLDB_INVALID_PROCESS_ID
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
@ eBroadcastAlways
Always send a broadcast when the value is modified.
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
lldb_private::Predicate< bool > process_reaped
static WaitStatus Decode(int wstatus)