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