21#include <sys/syscall.h>
28#include <mach-o/dyld.h>
29#include <mach/mach_init.h>
30#include <mach/mach_port.h>
33#if defined(__FreeBSD__)
34#include <pthread_np.h>
37#if defined(__NetBSD__)
59#include "llvm/ADT/SmallString.h"
60#include "llvm/Config/llvm-config.h"
61#include "llvm/Support/Errno.h"
62#include "llvm/Support/FileSystem.h"
72#ifndef _POSIX_SPAWN_DISABLE_ASLR
73#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
86#if !defined(__APPLE__)
110#if !defined(__APPLE__) && !defined(_WIN32)
121 char thread_name[256];
122 ::snprintf(thread_name,
sizeof(thread_name),
123 "<lldb.host.wait4(pid=%" PRIu64
")>", pid);
137 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
145 if (m_old_state != -1)
146 ::pthread_setcancelstate(m_old_state, 0);
155static thread_local volatile sig_atomic_t g_usr1_called;
157static void SigUsr1Handler(
int) { g_usr1_called = 1; }
167 ::pthread_testcancel();
182 struct sigaction sigUsr1Action;
183 memset(&sigUsr1Action, 0,
sizeof(sigUsr1Action));
184 sigUsr1Action.sa_handler = SigUsr1Handler;
185 ::sigaction(SIGUSR1, &sigUsr1Action,
nullptr);
190 LLDB_LOG(log,
"::waitpid({0}, &status, 0)...", pid);
195 const ::pid_t wait_pid = ::waitpid(pid, &status, 0);
197 LLDB_LOG(log,
"::waitpid({0}, &status, 0) => pid = {1}, status = {2:x}", pid,
205 if (errno != EINTR) {
206 LLDB_LOG(log,
"pid = {0}, thread exiting because waitpid failed ({1})...",
207 pid, llvm::sys::StrError());
214 if (WIFEXITED(status)) {
215 exit_status = WEXITSTATUS(status);
216 }
else if (WIFSIGNALED(status)) {
217 signal = WTERMSIG(status);
220 llvm_unreachable(
"Unknown status");
230 callback(pid, signal, exit_status);
262#if !defined(SIGIO) || (SIGPOLL != SIGIO)
335#if !defined(__APPLE__)
350 if (::dladdr(host_addr, &info)) {
351 if (info.dli_fname) {
352 module_filespec.
SetFile(info.dli_fname, FileSpec::Style::native);
356 return module_filespec;
361#if !defined(__linux__)
381 shell_info->pid = pid;
382 shell_info->signo = signo;
383 shell_info->status = status;
390 const FileSpec &working_dir,
int *status_ptr,
391 int *signo_ptr, std::string *command_output_ptr,
393 bool run_in_shell,
bool hide_stderr) {
395 status_ptr, signo_ptr, command_output_ptr, timeout,
396 run_in_shell, hide_stderr);
400 llvm::StringRef command,
401 const FileSpec &working_dir,
int *status_ptr,
402 int *signo_ptr, std::string *command_output_ptr,
404 bool run_in_shell,
bool hide_stderr) {
406 signo_ptr, command_output_ptr, timeout, run_in_shell,
411 int *status_ptr,
int *signo_ptr,
412 std::string *command_output_ptr,
414 bool run_in_shell,
bool hide_stderr) {
415 return RunShellCommand(llvm::StringRef(), args, working_dir, status_ptr,
416 signo_ptr, command_output_ptr, timeout, run_in_shell,
421 const FileSpec &working_dir,
int *status_ptr,
422 int *signo_ptr, std::string *command_output_ptr,
424 bool run_in_shell,
bool hide_stderr) {
430 FileSpec shell = HostInfo::GetDefaultShell();
431 if (!shell_path.empty())
436 const bool will_debug =
false;
437 const bool first_arg_is_full_shell_command =
false;
439 error, will_debug, first_arg_is_full_shell_command, 0);
442 const bool first_arg_is_executable =
true;
443 launch_info.
SetArguments(args, first_arg_is_executable);
450 llvm::SmallString<64> output_file_path;
452 if (command_output_ptr) {
456 if (
FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
457 tmpdir_file_spec.AppendPathComponent(
"lldb-shell-output.%%%%%%");
458 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
461 llvm::sys::fs::createTemporaryFile(
"lldb-shell-output.%%%%%%",
"",
466 FileSpec output_file_spec(output_file_path.str());
469 if (output_file_spec)
475 if (output_file_spec && !hide_stderr)
480 std::shared_ptr<ShellInfo> shell_info_sp(
new ShellInfo());
483 std::placeholders::_2, std::placeholders::_3));
491 if (
error.Success()) {
492 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(
true, timeout)) {
494 "timed out waiting for shell command to complete");
499 shell_info_sp->process_reaped.WaitForValueEqualTo(
500 true, std::chrono::seconds(1));
503 *status_ptr = shell_info_sp->status;
506 *signo_ptr = shell_info_sp->signo;
508 if (command_output_ptr) {
509 command_output_ptr->clear();
513 if (file_size > command_output_ptr->max_size()) {
515 "shell command output is too large to fit into a std::string");
521 command_output_ptr->assign(
522 reinterpret_cast<char *
>(Buffer->GetBytes()),
523 Buffer->GetByteSize());
530 llvm::sys::fs::remove(output_file_spec.
GetPath());
536#if !defined(__APPLE__)
538 std::unique_ptr<ProcessLauncher> delegate_launcher;
562#if !defined(__APPLE__)
566 return llvm::errorCodeToError(
567 std::error_code(ENOTSUP, std::system_category()));
575 if (url.starts_with(
"file://"))
581#if defined(LLVM_ON_UNIX)
583 if (WIFEXITED(wstatus))
584 return {
Exit, uint8_t(WEXITSTATUS(wstatus))};
585 else if (WIFSIGNALED(wstatus))
586 return {
Signal, uint8_t(WTERMSIG(wstatus))};
587 else if (WIFSTOPPED(wstatus))
588 return {
Stop, uint8_t(WSTOPSIG(wstatus))};
589 llvm_unreachable(
"Unknown wait status");
593void llvm::format_provider<WaitStatus>::format(
const WaitStatus &WS,
609 OS << formatv(
"{0}{1:x-2}", type, WS.
status);
617 desc =
"Exited with status";
620 desc =
"Killed by signal";
623 desc =
"Stopped by signal";
626 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)