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