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