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