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#if !defined(__APPLE__) && !defined(_WIN32)
102 char thread_name[256];
103 ::snprintf(thread_name,
sizeof(thread_name),
104 "<lldb.host.wait4(pid=%" PRIu64
")>", pid);
118 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
126 if (m_old_state != -1)
127 ::pthread_setcancelstate(m_old_state, 0);
136#if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
137static __thread
volatile sig_atomic_t g_usr1_called;
139static thread_local volatile sig_atomic_t g_usr1_called;
142static void SigUsr1Handler(
int) { g_usr1_called = 1; }
152 ::pthread_testcancel();
167 struct sigaction sigUsr1Action;
168 memset(&sigUsr1Action, 0,
sizeof(sigUsr1Action));
169 sigUsr1Action.sa_handler = SigUsr1Handler;
170 ::sigaction(SIGUSR1, &sigUsr1Action,
nullptr);
175 LLDB_LOG(log,
"::waitpid({0}, &status, 0)...", pid);
180 const ::pid_t wait_pid = ::waitpid(pid, &status, 0);
182 LLDB_LOG(log,
"::waitpid({0}, &status, 0) => pid = {1}, status = {2:x}", pid,
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");
215 callback(pid, signal, exit_status);
247#if !defined(SIGIO) || (SIGPOLL != SIGIO)
320#if !defined(__APPLE__)
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);
343 return module_filespec;
348#if !defined(__linux__)
368 shell_info->pid = pid;
369 shell_info->signo = signo;
370 shell_info->status = status;
377 const FileSpec &working_dir,
int *status_ptr,
378 int *signo_ptr, std::string *command_output_ptr,
380 bool run_in_shell,
bool hide_stderr) {
382 status_ptr, signo_ptr, command_output_ptr, timeout,
383 run_in_shell, hide_stderr);
387 llvm::StringRef command,
388 const FileSpec &working_dir,
int *status_ptr,
389 int *signo_ptr, std::string *command_output_ptr,
391 bool run_in_shell,
bool hide_stderr) {
393 signo_ptr, command_output_ptr, timeout, run_in_shell,
398 int *status_ptr,
int *signo_ptr,
399 std::string *command_output_ptr,
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,
408 const FileSpec &working_dir,
int *status_ptr,
409 int *signo_ptr, std::string *command_output_ptr,
411 bool run_in_shell,
bool hide_stderr) {
417 FileSpec shell = HostInfo::GetDefaultShell();
418 if (!shell_path.empty())
423 const bool will_debug =
false;
424 const bool first_arg_is_full_shell_command =
false;
426 error, will_debug, first_arg_is_full_shell_command, 0);
429 const bool first_arg_is_executable =
true;
430 launch_info.
SetArguments(args, first_arg_is_executable);
437 llvm::SmallString<64> output_file_path;
439 if (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());
456 if (output_file_spec)
462 if (output_file_spec && !hide_stderr)
467 std::shared_ptr<ShellInfo> shell_info_sp(
new ShellInfo());
470 std::placeholders::_2, std::placeholders::_3));
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");
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();
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");
507 command_output_ptr->assign(
508 reinterpret_cast<char *
>(Buffer->GetBytes()),
509 Buffer->GetByteSize());
516 llvm::sys::fs::remove(output_file_spec.
GetPath());
522#if !defined(__APPLE__)
524 std::unique_ptr<ProcessLauncher> delegate_launcher;
548#if !defined(__APPLE__)
552 return llvm::errorCodeToError(
553 std::error_code(ENOTSUP, std::system_category()));
561 if (url.startswith(
"file://"))
567#if defined(LLVM_ON_UNIX)
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");
579void llvm::format_provider<WaitStatus>::format(
const WaitStatus &WS,
595 OS << formatv(
"{0}{1:x-2}", type, WS.
status);
603 desc =
"Exited with status";
606 desc =
"Killed by signal";
609 desc =
"Stopped by signal";
612 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)