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 #include <csignal> 49 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/ProcessLauncher.h" 56 #include "lldb/Host/ThreadLauncher.h" 57 #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h" 58 #include "lldb/Target/FileAction.h" 59 #include "lldb/Target/ProcessLaunchInfo.h" 60 #include "lldb/Target/UnixSignals.h" 61 #include "lldb/Utility/DataBufferLLVM.h" 62 #include "lldb/Utility/FileSpec.h" 63 #include "lldb/Utility/Log.h" 64 #include "lldb/Utility/Predicate.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, FileSpec::Style::native); 424 FileSystem::Instance().Resolve(module_filespec); 425 } 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 const Timeout<std::micro> &timeout, 469 bool run_in_default_shell) { 470 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, 471 command_output_ptr, timeout, run_in_default_shell); 472 } 473 474 Status Host::RunShellCommand(const Args &args, const FileSpec &working_dir, 475 int *status_ptr, int *signo_ptr, 476 std::string *command_output_ptr, 477 const Timeout<std::micro> &timeout, 478 bool run_in_default_shell) { 479 Status error; 480 ProcessLaunchInfo launch_info; 481 launch_info.SetArchitecture(HostInfo::GetArchitecture()); 482 if (run_in_default_shell) { 483 // Run the command in a shell 484 launch_info.SetShell(HostInfo::GetDefaultShell()); 485 launch_info.GetArguments().AppendArguments(args); 486 const bool localhost = true; 487 const bool will_debug = false; 488 const bool first_arg_is_full_shell_command = false; 489 launch_info.ConvertArgumentsForLaunchingInShell( 490 error, localhost, will_debug, first_arg_is_full_shell_command, 0); 491 } else { 492 // No shell, just run it 493 const bool first_arg_is_executable = true; 494 launch_info.SetArguments(args, first_arg_is_executable); 495 } 496 497 if (working_dir) 498 launch_info.SetWorkingDirectory(working_dir); 499 llvm::SmallString<PATH_MAX> output_file_path; 500 501 if (command_output_ptr) { 502 // Create a temporary file to get the stdout/stderr and redirect the output 503 // of the command into this file. We will later read this file if all goes 504 // well and fill the data into "command_output_ptr" 505 if (FileSpec tmpdir_file_spec = HostInfo::GetProcessTempDir()) { 506 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%"); 507 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(), 508 output_file_path); 509 } else { 510 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "", 511 output_file_path); 512 } 513 } 514 515 FileSpec output_file_spec(output_file_path.c_str()); 516 517 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false); 518 if (output_file_spec) { 519 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false, 520 true); 521 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO); 522 } else { 523 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true); 524 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true); 525 } 526 527 std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo()); 528 const bool monitor_signals = false; 529 launch_info.SetMonitorProcessCallback( 530 std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1, 531 std::placeholders::_2, std::placeholders::_3, 532 std::placeholders::_4), 533 monitor_signals); 534 535 error = LaunchProcess(launch_info); 536 const lldb::pid_t pid = launch_info.GetProcessID(); 537 538 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID) 539 error.SetErrorString("failed to get process ID"); 540 541 if (error.Success()) { 542 if (!shell_info_sp->process_reaped.WaitForValueEqualTo(true, timeout)) { 543 error.SetErrorString("timed out waiting for shell command to complete"); 544 545 // Kill the process since it didn't complete within the timeout specified 546 Kill(pid, SIGKILL); 547 // Wait for the monitor callback to get the message 548 shell_info_sp->process_reaped.WaitForValueEqualTo( 549 true, std::chrono::seconds(1)); 550 } else { 551 if (status_ptr) 552 *status_ptr = shell_info_sp->status; 553 554 if (signo_ptr) 555 *signo_ptr = shell_info_sp->signo; 556 557 if (command_output_ptr) { 558 command_output_ptr->clear(); 559 uint64_t file_size = 560 FileSystem::Instance().GetByteSize(output_file_spec); 561 if (file_size > 0) { 562 if (file_size > command_output_ptr->max_size()) { 563 error.SetErrorStringWithFormat( 564 "shell command output is too large to fit into a std::string"); 565 } else { 566 auto Buffer = 567 FileSystem::Instance().CreateDataBuffer(output_file_spec); 568 if (error.Success()) 569 command_output_ptr->assign(Buffer->GetChars(), 570 Buffer->GetByteSize()); 571 } 572 } 573 } 574 } 575 } 576 577 llvm::sys::fs::remove(output_file_spec.GetPath()); 578 return error; 579 } 580 581 // The functions below implement process launching for non-Apple-based 582 // platforms 583 #if !defined(__APPLE__) 584 Status Host::LaunchProcess(ProcessLaunchInfo &launch_info) { 585 std::unique_ptr<ProcessLauncher> delegate_launcher; 586 #if defined(_WIN32) 587 delegate_launcher.reset(new ProcessLauncherWindows()); 588 #else 589 delegate_launcher.reset(new ProcessLauncherPosixFork()); 590 #endif 591 MonitoringProcessLauncher launcher(std::move(delegate_launcher)); 592 593 Status error; 594 HostProcess process = launcher.LaunchProcess(launch_info, error); 595 596 // TODO(zturner): It would be better if the entire HostProcess were returned 597 // instead of writing it into this structure. 598 launch_info.SetProcessID(process.GetProcessId()); 599 600 return error; 601 } 602 #endif // !defined(__APPLE__) 603 604 #ifndef _WIN32 605 void Host::Kill(lldb::pid_t pid, int signo) { ::kill(pid, signo); } 606 607 #endif 608 609 #if !defined(__APPLE__) 610 bool Host::OpenFileInExternalEditor(const FileSpec &file_spec, 611 uint32_t line_no) { 612 return false; 613 } 614 615 #endif 616 617 const UnixSignalsSP &Host::GetUnixSignals() { 618 static const auto s_unix_signals_sp = 619 UnixSignals::Create(HostInfo::GetArchitecture()); 620 return s_unix_signals_sp; 621 } 622 623 std::unique_ptr<Connection> Host::CreateDefaultConnection(llvm::StringRef url) { 624 #if defined(_WIN32) 625 if (url.startswith("file://")) 626 return std::unique_ptr<Connection>(new ConnectionGenericFile()); 627 #endif 628 return std::unique_ptr<Connection>(new ConnectionFileDescriptor()); 629 } 630 631 #if defined(LLVM_ON_UNIX) 632 WaitStatus WaitStatus::Decode(int wstatus) { 633 if (WIFEXITED(wstatus)) 634 return {Exit, uint8_t(WEXITSTATUS(wstatus))}; 635 else if (WIFSIGNALED(wstatus)) 636 return {Signal, uint8_t(WTERMSIG(wstatus))}; 637 else if (WIFSTOPPED(wstatus)) 638 return {Stop, uint8_t(WSTOPSIG(wstatus))}; 639 llvm_unreachable("Unknown wait status"); 640 } 641 #endif 642 643 void llvm::format_provider<WaitStatus>::format(const WaitStatus &WS, 644 raw_ostream &OS, 645 StringRef Options) { 646 if (Options == "g") { 647 char type; 648 switch (WS.type) { 649 case WaitStatus::Exit: 650 type = 'W'; 651 break; 652 case WaitStatus::Signal: 653 type = 'X'; 654 break; 655 case WaitStatus::Stop: 656 type = 'S'; 657 break; 658 } 659 OS << formatv("{0}{1:x-2}", type, WS.status); 660 return; 661 } 662 663 assert(Options.empty()); 664 const char *desc; 665 switch(WS.type) { 666 case WaitStatus::Exit: 667 desc = "Exited with status"; 668 break; 669 case WaitStatus::Signal: 670 desc = "Killed by signal"; 671 break; 672 case WaitStatus::Stop: 673 desc = "Stopped by signal"; 674 break; 675 } 676 OS << desc << " " << int(WS.status); 677 } 678