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_PID | LOG_NDELAY, LOG_USER); });
98 int level = LOG_DEBUG;
110 syslog(level,
"%s", message.data());
117 llvm::outs() << message;
120 llvm::errs() << message;
127#if !defined(__APPLE__) && !defined(_WIN32)
134 char thread_name[256];
135 ::snprintf(thread_name,
sizeof(thread_name),
136 "<lldb.host.wait4(pid=%" PRIu64
")>", pid);
150 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
158 if (m_old_state != -1)
159 ::pthread_setcancelstate(m_old_state, 0);
168static thread_local volatile sig_atomic_t g_usr1_called;
170static void SigUsr1Handler(
int) { g_usr1_called = 1; }
180 ::pthread_testcancel();
195 struct sigaction sigUsr1Action;
196 memset(&sigUsr1Action, 0,
sizeof(sigUsr1Action));
197 sigUsr1Action.sa_handler = SigUsr1Handler;
198 ::sigaction(SIGUSR1, &sigUsr1Action,
nullptr);
203 LLDB_LOG(log,
"::waitpid({0}, &status, 0)...", pid);
208 const ::pid_t wait_pid = ::waitpid(pid, &status, 0);
210 LLDB_LOG(log,
"::waitpid({0}, &status, 0) => pid = {1}, status = {2:x}", pid,
218 if (errno != EINTR) {
219 LLDB_LOG(log,
"pid = {0}, thread exiting because waitpid failed ({1})...",
220 pid, llvm::sys::StrError());
227 if (WIFEXITED(status)) {
228 exit_status = WEXITSTATUS(status);
229 }
else if (WIFSIGNALED(status)) {
230 signal = WTERMSIG(status);
233 llvm_unreachable(
"Unknown status");
243 callback(pid, signal, exit_status);
275#if !defined(SIGIO) || (SIGPOLL != SIGIO)
348#if !defined(__APPLE__)
362#if !defined(__ANDROID__)
364 if (::dladdr(host_addr, &info)) {
365 if (info.dli_fname) {
366 module_filespec.
SetFile(info.dli_fname, FileSpec::Style::native);
371 return module_filespec;
376#if !defined(__linux__)
396 shell_info->pid = pid;
397 shell_info->signo = signo;
398 shell_info->status = status;
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 status_ptr, signo_ptr, command_output_ptr, timeout,
411 run_in_shell, hide_stderr);
415 llvm::StringRef command,
416 const FileSpec &working_dir,
int *status_ptr,
417 int *signo_ptr, std::string *command_output_ptr,
419 bool run_in_shell,
bool hide_stderr) {
421 signo_ptr, command_output_ptr, timeout, run_in_shell,
426 int *status_ptr,
int *signo_ptr,
427 std::string *command_output_ptr,
429 bool run_in_shell,
bool hide_stderr) {
430 return RunShellCommand(llvm::StringRef(), args, working_dir, status_ptr,
431 signo_ptr, command_output_ptr, timeout, run_in_shell,
436 const FileSpec &working_dir,
int *status_ptr,
437 int *signo_ptr, std::string *command_output_ptr,
439 bool run_in_shell,
bool hide_stderr) {
445 FileSpec shell = HostInfo::GetDefaultShell();
446 if (!shell_path.empty())
451 const bool will_debug =
false;
452 const bool first_arg_is_full_shell_command =
false;
454 error, will_debug, first_arg_is_full_shell_command, 0);
457 const bool first_arg_is_executable =
true;
458 launch_info.
SetArguments(args, first_arg_is_executable);
465 llvm::SmallString<64> output_file_path;
467 if (command_output_ptr) {
471 if (
FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
472 tmpdir_file_spec.AppendPathComponent(
"lldb-shell-output.%%%%%%");
473 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
476 llvm::sys::fs::createTemporaryFile(
"lldb-shell-output.%%%%%%",
"",
481 FileSpec output_file_spec(output_file_path.str());
484 if (output_file_spec)
490 if (output_file_spec && !hide_stderr)
495 std::shared_ptr<ShellInfo> shell_info_sp(
new ShellInfo());
498 std::placeholders::_2, std::placeholders::_3));
504 error.SetErrorString(
"failed to get process ID");
506 if (
error.Success()) {
507 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(
true, timeout)) {
508 error.SetErrorString(
"timed out waiting for shell command to complete");
513 shell_info_sp->process_reaped.WaitForValueEqualTo(
514 true, std::chrono::seconds(1));
517 *status_ptr = shell_info_sp->status;
520 *signo_ptr = shell_info_sp->signo;
522 if (command_output_ptr) {
523 command_output_ptr->clear();
527 if (file_size > command_output_ptr->max_size()) {
528 error.SetErrorStringWithFormat(
529 "shell command output is too large to fit into a std::string");
535 command_output_ptr->assign(
536 reinterpret_cast<char *
>(Buffer->GetBytes()),
537 Buffer->GetByteSize());
544 llvm::sys::fs::remove(output_file_spec.
GetPath());
550#if !defined(__APPLE__)
552 std::unique_ptr<ProcessLauncher> delegate_launcher;
576#if !defined(__APPLE__)
580 return llvm::errorCodeToError(
581 std::error_code(ENOTSUP, std::system_category()));
589 if (url.starts_with(
"file://"))
595#if defined(LLVM_ON_UNIX)
597 if (WIFEXITED(wstatus))
598 return {
Exit, uint8_t(WEXITSTATUS(wstatus))};
599 else if (WIFSIGNALED(wstatus))
600 return {
Signal, uint8_t(WTERMSIG(wstatus))};
601 else if (WIFSTOPPED(wstatus))
602 return {
Stop, uint8_t(WSTOPSIG(wstatus))};
603 llvm_unreachable(
"Unknown wait status");
607void llvm::format_provider<WaitStatus>::format(
const WaitStatus &WS,
623 OS << formatv(
"{0}{1:x-2}", type, WS.
status);
631 desc =
"Exited with status";
634 desc =
"Killed by signal";
637 desc =
"Stopped by signal";
640 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)
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
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)