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/Host/Host.h" 11 #include "lldb/Core/ArchSpec.h" 12 #include "lldb/Core/ConstString.h" 13 #include "lldb/Core/Debugger.h" 14 #include "lldb/Core/Error.h" 15 #include "lldb/Core/Log.h" 16 #include "lldb/Core/StreamString.h" 17 #include "lldb/Core/ThreadSafeSTLMap.h" 18 #include "lldb/Host/Config.h" 19 #include "lldb/Host/Endian.h" 20 #include "lldb/Host/FileSpec.h" 21 #include "lldb/Host/Mutex.h" 22 #include "lldb/Target/Process.h" 23 #include "lldb/Target/TargetList.h" 24 25 #include "llvm/Support/Host.h" 26 #include "llvm/Support/MachO.h" 27 28 #include <dlfcn.h> 29 #include <errno.h> 30 #include <grp.h> 31 #include <limits.h> 32 #include <netdb.h> 33 #include <pwd.h> 34 #include <sys/types.h> 35 36 37 #if defined (__APPLE__) 38 39 #include <dispatch/dispatch.h> 40 #include <libproc.h> 41 #include <mach-o/dyld.h> 42 #include <sys/sysctl.h> 43 44 45 #elif defined (__linux__) 46 47 #include <sys/wait.h> 48 49 #elif defined (__FreeBSD__) 50 51 #include <sys/wait.h> 52 #include <sys/sysctl.h> 53 #include <pthread_np.h> 54 55 #endif 56 57 using namespace lldb; 58 using namespace lldb_private; 59 60 61 #if !defined (__APPLE__) 62 struct MonitorInfo 63 { 64 lldb::pid_t pid; // The process ID to monitor 65 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals 66 void *callback_baton; // The callback baton for the callback function 67 bool monitor_signals; // If true, call the callback when "pid" gets signaled. 68 }; 69 70 static void * 71 MonitorChildProcessThreadFunction (void *arg); 72 73 lldb::thread_t 74 Host::StartMonitoringChildProcess 75 ( 76 Host::MonitorChildProcessCallback callback, 77 void *callback_baton, 78 lldb::pid_t pid, 79 bool monitor_signals 80 ) 81 { 82 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD; 83 MonitorInfo * info_ptr = new MonitorInfo(); 84 85 info_ptr->pid = pid; 86 info_ptr->callback = callback; 87 info_ptr->callback_baton = callback_baton; 88 info_ptr->monitor_signals = monitor_signals; 89 90 char thread_name[256]; 91 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%i)>", pid); 92 thread = ThreadCreate (thread_name, 93 MonitorChildProcessThreadFunction, 94 info_ptr, 95 NULL); 96 97 return thread; 98 } 99 100 //------------------------------------------------------------------ 101 // Scoped class that will disable thread canceling when it is 102 // constructed, and exception safely restore the previous value it 103 // when it goes out of scope. 104 //------------------------------------------------------------------ 105 class ScopedPThreadCancelDisabler 106 { 107 public: 108 ScopedPThreadCancelDisabler() 109 { 110 // Disable the ability for this thread to be cancelled 111 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state); 112 if (err != 0) 113 m_old_state = -1; 114 115 } 116 117 ~ScopedPThreadCancelDisabler() 118 { 119 // Restore the ability for this thread to be cancelled to what it 120 // previously was. 121 if (m_old_state != -1) 122 ::pthread_setcancelstate (m_old_state, 0); 123 } 124 private: 125 int m_old_state; // Save the old cancelability state. 126 }; 127 128 static void * 129 MonitorChildProcessThreadFunction (void *arg) 130 { 131 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS)); 132 const char *function = __FUNCTION__; 133 if (log) 134 log->Printf ("%s (arg = %p) thread starting...", function, arg); 135 136 MonitorInfo *info = (MonitorInfo *)arg; 137 138 const Host::MonitorChildProcessCallback callback = info->callback; 139 void * const callback_baton = info->callback_baton; 140 const lldb::pid_t pid = info->pid; 141 const bool monitor_signals = info->monitor_signals; 142 143 delete info; 144 145 int status = -1; 146 const int options = 0; 147 while (1) 148 { 149 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 150 if (log) 151 log->Printf("%s ::wait_pid (pid = %i, &status, options = %i)...", function, pid, options); 152 153 // Wait for all child processes 154 ::pthread_testcancel (); 155 const lldb::pid_t wait_pid = ::waitpid (pid, &status, options); 156 ::pthread_testcancel (); 157 158 if (wait_pid == -1) 159 { 160 if (errno == EINTR) 161 continue; 162 else 163 break; 164 } 165 else if (wait_pid == pid) 166 { 167 bool exited = false; 168 int signal = 0; 169 int exit_status = 0; 170 const char *status_cstr = NULL; 171 if (WIFSTOPPED(status)) 172 { 173 signal = WSTOPSIG(status); 174 status_cstr = "STOPPED"; 175 } 176 else if (WIFEXITED(status)) 177 { 178 exit_status = WEXITSTATUS(status); 179 status_cstr = "EXITED"; 180 exited = true; 181 } 182 else if (WIFSIGNALED(status)) 183 { 184 signal = WTERMSIG(status); 185 status_cstr = "SIGNALED"; 186 exited = true; 187 exit_status = -1; 188 } 189 else 190 { 191 status_cstr = "(\?\?\?)"; 192 } 193 194 // Scope for pthread_cancel_disabler 195 { 196 ScopedPThreadCancelDisabler pthread_cancel_disabler; 197 198 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 199 if (log) 200 log->Printf ("%s ::waitpid (pid = %i, &status, options = %i) => pid = %i, status = 0x%8.8x (%s), signal = %i, exit_state = %i", 201 function, 202 wait_pid, 203 options, 204 pid, 205 status, 206 status_cstr, 207 signal, 208 exit_status); 209 210 if (exited || (signal != 0 && monitor_signals)) 211 { 212 bool callback_return = false; 213 if (callback) 214 callback_return = callback (callback_baton, pid, exited, signal, exit_status); 215 216 // If our process exited, then this thread should exit 217 if (exited) 218 break; 219 // If the callback returns true, it means this process should 220 // exit 221 if (callback_return) 222 break; 223 } 224 } 225 } 226 } 227 228 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS); 229 if (log) 230 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg); 231 232 return NULL; 233 } 234 235 236 void 237 Host::SystemLog (SystemLogType type, const char *format, va_list args) 238 { 239 vfprintf (stderr, format, args); 240 } 241 242 #endif // #if !defined (__APPLE__) 243 244 void 245 Host::SystemLog (SystemLogType type, const char *format, ...) 246 { 247 va_list args; 248 va_start (args, format); 249 SystemLog (type, format, args); 250 va_end (args); 251 } 252 253 size_t 254 Host::GetPageSize() 255 { 256 return ::getpagesize(); 257 } 258 259 const ArchSpec & 260 Host::GetArchitecture (SystemDefaultArchitecture arch_kind) 261 { 262 static bool g_supports_32 = false; 263 static bool g_supports_64 = false; 264 static ArchSpec g_host_arch_32; 265 static ArchSpec g_host_arch_64; 266 267 #if defined (__APPLE__) 268 269 // Apple is different in that it can support both 32 and 64 bit executables 270 // in the same operating system running concurrently. Here we detect the 271 // correct host architectures for both 32 and 64 bit including if 64 bit 272 // executables are supported on the system. 273 274 if (g_supports_32 == false && g_supports_64 == false) 275 { 276 // All apple systems support 32 bit execution. 277 g_supports_32 = true; 278 uint32_t cputype, cpusubtype; 279 uint32_t is_64_bit_capable = false; 280 size_t len = sizeof(cputype); 281 ArchSpec host_arch; 282 // These will tell us about the kernel architecture, which even on a 64 283 // bit machine can be 32 bit... 284 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0) 285 { 286 len = sizeof (cpusubtype); 287 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0) 288 cpusubtype = CPU_TYPE_ANY; 289 290 len = sizeof (is_64_bit_capable); 291 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0) 292 { 293 if (is_64_bit_capable) 294 g_supports_64 = true; 295 } 296 297 if (is_64_bit_capable) 298 { 299 #if defined (__i386__) || defined (__x86_64__) 300 if (cpusubtype == CPU_SUBTYPE_486) 301 cpusubtype = CPU_SUBTYPE_I386_ALL; 302 #endif 303 if (cputype & CPU_ARCH_ABI64) 304 { 305 // We have a 64 bit kernel on a 64 bit system 306 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype); 307 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 308 } 309 else 310 { 311 // We have a 32 bit kernel on a 64 bit system 312 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 313 cputype |= CPU_ARCH_ABI64; 314 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 315 } 316 } 317 else 318 { 319 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype); 320 g_host_arch_64.Clear(); 321 } 322 } 323 } 324 325 #else // #if defined (__APPLE__) 326 327 if (g_supports_32 == false && g_supports_64 == false) 328 { 329 llvm::Triple triple(llvm::sys::getDefaultTargetTriple()); 330 331 g_host_arch_32.Clear(); 332 g_host_arch_64.Clear(); 333 334 switch (triple.getArch()) 335 { 336 default: 337 g_host_arch_32.SetTriple(triple); 338 g_supports_32 = true; 339 break; 340 341 case llvm::Triple::x86_64: 342 case llvm::Triple::sparcv9: 343 case llvm::Triple::ppc64: 344 case llvm::Triple::cellspu: 345 g_host_arch_64.SetTriple(triple); 346 g_supports_64 = true; 347 break; 348 } 349 350 g_supports_32 = g_host_arch_32.IsValid(); 351 g_supports_64 = g_host_arch_64.IsValid(); 352 } 353 354 #endif // #else for #if defined (__APPLE__) 355 356 if (arch_kind == eSystemDefaultArchitecture32) 357 return g_host_arch_32; 358 else if (arch_kind == eSystemDefaultArchitecture64) 359 return g_host_arch_64; 360 361 if (g_supports_64) 362 return g_host_arch_64; 363 364 return g_host_arch_32; 365 } 366 367 const ConstString & 368 Host::GetVendorString() 369 { 370 static ConstString g_vendor; 371 if (!g_vendor) 372 { 373 #if defined (__APPLE__) 374 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture); 375 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName(); 376 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size()); 377 #elif defined (__linux__) 378 g_vendor.SetCString("gnu"); 379 #elif defined (__FreeBSD__) 380 g_vendor.SetCString("freebsd"); 381 #endif 382 } 383 return g_vendor; 384 } 385 386 const ConstString & 387 Host::GetOSString() 388 { 389 static ConstString g_os_string; 390 if (!g_os_string) 391 { 392 #if defined (__APPLE__) 393 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture); 394 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName(); 395 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size()); 396 #elif defined (__linux__) 397 g_os_string.SetCString("linux"); 398 #elif defined (__FreeBSD__) 399 g_os_string.SetCString("freebsd"); 400 #endif 401 } 402 return g_os_string; 403 } 404 405 const ConstString & 406 Host::GetTargetTriple() 407 { 408 static ConstString g_host_triple; 409 if (!(g_host_triple)) 410 { 411 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture); 412 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str()); 413 } 414 return g_host_triple; 415 } 416 417 lldb::pid_t 418 Host::GetCurrentProcessID() 419 { 420 return ::getpid(); 421 } 422 423 lldb::tid_t 424 Host::GetCurrentThreadID() 425 { 426 #if defined (__APPLE__) 427 return ::mach_thread_self(); 428 #elif defined(__FreeBSD__) 429 return lldb::tid_t(pthread_getthreadid_np()); 430 #else 431 return lldb::tid_t(pthread_self()); 432 #endif 433 } 434 435 lldb::thread_t 436 Host::GetCurrentThread () 437 { 438 return lldb::thread_t(pthread_self()); 439 } 440 441 const char * 442 Host::GetSignalAsCString (int signo) 443 { 444 switch (signo) 445 { 446 case SIGHUP: return "SIGHUP"; // 1 hangup 447 case SIGINT: return "SIGINT"; // 2 interrupt 448 case SIGQUIT: return "SIGQUIT"; // 3 quit 449 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught) 450 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught) 451 case SIGABRT: return "SIGABRT"; // 6 abort() 452 #if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE)) 453 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported) 454 #endif 455 #if !defined(_POSIX_C_SOURCE) 456 case SIGEMT: return "SIGEMT"; // 7 EMT instruction 457 #endif 458 case SIGFPE: return "SIGFPE"; // 8 floating point exception 459 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored) 460 case SIGBUS: return "SIGBUS"; // 10 bus error 461 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation 462 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call 463 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it 464 case SIGALRM: return "SIGALRM"; // 14 alarm clock 465 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill 466 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel 467 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty 468 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty 469 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process 470 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit 471 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read 472 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local<OSTOP) 473 #if !defined(_POSIX_C_SOURCE) 474 case SIGIO: return "SIGIO"; // 23 input/output possible signal 475 #endif 476 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit 477 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit 478 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm 479 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm 480 #if !defined(_POSIX_C_SOURCE) 481 case SIGWINCH: return "SIGWINCH"; // 28 window size changes 482 case SIGINFO: return "SIGINFO"; // 29 information request 483 #endif 484 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1 485 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2 486 default: 487 break; 488 } 489 return NULL; 490 } 491 492 void 493 Host::WillTerminate () 494 { 495 } 496 497 #if !defined (__APPLE__) && !defined (__FreeBSD__) // see macosx/Host.mm 498 void 499 Host::ThreadCreated (const char *thread_name) 500 { 501 } 502 503 void 504 Host::Backtrace (Stream &strm, uint32_t max_frames) 505 { 506 // TODO: Is there a way to backtrace the current process on linux? Other systems? 507 } 508 509 size_t 510 Host::GetEnvironment (StringList &env) 511 { 512 // TODO: Is there a way to the host environment for this process on linux? Other systems? 513 return 0; 514 } 515 516 #endif 517 518 struct HostThreadCreateInfo 519 { 520 std::string thread_name; 521 thread_func_t thread_fptr; 522 thread_arg_t thread_arg; 523 524 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) : 525 thread_name (name ? name : ""), 526 thread_fptr (fptr), 527 thread_arg (arg) 528 { 529 } 530 }; 531 532 static thread_result_t 533 ThreadCreateTrampoline (thread_arg_t arg) 534 { 535 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg; 536 Host::ThreadCreated (info->thread_name.c_str()); 537 thread_func_t thread_fptr = info->thread_fptr; 538 thread_arg_t thread_arg = info->thread_arg; 539 540 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD)); 541 if (log) 542 log->Printf("thread created"); 543 544 delete info; 545 return thread_fptr (thread_arg); 546 } 547 548 lldb::thread_t 549 Host::ThreadCreate 550 ( 551 const char *thread_name, 552 thread_func_t thread_fptr, 553 thread_arg_t thread_arg, 554 Error *error 555 ) 556 { 557 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD; 558 559 // Host::ThreadCreateTrampoline will delete this pointer for us. 560 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg); 561 562 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr); 563 if (err == 0) 564 { 565 if (error) 566 error->Clear(); 567 return thread; 568 } 569 570 if (error) 571 error->SetError (err, eErrorTypePOSIX); 572 573 return LLDB_INVALID_HOST_THREAD; 574 } 575 576 bool 577 Host::ThreadCancel (lldb::thread_t thread, Error *error) 578 { 579 int err = ::pthread_cancel (thread); 580 if (error) 581 error->SetError(err, eErrorTypePOSIX); 582 return err == 0; 583 } 584 585 bool 586 Host::ThreadDetach (lldb::thread_t thread, Error *error) 587 { 588 int err = ::pthread_detach (thread); 589 if (error) 590 error->SetError(err, eErrorTypePOSIX); 591 return err == 0; 592 } 593 594 bool 595 Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error) 596 { 597 int err = ::pthread_join (thread, thread_result_ptr); 598 if (error) 599 error->SetError(err, eErrorTypePOSIX); 600 return err == 0; 601 } 602 603 // rdar://problem/8153284 604 // Fixed a crasher where during shutdown, loggings attempted to access the 605 // thread name but the static map instance had already been destructed. 606 // So we are using a ThreadSafeSTLMap POINTER, initializing it with a 607 // pthread_once action. That map will get leaked. 608 // 609 // Another approach is to introduce a static guard object which monitors its 610 // own destruction and raises a flag, but this incurs more overhead. 611 612 static pthread_once_t g_thread_map_once = PTHREAD_ONCE_INIT; 613 static ThreadSafeSTLMap<uint64_t, std::string> *g_thread_names_map_ptr; 614 615 static void 616 InitThreadNamesMap() 617 { 618 g_thread_names_map_ptr = new ThreadSafeSTLMap<uint64_t, std::string>(); 619 } 620 621 //------------------------------------------------------------------ 622 // Control access to a static file thread name map using a single 623 // static function to avoid a static constructor. 624 //------------------------------------------------------------------ 625 static const char * 626 ThreadNameAccessor (bool get, lldb::pid_t pid, lldb::tid_t tid, const char *name) 627 { 628 int success = ::pthread_once (&g_thread_map_once, InitThreadNamesMap); 629 if (success != 0) 630 return NULL; 631 632 uint64_t pid_tid = ((uint64_t)pid << 32) | (uint64_t)tid; 633 634 if (get) 635 { 636 // See if the thread name exists in our thread name pool 637 std::string value; 638 bool found_it = g_thread_names_map_ptr->GetValueForKey (pid_tid, value); 639 if (found_it) 640 return value.c_str(); 641 else 642 return NULL; 643 } 644 else if (name) 645 { 646 // Set the thread name 647 g_thread_names_map_ptr->SetValueForKey (pid_tid, std::string(name)); 648 } 649 return NULL; 650 } 651 652 const char * 653 Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid) 654 { 655 const char *name = ThreadNameAccessor (true, pid, tid, NULL); 656 if (name == NULL) 657 { 658 #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5 659 // We currently can only get the name of a thread in the current process. 660 if (pid == Host::GetCurrentProcessID()) 661 { 662 char pthread_name[1024]; 663 if (::pthread_getname_np (::pthread_from_mach_thread_np (tid), pthread_name, sizeof(pthread_name)) == 0) 664 { 665 if (pthread_name[0]) 666 { 667 // Set the thread in our string pool 668 ThreadNameAccessor (false, pid, tid, pthread_name); 669 // Get our copy of the thread name string 670 name = ThreadNameAccessor (true, pid, tid, NULL); 671 } 672 } 673 674 if (name == NULL) 675 { 676 dispatch_queue_t current_queue = ::dispatch_get_current_queue (); 677 if (current_queue != NULL) 678 name = dispatch_queue_get_label (current_queue); 679 } 680 } 681 #endif 682 } 683 return name; 684 } 685 686 void 687 Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name) 688 { 689 lldb::pid_t curr_pid = Host::GetCurrentProcessID(); 690 lldb::tid_t curr_tid = Host::GetCurrentThreadID(); 691 if (pid == LLDB_INVALID_PROCESS_ID) 692 pid = curr_pid; 693 694 if (tid == LLDB_INVALID_THREAD_ID) 695 tid = curr_tid; 696 697 #if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5 698 // Set the pthread name if possible 699 if (pid == curr_pid && tid == curr_tid) 700 { 701 ::pthread_setname_np (name); 702 } 703 #endif 704 ThreadNameAccessor (false, pid, tid, name); 705 } 706 707 FileSpec 708 Host::GetProgramFileSpec () 709 { 710 static FileSpec g_program_filespec; 711 if (!g_program_filespec) 712 { 713 #if defined (__APPLE__) 714 char program_fullpath[PATH_MAX]; 715 // If DST is NULL, then return the number of bytes needed. 716 uint32_t len = sizeof(program_fullpath); 717 int err = _NSGetExecutablePath (program_fullpath, &len); 718 if (err == 0) 719 g_program_filespec.SetFile (program_fullpath, false); 720 else if (err == -1) 721 { 722 char *large_program_fullpath = (char *)::malloc (len + 1); 723 724 err = _NSGetExecutablePath (large_program_fullpath, &len); 725 if (err == 0) 726 g_program_filespec.SetFile (large_program_fullpath, false); 727 728 ::free (large_program_fullpath); 729 } 730 #elif defined (__linux__) 731 char exe_path[PATH_MAX]; 732 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1); 733 if (len > 0) { 734 exe_path[len] = 0; 735 g_program_filespec.SetFile(exe_path, false); 736 } 737 #elif defined (__FreeBSD__) 738 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() }; 739 size_t exe_path_size; 740 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0) 741 { 742 char *exe_path = new char[exe_path_size]; 743 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0) 744 g_program_filespec.SetFile(exe_path, false); 745 delete[] exe_path; 746 } 747 #endif 748 } 749 return g_program_filespec; 750 } 751 752 FileSpec 753 Host::GetModuleFileSpecForHostAddress (const void *host_addr) 754 { 755 FileSpec module_filespec; 756 Dl_info info; 757 if (::dladdr (host_addr, &info)) 758 { 759 if (info.dli_fname) 760 module_filespec.SetFile(info.dli_fname, true); 761 } 762 return module_filespec; 763 } 764 765 #if !defined (__APPLE__) // see Host.mm 766 767 bool 768 Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle) 769 { 770 bundle.Clear(); 771 return false; 772 } 773 774 bool 775 Host::ResolveExecutableInBundle (FileSpec &file) 776 { 777 return false; 778 } 779 #endif 780 781 // Opaque info that tracks a dynamic library that was loaded 782 struct DynamicLibraryInfo 783 { 784 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) : 785 file_spec (fs), 786 open_options (o), 787 handle (h) 788 { 789 } 790 791 const FileSpec file_spec; 792 uint32_t open_options; 793 void * handle; 794 }; 795 796 void * 797 Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error) 798 { 799 char path[PATH_MAX]; 800 if (file_spec.GetPath(path, sizeof(path))) 801 { 802 int mode = 0; 803 804 if (options & eDynamicLibraryOpenOptionLazy) 805 mode |= RTLD_LAZY; 806 else 807 mode |= RTLD_NOW; 808 809 810 if (options & eDynamicLibraryOpenOptionLocal) 811 mode |= RTLD_LOCAL; 812 else 813 mode |= RTLD_GLOBAL; 814 815 #ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED 816 if (options & eDynamicLibraryOpenOptionLimitGetSymbol) 817 mode |= RTLD_FIRST; 818 #endif 819 820 void * opaque = ::dlopen (path, mode); 821 822 if (opaque) 823 { 824 error.Clear(); 825 return new DynamicLibraryInfo (file_spec, options, opaque); 826 } 827 else 828 { 829 error.SetErrorString(::dlerror()); 830 } 831 } 832 else 833 { 834 error.SetErrorString("failed to extract path"); 835 } 836 return NULL; 837 } 838 839 Error 840 Host::DynamicLibraryClose (void *opaque) 841 { 842 Error error; 843 if (opaque == NULL) 844 { 845 error.SetErrorString ("invalid dynamic library handle"); 846 } 847 else 848 { 849 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque; 850 if (::dlclose (dylib_info->handle) != 0) 851 { 852 error.SetErrorString(::dlerror()); 853 } 854 855 dylib_info->open_options = 0; 856 dylib_info->handle = 0; 857 delete dylib_info; 858 } 859 return error; 860 } 861 862 void * 863 Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error) 864 { 865 if (opaque == NULL) 866 { 867 error.SetErrorString ("invalid dynamic library handle"); 868 } 869 else 870 { 871 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque; 872 873 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name); 874 if (symbol_addr) 875 { 876 #ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED 877 // This host doesn't support limiting searches to this shared library 878 // so we need to verify that the match came from this shared library 879 // if it was requested in the Host::DynamicLibraryOpen() function. 880 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol) 881 { 882 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr)); 883 if (match_dylib_spec != dylib_info->file_spec) 884 { 885 char dylib_path[PATH_MAX]; 886 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path))) 887 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path); 888 else 889 error.SetErrorString ("symbol not found"); 890 return NULL; 891 } 892 } 893 #endif 894 error.Clear(); 895 return symbol_addr; 896 } 897 else 898 { 899 error.SetErrorString(::dlerror()); 900 } 901 } 902 return NULL; 903 } 904 905 bool 906 Host::GetLLDBPath (PathType path_type, FileSpec &file_spec) 907 { 908 // To get paths related to LLDB we get the path to the executable that 909 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB", 910 // on linux this is assumed to be the "lldb" main executable. If LLDB on 911 // linux is actually in a shared library (lldb.so??) then this function will 912 // need to be modified to "do the right thing". 913 914 switch (path_type) 915 { 916 case ePathTypeLLDBShlibDir: 917 { 918 static ConstString g_lldb_so_dir; 919 if (!g_lldb_so_dir) 920 { 921 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath)); 922 g_lldb_so_dir = lldb_file_spec.GetDirectory(); 923 } 924 file_spec.GetDirectory() = g_lldb_so_dir; 925 return file_spec.GetDirectory(); 926 } 927 break; 928 929 case ePathTypeSupportExecutableDir: 930 { 931 static ConstString g_lldb_support_exe_dir; 932 if (!g_lldb_support_exe_dir) 933 { 934 FileSpec lldb_file_spec; 935 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 936 { 937 char raw_path[PATH_MAX]; 938 char resolved_path[PATH_MAX]; 939 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 940 941 #if defined (__APPLE__) 942 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 943 if (framework_pos) 944 { 945 framework_pos += strlen("LLDB.framework"); 946 #if !defined (__arm__) 947 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path)); 948 #endif 949 } 950 #endif 951 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 952 g_lldb_support_exe_dir.SetCString(resolved_path); 953 } 954 } 955 file_spec.GetDirectory() = g_lldb_support_exe_dir; 956 return file_spec.GetDirectory(); 957 } 958 break; 959 960 case ePathTypeHeaderDir: 961 { 962 static ConstString g_lldb_headers_dir; 963 if (!g_lldb_headers_dir) 964 { 965 #if defined (__APPLE__) 966 FileSpec lldb_file_spec; 967 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 968 { 969 char raw_path[PATH_MAX]; 970 char resolved_path[PATH_MAX]; 971 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 972 973 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 974 if (framework_pos) 975 { 976 framework_pos += strlen("LLDB.framework"); 977 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path)); 978 } 979 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 980 g_lldb_headers_dir.SetCString(resolved_path); 981 } 982 #else 983 // TODO: Anyone know how we can determine this for linux? Other systems?? 984 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb"); 985 #endif 986 } 987 file_spec.GetDirectory() = g_lldb_headers_dir; 988 return file_spec.GetDirectory(); 989 } 990 break; 991 992 case ePathTypePythonDir: 993 { 994 // TODO: Anyone know how we can determine this for linux? Other systems? 995 // For linux and FreeBSD we are currently assuming the 996 // location of the lldb binary that contains this function is 997 // the directory that will contain a python directory which 998 // has our lldb module. This is how files get placed when 999 // compiling with Makefiles. 1000 1001 static ConstString g_lldb_python_dir; 1002 if (!g_lldb_python_dir) 1003 { 1004 FileSpec lldb_file_spec; 1005 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 1006 { 1007 char raw_path[PATH_MAX]; 1008 char resolved_path[PATH_MAX]; 1009 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 1010 1011 #if defined (__APPLE__) 1012 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 1013 if (framework_pos) 1014 { 1015 framework_pos += strlen("LLDB.framework"); 1016 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path)); 1017 } 1018 #else 1019 // We may get our string truncated. Should we protect 1020 // this with an assert? 1021 ::strncat(raw_path, "/python", sizeof(raw_path) - strlen(raw_path) - 1); 1022 #endif 1023 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 1024 g_lldb_python_dir.SetCString(resolved_path); 1025 } 1026 } 1027 file_spec.GetDirectory() = g_lldb_python_dir; 1028 return file_spec.GetDirectory(); 1029 } 1030 break; 1031 1032 case ePathTypeLLDBSystemPlugins: // System plug-ins directory 1033 { 1034 #if defined (__APPLE__) 1035 static ConstString g_lldb_system_plugin_dir; 1036 static bool g_lldb_system_plugin_dir_located = false; 1037 if (!g_lldb_system_plugin_dir_located) 1038 { 1039 g_lldb_system_plugin_dir_located = true; 1040 FileSpec lldb_file_spec; 1041 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec)) 1042 { 1043 char raw_path[PATH_MAX]; 1044 char resolved_path[PATH_MAX]; 1045 lldb_file_spec.GetPath(raw_path, sizeof(raw_path)); 1046 1047 char *framework_pos = ::strstr (raw_path, "LLDB.framework"); 1048 if (framework_pos) 1049 { 1050 framework_pos += strlen("LLDB.framework"); 1051 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path)); 1052 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path)); 1053 g_lldb_system_plugin_dir.SetCString(resolved_path); 1054 } 1055 return false; 1056 } 1057 } 1058 1059 if (g_lldb_system_plugin_dir) 1060 { 1061 file_spec.GetDirectory() = g_lldb_system_plugin_dir; 1062 return true; 1063 } 1064 #endif 1065 // TODO: where would system LLDB plug-ins be located on linux? Other systems? 1066 return false; 1067 } 1068 break; 1069 1070 case ePathTypeLLDBUserPlugins: // User plug-ins directory 1071 { 1072 #if defined (__APPLE__) 1073 static ConstString g_lldb_user_plugin_dir; 1074 if (!g_lldb_user_plugin_dir) 1075 { 1076 char user_plugin_path[PATH_MAX]; 1077 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns", 1078 user_plugin_path, 1079 sizeof(user_plugin_path))) 1080 { 1081 g_lldb_user_plugin_dir.SetCString(user_plugin_path); 1082 } 1083 } 1084 file_spec.GetDirectory() = g_lldb_user_plugin_dir; 1085 return file_spec.GetDirectory(); 1086 #endif 1087 // TODO: where would user LLDB plug-ins be located on linux? Other systems? 1088 return false; 1089 } 1090 default: 1091 assert (!"Unhandled PathType"); 1092 break; 1093 } 1094 1095 return false; 1096 } 1097 1098 1099 bool 1100 Host::GetHostname (std::string &s) 1101 { 1102 char hostname[PATH_MAX]; 1103 hostname[sizeof(hostname) - 1] = '\0'; 1104 if (::gethostname (hostname, sizeof(hostname) - 1) == 0) 1105 { 1106 struct hostent* h = ::gethostbyname (hostname); 1107 if (h) 1108 s.assign (h->h_name); 1109 else 1110 s.assign (hostname); 1111 return true; 1112 } 1113 return false; 1114 } 1115 1116 const char * 1117 Host::GetUserName (uint32_t uid, std::string &user_name) 1118 { 1119 struct passwd user_info; 1120 struct passwd *user_info_ptr = &user_info; 1121 char user_buffer[PATH_MAX]; 1122 size_t user_buffer_size = sizeof(user_buffer); 1123 if (::getpwuid_r (uid, 1124 &user_info, 1125 user_buffer, 1126 user_buffer_size, 1127 &user_info_ptr) == 0) 1128 { 1129 if (user_info_ptr) 1130 { 1131 user_name.assign (user_info_ptr->pw_name); 1132 return user_name.c_str(); 1133 } 1134 } 1135 user_name.clear(); 1136 return NULL; 1137 } 1138 1139 const char * 1140 Host::GetGroupName (uint32_t gid, std::string &group_name) 1141 { 1142 char group_buffer[PATH_MAX]; 1143 size_t group_buffer_size = sizeof(group_buffer); 1144 struct group group_info; 1145 struct group *group_info_ptr = &group_info; 1146 // Try the threadsafe version first 1147 if (::getgrgid_r (gid, 1148 &group_info, 1149 group_buffer, 1150 group_buffer_size, 1151 &group_info_ptr) == 0) 1152 { 1153 if (group_info_ptr) 1154 { 1155 group_name.assign (group_info_ptr->gr_name); 1156 return group_name.c_str(); 1157 } 1158 } 1159 else 1160 { 1161 // The threadsafe version isn't currently working 1162 // for me on darwin, but the non-threadsafe version 1163 // is, so I am calling it below. 1164 group_info_ptr = ::getgrgid (gid); 1165 if (group_info_ptr) 1166 { 1167 group_name.assign (group_info_ptr->gr_name); 1168 return group_name.c_str(); 1169 } 1170 } 1171 group_name.clear(); 1172 return NULL; 1173 } 1174 1175 #if !defined (__APPLE__) && !defined (__FreeBSD__) // see macosx/Host.mm 1176 bool 1177 Host::GetOSBuildString (std::string &s) 1178 { 1179 s.clear(); 1180 return false; 1181 } 1182 1183 bool 1184 Host::GetOSKernelDescription (std::string &s) 1185 { 1186 s.clear(); 1187 return false; 1188 } 1189 #endif 1190 1191 uint32_t 1192 Host::GetUserID () 1193 { 1194 return getuid(); 1195 } 1196 1197 uint32_t 1198 Host::GetGroupID () 1199 { 1200 return getgid(); 1201 } 1202 1203 uint32_t 1204 Host::GetEffectiveUserID () 1205 { 1206 return geteuid(); 1207 } 1208 1209 uint32_t 1210 Host::GetEffectiveGroupID () 1211 { 1212 return getegid(); 1213 } 1214 1215 #if !defined (__APPLE__) 1216 uint32_t 1217 Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) 1218 { 1219 process_infos.Clear(); 1220 return process_infos.GetSize(); 1221 } 1222 #endif 1223 1224 #if !defined (__APPLE__) && !defined (__FreeBSD__) 1225 bool 1226 Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 1227 { 1228 process_info.Clear(); 1229 return false; 1230 } 1231 #endif 1232 1233 lldb::TargetSP 1234 Host::GetDummyTarget (lldb_private::Debugger &debugger) 1235 { 1236 static TargetSP g_dummy_target_sp; 1237 1238 // FIXME: Maybe the dummy target should be per-Debugger 1239 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid()) 1240 { 1241 ArchSpec arch(Target::GetDefaultArchitecture()); 1242 if (!arch.IsValid()) 1243 arch = Host::GetArchitecture (); 1244 Error err = debugger.GetTargetList().CreateTarget(debugger, 1245 FileSpec(), 1246 arch.GetTriple().getTriple().c_str(), 1247 false, 1248 NULL, 1249 g_dummy_target_sp); 1250 } 1251 1252 return g_dummy_target_sp; 1253 } 1254 1255 struct ShellInfo 1256 { 1257 ShellInfo () : 1258 process_reaped (false), 1259 can_delete (false), 1260 pid (LLDB_INVALID_PROCESS_ID), 1261 signo(-1), 1262 status(-1) 1263 { 1264 } 1265 1266 lldb_private::Predicate<bool> process_reaped; 1267 lldb_private::Predicate<bool> can_delete; 1268 lldb::pid_t pid; 1269 int signo; 1270 int status; 1271 }; 1272 1273 static bool 1274 MonitorShellCommand (void *callback_baton, 1275 lldb::pid_t pid, 1276 bool exited, // True if the process did exit 1277 int signo, // Zero for no signal 1278 int status) // Exit value of process if signal is zero 1279 { 1280 ShellInfo *shell_info = (ShellInfo *)callback_baton; 1281 shell_info->pid = pid; 1282 shell_info->signo = signo; 1283 shell_info->status = status; 1284 // Let the thread running Host::RunShellCommand() know that the process 1285 // exited and that ShellInfo has been filled in by broadcasting to it 1286 shell_info->process_reaped.SetValue(1, eBroadcastAlways); 1287 // Now wait for a handshake back from that thread running Host::RunShellCommand 1288 // so we know that we can delete shell_info_ptr 1289 shell_info->can_delete.WaitForValueEqualTo(true); 1290 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete... 1291 usleep(1000); 1292 // Now delete the shell info that was passed into this function 1293 delete shell_info; 1294 return true; 1295 } 1296 1297 Error 1298 Host::RunShellCommand (const char *command, 1299 const char *working_dir, 1300 int *status_ptr, 1301 int *signo_ptr, 1302 std::string *command_output_ptr, 1303 uint32_t timeout_sec) 1304 { 1305 Error error; 1306 ProcessLaunchInfo launch_info; 1307 launch_info.SetShell("/bin/bash"); 1308 launch_info.GetArguments().AppendArgument(command); 1309 const bool localhost = true; 1310 const bool will_debug = false; 1311 const bool first_arg_is_full_shell_command = true; 1312 launch_info.ConvertArgumentsForLaunchingInShell (error, 1313 localhost, 1314 will_debug, 1315 first_arg_is_full_shell_command); 1316 1317 if (working_dir) 1318 launch_info.SetWorkingDirectory(working_dir); 1319 char output_file_path_buffer[L_tmpnam]; 1320 const char *output_file_path = NULL; 1321 if (command_output_ptr) 1322 { 1323 // Create a temporary file to get the stdout/stderr and redirect the 1324 // output of the command into this file. We will later read this file 1325 // if all goes well and fill the data into "command_output_ptr" 1326 output_file_path = ::tmpnam(output_file_path_buffer); 1327 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false); 1328 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true); 1329 launch_info.AppendDuplicateFileAction(STDERR_FILENO, STDOUT_FILENO); 1330 } 1331 else 1332 { 1333 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false); 1334 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true); 1335 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true); 1336 } 1337 1338 // The process monitor callback will delete the 'shell_info_ptr' below... 1339 std::auto_ptr<ShellInfo> shell_info_ap (new ShellInfo()); 1340 1341 const bool monitor_signals = false; 1342 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals); 1343 1344 error = LaunchProcess (launch_info); 1345 const lldb::pid_t pid = launch_info.GetProcessID(); 1346 if (pid != LLDB_INVALID_PROCESS_ID) 1347 { 1348 // The process successfully launched, so we can defer ownership of 1349 // "shell_info" to the MonitorShellCommand callback function that will 1350 // get called when the process dies. We release the std::auto_ptr as it 1351 // doesn't need to delete the ShellInfo anymore. 1352 ShellInfo *shell_info = shell_info_ap.release(); 1353 TimeValue timeout_time(TimeValue::Now()); 1354 timeout_time.OffsetWithSeconds(timeout_sec); 1355 bool timed_out = false; 1356 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out); 1357 if (timed_out) 1358 { 1359 error.SetErrorString("timed out waiting for shell command to complete"); 1360 1361 // Kill the process since it didn't complete withint the timeout specified 1362 ::kill (pid, SIGKILL); 1363 // Wait for the monitor callback to get the message 1364 timeout_time = TimeValue::Now(); 1365 timeout_time.OffsetWithSeconds(1); 1366 timed_out = false; 1367 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out); 1368 } 1369 else 1370 { 1371 if (status_ptr) 1372 *status_ptr = shell_info->status; 1373 1374 if (signo_ptr) 1375 *signo_ptr = shell_info->signo; 1376 1377 if (command_output_ptr) 1378 { 1379 command_output_ptr->clear(); 1380 FileSpec file_spec(output_file_path, File::eOpenOptionRead); 1381 uint64_t file_size = file_spec.GetByteSize(); 1382 if (file_size > 0) 1383 { 1384 if (file_size > command_output_ptr->max_size()) 1385 { 1386 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string"); 1387 } 1388 else 1389 { 1390 command_output_ptr->resize(file_size); 1391 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error); 1392 } 1393 } 1394 } 1395 } 1396 shell_info->can_delete.SetValue(true, eBroadcastAlways); 1397 } 1398 else 1399 { 1400 error.SetErrorString("failed to get process ID"); 1401 } 1402 1403 if (output_file_path) 1404 ::unlink (output_file_path); 1405 // Handshake with the monitor thread, or just let it know in advance that 1406 // it can delete "shell_info" in case we timed out and were not able to kill 1407 // the process... 1408 return error; 1409 } 1410 1411 1412 1413 #if !defined (__APPLE__) 1414 bool 1415 Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no) 1416 { 1417 return false; 1418 } 1419 1420 void 1421 Host::SetCrashDescriptionWithFormat (const char *format, ...) 1422 { 1423 } 1424 1425 void 1426 Host::SetCrashDescription (const char *description) 1427 { 1428 } 1429 1430 lldb::pid_t 1431 LaunchApplication (const FileSpec &app_file_spec) 1432 { 1433 return LLDB_INVALID_PROCESS_ID; 1434 } 1435 1436 #endif 1437