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/Config/llvm-config.h"
67#include "llvm/Support/Errno.h"
68#include "llvm/Support/FileSystem.h"
78#ifndef _POSIX_SPAWN_DISABLE_ASLR
79#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
92#if !defined(__APPLE__)
116#if !defined(__APPLE__) && !defined(_WIN32)
123 char thread_name[256];
124 ::snprintf(thread_name,
sizeof(thread_name),
125 "<lldb.host.wait4(pid=%" PRIu64
")>", pid);
139 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
147 if (m_old_state != -1)
148 ::pthread_setcancelstate(m_old_state, 0);
157static thread_local volatile sig_atomic_t g_usr1_called;
159static void SigUsr1Handler(
int) { g_usr1_called = 1; }
169 ::pthread_testcancel();
184 struct sigaction sigUsr1Action;
185 memset(&sigUsr1Action, 0,
sizeof(sigUsr1Action));
186 sigUsr1Action.sa_handler = SigUsr1Handler;
187 ::sigaction(SIGUSR1, &sigUsr1Action,
nullptr);
192 LLDB_LOG(log,
"::waitpid({0}, &status, 0)...", pid);
197 const ::pid_t wait_pid = ::waitpid(pid, &status, 0);
199 LLDB_LOG(log,
"::waitpid({0}, &status, 0) => pid = {1}, status = {2:x}", pid,
207 if (errno != EINTR) {
208 LLDB_LOG(log,
"pid = {0}, thread exiting because waitpid failed ({1})...",
209 pid, llvm::sys::StrError());
216 if (WIFEXITED(status)) {
217 exit_status = WEXITSTATUS(status);
218 }
else if (WIFSIGNALED(status)) {
219 signal = WTERMSIG(status);
222 llvm_unreachable(
"Unknown status");
232 callback(pid, signal, exit_status);
264#if !defined(SIGIO) || (SIGPOLL != SIGIO)
337#if !defined(__APPLE__)
351#if !defined(__ANDROID__)
353 if (::dladdr(host_addr, &info)) {
354 if (info.dli_fname) {
355 module_filespec.
SetFile(info.dli_fname, FileSpec::Style::native);
360 return module_filespec;
365#if !defined(__linux__)
385 shell_info->pid = pid;
386 shell_info->signo = signo;
387 shell_info->status = status;
394 const FileSpec &working_dir,
int *status_ptr,
395 int *signo_ptr, std::string *command_output_ptr,
397 bool run_in_shell,
bool hide_stderr) {
399 status_ptr, signo_ptr, command_output_ptr, timeout,
400 run_in_shell, hide_stderr);
404 llvm::StringRef command,
405 const FileSpec &working_dir,
int *status_ptr,
406 int *signo_ptr, std::string *command_output_ptr,
408 bool run_in_shell,
bool hide_stderr) {
410 signo_ptr, command_output_ptr, timeout, run_in_shell,
415 int *status_ptr,
int *signo_ptr,
416 std::string *command_output_ptr,
418 bool run_in_shell,
bool hide_stderr) {
419 return RunShellCommand(llvm::StringRef(), args, working_dir, status_ptr,
420 signo_ptr, command_output_ptr, timeout, run_in_shell,
425 const FileSpec &working_dir,
int *status_ptr,
426 int *signo_ptr, std::string *command_output_ptr,
428 bool run_in_shell,
bool hide_stderr) {
434 FileSpec shell = HostInfo::GetDefaultShell();
435 if (!shell_path.empty())
440 const bool will_debug =
false;
441 const bool first_arg_is_full_shell_command =
false;
443 error, will_debug, first_arg_is_full_shell_command, 0);
446 const bool first_arg_is_executable =
true;
447 launch_info.
SetArguments(args, first_arg_is_executable);
454 llvm::SmallString<64> output_file_path;
456 if (command_output_ptr) {
460 if (
FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
461 tmpdir_file_spec.AppendPathComponent(
"lldb-shell-output.%%%%%%");
462 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
465 llvm::sys::fs::createTemporaryFile(
"lldb-shell-output.%%%%%%",
"",
470 FileSpec output_file_spec(output_file_path.str());
473 if (output_file_spec)
479 if (output_file_spec && !hide_stderr)
484 std::shared_ptr<ShellInfo> shell_info_sp(
new ShellInfo());
487 std::placeholders::_2, std::placeholders::_3));
495 if (
error.Success()) {
496 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(
true, timeout)) {
498 "timed out waiting for shell command to complete");
503 shell_info_sp->process_reaped.WaitForValueEqualTo(
504 true, std::chrono::seconds(1));
507 *status_ptr = shell_info_sp->status;
510 *signo_ptr = shell_info_sp->signo;
512 if (command_output_ptr) {
513 command_output_ptr->clear();
517 if (file_size > command_output_ptr->max_size()) {
519 "shell command output is too large to fit into a std::string");
525 command_output_ptr->assign(
526 reinterpret_cast<char *
>(Buffer->GetBytes()),
527 Buffer->GetByteSize());
534 llvm::sys::fs::remove(output_file_spec.
GetPath());
540#if !defined(__APPLE__)
542 std::unique_ptr<ProcessLauncher> delegate_launcher;
566#if !defined(__APPLE__)
570 return llvm::errorCodeToError(
571 std::error_code(ENOTSUP, std::system_category()));
579 if (url.starts_with(
"file://"))
585#if defined(LLVM_ON_UNIX)
587 if (WIFEXITED(wstatus))
588 return {
Exit, uint8_t(WEXITSTATUS(wstatus))};
589 else if (WIFSIGNALED(wstatus))
590 return {
Signal, uint8_t(WTERMSIG(wstatus))};
591 else if (WIFSTOPPED(wstatus))
592 return {
Stop, uint8_t(WSTOPSIG(wstatus))};
593 llvm_unreachable(
"Unknown wait status");
597void llvm::format_provider<WaitStatus>::format(
const WaitStatus &WS,
613 OS << formatv(
"{0}{1:x-2}", type, WS.
status);
621 desc =
"Exited with status";
624 desc =
"Killed by signal";
627 desc =
"Stopped by signal";
630 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...
static void SystemLog(lldb::Severity severity, llvm::StringRef message)
Emit the given message to the operating system log.
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 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)
void Disable(std::optional< MaskType > flags=std::nullopt)
void Enable(const std::shared_ptr< LogHandler > &handler_sp, std::optional< MaskType > flags=std::nullopt, uint32_t options=0)
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)
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
static Status FromErrorString(const char *str)
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 constexpr Log::Category g_categories[]
static bool CheckForMonitorCancellation()
static void MonitorShellCommand(std::shared_ptr< ShellInfo > shell_info, lldb::pid_t pid, int signo, int status)
static Log g_system_log(g_system_channel)
static thread_result_t MonitorChildProcessThreadFunction(::pid_t pid, Host::MonitorChildProcessCallback callback)
static Log::Channel g_system_channel(g_categories, SystemLog::System)
#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.
Log::Channel & LogChannelFor< SystemLog >()
@ eBroadcastAlways
Always send a broadcast when the value is modified.
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Severity
Used for expressing severity in logs and diagnostics.
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
lldb_private::Predicate< bool > process_reaped
static WaitStatus Decode(int wstatus)