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 #include "lldb/lldb-python.h" 11 12 // C includes 13 #include <errno.h> 14 #include <limits.h> 15 #include <sys/types.h> 16 #ifdef _WIN32 17 #include "lldb/Host/windows/windows.h" 18 #include <winsock2.h> 19 #include <WS2tcpip.h> 20 #else 21 #include <dlfcn.h> 22 #include <grp.h> 23 #include <netdb.h> 24 #include <pwd.h> 25 #endif 26 27 #if !defined (__GNU__) && !defined (_WIN32) 28 // Does not exist under GNU/HURD or Windows 29 #include <sys/sysctl.h> 30 #endif 31 32 #if defined (__APPLE__) 33 #include <mach/mach_port.h> 34 #include <mach/mach_init.h> 35 #include <mach-o/dyld.h> 36 #endif 37 38 #if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) 39 #include <spawn.h> 40 #include <sys/wait.h> 41 #include <sys/syscall.h> 42 #endif 43 44 #if defined (__FreeBSD__) 45 #include <pthread_np.h> 46 #endif 47 48 #include "lldb/Host/Host.h" 49 #include "lldb/Core/ArchSpec.h" 50 #include "lldb/Core/ConstString.h" 51 #include "lldb/Core/Debugger.h" 52 #include "lldb/Core/Error.h" 53 #include "lldb/Core/Log.h" 54 #include "lldb/Core/Module.h" 55 #include "lldb/Core/StreamString.h" 56 #include "lldb/Core/ThreadSafeSTLMap.h" 57 #include "lldb/Host/Config.h" 58 #include "lldb/Host/Endian.h" 59 #include "lldb/Host/FileSpec.h" 60 #include "lldb/Host/Mutex.h" 61 #include "lldb/Target/Process.h" 62 #include "lldb/Target/TargetList.h" 63 #include "lldb/Utility/CleanUp.h" 64 65 #include "llvm/ADT/SmallString.h" 66 #include "llvm/Support/Host.h" 67 #include "llvm/Support/raw_ostream.h" 68 69 70 using namespace lldb; 71 using namespace lldb_private; 72 73 74 #if !defined (__APPLE__) && !defined (_WIN32) 75 struct MonitorInfo 76 { 77 lldb::pid_t pid; // The process ID to monitor 78 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals 79 void *callback_baton; // The callback baton for the callback function 80 bool monitor_signals; // If true, call the callback when "pid" gets signaled. 81 }; 82 83 static thread_result_t 84 MonitorChildProcessThreadFunction (void *arg); 85 86 lldb::thread_t 87 Host::StartMonitoringChildProcess 88 ( 89 Host::MonitorChildProcessCallback callback, 90 void *callback_baton, 91 lldb::pid_t pid, 92 bool monitor_signals 93 ) 94 { 95 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD; 96 MonitorInfo * info_ptr = new MonitorInfo(); 97 98 info_ptr->pid = pid; 99 info_ptr->callback = callback; 100 info_ptr->callback_baton = callback_baton; 101 info_ptr->monitor_signals = monitor_signals; 102 103 char thread_name[256]; 104 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid); 105 thread = ThreadCreate (thread_name, 106 MonitorChildProcessThreadFunction, 107 info_ptr, 108 NULL); 109 110 return thread; 111 } 112 113 //------------------------------------------------------------------ 114 // Scoped class that will disable thread canceling when it is 115 // constructed, and exception safely restore the previous value it 116 // when it goes out of scope. 117 //------------------------------------------------------------------ 118 class ScopedPThreadCancelDisabler 119 { 120 public: 121 ScopedPThreadCancelDisabler() 122 { 123 // Disable the ability for this thread to be cancelled 124 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state); 125 if (err != 0) 126 m_old_state = -1; 127 128 } 129 130 ~ScopedPThreadCancelDisabler() 131 { 132 // Restore the ability for this thread to be cancelled to what it 133 // previously was. 134 if (m_old_state != -1) 135 ::pthread_setcancelstate (m_old_state, 0); 136 } 137 private: 138 int m_old_state; // Save the old cancelability state. 139 }; 140 141 static thread_result_t 142 MonitorChildProcessThreadFunction (void *arg) 143 { 144 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 145 const char *function = __FUNCTION__; 146 if (log) 147 log->Printf ("%s (arg = %p) thread starting...", function, arg); 148 149 MonitorInfo *info = (MonitorInfo *)arg; 150 151 const Host::MonitorChildProcessCallback callback = info->callback; 152 void * const callback_baton = info->callback_baton; 153 const bool monitor_signals = info->monitor_signals; 154 155 assert (info->pid <= UINT32_MAX); 156 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid; 157 158 delete info; 159 160 int status = -1; 161 #if defined (__FreeBSD__) || defined (__FreeBSD_kernel__) 162 #define __WALL 0 163 #endif 164 const int options = __WALL; 165 166 while (1) 167 { 168 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 169 if (log) 170 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options); 171 172 // Wait for all child processes 173 ::pthread_testcancel (); 174 // Get signals from all children with same process group of pid 175 const ::pid_t wait_pid = ::waitpid (pid, &status, options); 176 ::pthread_testcancel (); 177 178 if (wait_pid == -1) 179 { 180 if (errno == EINTR) 181 continue; 182 else 183 { 184 if (log) 185 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno)); 186 break; 187 } 188 } 189 else if (wait_pid > 0) 190 { 191 bool exited = false; 192 int signal = 0; 193 int exit_status = 0; 194 const char *status_cstr = NULL; 195 if (WIFSTOPPED(status)) 196 { 197 signal = WSTOPSIG(status); 198 status_cstr = "STOPPED"; 199 } 200 else if (WIFEXITED(status)) 201 { 202 exit_status = WEXITSTATUS(status); 203 status_cstr = "EXITED"; 204 exited = true; 205 } 206 else if (WIFSIGNALED(status)) 207 { 208 signal = WTERMSIG(status); 209 status_cstr = "SIGNALED"; 210 if (wait_pid == abs(pid)) { 211 exited = true; 212 exit_status = -1; 213 } 214 } 215 else 216 { 217 status_cstr = "(\?\?\?)"; 218 } 219 220 // Scope for pthread_cancel_disabler 221 { 222 ScopedPThreadCancelDisabler pthread_cancel_disabler; 223 224 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 225 if (log) 226 log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i", 227 function, 228 wait_pid, 229 options, 230 pid, 231 status, 232 status_cstr, 233 signal, 234 exit_status); 235 236 if (exited || (signal != 0 && monitor_signals)) 237 { 238 bool callback_return = false; 239 if (callback) 240 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status); 241 242 // If our process exited, then this thread should exit 243 if (exited && wait_pid == abs(pid)) 244 { 245 if (log) 246 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg); 247 break; 248 } 249 // If the callback returns true, it means this process should 250 // exit 251 if (callback_return) 252 { 253 if (log) 254 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg); 255 break; 256 } 257 } 258 } 259 } 260 } 261 262 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 263 if (log) 264 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg); 265 266 return NULL; 267 } 268 269 #endif // #if !defined (__APPLE__) && !defined (_WIN32) 270 271 #if !defined (__APPLE__) 272 273 void 274 Host::SystemLog (SystemLogType type, const char *format, va_list args) 275 { 276 vfprintf (stderr, format, args); 277 } 278 279 #endif 280 281 void 282 Host::SystemLog (SystemLogType type, const char *format, ...) 283 { 284 va_list args; 285 va_start (args, format); 286 SystemLog (type, format, args); 287 va_end (args); 288 } 289 290 const ArchSpec & 291 Host::GetArchitecture (SystemDefaultArchitecture arch_kind) 292 { 293 static bool g_supports_32 = false; 294 static bool g_supports_64 = false; 295 static ArchSpec g_host_arch_32; 296 static ArchSpec g_host_arch_64; 297 298 #if defined (__APPLE__) 299 300 // Apple is different in that it can support both 32 and 64 bit executables 301 // in the same operating system running concurrently. Here we detect the 302 // correct host architectures for both 32 and 64 bit including if 64 bit 303 // executables are supported on the system. 304 305 if (g_supports_32 == false && g_supports_64 == false) 306 { 307 // All apple systems support 32 bit execution. 308 g_supports_32 = true; 309 uint32_t cputype, cpusubtype; 310 uint32_t is_64_bit_capable = false; 311 size_t len = sizeof(cputype); 312 ArchSpec host_arch; 313 // These will tell us about the kernel architecture, which even on a 64 314 // bit machine can be 32 bit... 315 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0) 316 { 317 len = sizeof (cpusubtype); 318 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0) 319 cpusubtype = CPU_TYPE_ANY; 320 321 len = sizeof (is_64_bit_capable); 322 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0) 323 { 324 if (is_64_bit_capable) 325 g_supports_64 = true; 326 } 327 328 if (is_64_bit_capable) 329 { 330 #if defined (__i386__) || defined (__x86_64__) 331 if (cpusubtype == CPU_SUBTYPE_486) 332 cpusubtype = CPU_SUBTYPE_I386_ALL; 333 #endif 334 if (cputype & CPU_ARCH_ABI64) 335 { 336 // We have a 64 bit kernel on a 64 bit system 337 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype); 338 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 339 } 340 else 341 { 342 // We have a 32 bit kernel on a 64 bit system 343 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 344 cputype |= CPU_ARCH_ABI64; 345 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 346 } 347 } 348 else 349 { 350 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 351 g_host_arch_64.Clear(); 352 } 353 } 354 } 355 356 #else // #if defined (__APPLE__) 357 358 if (g_supports_32 == false && g_supports_64 == false) 359 { 360 llvm::Triple triple(llvm::sys::getDefaultTargetTriple()); 361 362 g_host_arch_32.Clear(); 363 g_host_arch_64.Clear(); 364 365 // If the OS is Linux, "unknown" in the vendor slot isn't what we want 366 // for the default triple. It's probably an artifact of config.guess. 367 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor) 368 triple.setVendorName(""); 369 370 switch (triple.getArch()) 371 { 372 default: 373 g_host_arch_32.SetTriple(triple); 374 g_supports_32 = true; 375 break; 376 377 case llvm::Triple::x86_64: 378 g_host_arch_64.SetTriple(triple); 379 g_supports_64 = true; 380 g_host_arch_32.SetTriple(triple.get32BitArchVariant()); 381 g_supports_32 = true; 382 break; 383 384 case llvm::Triple::sparcv9: 385 case llvm::Triple::ppc64: 386 g_host_arch_64.SetTriple(triple); 387 g_supports_64 = true; 388 break; 389 } 390 391 g_supports_32 = g_host_arch_32.IsValid(); 392 g_supports_64 = g_host_arch_64.IsValid(); 393 } 394 395 #endif // #else for #if defined (__APPLE__) 396 397 if (arch_kind == eSystemDefaultArchitecture32) 398 return g_host_arch_32; 399 else if (arch_kind == eSystemDefaultArchitecture64) 400 return g_host_arch_64; 401 402 if (g_supports_64) 403 return g_host_arch_64; 404 405 return g_host_arch_32; 406 } 407 408 const ConstString & 409 Host::GetVendorString() 410 { 411 static ConstString g_vendor; 412 if (!g_vendor) 413 { 414 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture); 415 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName(); 416 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size()); 417 } 418 return g_vendor; 419 } 420 421 const ConstString & 422 Host::GetOSString() 423 { 424 static ConstString g_os_string; 425 if (!g_os_string) 426 { 427 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture); 428 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName(); 429 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size()); 430 } 431 return g_os_string; 432 } 433 434 const ConstString & 435 Host::GetTargetTriple() 436 { 437 static ConstString g_host_triple; 438 if (!(g_host_triple)) 439 { 440 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture); 441 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str()); 442 } 443 return g_host_triple; 444 } 445 446 lldb::pid_t 447 Host::GetCurrentProcessID() 448 { 449 return ::getpid(); 450 } 451 452 #ifndef _WIN32 453 454 lldb::tid_t 455 Host::GetCurrentThreadID() 456 { 457 #if defined (__APPLE__) 458 // Calling "mach_port_deallocate()" bumps the reference count on the thread 459 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref 460 // count. 461 thread_port_t thread_self = mach_thread_self(); 462 mach_port_deallocate(mach_task_self(), thread_self); 463 return thread_self; 464 #elif defined(__FreeBSD__) 465 return lldb::tid_t(pthread_getthreadid_np()); 466 #elif defined(__linux__) 467 return lldb::tid_t(syscall(SYS_gettid)); 468 #else 469 return lldb::tid_t(pthread_self()); 470 #endif 471 } 472 473 lldb::thread_t 474 Host::GetCurrentThread () 475 { 476 return lldb::thread_t(pthread_self()); 477 } 478 479 const char * 480 Host::GetSignalAsCString (int signo) 481 { 482 switch (signo) 483 { 484 case SIGHUP: return "SIGHUP"; // 1 hangup 485 case SIGINT: return "SIGINT"; // 2 interrupt 486 case SIGQUIT: return "SIGQUIT"; // 3 quit 487 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught) 488 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught) 489 case SIGABRT: return "SIGABRT"; // 6 abort() 490 #if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE)) 491 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported) 492 #endif 493 #if !defined(_POSIX_C_SOURCE) 494 case SIGEMT: return "SIGEMT"; // 7 EMT instruction 495 #endif 496 case SIGFPE: return "SIGFPE"; // 8 floating point exception 497 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored) 498 case SIGBUS: return "SIGBUS"; // 10 bus error 499 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation 500 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call 501 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it 502 case SIGALRM: return "SIGALRM"; // 14 alarm clock 503 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill 504 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel 505 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty 506 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty 507 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process 508 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit 509 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read 510 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local<OSTOP) 511 #if !defined(_POSIX_C_SOURCE) 512 case SIGIO: return "SIGIO"; // 23 input/output possible signal 513 #endif 514 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit 515 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit 516 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm 517 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm 518 #if !defined(_POSIX_C_SOURCE) 519 case SIGWINCH: return "SIGWINCH"; // 28 window size changes 520 case SIGINFO: return "SIGINFO"; // 29 information request 521 #endif 522 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1 523 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2 524 default: 525 break; 526 } 527 return NULL; 528 } 529 530 #endif 531 532 void 533 Host::WillTerminate () 534 { 535 } 536 537 #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm 538 539 void 540 Host::ThreadCreated (const char *thread_name) 541 { 542 } 543 544 void 545 Host::Backtrace (Stream &strm, uint32_t max_frames) 546 { 547 // TODO: Is there a way to backtrace the current process on other systems? 548 } 549 550 size_t 551 Host::GetEnvironment (StringList &env) 552 { 553 // TODO: Is there a way to the host environment for this process on other systems? 554 return 0; 555 } 556 557 #endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) 558 559 struct HostThreadCreateInfo 560 { 561 std::string thread_name; 562 thread_func_t thread_fptr; 563 thread_arg_t thread_arg; 564 565 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) : 566 thread_name (name ? name : ""), 567 thread_fptr (fptr), 568 thread_arg (arg) 569 { 570 } 571 }; 572 573 static thread_result_t 574 #ifdef _WIN32 575 __stdcall 576 #endif 577 ThreadCreateTrampoline (thread_arg_t arg) 578 { 579 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg; 580 Host::ThreadCreated (info->thread_name.c_str()); 581 thread_func_t thread_fptr = info->thread_fptr; 582 thread_arg_t thread_arg = info->thread_arg; 583 584 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 585 if (log) 586 log->Printf("thread created"); 587 588 delete info; 589 return thread_fptr (thread_arg); 590 } 591 592 lldb::thread_t 593 Host::ThreadCreate 594 ( 595 const char *thread_name, 596 thread_func_t thread_fptr, 597 thread_arg_t thread_arg, 598 Error *error 599 ) 600 { 601 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD; 602 603 // Host::ThreadCreateTrampoline will delete this pointer for us. 604 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg); 605 606 #ifdef _WIN32 607 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL); 608 int err = thread <= 0 ? GetLastError() : 0; 609 #else 610 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr); 611 #endif 612 if (err == 0) 613 { 614 if (error) 615 error->Clear(); 616 return thread; 617 } 618 619 if (error) 620 error->SetError (err, eErrorTypePOSIX); 621 622 return LLDB_INVALID_HOST_THREAD; 623 } 624 625 #ifndef _WIN32 626 627 bool 628 Host::ThreadCancel (lldb::thread_t thread, Error *error) 629 { 630 int err = ::pthread_cancel (thread); 631 if (error) 632 error->SetError(err, eErrorTypePOSIX); 633 return err == 0; 634 } 635 636 bool 637 Host::ThreadDetach (lldb::thread_t thread, Error *error) 638 { 639 int err = ::pthread_detach (thread); 640 if (error) 641 error->SetError(err, eErrorTypePOSIX); 642 return err == 0; 643 } 644 645 bool 646 Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error) 647 { 648 int err = ::pthread_join (thread, thread_result_ptr); 649 if (error) 650 error->SetError(err, eErrorTypePOSIX); 651 return err == 0; 652 } 653 654 lldb::thread_key_t 655 Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback) 656 { 657 pthread_key_t key; 658 ::pthread_key_create (&key, callback); 659 return key; 660 } 661 662 void* 663 Host::ThreadLocalStorageGet(lldb::thread_key_t key) 664 { 665 return ::pthread_getspecific (key); 666 } 667 668 void 669 Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value) 670 { 671 ::pthread_setspecific (key, value); 672 } 673 674 bool 675 Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name) 676 { 677 #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5 678 lldb::pid_t curr_pid = Host::GetCurrentProcessID(); 679 lldb::tid_t curr_tid = Host::GetCurrentThreadID(); 680 if (pid == LLDB_INVALID_PROCESS_ID) 681 pid = curr_pid; 682 683 if (tid == LLDB_INVALID_THREAD_ID) 684 tid = curr_tid; 685 686 // Set the pthread name if possible 687 if (pid == curr_pid && tid == curr_tid) 688 { 689 if (::pthread_setname_np (name) == 0) 690 return true; 691 } 692 return false; 693 #elif defined (__FreeBSD__) 694 lldb::pid_t curr_pid = Host::GetCurrentProcessID(); 695 lldb::tid_t curr_tid = Host::GetCurrentThreadID(); 696 if (pid == LLDB_INVALID_PROCESS_ID) 697 pid = curr_pid; 698 699 if (tid == LLDB_INVALID_THREAD_ID) 700 tid = curr_tid; 701 702 // Set the pthread name if possible 703 if (pid == curr_pid && tid == curr_tid) 704 { 705 ::pthread_set_name_np (::pthread_self(), name); 706 return true; 707 } 708 return false; 709 #elif defined (__linux__) || defined (__GLIBC__) 710 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np"); 711 if (fn) 712 { 713 lldb::pid_t curr_pid = Host::GetCurrentProcessID(); 714 lldb::tid_t curr_tid = Host::GetCurrentThreadID(); 715 if (pid == LLDB_INVALID_PROCESS_ID) 716 pid = curr_pid; 717 718 if (tid == LLDB_INVALID_THREAD_ID) 719 tid = curr_tid; 720 721 if (pid == curr_pid && tid == curr_tid) 722 { 723 int (*pthread_setname_np_func)(pthread_t thread, const char *name); 724 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn; 725 726 if (pthread_setname_np_func (::pthread_self(), name) == 0) 727 return true; 728 } 729 } 730 return false; 731 #else 732 return false; 733 #endif 734 } 735 736 bool 737 Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid, 738 const char *thread_name, size_t len) 739 { 740 char *namebuf = (char *)::malloc (len + 1); 741 742 // Thread names are coming in like '<lldb.comm.debugger.edit>' and 743 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string 744 // off leads to a lot of similar named threads. Go through the thread name 745 // and search for the last dot and use that. 746 const char *lastdot = ::strrchr (thread_name, '.'); 747 748 if (lastdot && lastdot != thread_name) 749 thread_name = lastdot + 1; 750 ::strncpy (namebuf, thread_name, len); 751 namebuf[len] = 0; 752 753 int namebuflen = strlen(namebuf); 754 if (namebuflen > 0) 755 { 756 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>') 757 { 758 // Trim off trailing '(' and '>' characters for a bit more cleanup. 759 namebuflen--; 760 namebuf[namebuflen] = 0; 761 } 762 return Host::SetThreadName (pid, tid, namebuf); 763 } 764 765 ::free(namebuf); 766 return false; 767 } 768 769 #endif 770 771 FileSpec 772 Host::GetProgramFileSpec () 773 { 774 static FileSpec g_program_filespec; 775 if (!g_program_filespec) 776 { 777 #if defined (__APPLE__) 778 char program_fullpath[PATH_MAX]; 779 // If DST is NULL, then return the number of bytes needed. 780 uint32_t len = sizeof(program_fullpath); 781 int err = _NSGetExecutablePath (program_fullpath, &len); 782 if (err == 0) 783 g_program_filespec.SetFile (program_fullpath, false); 784 else if (err == -1) 785 { 786 char *large_program_fullpath = (char *)::malloc (len + 1); 787 788 err = _NSGetExecutablePath (large_program_fullpath, &len); 789 if (err == 0) 790 g_program_filespec.SetFile (large_program_fullpath, false); 791 792 ::free (large_program_fullpath); 793 } 794 #elif defined (__linux__) 795 char exe_path[PATH_MAX]; 796 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1); 797 if (len > 0) { 798 exe_path[len] = 0; 799 g_program_filespec.SetFile(exe_path, false); 800 } 801 #elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__) 802 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() }; 803 size_t exe_path_size; 804 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0) 805 { 806 char *exe_path = new char[exe_path_size]; 807 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0) 808 g_program_filespec.SetFile(exe_path, false); 809 delete[] exe_path; 810 } 811 #endif 812 } 813 return g_program_filespec; 814 } 815 816 #if !defined (__APPLE__) // see Host.mm 817 818 bool 819 Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle) 820 { 821 bundle.Clear(); 822 return false; 823 } 824 825 bool 826 Host::ResolveExecutableInBundle (FileSpec &file) 827 { 828 return false; 829 } 830 #endif 831 832 #ifndef _WIN32 833 834 // Opaque info that tracks a dynamic library that was loaded 835 struct DynamicLibraryInfo 836 { 837 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) : 838 file_spec (fs), 839 open_options (o), 840 handle (h) 841 { 842 } 843 844 const FileSpec file_spec; 845 uint32_t open_options; 846 void * handle; 847 }; 848 849 void * 850 Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error) 851 { 852 char path[PATH_MAX]; 853 if (file_spec.GetPath(path, sizeof(path))) 854 { 855 int mode = 0; 856 857 if (options & eDynamicLibraryOpenOptionLazy) 858 mode |= RTLD_LAZY; 859 else 860 mode |= RTLD_NOW; 861 862 863 if (options & eDynamicLibraryOpenOptionLocal) 864 mode |= RTLD_LOCAL; 865 else 866 mode |= RTLD_GLOBAL; 867 868 #ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED 869 if (options & eDynamicLibraryOpenOptionLimitGetSymbol) 870 mode |= RTLD_FIRST; 871 #endif 872 873 void * opaque = ::dlopen (path, mode); 874 875 if (opaque) 876 { 877 error.Clear(); 878 return new DynamicLibraryInfo (file_spec, options, opaque); 879 } 880 else 881 { 882 error.SetErrorString(::dlerror()); 883 } 884 } 885 else 886 { 887 error.SetErrorString("failed to extract path"); 888 } 889 return NULL; 890 } 891 892 Error 893 Host::DynamicLibraryClose (void *opaque) 894 { 895 Error error; 896 if (opaque == NULL) 897 { 898 error.SetErrorString ("invalid dynamic library handle"); 899 } 900 else 901 { 902 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque; 903 if (::dlclose (dylib_info->handle) != 0) 904 { 905 error.SetErrorString(::dlerror()); 906 } 907 908 dylib_info->open_options = 0; 909 dylib_info->handle = 0; 910 delete dylib_info; 911 } 912 return error; 913 } 914 915 void * 916 Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error) 917 { 918 if (opaque == NULL) 919 { 920 error.SetErrorString ("invalid dynamic library handle"); 921 } 922 else 923 { 924 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque; 925 926 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name); 927 if (symbol_addr) 928 { 929 #ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED 930 // This host doesn't support limiting searches to this shared library 931 // so we need to verify that the match came from this shared library 932 // if it was requested in the Host::DynamicLibraryOpen() function. 933 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol) 934 { 935 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr)); 936 if (match_dylib_spec != dylib_info->file_spec) 937 { 938 char dylib_path[PATH_MAX]; 939 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path))) 940 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path); 941 else 942 error.SetErrorString ("symbol not found"); 943 return NULL; 944 } 945 } 946 #endif 947 error.Clear(); 948 return symbol_addr; 949 } 950 else 951 { 952 error.SetErrorString(::dlerror()); 953 } 954 } 955 return NULL; 956 } 957 958 FileSpec 959 Host::GetModuleFileSpecForHostAddress (const void *host_addr) 960 { 961 FileSpec module_filespec; 962 Dl_info info; 963 if (::dladdr (host_addr, &info)) 964 { 965 if (info.dli_fname) 966 module_filespec.SetFile(info.dli_fname, true); 967 } 968 return module_filespec; 969 } 970 971 #endif 972 973 bool 974 Host::GetLLDBPath (PathType path_type, FileSpec &file_spec) 975 { 976 // To get paths related to LLDB we get the path to the executable that 977 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB", 978 // on linux this is assumed to be the "lldb" main executable. If LLDB on 979 // linux is actually in a shared library (liblldb.so) then this function will 980 // need to be modified to "do the right thing". 981 982 switch (path_type) 983 { 984 case ePathTypeLLDBShlibDir: 985 { 986 static ConstString g_lldb_so_dir; 987 if (!g_lldb_so_dir) 988 { 989 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath)); 990 g_lldb_so_dir = lldb_file_spec.GetDirectory(); 991 } 992 file_spec.GetDirectory() = g_lldb_so_dir; 993 return (bool)file_spec.GetDirectory(); 994 } 995 break; 996 997 case ePathTypeSupportExecutableDir: 998 { 999 static ConstString g_lldb_support_exe_dir; 1000 if (!g_lldb_support_exe_dir) 1001 { 1002 FileSpec lldb_file_spec; 1003 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 1004 { 1005 char raw_path[PATH_MAX]; 1006 char resolved_path[PATH_MAX]; 1007 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 1008 1009 #if defined (__APPLE__) 1010 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 1011 if (framework_pos) 1012 { 1013 framework_pos += strlen("LLDB.framework"); 1014 #if !defined (__arm__) 1015 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path)); 1016 #endif 1017 } 1018 #endif 1019 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 1020 g_lldb_support_exe_dir.SetCString(resolved_path); 1021 } 1022 } 1023 file_spec.GetDirectory() = g_lldb_support_exe_dir; 1024 return (bool)file_spec.GetDirectory(); 1025 } 1026 break; 1027 1028 case ePathTypeHeaderDir: 1029 { 1030 static ConstString g_lldb_headers_dir; 1031 if (!g_lldb_headers_dir) 1032 { 1033 #if defined (__APPLE__) 1034 FileSpec lldb_file_spec; 1035 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 1036 { 1037 char raw_path[PATH_MAX]; 1038 char resolved_path[PATH_MAX]; 1039 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 1040 1041 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 1042 if (framework_pos) 1043 { 1044 framework_pos += strlen("LLDB.framework"); 1045 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path)); 1046 } 1047 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 1048 g_lldb_headers_dir.SetCString(resolved_path); 1049 } 1050 #else 1051 // TODO: Anyone know how we can determine this for linux? Other systems?? 1052 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb"); 1053 #endif 1054 } 1055 file_spec.GetDirectory() = g_lldb_headers_dir; 1056 return (bool)file_spec.GetDirectory(); 1057 } 1058 break; 1059 1060 #ifdef LLDB_DISABLE_PYTHON 1061 case ePathTypePythonDir: 1062 return false; 1063 #else 1064 case ePathTypePythonDir: 1065 { 1066 static ConstString g_lldb_python_dir; 1067 if (!g_lldb_python_dir) 1068 { 1069 FileSpec lldb_file_spec; 1070 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 1071 { 1072 char raw_path[PATH_MAX]; 1073 char resolved_path[PATH_MAX]; 1074 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 1075 1076 #if defined (__APPLE__) 1077 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 1078 if (framework_pos) 1079 { 1080 framework_pos += strlen("LLDB.framework"); 1081 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path)); 1082 } 1083 #else 1084 llvm::SmallString<256> python_version_dir; 1085 llvm::raw_svector_ostream os(python_version_dir); 1086 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages"; 1087 os.flush(); 1088 1089 // We may get our string truncated. Should we protect 1090 // this with an assert? 1091 1092 ::strncat(raw_path, python_version_dir.c_str(), 1093 sizeof(raw_path) - strlen(raw_path) - 1); 1094 1095 #endif 1096 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 1097 g_lldb_python_dir.SetCString(resolved_path); 1098 } 1099 } 1100 file_spec.GetDirectory() = g_lldb_python_dir; 1101 return (bool)file_spec.GetDirectory(); 1102 } 1103 break; 1104 #endif 1105 1106 case ePathTypeLLDBSystemPlugins: // System plug-ins directory 1107 { 1108 #if defined (__APPLE__) || defined(__linux__) 1109 static ConstString g_lldb_system_plugin_dir; 1110 static bool g_lldb_system_plugin_dir_located = false; 1111 if (!g_lldb_system_plugin_dir_located) 1112 { 1113 g_lldb_system_plugin_dir_located = true; 1114 #if defined (__APPLE__) 1115 FileSpec lldb_file_spec; 1116 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 1117 { 1118 char raw_path[PATH_MAX]; 1119 char resolved_path[PATH_MAX]; 1120 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 1121 1122 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 1123 if (framework_pos) 1124 { 1125 framework_pos += strlen("LLDB.framework"); 1126 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path)); 1127 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 1128 g_lldb_system_plugin_dir.SetCString(resolved_path); 1129 } 1130 return false; 1131 } 1132 #elif defined (__linux__) 1133 FileSpec lldb_file_spec("/usr/lib/lldb", true); 1134 if (lldb_file_spec.Exists()) 1135 { 1136 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str()); 1137 } 1138 #endif // __APPLE__ || __linux__ 1139 } 1140 1141 if (g_lldb_system_plugin_dir) 1142 { 1143 file_spec.GetDirectory() = g_lldb_system_plugin_dir; 1144 return true; 1145 } 1146 #else 1147 // TODO: where would system LLDB plug-ins be located on other systems? 1148 return false; 1149 #endif 1150 } 1151 break; 1152 1153 case ePathTypeLLDBUserPlugins: // User plug-ins directory 1154 { 1155 #if defined (__APPLE__) 1156 static ConstString g_lldb_user_plugin_dir; 1157 if (!g_lldb_user_plugin_dir) 1158 { 1159 char user_plugin_path[PATH_MAX]; 1160 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns", 1161 user_plugin_path, 1162 sizeof(user_plugin_path))) 1163 { 1164 g_lldb_user_plugin_dir.SetCString(user_plugin_path); 1165 } 1166 } 1167 file_spec.GetDirectory() = g_lldb_user_plugin_dir; 1168 return (bool)file_spec.GetDirectory(); 1169 #elif defined (__linux__) 1170 static ConstString g_lldb_user_plugin_dir; 1171 if (!g_lldb_user_plugin_dir) 1172 { 1173 // XDG Base Directory Specification 1174 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html 1175 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb. 1176 FileSpec lldb_file_spec; 1177 const char *xdg_data_home = getenv("XDG_DATA_HOME"); 1178 if (xdg_data_home && xdg_data_home[0]) 1179 { 1180 std::string user_plugin_dir (xdg_data_home); 1181 user_plugin_dir += "/lldb"; 1182 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true); 1183 } 1184 else 1185 { 1186 const char *home_dir = getenv("HOME"); 1187 if (home_dir && home_dir[0]) 1188 { 1189 std::string user_plugin_dir (home_dir); 1190 user_plugin_dir += "/.local/share/lldb"; 1191 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true); 1192 } 1193 } 1194 1195 if (lldb_file_spec.Exists()) 1196 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str()); 1197 } 1198 file_spec.GetDirectory() = g_lldb_user_plugin_dir; 1199 return (bool)file_spec.GetDirectory(); 1200 #endif 1201 // TODO: where would user LLDB plug-ins be located on other systems? 1202 return false; 1203 } 1204 } 1205 1206 return false; 1207 } 1208 1209 1210 bool 1211 Host::GetHostname (std::string &s) 1212 { 1213 char hostname[PATH_MAX]; 1214 hostname[sizeof(hostname) - 1] = '\0'; 1215 if (::gethostname (hostname, sizeof(hostname) - 1) == 0) 1216 { 1217 struct hostent* h = ::gethostbyname (hostname); 1218 if (h) 1219 s.assign (h->h_name); 1220 else 1221 s.assign (hostname); 1222 return true; 1223 } 1224 return false; 1225 } 1226 1227 #ifndef _WIN32 1228 1229 const char * 1230 Host::GetUserName (uint32_t uid, std::string &user_name) 1231 { 1232 struct passwd user_info; 1233 struct passwd *user_info_ptr = &user_info; 1234 char user_buffer[PATH_MAX]; 1235 size_t user_buffer_size = sizeof(user_buffer); 1236 if (::getpwuid_r (uid, 1237 &user_info, 1238 user_buffer, 1239 user_buffer_size, 1240 &user_info_ptr) == 0) 1241 { 1242 if (user_info_ptr) 1243 { 1244 user_name.assign (user_info_ptr->pw_name); 1245 return user_name.c_str(); 1246 } 1247 } 1248 user_name.clear(); 1249 return NULL; 1250 } 1251 1252 const char * 1253 Host::GetGroupName (uint32_t gid, std::string &group_name) 1254 { 1255 char group_buffer[PATH_MAX]; 1256 size_t group_buffer_size = sizeof(group_buffer); 1257 struct group group_info; 1258 struct group *group_info_ptr = &group_info; 1259 // Try the threadsafe version first 1260 if (::getgrgid_r (gid, 1261 &group_info, 1262 group_buffer, 1263 group_buffer_size, 1264 &group_info_ptr) == 0) 1265 { 1266 if (group_info_ptr) 1267 { 1268 group_name.assign (group_info_ptr->gr_name); 1269 return group_name.c_str(); 1270 } 1271 } 1272 else 1273 { 1274 // The threadsafe version isn't currently working 1275 // for me on darwin, but the non-threadsafe version 1276 // is, so I am calling it below. 1277 group_info_ptr = ::getgrgid (gid); 1278 if (group_info_ptr) 1279 { 1280 group_name.assign (group_info_ptr->gr_name); 1281 return group_name.c_str(); 1282 } 1283 } 1284 group_name.clear(); 1285 return NULL; 1286 } 1287 1288 uint32_t 1289 Host::GetUserID () 1290 { 1291 return getuid(); 1292 } 1293 1294 uint32_t 1295 Host::GetGroupID () 1296 { 1297 return getgid(); 1298 } 1299 1300 uint32_t 1301 Host::GetEffectiveUserID () 1302 { 1303 return geteuid(); 1304 } 1305 1306 uint32_t 1307 Host::GetEffectiveGroupID () 1308 { 1309 return getegid(); 1310 } 1311 1312 #endif 1313 1314 #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm 1315 bool 1316 Host::GetOSBuildString (std::string &s) 1317 { 1318 s.clear(); 1319 return false; 1320 } 1321 1322 bool 1323 Host::GetOSKernelDescription (std::string &s) 1324 { 1325 s.clear(); 1326 return false; 1327 } 1328 #endif 1329 1330 #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__) 1331 uint32_t 1332 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) 1333 { 1334 process_infos.Clear(); 1335 return process_infos.GetSize(); 1336 } 1337 1338 bool 1339 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 1340 { 1341 process_info.Clear(); 1342 return false; 1343 } 1344 #endif 1345 1346 #if !defined(__linux__) 1347 bool 1348 Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach) 1349 { 1350 return false; 1351 } 1352 #endif 1353 1354 lldb::TargetSP 1355 Host::GetDummyTarget (lldb_private::Debugger &debugger) 1356 { 1357 static TargetSP g_dummy_target_sp; 1358 1359 // FIXME: Maybe the dummy target should be per-Debugger 1360 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid()) 1361 { 1362 ArchSpec arch(Target::GetDefaultArchitecture()); 1363 if (!arch.IsValid()) 1364 arch = Host::GetArchitecture (); 1365 Error err = debugger.GetTargetList().CreateTarget(debugger, 1366 NULL, 1367 arch.GetTriple().getTriple().c_str(), 1368 false, 1369 NULL, 1370 g_dummy_target_sp); 1371 } 1372 1373 return g_dummy_target_sp; 1374 } 1375 1376 struct ShellInfo 1377 { 1378 ShellInfo () : 1379 process_reaped (false), 1380 can_delete (false), 1381 pid (LLDB_INVALID_PROCESS_ID), 1382 signo(-1), 1383 status(-1) 1384 { 1385 } 1386 1387 lldb_private::Predicate<bool> process_reaped; 1388 lldb_private::Predicate<bool> can_delete; 1389 lldb::pid_t pid; 1390 int signo; 1391 int status; 1392 }; 1393 1394 static bool 1395 MonitorShellCommand (void *callback_baton, 1396 lldb::pid_t pid, 1397 bool exited, // True if the process did exit 1398 int signo, // Zero for no signal 1399 int status) // Exit value of process if signal is zero 1400 { 1401 ShellInfo *shell_info = (ShellInfo *)callback_baton; 1402 shell_info->pid = pid; 1403 shell_info->signo = signo; 1404 shell_info->status = status; 1405 // Let the thread running Host::RunShellCommand() know that the process 1406 // exited and that ShellInfo has been filled in by broadcasting to it 1407 shell_info->process_reaped.SetValue(1, eBroadcastAlways); 1408 // Now wait for a handshake back from that thread running Host::RunShellCommand 1409 // so we know that we can delete shell_info_ptr 1410 shell_info->can_delete.WaitForValueEqualTo(true); 1411 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete... 1412 usleep(1000); 1413 // Now delete the shell info that was passed into this function 1414 delete shell_info; 1415 return true; 1416 } 1417 1418 Error 1419 Host::RunShellCommand (const char *command, 1420 const char *working_dir, 1421 int *status_ptr, 1422 int *signo_ptr, 1423 std::string *command_output_ptr, 1424 uint32_t timeout_sec, 1425 const char *shell) 1426 { 1427 Error error; 1428 ProcessLaunchInfo launch_info; 1429 if (shell && shell[0]) 1430 { 1431 // Run the command in a shell 1432 launch_info.SetShell(shell); 1433 launch_info.GetArguments().AppendArgument(command); 1434 const bool localhost = true; 1435 const bool will_debug = false; 1436 const bool first_arg_is_full_shell_command = true; 1437 launch_info.ConvertArgumentsForLaunchingInShell (error, 1438 localhost, 1439 will_debug, 1440 first_arg_is_full_shell_command, 1441 0); 1442 } 1443 else 1444 { 1445 // No shell, just run it 1446 Args args (command); 1447 const bool first_arg_is_executable = true; 1448 launch_info.SetArguments(args, first_arg_is_executable); 1449 } 1450 1451 if (working_dir) 1452 launch_info.SetWorkingDirectory(working_dir); 1453 char output_file_path_buffer[L_tmpnam]; 1454 const char *output_file_path = NULL; 1455 if (command_output_ptr) 1456 { 1457 // Create a temporary file to get the stdout/stderr and redirect the 1458 // output of the command into this file. We will later read this file 1459 // if all goes well and fill the data into "command_output_ptr" 1460 output_file_path = ::tmpnam(output_file_path_buffer); 1461 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false); 1462 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true); 1463 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO); 1464 } 1465 else 1466 { 1467 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false); 1468 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true); 1469 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true); 1470 } 1471 1472 // The process monitor callback will delete the 'shell_info_ptr' below... 1473 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo()); 1474 1475 const bool monitor_signals = false; 1476 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals); 1477 1478 error = LaunchProcess (launch_info); 1479 const lldb::pid_t pid = launch_info.GetProcessID(); 1480 1481 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID) 1482 error.SetErrorString("failed to get process ID"); 1483 1484 if (error.Success()) 1485 { 1486 // The process successfully launched, so we can defer ownership of 1487 // "shell_info" to the MonitorShellCommand callback function that will 1488 // get called when the process dies. We release the unique pointer as it 1489 // doesn't need to delete the ShellInfo anymore. 1490 ShellInfo *shell_info = shell_info_ap.release(); 1491 TimeValue *timeout_ptr = nullptr; 1492 TimeValue timeout_time(TimeValue::Now()); 1493 if (timeout_sec > 0) { 1494 timeout_time.OffsetWithSeconds(timeout_sec); 1495 timeout_ptr = &timeout_time; 1496 } 1497 bool timed_out = false; 1498 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out); 1499 if (timed_out) 1500 { 1501 error.SetErrorString("timed out waiting for shell command to complete"); 1502 1503 // Kill the process since it didn't complete withint the timeout specified 1504 Kill (pid, SIGKILL); 1505 // Wait for the monitor callback to get the message 1506 timeout_time = TimeValue::Now(); 1507 timeout_time.OffsetWithSeconds(1); 1508 timed_out = false; 1509 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out); 1510 } 1511 else 1512 { 1513 if (status_ptr) 1514 *status_ptr = shell_info->status; 1515 1516 if (signo_ptr) 1517 *signo_ptr = shell_info->signo; 1518 1519 if (command_output_ptr) 1520 { 1521 command_output_ptr->clear(); 1522 FileSpec file_spec(output_file_path, File::eOpenOptionRead); 1523 uint64_t file_size = file_spec.GetByteSize(); 1524 if (file_size > 0) 1525 { 1526 if (file_size > command_output_ptr->max_size()) 1527 { 1528 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string"); 1529 } 1530 else 1531 { 1532 command_output_ptr->resize(file_size); 1533 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error); 1534 } 1535 } 1536 } 1537 } 1538 shell_info->can_delete.SetValue(true, eBroadcastAlways); 1539 } 1540 1541 if (output_file_path) 1542 ::unlink (output_file_path); 1543 // Handshake with the monitor thread, or just let it know in advance that 1544 // it can delete "shell_info" in case we timed out and were not able to kill 1545 // the process... 1546 return error; 1547 } 1548 1549 #if defined(__linux__) or defined(__FreeBSD__) 1550 // The functions below implement process launching via posix_spawn() for Linux 1551 // and FreeBSD. 1552 1553 // The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0, 1554 static Error 1555 LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid) 1556 { 1557 Error error; 1558 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS)); 1559 1560 assert(exe_path); 1561 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug)); 1562 1563 posix_spawnattr_t attr; 1564 1565 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX); 1566 error.LogIfError(log, "::posix_spawnattr_init ( &attr )"); 1567 if (error.Fail()) 1568 return error; 1569 1570 // Make a quick class that will cleanup the posix spawn attributes in case 1571 // we return in the middle of this function. 1572 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy); 1573 1574 sigset_t no_signals; 1575 sigset_t all_signals; 1576 sigemptyset (&no_signals); 1577 sigfillset (&all_signals); 1578 ::posix_spawnattr_setsigmask(&attr, &all_signals); 1579 ::posix_spawnattr_setsigdefault(&attr, &no_signals); 1580 1581 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK; 1582 1583 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX); 1584 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags); 1585 if (error.Fail()) 1586 return error; 1587 1588 const size_t num_file_actions = launch_info.GetNumFileActions (); 1589 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL; 1590 // Make a quick class that will cleanup the posix spawn attributes in case 1591 // we return in the middle of this function. 1592 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> 1593 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy); 1594 1595 if (num_file_actions > 0) 1596 { 1597 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX); 1598 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )"); 1599 if (error.Fail()) 1600 return error; 1601 1602 file_action_ptr = &file_actions; 1603 posix_spawn_file_actions_cleanup.set(file_action_ptr); 1604 1605 for (size_t i = 0; i < num_file_actions; ++i) 1606 { 1607 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i); 1608 if (launch_file_action && 1609 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions, 1610 launch_file_action, 1611 log, 1612 error)) 1613 return error; 1614 } 1615 } 1616 1617 // Change working directory if neccessary. 1618 char current_dir[PATH_MAX]; 1619 current_dir[0] = '\0'; 1620 1621 const char *working_dir = launch_info.GetWorkingDirectory(); 1622 if (working_dir != NULL) 1623 { 1624 if (::getcwd(current_dir, sizeof(current_dir)) == NULL) 1625 { 1626 error.SetError(errno, eErrorTypePOSIX); 1627 error.LogIfError(log, "unable to save the current directory"); 1628 return error; 1629 } 1630 1631 if (::chdir(working_dir) == -1) 1632 { 1633 error.SetError(errno, eErrorTypePOSIX); 1634 error.LogIfError(log, "unable to change working directory to %s", working_dir); 1635 return error; 1636 } 1637 } 1638 1639 const char *tmp_argv[2]; 1640 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector(); 1641 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector(); 1642 1643 // Prepare minimal argument list if we didn't get it from the launch_info structure. 1644 // We must pass argv into posix_spawnp and it must contain at least two items - 1645 // pointer to an executable and NULL. 1646 if (argv == NULL) 1647 { 1648 tmp_argv[0] = exe_path; 1649 tmp_argv[1] = NULL; 1650 argv = (char * const*)tmp_argv; 1651 } 1652 1653 error.SetError (::posix_spawnp (&pid, 1654 exe_path, 1655 (num_file_actions > 0) ? &file_actions : NULL, 1656 &attr, 1657 argv, 1658 envp), 1659 eErrorTypePOSIX); 1660 1661 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", 1662 pid, exe_path, file_action_ptr, &attr, argv, envp); 1663 1664 // Change back the current directory. 1665 // NOTE: do not override previously established error from posix_spawnp. 1666 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success()) 1667 { 1668 error.SetError(errno, eErrorTypePOSIX); 1669 error.LogIfError(log, "unable to change current directory back to %s", 1670 current_dir); 1671 } 1672 1673 return error; 1674 } 1675 1676 1677 Error 1678 Host::LaunchProcess (ProcessLaunchInfo &launch_info) 1679 { 1680 Error error; 1681 char exe_path[PATH_MAX]; 1682 1683 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ()); 1684 1685 const ArchSpec &arch_spec = launch_info.GetArchitecture(); 1686 1687 FileSpec exe_spec(launch_info.GetExecutableFile()); 1688 1689 FileSpec::FileType file_type = exe_spec.GetFileType(); 1690 if (file_type != FileSpec::eFileTypeRegular) 1691 { 1692 lldb::ModuleSP exe_module_sp; 1693 error = host_platform_sp->ResolveExecutable (exe_spec, 1694 arch_spec, 1695 exe_module_sp, 1696 NULL); 1697 1698 if (error.Fail()) 1699 return error; 1700 1701 if (exe_module_sp) 1702 exe_spec = exe_module_sp->GetFileSpec(); 1703 } 1704 1705 if (exe_spec.Exists()) 1706 { 1707 exe_spec.GetPath (exe_path, sizeof(exe_path)); 1708 } 1709 else 1710 { 1711 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path)); 1712 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path); 1713 return error; 1714 } 1715 1716 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY)); 1717 1718 ::pid_t pid = LLDB_INVALID_PROCESS_ID; 1719 1720 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid); 1721 1722 if (pid != LLDB_INVALID_PROCESS_ID) 1723 { 1724 // If all went well, then set the process ID into the launch info 1725 launch_info.SetProcessID(pid); 1726 1727 // Make sure we reap any processes we spawn or we will have zombies. 1728 if (!launch_info.MonitorProcess()) 1729 { 1730 const bool monitor_signals = false; 1731 StartMonitoringChildProcess (Process::SetProcessExitStatus, 1732 NULL, 1733 pid, 1734 monitor_signals); 1735 } 1736 } 1737 else 1738 { 1739 // Invalid process ID, something didn't go well 1740 if (error.Success()) 1741 error.SetErrorString ("process launch failed for unknown reasons"); 1742 } 1743 return error; 1744 } 1745 1746 #endif // defined(__linux__) or defined(__FreeBSD__) 1747 1748 #ifndef _WIN32 1749 1750 size_t 1751 Host::GetPageSize() 1752 { 1753 return ::getpagesize(); 1754 } 1755 1756 uint32_t 1757 Host::GetNumberCPUS () 1758 { 1759 static uint32_t g_num_cores = UINT32_MAX; 1760 if (g_num_cores == UINT32_MAX) 1761 { 1762 #if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__) 1763 1764 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN); 1765 1766 #else 1767 1768 // Assume POSIX support if a host specific case has not been supplied above 1769 g_num_cores = 0; 1770 int num_cores = 0; 1771 size_t num_cores_len = sizeof(num_cores); 1772 #ifdef HW_AVAILCPU 1773 int mib[] = { CTL_HW, HW_AVAILCPU }; 1774 #else 1775 int mib[] = { CTL_HW, HW_NCPU }; 1776 #endif 1777 1778 /* get the number of CPUs from the system */ 1779 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0)) 1780 { 1781 g_num_cores = num_cores; 1782 } 1783 else 1784 { 1785 mib[1] = HW_NCPU; 1786 num_cores_len = sizeof(num_cores); 1787 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0)) 1788 { 1789 if (num_cores > 0) 1790 g_num_cores = num_cores; 1791 } 1792 } 1793 #endif 1794 } 1795 return g_num_cores; 1796 } 1797 1798 void 1799 Host::Kill(lldb::pid_t pid, int signo) 1800 { 1801 ::kill(pid, signo); 1802 } 1803 1804 #endif 1805 1806 #if !defined (__APPLE__) 1807 bool 1808 Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no) 1809 { 1810 return false; 1811 } 1812 1813 void 1814 Host::SetCrashDescriptionWithFormat (const char *format, ...) 1815 { 1816 } 1817 1818 void 1819 Host::SetCrashDescription (const char *description) 1820 { 1821 } 1822 1823 lldb::pid_t 1824 Host::LaunchApplication (const FileSpec &app_file_spec) 1825 { 1826 return LLDB_INVALID_PROCESS_ID; 1827 } 1828 1829 uint32_t 1830 Host::MakeDirectory (const char* path, mode_t mode) 1831 { 1832 return UINT32_MAX; 1833 } 1834 #endif 1835 1836 typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap; 1837 FDToFileMap& GetFDToFileMap() 1838 { 1839 static FDToFileMap g_fd2filemap; 1840 return g_fd2filemap; 1841 } 1842 1843 lldb::user_id_t 1844 Host::OpenFile (const FileSpec& file_spec, 1845 uint32_t flags, 1846 mode_t mode, 1847 Error &error) 1848 { 1849 std::string path (file_spec.GetPath()); 1850 if (path.empty()) 1851 { 1852 error.SetErrorString("empty path"); 1853 return UINT64_MAX; 1854 } 1855 FileSP file_sp(new File()); 1856 error = file_sp->Open(path.c_str(),flags,mode); 1857 if (file_sp->IsValid() == false) 1858 return UINT64_MAX; 1859 lldb::user_id_t fd = file_sp->GetDescriptor(); 1860 GetFDToFileMap()[fd] = file_sp; 1861 return fd; 1862 } 1863 1864 bool 1865 Host::CloseFile (lldb::user_id_t fd, Error &error) 1866 { 1867 if (fd == UINT64_MAX) 1868 { 1869 error.SetErrorString ("invalid file descriptor"); 1870 return false; 1871 } 1872 FDToFileMap& file_map = GetFDToFileMap(); 1873 FDToFileMap::iterator pos = file_map.find(fd); 1874 if (pos == file_map.end()) 1875 { 1876 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd); 1877 return false; 1878 } 1879 FileSP file_sp = pos->second; 1880 if (!file_sp) 1881 { 1882 error.SetErrorString ("invalid host backing file"); 1883 return false; 1884 } 1885 error = file_sp->Close(); 1886 file_map.erase(pos); 1887 return error.Success(); 1888 } 1889 1890 uint64_t 1891 Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error) 1892 { 1893 if (fd == UINT64_MAX) 1894 { 1895 error.SetErrorString ("invalid file descriptor"); 1896 return UINT64_MAX; 1897 } 1898 FDToFileMap& file_map = GetFDToFileMap(); 1899 FDToFileMap::iterator pos = file_map.find(fd); 1900 if (pos == file_map.end()) 1901 { 1902 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd); 1903 return false; 1904 } 1905 FileSP file_sp = pos->second; 1906 if (!file_sp) 1907 { 1908 error.SetErrorString ("invalid host backing file"); 1909 return UINT64_MAX; 1910 } 1911 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail()) 1912 return UINT64_MAX; 1913 size_t bytes_written = src_len; 1914 error = file_sp->Write(src, bytes_written); 1915 if (error.Fail()) 1916 return UINT64_MAX; 1917 return bytes_written; 1918 } 1919 1920 uint64_t 1921 Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error) 1922 { 1923 if (fd == UINT64_MAX) 1924 { 1925 error.SetErrorString ("invalid file descriptor"); 1926 return UINT64_MAX; 1927 } 1928 FDToFileMap& file_map = GetFDToFileMap(); 1929 FDToFileMap::iterator pos = file_map.find(fd); 1930 if (pos == file_map.end()) 1931 { 1932 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd); 1933 return false; 1934 } 1935 FileSP file_sp = pos->second; 1936 if (!file_sp) 1937 { 1938 error.SetErrorString ("invalid host backing file"); 1939 return UINT64_MAX; 1940 } 1941 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail()) 1942 return UINT64_MAX; 1943 size_t bytes_read = dst_len; 1944 error = file_sp->Read(dst ,bytes_read); 1945 if (error.Fail()) 1946 return UINT64_MAX; 1947 return bytes_read; 1948 } 1949 1950 lldb::user_id_t 1951 Host::GetFileSize (const FileSpec& file_spec) 1952 { 1953 return file_spec.GetByteSize(); 1954 } 1955 1956 bool 1957 Host::GetFileExists (const FileSpec& file_spec) 1958 { 1959 return file_spec.Exists(); 1960 } 1961 1962 bool 1963 Host::CalculateMD5 (const FileSpec& file_spec, 1964 uint64_t &low, 1965 uint64_t &high) 1966 { 1967 #if defined (__APPLE__) 1968 StreamString md5_cmd_line; 1969 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str()); 1970 std::string hash_string; 1971 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60); 1972 if (err.Fail()) 1973 return false; 1974 // a correctly formed MD5 is 16-bytes, that is 32 hex digits 1975 // if the output is any other length it is probably wrong 1976 if (hash_string.size() != 32) 1977 return false; 1978 std::string part1(hash_string,0,16); 1979 std::string part2(hash_string,16); 1980 const char* part1_cstr = part1.c_str(); 1981 const char* part2_cstr = part2.c_str(); 1982 high = ::strtoull(part1_cstr, NULL, 16); 1983 low = ::strtoull(part2_cstr, NULL, 16); 1984 return true; 1985 #else 1986 // your own MD5 implementation here 1987 return false; 1988 #endif 1989 } 1990