blob: 2e4a863113d17b1a1ad60ba54b96d0359ad6374c [file] [log] [blame]
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001//===-- 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/Error.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000014#include "lldb/Core/Log.h"
15#include "lldb/Core/StreamString.h"
Greg Clayton14ef59f2011-02-08 00:35:34 +000016#include "lldb/Host/Config.h"
Greg Claytoncd548032011-02-01 01:31:41 +000017#include "lldb/Host/Endian.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000018#include "lldb/Host/FileSpec.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000019#include "lldb/Host/Mutex.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000020#include "lldb/Target/Process.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000021
Stephen Wilson7f513ba2011-02-24 19:15:09 +000022#include "llvm/Support/Host.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000023#include "llvm/Support/MachO.h"
Stephen Wilson7f513ba2011-02-24 19:15:09 +000024
Greg Clayton8f3b21d2010-09-07 20:11:56 +000025#include <dlfcn.h>
26#include <errno.h>
Greg Clayton8f3b21d2010-09-07 20:11:56 +000027
28#if defined (__APPLE__)
Greg Clayton14ef59f2011-02-08 00:35:34 +000029
Greg Clayton49ce6822010-10-31 03:01:06 +000030#include <dispatch/dispatch.h>
Greg Clayton8f3b21d2010-09-07 20:11:56 +000031#include <libproc.h>
32#include <mach-o/dyld.h>
Greg Claytonb5f67fb2011-02-05 06:36:35 +000033#include <sys/sysctl.h>
Greg Clayton14ef59f2011-02-08 00:35:34 +000034
Greg Clayton0f577c22011-02-07 17:43:47 +000035#elif defined (__linux__)
Greg Clayton14ef59f2011-02-08 00:35:34 +000036
Greg Clayton0f577c22011-02-07 17:43:47 +000037#include <sys/wait.h>
Greg Clayton14ef59f2011-02-08 00:35:34 +000038
Greg Clayton8f3b21d2010-09-07 20:11:56 +000039#endif
40
41using namespace lldb;
42using namespace lldb_private;
43
44struct MonitorInfo
45{
46 lldb::pid_t pid; // The process ID to monitor
47 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
48 void *callback_baton; // The callback baton for the callback function
49 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
50};
51
52static void *
53MonitorChildProcessThreadFunction (void *arg);
54
55lldb::thread_t
56Host::StartMonitoringChildProcess
57(
58 Host::MonitorChildProcessCallback callback,
59 void *callback_baton,
60 lldb::pid_t pid,
61 bool monitor_signals
62)
63{
64 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
65 if (callback)
66 {
67 std::auto_ptr<MonitorInfo> info_ap(new MonitorInfo);
68
69 info_ap->pid = pid;
70 info_ap->callback = callback;
71 info_ap->callback_baton = callback_baton;
72 info_ap->monitor_signals = monitor_signals;
73
74 char thread_name[256];
75 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%i)>", pid);
76 thread = ThreadCreate (thread_name,
77 MonitorChildProcessThreadFunction,
78 info_ap.get(),
79 NULL);
80
Greg Clayton09c81ef2011-02-08 01:34:25 +000081 if (IS_VALID_LLDB_HOST_THREAD(thread))
Greg Clayton8f3b21d2010-09-07 20:11:56 +000082 info_ap.release();
83 }
84 return thread;
85}
86
87//------------------------------------------------------------------
88// Scoped class that will disable thread canceling when it is
89// constructed, and exception safely restore the previous value it
90// when it goes out of scope.
91//------------------------------------------------------------------
92class ScopedPThreadCancelDisabler
93{
94public:
95 ScopedPThreadCancelDisabler()
96 {
97 // Disable the ability for this thread to be cancelled
98 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
99 if (err != 0)
100 m_old_state = -1;
101
102 }
103
104 ~ScopedPThreadCancelDisabler()
105 {
106 // Restore the ability for this thread to be cancelled to what it
107 // previously was.
108 if (m_old_state != -1)
109 ::pthread_setcancelstate (m_old_state, 0);
110 }
111private:
112 int m_old_state; // Save the old cancelability state.
113};
114
115static void *
116MonitorChildProcessThreadFunction (void *arg)
117{
Greg Claytone005f2c2010-11-06 01:53:30 +0000118 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000119 const char *function = __FUNCTION__;
120 if (log)
121 log->Printf ("%s (arg = %p) thread starting...", function, arg);
122
123 MonitorInfo *info = (MonitorInfo *)arg;
124
125 const Host::MonitorChildProcessCallback callback = info->callback;
126 void * const callback_baton = info->callback_baton;
127 const lldb::pid_t pid = info->pid;
128 const bool monitor_signals = info->monitor_signals;
129
130 delete info;
131
132 int status = -1;
133 const int options = 0;
134 struct rusage *rusage = NULL;
135 while (1)
136 {
Caroline Tice926060e2010-10-29 21:48:37 +0000137 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000138 if (log)
139 log->Printf("%s ::wait4 (pid = %i, &status, options = %i, rusage = %p)...", function, pid, options, rusage);
140
141 // Wait for all child processes
142 ::pthread_testcancel ();
143 const lldb::pid_t wait_pid = ::wait4 (pid, &status, options, rusage);
144 ::pthread_testcancel ();
145
146 if (wait_pid == -1)
147 {
148 if (errno == EINTR)
149 continue;
150 else
151 break;
152 }
153 else if (wait_pid == pid)
154 {
155 bool exited = false;
156 int signal = 0;
157 int exit_status = 0;
158 const char *status_cstr = NULL;
159 if (WIFSTOPPED(status))
160 {
161 signal = WSTOPSIG(status);
162 status_cstr = "STOPPED";
163 }
164 else if (WIFEXITED(status))
165 {
166 exit_status = WEXITSTATUS(status);
167 status_cstr = "EXITED";
168 exited = true;
169 }
170 else if (WIFSIGNALED(status))
171 {
172 signal = WTERMSIG(status);
173 status_cstr = "SIGNALED";
174 exited = true;
175 exit_status = -1;
176 }
177 else
178 {
179 status_cstr = "(???)";
180 }
181
182 // Scope for pthread_cancel_disabler
183 {
184 ScopedPThreadCancelDisabler pthread_cancel_disabler;
185
Caroline Tice926060e2010-10-29 21:48:37 +0000186 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000187 if (log)
188 log->Printf ("%s ::wait4 (pid = %i, &status, options = %i, rusage = %p) => pid = %i, status = 0x%8.8x (%s), signal = %i, exit_state = %i",
189 function,
190 wait_pid,
191 options,
192 rusage,
193 pid,
194 status,
195 status_cstr,
196 signal,
197 exit_status);
198
199 if (exited || (signal != 0 && monitor_signals))
200 {
201 bool callback_return = callback (callback_baton, pid, signal, exit_status);
202
203 // If our process exited, then this thread should exit
204 if (exited)
205 break;
206 // If the callback returns true, it means this process should
207 // exit
208 if (callback_return)
209 break;
210 }
211 }
212 }
213 }
214
Caroline Tice926060e2010-10-29 21:48:37 +0000215 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000216 if (log)
217 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
218
219 return NULL;
220}
221
222size_t
223Host::GetPageSize()
224{
225 return ::getpagesize();
226}
227
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000228const ArchSpec &
Greg Clayton395fc332011-02-15 21:59:32 +0000229Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000230{
Greg Clayton395fc332011-02-15 21:59:32 +0000231 static bool g_supports_32 = false;
232 static bool g_supports_64 = false;
233 static ArchSpec g_host_arch_32;
234 static ArchSpec g_host_arch_64;
235
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000236#if defined (__APPLE__)
Greg Clayton395fc332011-02-15 21:59:32 +0000237
238 // Apple is different in that it can support both 32 and 64 bit executables
239 // in the same operating system running concurrently. Here we detect the
240 // correct host architectures for both 32 and 64 bit including if 64 bit
241 // executables are supported on the system.
242
243 if (g_supports_32 == false && g_supports_64 == false)
244 {
245 // All apple systems support 32 bit execution.
246 g_supports_32 = true;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000247 uint32_t cputype, cpusubtype;
Greg Clayton395fc332011-02-15 21:59:32 +0000248 uint32_t is_64_bit_capable = false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000249 size_t len = sizeof(cputype);
Greg Clayton395fc332011-02-15 21:59:32 +0000250 ArchSpec host_arch;
251 // These will tell us about the kernel architecture, which even on a 64
252 // bit machine can be 32 bit...
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000253 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
254 {
Greg Clayton395fc332011-02-15 21:59:32 +0000255 len = sizeof (cpusubtype);
256 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
257 cpusubtype = CPU_TYPE_ANY;
258
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000259 len = sizeof (is_64_bit_capable);
260 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
261 {
262 if (is_64_bit_capable)
Greg Clayton395fc332011-02-15 21:59:32 +0000263 g_supports_64 = true;
264 }
265
266 if (is_64_bit_capable)
267 {
Greg Clayton75c703d2011-02-16 04:46:07 +0000268#if defined (__i386__) || defined (__x86_64__)
269 if (cpusubtype == CPU_SUBTYPE_486)
270 cpusubtype = CPU_SUBTYPE_I386_ALL;
271#endif
Greg Clayton395fc332011-02-15 21:59:32 +0000272 if (cputype & CPU_ARCH_ABI64)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000273 {
Greg Clayton395fc332011-02-15 21:59:32 +0000274 // We have a 64 bit kernel on a 64 bit system
Greg Clayton940b1032011-02-23 00:35:02 +0000275 g_host_arch_32.SetArchitecture (lldb::eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
276 g_host_arch_64.SetArchitecture (lldb::eArchTypeMachO, cputype, cpusubtype);
Greg Clayton395fc332011-02-15 21:59:32 +0000277 }
278 else
279 {
280 // We have a 32 bit kernel on a 64 bit system
Greg Clayton940b1032011-02-23 00:35:02 +0000281 g_host_arch_32.SetArchitecture (lldb::eArchTypeMachO, cputype, cpusubtype);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000282 cputype |= CPU_ARCH_ABI64;
Greg Clayton940b1032011-02-23 00:35:02 +0000283 g_host_arch_64.SetArchitecture (lldb::eArchTypeMachO, cputype, cpusubtype);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000284 }
285 }
Greg Clayton395fc332011-02-15 21:59:32 +0000286 else
287 {
Greg Clayton940b1032011-02-23 00:35:02 +0000288 g_host_arch_32.SetArchitecture (lldb::eArchTypeMachO, cputype, cpusubtype);
Greg Clayton395fc332011-02-15 21:59:32 +0000289 g_host_arch_64.Clear();
290 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000291 }
Greg Clayton395fc332011-02-15 21:59:32 +0000292 }
293
294#else // #if defined (__APPLE__)
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000295
Greg Clayton395fc332011-02-15 21:59:32 +0000296 if (g_supports_32 == false && g_supports_64 == false)
297 {
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000298 llvm::Triple triple(llvm::sys::getHostTriple());
Greg Clayton395fc332011-02-15 21:59:32 +0000299
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000300 g_host_arch_32.Clear();
301 g_host_arch_64.Clear();
Greg Clayton395fc332011-02-15 21:59:32 +0000302
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000303 switch (triple.getArch())
304 {
305 default:
306 g_host_arch_32.SetTriple(triple);
307 g_supports_32 = true;
308 break;
Greg Clayton395fc332011-02-15 21:59:32 +0000309
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000310 case llvm::Triple::alpha:
311 case llvm::Triple::x86_64:
312 case llvm::Triple::sparcv9:
313 case llvm::Triple::ppc64:
314 case llvm::Triple::systemz:
315 case llvm::Triple::cellspu:
316 g_host_arch_64.SetTriple(triple);
317 g_supports_64 = true;
318 break;
319 }
Greg Clayton4fefe322011-02-17 02:05:38 +0000320
321 g_supports_32 = g_host_arch_32.IsValid();
322 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000323 }
Greg Clayton395fc332011-02-15 21:59:32 +0000324
325#endif // #else for #if defined (__APPLE__)
326
327 if (arch_kind == eSystemDefaultArchitecture32)
328 return g_host_arch_32;
329 else if (arch_kind == eSystemDefaultArchitecture64)
330 return g_host_arch_64;
331
332 if (g_supports_64)
333 return g_host_arch_64;
334
335 return g_host_arch_32;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000336}
337
338const ConstString &
339Host::GetVendorString()
340{
341 static ConstString g_vendor;
342 if (!g_vendor)
343 {
344#if defined (__APPLE__)
345 char ostype[64];
346 size_t len = sizeof(ostype);
347 if (::sysctlbyname("kern.ostype", &ostype, &len, NULL, 0) == 0)
348 g_vendor.SetCString (ostype);
349 else
350 g_vendor.SetCString("apple");
351#elif defined (__linux__)
352 g_vendor.SetCString("gnu");
353#endif
354 }
355 return g_vendor;
356}
357
358const ConstString &
359Host::GetOSString()
360{
361 static ConstString g_os_string;
362 if (!g_os_string)
363 {
364#if defined (__APPLE__)
365 g_os_string.SetCString("darwin");
366#elif defined (__linux__)
367 g_os_string.SetCString("linux");
368#endif
369 }
370 return g_os_string;
371}
372
373const ConstString &
374Host::GetTargetTriple()
375{
376 static ConstString g_host_triple;
377 if (!(g_host_triple))
378 {
379 StreamString triple;
380 triple.Printf("%s-%s-%s",
Greg Clayton940b1032011-02-23 00:35:02 +0000381 GetArchitecture().GetArchitectureName(),
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000382 GetVendorString().AsCString(),
383 GetOSString().AsCString());
384
385 std::transform (triple.GetString().begin(),
386 triple.GetString().end(),
387 triple.GetString().begin(),
388 ::tolower);
389
390 g_host_triple.SetCString(triple.GetString().c_str());
391 }
392 return g_host_triple;
393}
394
395lldb::pid_t
396Host::GetCurrentProcessID()
397{
398 return ::getpid();
399}
400
401lldb::tid_t
402Host::GetCurrentThreadID()
403{
404#if defined (__APPLE__)
405 return ::mach_thread_self();
406#else
407 return lldb::tid_t(pthread_self());
408#endif
409}
410
411const char *
412Host::GetSignalAsCString (int signo)
413{
414 switch (signo)
415 {
416 case SIGHUP: return "SIGHUP"; // 1 hangup
417 case SIGINT: return "SIGINT"; // 2 interrupt
418 case SIGQUIT: return "SIGQUIT"; // 3 quit
419 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
420 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
421 case SIGABRT: return "SIGABRT"; // 6 abort()
422#if defined(_POSIX_C_SOURCE)
423 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
424#else // !_POSIX_C_SOURCE
425 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
426#endif // !_POSIX_C_SOURCE
427 case SIGFPE: return "SIGFPE"; // 8 floating point exception
428 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
429 case SIGBUS: return "SIGBUS"; // 10 bus error
430 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
431 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
432 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
433 case SIGALRM: return "SIGALRM"; // 14 alarm clock
434 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
435 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
436 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
437 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
438 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
439 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
440 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
441 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
442#if !defined(_POSIX_C_SOURCE)
443 case SIGIO: return "SIGIO"; // 23 input/output possible signal
444#endif
445 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
446 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
447 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
448 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
449#if !defined(_POSIX_C_SOURCE)
450 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
451 case SIGINFO: return "SIGINFO"; // 29 information request
452#endif
453 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
454 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
455 default:
456 break;
457 }
458 return NULL;
459}
460
461void
462Host::WillTerminate ()
463{
464}
465
466#if !defined (__APPLE__) // see macosx/Host.mm
467void
468Host::ThreadCreated (const char *thread_name)
469{
470}
Greg Claytonb749a262010-12-03 06:02:24 +0000471
472void
473Host::Backtrace (Stream &strm, uint32_t max_frames)
474{
Greg Clayton52fd9842011-02-02 02:24:04 +0000475 // TODO: Is there a way to backtrace the current process on linux? Other systems?
Greg Claytonb749a262010-12-03 06:02:24 +0000476}
477
Greg Clayton638351a2010-12-04 00:10:17 +0000478
479size_t
480Host::GetEnvironment (StringList &env)
481{
Greg Clayton52fd9842011-02-02 02:24:04 +0000482 // TODO: Is there a way to the host environment for this process on linux? Other systems?
Greg Clayton638351a2010-12-04 00:10:17 +0000483 return 0;
484}
485
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000486#endif
487
488struct HostThreadCreateInfo
489{
490 std::string thread_name;
491 thread_func_t thread_fptr;
492 thread_arg_t thread_arg;
493
494 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
495 thread_name (name ? name : ""),
496 thread_fptr (fptr),
497 thread_arg (arg)
498 {
499 }
500};
501
502static thread_result_t
503ThreadCreateTrampoline (thread_arg_t arg)
504{
505 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
506 Host::ThreadCreated (info->thread_name.c_str());
507 thread_func_t thread_fptr = info->thread_fptr;
508 thread_arg_t thread_arg = info->thread_arg;
509
Greg Claytone005f2c2010-11-06 01:53:30 +0000510 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000511 if (log)
512 log->Printf("thread created");
513
514 delete info;
515 return thread_fptr (thread_arg);
516}
517
518lldb::thread_t
519Host::ThreadCreate
520(
521 const char *thread_name,
522 thread_func_t thread_fptr,
523 thread_arg_t thread_arg,
524 Error *error
525)
526{
527 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
528
529 // Host::ThreadCreateTrampoline will delete this pointer for us.
530 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
531
532 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
533 if (err == 0)
534 {
535 if (error)
536 error->Clear();
537 return thread;
538 }
539
540 if (error)
541 error->SetError (err, eErrorTypePOSIX);
542
543 return LLDB_INVALID_HOST_THREAD;
544}
545
546bool
547Host::ThreadCancel (lldb::thread_t thread, Error *error)
548{
549 int err = ::pthread_cancel (thread);
550 if (error)
551 error->SetError(err, eErrorTypePOSIX);
552 return err == 0;
553}
554
555bool
556Host::ThreadDetach (lldb::thread_t thread, Error *error)
557{
558 int err = ::pthread_detach (thread);
559 if (error)
560 error->SetError(err, eErrorTypePOSIX);
561 return err == 0;
562}
563
564bool
565Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
566{
567 int err = ::pthread_join (thread, thread_result_ptr);
568 if (error)
569 error->SetError(err, eErrorTypePOSIX);
570 return err == 0;
571}
572
573//------------------------------------------------------------------
574// Control access to a static file thread name map using a single
575// static function to avoid a static constructor.
576//------------------------------------------------------------------
577static const char *
578ThreadNameAccessor (bool get, lldb::pid_t pid, lldb::tid_t tid, const char *name)
579{
580 uint64_t pid_tid = ((uint64_t)pid << 32) | (uint64_t)tid;
581
582 static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
583 Mutex::Locker locker(&g_mutex);
584
585 typedef std::map<uint64_t, std::string> thread_name_map;
586 // rdar://problem/8153284
587 // Fixed a crasher where during shutdown, loggings attempted to access the
588 // thread name but the static map instance had already been destructed.
589 // Another approach is to introduce a static guard object which monitors its
590 // own destruction and raises a flag, but this incurs more overhead.
591 static thread_name_map *g_thread_names_ptr = new thread_name_map();
592 thread_name_map &g_thread_names = *g_thread_names_ptr;
593
594 if (get)
595 {
596 // See if the thread name exists in our thread name pool
597 thread_name_map::iterator pos = g_thread_names.find(pid_tid);
598 if (pos != g_thread_names.end())
599 return pos->second.c_str();
600 }
601 else
602 {
603 // Set the thread name
604 g_thread_names[pid_tid] = name;
605 }
606 return NULL;
607}
608
609const char *
610Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
611{
612 const char *name = ThreadNameAccessor (true, pid, tid, NULL);
613 if (name == NULL)
614 {
615#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
616 // We currently can only get the name of a thread in the current process.
617 if (pid == Host::GetCurrentProcessID())
618 {
619 char pthread_name[1024];
620 if (::pthread_getname_np (::pthread_from_mach_thread_np (tid), pthread_name, sizeof(pthread_name)) == 0)
621 {
622 if (pthread_name[0])
623 {
624 // Set the thread in our string pool
625 ThreadNameAccessor (false, pid, tid, pthread_name);
626 // Get our copy of the thread name string
627 name = ThreadNameAccessor (true, pid, tid, NULL);
628 }
629 }
Greg Clayton49ce6822010-10-31 03:01:06 +0000630
631 if (name == NULL)
632 {
633 dispatch_queue_t current_queue = ::dispatch_get_current_queue ();
634 if (current_queue != NULL)
635 name = dispatch_queue_get_label (current_queue);
636 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000637 }
638#endif
639 }
640 return name;
641}
642
643void
644Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
645{
646 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
647 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
648 if (pid == LLDB_INVALID_PROCESS_ID)
649 pid = curr_pid;
650
651 if (tid == LLDB_INVALID_THREAD_ID)
652 tid = curr_tid;
653
654#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
655 // Set the pthread name if possible
656 if (pid == curr_pid && tid == curr_tid)
657 {
658 ::pthread_setname_np (name);
659 }
660#endif
661 ThreadNameAccessor (false, pid, tid, name);
662}
663
664FileSpec
665Host::GetProgramFileSpec ()
666{
667 static FileSpec g_program_filespec;
668 if (!g_program_filespec)
669 {
670#if defined (__APPLE__)
671 char program_fullpath[PATH_MAX];
672 // If DST is NULL, then return the number of bytes needed.
673 uint32_t len = sizeof(program_fullpath);
674 int err = _NSGetExecutablePath (program_fullpath, &len);
675 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000676 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000677 else if (err == -1)
678 {
679 char *large_program_fullpath = (char *)::malloc (len + 1);
680
681 err = _NSGetExecutablePath (large_program_fullpath, &len);
682 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000683 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000684
685 ::free (large_program_fullpath);
686 }
687#elif defined (__linux__)
688 char exe_path[PATH_MAX];
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000689 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
690 if (len > 0) {
691 exe_path[len] = 0;
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000692 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000693 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000694#elif defined (__FreeBSD__)
695 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
696 size_t exe_path_size;
697 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
698 {
Greg Clayton366795e2011-01-13 01:27:55 +0000699 char *exe_path = new char[exe_path_size];
700 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
701 g_program_filespec.SetFile(exe_path, false);
702 delete[] exe_path;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000703 }
704#endif
705 }
706 return g_program_filespec;
707}
708
709FileSpec
710Host::GetModuleFileSpecForHostAddress (const void *host_addr)
711{
712 FileSpec module_filespec;
713 Dl_info info;
714 if (::dladdr (host_addr, &info))
715 {
716 if (info.dli_fname)
Greg Clayton537a7a82010-10-20 20:54:39 +0000717 module_filespec.SetFile(info.dli_fname, true);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000718 }
719 return module_filespec;
720}
721
722#if !defined (__APPLE__) // see Host.mm
723bool
Greg Clayton24b48ff2010-10-17 22:03:32 +0000724Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000725{
Greg Clayton24b48ff2010-10-17 22:03:32 +0000726 return false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000727}
728#endif
729
Greg Clayton14ef59f2011-02-08 00:35:34 +0000730// Opaque info that tracks a dynamic library that was loaded
731struct DynamicLibraryInfo
Greg Clayton52fd9842011-02-02 02:24:04 +0000732{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000733 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
734 file_spec (fs),
735 open_options (o),
736 handle (h)
737 {
738 }
739
740 const FileSpec file_spec;
741 uint32_t open_options;
742 void * handle;
743};
744
745void *
746Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
747{
Greg Clayton52fd9842011-02-02 02:24:04 +0000748 char path[PATH_MAX];
749 if (file_spec.GetPath(path, sizeof(path)))
750 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000751 int mode = 0;
752
753 if (options & eDynamicLibraryOpenOptionLazy)
754 mode |= RTLD_LAZY;
Greg Claytonbf467b02011-02-08 05:24:57 +0000755 else
756 mode |= RTLD_NOW;
757
Greg Clayton14ef59f2011-02-08 00:35:34 +0000758
759 if (options & eDynamicLibraryOpenOptionLocal)
760 mode |= RTLD_LOCAL;
761 else
762 mode |= RTLD_GLOBAL;
763
764#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
765 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
766 mode |= RTLD_FIRST;
Greg Clayton0f577c22011-02-07 17:43:47 +0000767#endif
Greg Clayton14ef59f2011-02-08 00:35:34 +0000768
769 void * opaque = ::dlopen (path, mode);
770
771 if (opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000772 {
773 error.Clear();
Greg Clayton14ef59f2011-02-08 00:35:34 +0000774 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton52fd9842011-02-02 02:24:04 +0000775 }
776 else
777 {
778 error.SetErrorString(::dlerror());
779 }
780 }
781 else
782 {
783 error.SetErrorString("failed to extract path");
784 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000785 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000786}
787
788Error
Greg Clayton14ef59f2011-02-08 00:35:34 +0000789Host::DynamicLibraryClose (void *opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000790{
791 Error error;
Greg Clayton14ef59f2011-02-08 00:35:34 +0000792 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000793 {
794 error.SetErrorString ("invalid dynamic library handle");
795 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000796 else
Greg Clayton52fd9842011-02-02 02:24:04 +0000797 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000798 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
799 if (::dlclose (dylib_info->handle) != 0)
800 {
801 error.SetErrorString(::dlerror());
802 }
803
804 dylib_info->open_options = 0;
805 dylib_info->handle = 0;
806 delete dylib_info;
Greg Clayton52fd9842011-02-02 02:24:04 +0000807 }
808 return error;
809}
810
811void *
Greg Clayton14ef59f2011-02-08 00:35:34 +0000812Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton52fd9842011-02-02 02:24:04 +0000813{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000814 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000815 {
816 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton52fd9842011-02-02 02:24:04 +0000817 }
Greg Clayton52fd9842011-02-02 02:24:04 +0000818 else
Greg Clayton14ef59f2011-02-08 00:35:34 +0000819 {
820 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
821
822 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
823 if (symbol_addr)
824 {
825#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
826 // This host doesn't support limiting searches to this shared library
827 // so we need to verify that the match came from this shared library
828 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonbf467b02011-02-08 05:24:57 +0000829 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton14ef59f2011-02-08 00:35:34 +0000830 {
831 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
832 if (match_dylib_spec != dylib_info->file_spec)
833 {
834 char dylib_path[PATH_MAX];
835 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
836 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
837 else
838 error.SetErrorString ("symbol not found");
839 return NULL;
840 }
841 }
842#endif
843 error.Clear();
844 return symbol_addr;
845 }
846 else
847 {
848 error.SetErrorString(::dlerror());
849 }
850 }
851 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000852}
Greg Clayton24b48ff2010-10-17 22:03:32 +0000853
854bool
855Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
856{
Greg Clayton5d187e52011-01-08 20:28:42 +0000857 // To get paths related to LLDB we get the path to the executable that
Greg Clayton24b48ff2010-10-17 22:03:32 +0000858 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
859 // on linux this is assumed to be the "lldb" main executable. If LLDB on
860 // linux is actually in a shared library (lldb.so??) then this function will
861 // need to be modified to "do the right thing".
862
863 switch (path_type)
864 {
865 case ePathTypeLLDBShlibDir:
866 {
867 static ConstString g_lldb_so_dir;
868 if (!g_lldb_so_dir)
869 {
870 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
871 g_lldb_so_dir = lldb_file_spec.GetDirectory();
872 }
873 file_spec.GetDirectory() = g_lldb_so_dir;
874 return file_spec.GetDirectory();
875 }
876 break;
877
878 case ePathTypeSupportExecutableDir:
879 {
880 static ConstString g_lldb_support_exe_dir;
881 if (!g_lldb_support_exe_dir)
882 {
883 FileSpec lldb_file_spec;
884 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
885 {
886 char raw_path[PATH_MAX];
887 char resolved_path[PATH_MAX];
888 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
889
890#if defined (__APPLE__)
891 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
892 if (framework_pos)
893 {
894 framework_pos += strlen("LLDB.framework");
895 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
896 }
897#endif
898 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
899 g_lldb_support_exe_dir.SetCString(resolved_path);
900 }
901 }
902 file_spec.GetDirectory() = g_lldb_support_exe_dir;
903 return file_spec.GetDirectory();
904 }
905 break;
906
907 case ePathTypeHeaderDir:
908 {
909 static ConstString g_lldb_headers_dir;
910 if (!g_lldb_headers_dir)
911 {
912#if defined (__APPLE__)
913 FileSpec lldb_file_spec;
914 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
915 {
916 char raw_path[PATH_MAX];
917 char resolved_path[PATH_MAX];
918 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
919
920 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
921 if (framework_pos)
922 {
923 framework_pos += strlen("LLDB.framework");
924 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
925 }
926 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
927 g_lldb_headers_dir.SetCString(resolved_path);
928 }
929#else
Greg Clayton52fd9842011-02-02 02:24:04 +0000930 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Clayton24b48ff2010-10-17 22:03:32 +0000931 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
932#endif
933 }
934 file_spec.GetDirectory() = g_lldb_headers_dir;
935 return file_spec.GetDirectory();
936 }
937 break;
938
939 case ePathTypePythonDir:
940 {
Greg Clayton52fd9842011-02-02 02:24:04 +0000941 // TODO: Anyone know how we can determine this for linux? Other systems?
Greg Clayton24b48ff2010-10-17 22:03:32 +0000942 // For linux we are currently assuming the location of the lldb
943 // binary that contains this function is the directory that will
944 // contain lldb.so, lldb.py and embedded_interpreter.py...
945
946 static ConstString g_lldb_python_dir;
947 if (!g_lldb_python_dir)
948 {
949 FileSpec lldb_file_spec;
950 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
951 {
952 char raw_path[PATH_MAX];
953 char resolved_path[PATH_MAX];
954 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
955
956#if defined (__APPLE__)
957 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
958 if (framework_pos)
959 {
960 framework_pos += strlen("LLDB.framework");
961 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
962 }
963#endif
964 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
965 g_lldb_python_dir.SetCString(resolved_path);
966 }
967 }
968 file_spec.GetDirectory() = g_lldb_python_dir;
969 return file_spec.GetDirectory();
970 }
971 break;
972
Greg Clayton52fd9842011-02-02 02:24:04 +0000973 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
974 {
975#if defined (__APPLE__)
976 static ConstString g_lldb_system_plugin_dir;
977 if (!g_lldb_system_plugin_dir)
978 {
979 FileSpec lldb_file_spec;
980 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
981 {
982 char raw_path[PATH_MAX];
983 char resolved_path[PATH_MAX];
984 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
985
986 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
987 if (framework_pos)
988 {
989 framework_pos += strlen("LLDB.framework");
990 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
991 }
992 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
993 g_lldb_system_plugin_dir.SetCString(resolved_path);
994 }
995 }
996 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
997 return file_spec.GetDirectory();
998#endif
999 // TODO: where would system LLDB plug-ins be located on linux? Other systems?
1000 return false;
1001 }
1002 break;
1003
1004 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1005 {
1006#if defined (__APPLE__)
1007 static ConstString g_lldb_user_plugin_dir;
1008 if (!g_lldb_user_plugin_dir)
1009 {
1010 char user_plugin_path[PATH_MAX];
1011 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1012 user_plugin_path,
1013 sizeof(user_plugin_path)))
1014 {
1015 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1016 }
1017 }
1018 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1019 return file_spec.GetDirectory();
1020#endif
1021 // TODO: where would user LLDB plug-ins be located on linux? Other systems?
1022 return false;
1023 }
Greg Clayton24b48ff2010-10-17 22:03:32 +00001024 default:
1025 assert (!"Unhandled PathType");
1026 break;
1027 }
1028
1029 return false;
1030}
1031
Greg Claytona733c042011-03-21 21:25:07 +00001032#if !defined (__APPLE__) // see macosx/Host.mm
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001033
1034uint32_t
1035Host::FindProcessesByName (const char *name, NameMatchType name_match_type, ProcessInfoList &process_infos)
1036{
1037 process_infos.Clear();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001038 return process_infos.GetSize();
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001039}
1040
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001041bool
1042Host::GetProcessInfo (lldb::pid_t pid, ProcessInfo &process_info)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001043{
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001044 process_info.Clear();
1045 return false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001046}
1047
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001048bool
Greg Claytonb73620c2010-12-18 01:54:34 +00001049Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001050{
1051 return false;
1052}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001053
Greg Claytone98ac252010-11-10 04:57:04 +00001054void
1055Host::SetCrashDescriptionWithFormat (const char *format, ...)
1056{
1057}
1058
1059void
1060Host::SetCrashDescription (const char *description)
1061{
1062}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001063
1064lldb::pid_t
1065LaunchApplication (const FileSpec &app_file_spec)
1066{
1067 return LLDB_INVALID_PROCESS_ID;
1068}
1069
1070lldb::pid_t
1071Host::LaunchInNewTerminal
1072(
Greg Claytonb73620c2010-12-18 01:54:34 +00001073 const char *tty_name,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001074 const char **argv,
1075 const char **envp,
Greg Claytonde915be2011-01-23 05:56:20 +00001076 const char *working_dir,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001077 const ArchSpec *arch_spec,
1078 bool stop_at_entry,
1079 bool disable_aslr
1080)
1081{
1082 return LLDB_INVALID_PROCESS_ID;
1083}
1084
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001085#endif