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