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__)
60#include "llvm/ADT/SmallString.h"
61#include "llvm/ADT/StringExtras.h"
62#include "llvm/Config/llvm-config.h"
63#include "llvm/Support/Errno.h"
64#include "llvm/Support/FileSystem.h"
65#include "llvm/Support/Program.h"
75#ifndef _POSIX_SPAWN_DISABLE_ASLR
76#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
89#if !defined(__APPLE__) && !defined(_WIN32)
109 g_system_log.Enable(std::make_shared<SystemLogHandler>());
114#if !defined(__APPLE__) && !defined(_WIN32)
125 char thread_name[256];
126 ::snprintf(thread_name,
sizeof(thread_name),
127 "<lldb.host.wait4(pid=%" PRIu64
")>", pid);
141 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &
m_old_state);
159static thread_local volatile sig_atomic_t g_usr1_called;
161static void SigUsr1Handler(
int) { g_usr1_called = 1; }
171 ::pthread_testcancel();
186 struct sigaction sigUsr1Action;
187 memset(&sigUsr1Action, 0,
sizeof(sigUsr1Action));
188 sigUsr1Action.sa_handler = SigUsr1Handler;
189 ::sigaction(SIGUSR1, &sigUsr1Action,
nullptr);
194 LLDB_LOG(log,
"::waitpid({0}, &status, 0)...", pid);
199 const ::pid_t wait_pid = ::waitpid(pid, &status, 0);
201 LLDB_LOG(log,
"::waitpid({0}, &status, 0) => pid = {1}, status = {2:x}",
202 pid, wait_pid, status);
209 if (errno != EINTR) {
210 LLDB_LOG(log,
"pid = {0}, thread exiting because waitpid failed ({1})...",
211 pid, llvm::sys::StrError());
218 if (WIFEXITED(status)) {
219 exit_status = WEXITSTATUS(status);
220 }
else if (WIFSIGNALED(status)) {
221 signal = WTERMSIG(status);
224 llvm_unreachable(
"Unknown status");
234 callback(pid, signal, exit_status);
266#if !defined(SIGIO) || (SIGPOLL != SIGIO)
339#if !defined(__APPLE__)
354 if (::dladdr(host_addr, &info)) {
355 if (info.dli_fname) {
356 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,
396 std::string *separated_error_output,
400 status_ptr, signo_ptr, command_output_ptr,
401 separated_error_output, timeout, run_in_shell);
405 llvm::StringRef command,
406 const FileSpec &working_dir,
int *status_ptr,
407 int *signo_ptr, std::string *command_output_ptr,
408 std::string *separated_error_output,
412 signo_ptr, command_output_ptr, separated_error_output,
413 timeout, run_in_shell);
417 int *status_ptr,
int *signo_ptr,
418 std::string *command_output_ptr,
419 std::string *separated_error_output,
422 return RunShellCommand(llvm::StringRef(), args, working_dir, status_ptr,
423 signo_ptr, command_output_ptr, separated_error_output,
424 timeout, run_in_shell);
428 const FileSpec &working_dir,
int *status_ptr,
429 int *signo_ptr, std::string *command_output_ptr,
430 std::string *separated_error_output,
438 FileSpec shell = HostInfo::GetDefaultShell();
439 if (!shell_path.empty())
444 const bool will_debug =
false;
445 const bool first_arg_is_full_shell_command =
false;
447 error, will_debug, first_arg_is_full_shell_command, 0);
450 const bool first_arg_is_executable =
true;
451 launch_info.
SetArguments(args, first_arg_is_executable);
458 llvm::SmallString<64> output_file_path;
459 llvm::SmallString<64> error_file_path;
461 if (command_output_ptr) {
465 if (
FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
466 tmpdir_file_spec.AppendPathComponent(
"lldb-shell-output.%%%%%%");
467 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
470 llvm::sys::fs::createTemporaryFile(
"lldb-shell-output.%%%%%%",
"",
475 if (separated_error_output) {
479 if (
FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) {
480 tmpdir_file_spec.AppendPathComponent(
"lldb-shell-error.%%%%%%");
481 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
484 llvm::sys::fs::createTemporaryFile(
"lldb-shell-error.%%%%%%",
"",
489 FileSpec output_file_spec(output_file_path.str());
490 FileSpec error_file_spec(error_file_path.str());
493 if (output_file_spec)
505 std::shared_ptr<ShellInfo> shell_info_sp(
new ShellInfo());
508 std::placeholders::_2, std::placeholders::_3));
516 if (
error.Success()) {
517 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(
true, timeout)) {
519 "timed out waiting for shell command to complete");
524 shell_info_sp->process_reaped.WaitForValueEqualTo(
525 true, std::chrono::seconds(1));
528 *status_ptr = shell_info_sp->status;
531 *signo_ptr = shell_info_sp->signo;
533 if (command_output_ptr) {
534 command_output_ptr->clear();
538 if (file_size > command_output_ptr->max_size()) {
540 "shell command output is too large to fit into a std::string");
546 command_output_ptr->assign(
547 reinterpret_cast<char *
>(Buffer->GetBytes()),
548 Buffer->GetByteSize());
552 if (separated_error_output) {
553 separated_error_output->clear();
557 if (file_size > separated_error_output->max_size()) {
559 "shell command error output is too large to fit into a "
566 separated_error_output->assign(
567 reinterpret_cast<char *
>(Buffer->GetBytes()),
568 Buffer->GetByteSize());
575 if (output_file_spec)
576 llvm::sys::fs::remove(output_file_spec.
GetPath());
578 llvm::sys::fs::remove(error_file_spec.
GetPath());
584#if !defined(__APPLE__)
586 std::unique_ptr<ProcessLauncher> delegate_launcher;
610#if !defined(__APPLE__)
614 return llvm::errorCodeToError(
615 std::error_code(ENOTSUP, std::system_category()));
622 return llvm::createStringError(
"cannot open empty URL");
628 return llvm::errorCodeToError(
629 std::error_code(ENOTSUP, std::system_category()));
634 llvm::ErrorOr<std::string> xdg_open =
635 llvm::sys::findProgramByName(
"xdg-open");
637 return llvm::createStringError(
"could not find xdg-open to open the URL");
647 args,
FileSpec(), &status, &signo, &output,
648 nullptr, std::chrono::seconds(10),
651 return error.takeError();
653 return llvm::createStringError(
654 llvm::formatv(
"xdg-open exited with status {0}", status));
655 return llvm::Error::success();
662 llvm::raw_string_ostream os(out);
663 llvm::printPercentEncoded(str, os);
669 if (url.starts_with(
"file://"))
675#if defined(LLVM_ON_UNIX)
677 if (WIFEXITED(wstatus))
678 return {
Exit, uint8_t(WEXITSTATUS(wstatus))};
679 else if (WIFSIGNALED(wstatus))
680 return {
Signal, uint8_t(WTERMSIG(wstatus))};
681 else if (WIFSTOPPED(wstatus))
682 return {
Stop, uint8_t(WSTOPSIG(wstatus))};
683 llvm_unreachable(
"Unknown wait status");
687void llvm::format_provider<WaitStatus>::format(
const WaitStatus &WS,
703 OS << formatv(
"{0}{1:x-2}", type, WS.
status);
711 desc =
"Exited with status";
714 desc =
"Killed by signal";
717 desc =
"Stopped by signal";
720 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 AppendArgument(llvm::StringRef arg_str, char quote_char='\0')
Appends a new argument to the end of the list argument list.
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.
std::shared_ptr< WritableDataBuffer > CreateWritableDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
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 llvm::Error OpenURL(llvm::StringRef url)
Open a URL with the host's default handler (Launch Services on macOS, xdg-open on other Unix).
static std::string URLEncode(llvm::StringRef str)
Percent-encode a string for use in a URL query component, per RFC 3986 (alphanumerics and "-_....
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 Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *error_output, const Timeout< std::micro > &timeout, bool run_in_shell=true)
Run a shell command.
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)
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)