1 //===-- Host.cpp ------------------------------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // C includes 10 #include <errno.h> 11 #include <limits.h> 12 #include <stdlib.h> 13 #include <sys/types.h> 14 #ifndef _WIN32 15 #include <dlfcn.h> 16 #include <grp.h> 17 #include <netdb.h> 18 #include <pwd.h> 19 #include <sys/stat.h> 20 #include <unistd.h> 21 #endif 22 23 #if defined(__APPLE__) 24 #include <mach-o/dyld.h> 25 #include <mach/mach_init.h> 26 #include <mach/mach_port.h> 27 #endif 28 29 #if defined(__linux__) || defined(__FreeBSD__) || \ 30 defined(__FreeBSD_kernel__) || defined(__APPLE__) || \ 31 defined(__NetBSD__) || defined(__OpenBSD__) 32 #if !defined(__ANDROID__) 33 #include <spawn.h> 34 #endif 35 #include <sys/syscall.h> 36 #include <sys/wait.h> 37 #endif 38 39 #if defined(__FreeBSD__) 40 #include <pthread_np.h> 41 #endif 42 43 #if defined(__NetBSD__) 44 #include <lwp.h> 45 #endif 46 47 #include <csignal> 48 49 #include "lldb/Host/FileAction.h" 50 #include "lldb/Host/FileSystem.h" 51 #include "lldb/Host/Host.h" 52 #include "lldb/Host/HostInfo.h" 53 #include "lldb/Host/HostProcess.h" 54 #include "lldb/Host/MonitoringProcessLauncher.h" 55 #include "lldb/Host/ProcessLaunchInfo.h" 56 #include "lldb/Host/ProcessLauncher.h" 57 #include "lldb/Host/ThreadLauncher.h" 58 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" 59 #include "lldb/Utility/DataBufferLLVM.h" 60 #include "lldb/Utility/FileSpec.h" 61 #include "lldb/Utility/Log.h" 62 #include "lldb/Utility/Predicate.h" 63 #include "lldb/Utility/Status.h" 64 #include "lldb/lldb-private-forward.h" 65 #include "llvm/ADT/SmallString.h" 66 #include "llvm/ADT/StringSwitch.h" 67 #include "llvm/Support/Errno.h" 68 #include "llvm/Support/FileSystem.h" 69 70 #if defined(_WIN32) 71 #include "lldb/Host/windows/ConnectionGenericFileWindows.h" 72 #include "lldb/Host/windows/ProcessLauncherWindows.h" 73 #else 74 #include "lldb/Host/posix/ProcessLauncherPosixFork.h" 75 #endif 76 77 #if defined(__APPLE__) 78 #ifndef _POSIX_SPAWN_DISABLE_ASLR 79 #define _POSIX_SPAWN_DISABLE_ASLR 0x0100 80 #endif 81 82 extern "C" { 83 int __pthread_chdir(const char *path); 84 int __pthread_fchdir(int fildes); 85 } 86 87 #endif 88 89 using namespace lldb; 90 using namespace lldb_private; 91 92 #if !defined(__APPLE__) && !defined(_WIN32) 93 struct MonitorInfo { 94 lldb::pid_t pid; // The process ID to monitor 95 Host::MonitorChildProcessCallback 96 callback; // The callback function to call when "pid" exits or signals 97 bool monitor_signals; // If true, call the callback when "pid" gets signaled. 98 }; 99 100 static thread_result_t MonitorChildProcessThreadFunction(void *arg); 101 102 llvm::Expected<HostThread> Host::StartMonitoringChildProcess( 103 const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid, 104 bool monitor_signals) { 105 MonitorInfo *info_ptr = new MonitorInfo(); 106 107 info_ptr->pid = pid; 108 info_ptr->callback = callback; 109 info_ptr->monitor_signals = monitor_signals; 110 111 char thread_name[256]; 112 ::snprintf(thread_name, sizeof(thread_name), 113 "<lldb.host.wait4(pid=%" PRIu64 ")>", pid); 114 return ThreadLauncher::LaunchThread( 115 thread_name, MonitorChildProcessThreadFunction, info_ptr, 0); 116 } 117 118 #ifndef __linux__ 119 // Scoped class that will disable thread canceling when it is constructed, and 120 // exception safely restore the previous value it when it goes out of scope. 121 class ScopedPThreadCancelDisabler { 122 public: 123 ScopedPThreadCancelDisabler() { 124 // Disable the ability for this thread to be cancelled 125 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state); 126 if (err != 0) 127 m_old_state = -1; 128 } 129 130 ~ScopedPThreadCancelDisabler() { 131 // Restore the ability for this thread to be cancelled to what it 132 // previously was. 133 if (m_old_state != -1) 134 ::pthread_setcancelstate(m_old_state, 0); 135 } 136 137 private: 138 int m_old_state; // Save the old cancelability state. 139 }; 140 #endif // __linux__ 141 142 #ifdef __linux__ 143 #if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) 144 static __thread volatile sig_atomic_t g_usr1_called; 145 #else 146 static thread_local volatile sig_atomic_t g_usr1_called; 147 #endif 148 149 static void SigUsr1Handler(int) { g_usr1_called = 1; } 150 #endif // __linux__ 151 152 static bool CheckForMonitorCancellation() { 153 #ifdef __linux__ 154 if (g_usr1_called) { 155 g_usr1_called = 0; 156 return true; 157 } 158 #else 159 ::pthread_testcancel(); 160 #endif 161 return false; 162 } 163 164 static thread_result_t MonitorChildProcessThreadFunction(void *arg) { 165 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS)); 166 const char *function = __FUNCTION__; 167 if (log) 168 log->Printf("%s (arg = %p) thread starting...", function, arg); 169 170 MonitorInfo *info = (MonitorInfo *)arg; 171 172 const Host::MonitorChildProcessCallback callback = info->callback; 173 const bool monitor_signals = info->monitor_signals; 174 175 assert(info->pid <= UINT32_MAX); 176 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid; 177 178 delete info; 179 180 int status = -1; 181 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) 182 #define __WALL 0 183 #endif 184 const int options = __WALL; 185 186 #ifdef __linux__ 187 // This signal is only used to interrupt the thread from waitpid 188 struct sigaction sigUsr1Action; 189 memset(&sigUsr1Action, 0, sizeof(sigUsr1Action)); 190 sigUsr1Action.sa_handler = SigUsr1Handler; 191 ::sigaction(SIGUSR1, &sigUsr1Action, nullptr); 192 #endif // __linux__ 193 194 while (1) { 195 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS); 196 if (log) 197 log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...", 198 function, pid, options); 199 200 if (CheckForMonitorCancellation()) 201 break; 202 203 // Get signals from all children with same process group of pid 204 const ::pid_t wait_pid = ::waitpid(pid, &status, options); 205 206 if (CheckForMonitorCancellation()) 207 break; 208 209 if (wait_pid == -1) { 210 if (errno == EINTR) 211 continue; 212 else { 213 LLDB_LOG(log, 214 "arg = {0}, thread exiting because waitpid failed ({1})...", 215 arg, llvm::sys::StrError()); 216 break; 217 } 218 } else if (wait_pid > 0) { 219 bool exited = false; 220 int signal = 0; 221 int exit_status = 0; 222 const char *status_cstr = nullptr; 223 if (WIFSTOPPED(status)) { 224 signal = WSTOPSIG(status); 225 status_cstr = "STOPPED"; 226 } else if (WIFEXITED(status)) { 227 exit_status = WEXITSTATUS(status); 228 status_cstr = "EXITED"; 229 exited = true; 230 } else if (WIFSIGNALED(status)) { 231 signal = WTERMSIG(status); 232 status_cstr = "SIGNALED"; 233 if (wait_pid == abs(pid)) { 234 exited = true; 235 exit_status = -1; 236 } 237 } else { 238 status_cstr = "(\?\?\?)"; 239 } 240 241 // Scope for pthread_cancel_disabler 242 { 243 #ifndef __linux__ 244 ScopedPThreadCancelDisabler pthread_cancel_disabler; 245 #endif 246 247 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS); 248 if (log) 249 log->Printf("%s ::waitpid (pid = %" PRIi32 250 ", &status, options = %i) => pid = %" PRIi32 251 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i", 252 function, pid, options, wait_pid, status, status_cstr, 253 signal, exit_status); 254 255 if (exited || (signal != 0 && monitor_signals)) { 256 bool callback_return = false; 257 if (callback) 258 callback_return = callback(wait_pid, exited, signal, exit_status); 259 260 // If our process exited, then this thread should exit 261 if (exited && wait_pid == abs(pid)) { 262 if (log) 263 log->Printf("%s (arg = %p) thread exiting because pid received " 264 "exit signal...", 265 __FUNCTION__, arg); 266 break; 267 } 268 // If the callback returns true, it means this process should exit 269 if (callback_return) { 270 if (log) 271 log->Printf("%s (arg = %p) thread exiting because callback " 272 "returned true...", 273 __FUNCTION__, arg); 274 break; 275 } 276 } 277 } 278 } 279 } 280 281 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS); 282 if (log) 283 log->Printf("%s (arg = %p) thread exiting...", __FUNCTION__, arg); 284 285 return nullptr; 286 } 287 288 #endif // #if !defined (__APPLE__) && !defined (_WIN32) 289 290 #if !defined(__APPLE__) 291 292 void Host::SystemLog(SystemLogType type, const char *format, va_list args) { 293 vfprintf(stderr, format, args); 294 } 295 296 #endif 297 298 void Host::SystemLog(SystemLogType type, const char *format, ...) { 299 va_list args; 300 va_start(args, format); 301 SystemLog(type, format, args); 302 va_end(args); 303 } 304 305 lldb::pid_t Host::GetCurrentProcessID() { return ::getpid(); } 306 307 #ifndef _WIN32 308 309 lldb::thread_t Host::GetCurrentThread() { 310 return lldb::thread_t(pthread_self()); 311 } 312 313 const char *Host::GetSignalAsCString(int signo) { 314 switch (signo) { 315 case SIGHUP: 316 return "SIGHUP"; // 1 hangup 317 case SIGINT: 318 return "SIGINT"; // 2 interrupt 319 case SIGQUIT: 320 return "SIGQUIT"; // 3 quit 321 case SIGILL: 322 return "SIGILL"; // 4 illegal instruction (not reset when caught) 323 case SIGTRAP: 324 return "SIGTRAP"; // 5 trace trap (not reset when caught) 325 case SIGABRT: 326 return "SIGABRT"; // 6 abort() 327 #if defined(SIGPOLL) 328 #if !defined(SIGIO) || (SIGPOLL != SIGIO) 329 // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to 330 // fail with 'multiple define cases with same value' 331 case SIGPOLL: 332 return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported) 333 #endif 334 #endif 335 #if defined(SIGEMT) 336 case SIGEMT: 337 return "SIGEMT"; // 7 EMT instruction 338 #endif 339 case SIGFPE: 340 return "SIGFPE"; // 8 floating point exception 341 case SIGKILL: 342 return "SIGKILL"; // 9 kill (cannot be caught or ignored) 343 case SIGBUS: 344 return "SIGBUS"; // 10 bus error 345 case SIGSEGV: 346 return "SIGSEGV"; // 11 segmentation violation 347 case SIGSYS: 348 return "SIGSYS"; // 12 bad argument to system call 349 case SIGPIPE: 350 return "SIGPIPE"; // 13 write on a pipe with no one to read it 351 case SIGALRM: 352 return "SIGALRM"; // 14 alarm clock 353 case SIGTERM: 354 return "SIGTERM"; // 15 software termination signal from kill 355 case SIGURG: 356 return "SIGURG"; // 16 urgent condition on IO channel 357 case SIGSTOP: 358 return "SIGSTOP"; // 17 sendable stop signal not from tty 359 case SIGTSTP: 360 return "SIGTSTP"; // 18 stop signal from tty 361 case SIGCONT: 362 return "SIGCONT"; // 19 continue a stopped process 363 case SIGCHLD: 364 return "SIGCHLD"; // 20 to parent on child stop or exit 365 case SIGTTIN: 366 return "SIGTTIN"; // 21 to readers pgrp upon background tty read 367 case SIGTTOU: 368 return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local<OSTOP) 369 #if defined(SIGIO) 370 case SIGIO: 371 return "SIGIO"; // 23 input/output possible signal 372 #endif 373 case SIGXCPU: 374 return "SIGXCPU"; // 24 exceeded CPU time limit 375 case SIGXFSZ: 376 return "SIGXFSZ"; // 25 exceeded file size limit 377 case SIGVTALRM: 378 return "SIGVTALRM"; // 26 virtual time alarm 379 case SIGPROF: 380 return "SIGPROF"; // 27 profiling time alarm 381 #if defined(SIGWINCH) 382 case SIGWINCH: 383 return "SIGWINCH"; // 28 window size changes 384 #endif 385 #if defined(SIGINFO) 386 case SIGINFO: 387 return "SIGINFO"; // 29 information request 388 #endif 389 case SIGUSR1: 390 return "SIGUSR1"; // 30 user defined signal 1 391 case SIGUSR2: 392 return "SIGUSR2"; // 31 user defined signal 2 393 default: 394 break; 395 } 396 return nullptr; 397 } 398 399 #endif 400 401 #if !defined(__APPLE__) // see Host.mm 402 403 bool Host::GetBundleDirectory(const FileSpec &file, FileSpec &bundle) { 404 bundle.Clear(); 405 return false; 406 } 407 408 bool Host::ResolveExecutableInBundle(FileSpec &file) { return false; } 409 #endif 410 411 #ifndef _WIN32 412 413 FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) { 414 FileSpec module_filespec; 415 #if !defined(__ANDROID__) 416 Dl_info info; 417 if (::dladdr(host_addr, &info)) { 418 if (info.dli_fname) { 419 module_filespec.SetFile(info.dli_fname, FileSpec::Style::native); 420 FileSystem::Instance().Resolve(module_filespec); 421 } 422 } 423 #endif 424 return module_filespec; 425 } 426 427 #endif 428 429 #if !defined(__linux__) 430 bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) { 431 return false; 432 } 433 #endif 434 435 struct ShellInfo { 436 ShellInfo() 437 : process_reaped(false), pid(LLDB_INVALID_PROCESS_ID), signo(-1), 438 status(-1) {} 439 440 lldb_private::Predicate<bool> process_reaped; 441 lldb::pid_t pid; 442 int signo; 443 int status; 444 }; 445 446 static bool 447 MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid, 448 bool exited, // True if the process did exit 449 int signo, // Zero for no signal 450 int status) // Exit value of process if signal is zero 451 { 452 shell_info->pid = pid; 453 shell_info->signo = signo; 454 shell_info->status = status; 455 // Let the thread running Host::RunShellCommand() know that the process 456 // exited and that ShellInfo has been filled in by broadcasting to it 457 shell_info->process_reaped.SetValue(true, eBroadcastAlways); 458 return true; 459 } 460 461 Status Host::RunShellCommand(const char *command, const FileSpec &working_dir, 462 int *status_ptr, int *signo_ptr, 463 std::string *command_output_ptr, 464 const Timeout<std::micro> &timeout, 465 bool run_in_default_shell, 466 bool hide_stderr) { 467 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, 468 command_output_ptr, timeout, run_in_default_shell, 469 hide_stderr); 470 } 471 472 Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir, 473 int *status_ptr, int *signo_ptr, 474 std::string *command_output_ptr, 475 const Timeout<std::micro> &timeout, 476 bool run_in_default_shell, 477 bool hide_stderr) { 478 Status error; 479 ProcessLaunchInfo launch_info; 480 launch_info.SetArchitecture(HostInfo::GetArchitecture()); 481 if (run_in_default_shell) { 482 // Run the command in a shell 483 launch_info.SetShell(HostInfo::GetDefaultShell()); 484 launch_info.GetArguments().AppendArguments(args); 485 const bool localhost = true; 486 const bool will_debug = false; 487 const bool first_arg_is_full_shell_command = false; 488 launch_info.ConvertArgumentsForLaunchingInShell( 489 error, localhost, will_debug, first_arg_is_full_shell_command, 0); 490 } else { 491 // No shell, just run it 492 const bool first_arg_is_executable = true; 493 launch_info.SetArguments(args, first_arg_is_executable); 494 } 495 496 if (working_dir) 497 launch_info.SetWorkingDirectory(working_dir); 498 llvm::SmallString<64> output_file_path; 499 500 if (command_output_ptr) { 501 // Create a temporary file to get the stdout/stderr and redirect the output 502 // of the command into this file. We will later read this file if all goes 503 // well and fill the data into "command_output_ptr" 504 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) { 505 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%"); 506 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(), 507 output_file_path); 508 } else { 509 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "", 510 output_file_path); 511 } 512 } 513 514 FileSpec output_file_spec(output_file_path.c_str()); 515 // Set up file descriptors. 516 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false); 517 if (output_file_spec) 518 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false, 519 true); 520 else 521 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true); 522 523 if (output_file_spec && !hide_stderr) 524 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO); 525 else 526 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true); 527 528 std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo()); 529 const bool monitor_signals = false; 530 launch_info.SetMonitorProcessCallback( 531 std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1, 532 std::placeholders::_2, std::placeholders::_3, 533 std::placeholders::_4), 534 monitor_signals); 535 536 error = LaunchProcess(launch_info); 537 const lldb::pid_t pid = launch_info.GetProcessID(); 538 539 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID) 540 error.SetErrorString("failed to get process ID"); 541 542 if (error.Success()) { 543 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(true, timeout)) { 544 error.SetErrorString("timed out waiting for shell command to complete"); 545 546 // Kill the process since it didn't complete within the timeout specified 547 Kill(pid, SIGKILL); 548 // Wait for the monitor callback to get the message 549 shell_info_sp->process_reaped.WaitForValueEqualTo( 550 true, std::chrono::seconds(1)); 551 } else { 552 if (status_ptr) 553 *status_ptr = shell_info_sp->status; 554 555 if (signo_ptr) 556 *signo_ptr = shell_info_sp->signo; 557 558 if (command_output_ptr) { 559 command_output_ptr->clear(); 560 uint64_t file_size = 561 FileSystem::Instance().GetByteSize(output_file_spec); 562 if (file_size > 0) { 563 if (file_size > command_output_ptr->max_size()) { 564 error.SetErrorStringWithFormat( 565 "shell command output is too large to fit into a std::string"); 566 } else { 567 auto Buffer = 568 FileSystem::Instance().CreateDataBuffer(output_file_spec); 569 if (error.Success()) 570 command_output_ptr->assign(Buffer->GetChars(), 571 Buffer->GetByteSize()); 572 } 573 } 574 } 575 } 576 } 577 578 llvm::sys::fs::remove(output_file_spec.GetPath()); 579 return error; 580 } 581 582 // The functions below implement process launching for non-Apple-based 583 // platforms 584 #if !defined(__APPLE__) 585 Status Host::LaunchProcess(ProcessLaunchInfo &launch_info) { 586 std::unique_ptr<ProcessLauncher> delegate_launcher; 587 #if defined(_WIN32) 588 delegate_launcher.reset(new ProcessLauncherWindows()); 589 #else 590 delegate_launcher.reset(new ProcessLauncherPosixFork()); 591 #endif 592 MonitoringProcessLauncher launcher(std::move(delegate_launcher)); 593 594 Status error; 595 HostProcess process = launcher.LaunchProcess(launch_info, error); 596 597 // TODO(zturner): It would be better if the entire HostProcess were returned 598 // instead of writing it into this structure. 599 launch_info.SetProcessID(process.GetProcessId()); 600 601 return error; 602 } 603 #endif // !defined(__APPLE__) 604 605 #ifndef _WIN32 606 void Host::Kill(lldb::pid_t pid, int signo) { ::kill(pid, signo); } 607 608 #endif 609 610 #if !defined(__APPLE__) 611 bool Host::OpenFileInExternalEditor(const FileSpec &file_spec, 612 uint32_t line_no) { 613 return false; 614 } 615 616 #endif 617 618 std::unique_ptr<Connection> Host::CreateDefaultConnection(llvm::StringRef url) { 619 #if defined(_WIN32) 620 if (url.startswith("file://")) 621 return std::unique_ptr<Connection>(new ConnectionGenericFile()); 622 #endif 623 return std::unique_ptr<Connection>(new ConnectionFileDescriptor()); 624 } 625 626 #if defined(LLVM_ON_UNIX) 627 WaitStatus WaitStatus::Decode(int wstatus) { 628 if (WIFEXITED(wstatus)) 629 return {Exit, uint8_t(WEXITSTATUS(wstatus))}; 630 else if (WIFSIGNALED(wstatus)) 631 return {Signal, uint8_t(WTERMSIG(wstatus))}; 632 else if (WIFSTOPPED(wstatus)) 633 return {Stop, uint8_t(WSTOPSIG(wstatus))}; 634 llvm_unreachable("Unknown wait status"); 635 } 636 #endif 637 638 void llvm::format_provider<WaitStatus>::format(const WaitStatus &WS, 639 raw_ostream &OS, 640 StringRef Options) { 641 if (Options == "g") { 642 char type; 643 switch (WS.type) { 644 case WaitStatus::Exit: 645 type = 'W'; 646 break; 647 case WaitStatus::Signal: 648 type = 'X'; 649 break; 650 case WaitStatus::Stop: 651 type = 'S'; 652 break; 653 } 654 OS << formatv("{0}{1:x-2}", type, WS.status); 655 return; 656 } 657 658 assert(Options.empty()); 659 const char *desc; 660 switch(WS.type) { 661 case WaitStatus::Exit: 662 desc = "Exited with status"; 663 break; 664 case WaitStatus::Signal: 665 desc = "Killed by signal"; 666 break; 667 case WaitStatus::Stop: 668 desc = "Stopped by signal"; 669 break; 670 } 671 OS << desc << " " << int(WS.status); 672 } 673