blob: 4c72e50c277b9621cb040110411512131e100593 [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 Clayton5f54ac32011-02-08 05:05:52 +000014#include "lldb/Host/FileSpec.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000015#include "lldb/Core/Log.h"
16#include "lldb/Core/StreamString.h"
Greg Clayton14ef59f2011-02-08 00:35:34 +000017#include "lldb/Host/Config.h"
Greg Claytoncd548032011-02-01 01:31:41 +000018#include "lldb/Host/Endian.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000019#include "lldb/Host/Mutex.h"
20
21#include <dlfcn.h>
22#include <errno.h>
Greg Clayton8f3b21d2010-09-07 20:11:56 +000023
24#if defined (__APPLE__)
Greg Clayton14ef59f2011-02-08 00:35:34 +000025
Greg Clayton49ce6822010-10-31 03:01:06 +000026#include <dispatch/dispatch.h>
Greg Clayton8f3b21d2010-09-07 20:11:56 +000027#include <libproc.h>
28#include <mach-o/dyld.h>
Greg Claytonb5f67fb2011-02-05 06:36:35 +000029#include <sys/sysctl.h>
Greg Clayton14ef59f2011-02-08 00:35:34 +000030
Greg Clayton0f577c22011-02-07 17:43:47 +000031#elif defined (__linux__)
Greg Clayton14ef59f2011-02-08 00:35:34 +000032
Greg Clayton0f577c22011-02-07 17:43:47 +000033#include <sys/wait.h>
Greg Clayton14ef59f2011-02-08 00:35:34 +000034
Greg Clayton8f3b21d2010-09-07 20:11:56 +000035#endif
36
37using namespace lldb;
38using namespace lldb_private;
39
40struct MonitorInfo
41{
42 lldb::pid_t pid; // The process ID to monitor
43 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
44 void *callback_baton; // The callback baton for the callback function
45 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
46};
47
48static void *
49MonitorChildProcessThreadFunction (void *arg);
50
51lldb::thread_t
52Host::StartMonitoringChildProcess
53(
54 Host::MonitorChildProcessCallback callback,
55 void *callback_baton,
56 lldb::pid_t pid,
57 bool monitor_signals
58)
59{
60 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
61 if (callback)
62 {
63 std::auto_ptr<MonitorInfo> info_ap(new MonitorInfo);
64
65 info_ap->pid = pid;
66 info_ap->callback = callback;
67 info_ap->callback_baton = callback_baton;
68 info_ap->monitor_signals = monitor_signals;
69
70 char thread_name[256];
71 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%i)>", pid);
72 thread = ThreadCreate (thread_name,
73 MonitorChildProcessThreadFunction,
74 info_ap.get(),
75 NULL);
76
Greg Clayton09c81ef2011-02-08 01:34:25 +000077 if (IS_VALID_LLDB_HOST_THREAD(thread))
Greg Clayton8f3b21d2010-09-07 20:11:56 +000078 info_ap.release();
79 }
80 return thread;
81}
82
83//------------------------------------------------------------------
84// Scoped class that will disable thread canceling when it is
85// constructed, and exception safely restore the previous value it
86// when it goes out of scope.
87//------------------------------------------------------------------
88class ScopedPThreadCancelDisabler
89{
90public:
91 ScopedPThreadCancelDisabler()
92 {
93 // Disable the ability for this thread to be cancelled
94 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
95 if (err != 0)
96 m_old_state = -1;
97
98 }
99
100 ~ScopedPThreadCancelDisabler()
101 {
102 // Restore the ability for this thread to be cancelled to what it
103 // previously was.
104 if (m_old_state != -1)
105 ::pthread_setcancelstate (m_old_state, 0);
106 }
107private:
108 int m_old_state; // Save the old cancelability state.
109};
110
111static void *
112MonitorChildProcessThreadFunction (void *arg)
113{
Greg Claytone005f2c2010-11-06 01:53:30 +0000114 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000115 const char *function = __FUNCTION__;
116 if (log)
117 log->Printf ("%s (arg = %p) thread starting...", function, arg);
118
119 MonitorInfo *info = (MonitorInfo *)arg;
120
121 const Host::MonitorChildProcessCallback callback = info->callback;
122 void * const callback_baton = info->callback_baton;
123 const lldb::pid_t pid = info->pid;
124 const bool monitor_signals = info->monitor_signals;
125
126 delete info;
127
128 int status = -1;
129 const int options = 0;
130 struct rusage *rusage = NULL;
131 while (1)
132 {
Caroline Tice926060e2010-10-29 21:48:37 +0000133 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000134 if (log)
135 log->Printf("%s ::wait4 (pid = %i, &status, options = %i, rusage = %p)...", function, pid, options, rusage);
136
137 // Wait for all child processes
138 ::pthread_testcancel ();
139 const lldb::pid_t wait_pid = ::wait4 (pid, &status, options, rusage);
140 ::pthread_testcancel ();
141
142 if (wait_pid == -1)
143 {
144 if (errno == EINTR)
145 continue;
146 else
147 break;
148 }
149 else if (wait_pid == pid)
150 {
151 bool exited = false;
152 int signal = 0;
153 int exit_status = 0;
154 const char *status_cstr = NULL;
155 if (WIFSTOPPED(status))
156 {
157 signal = WSTOPSIG(status);
158 status_cstr = "STOPPED";
159 }
160 else if (WIFEXITED(status))
161 {
162 exit_status = WEXITSTATUS(status);
163 status_cstr = "EXITED";
164 exited = true;
165 }
166 else if (WIFSIGNALED(status))
167 {
168 signal = WTERMSIG(status);
169 status_cstr = "SIGNALED";
170 exited = true;
171 exit_status = -1;
172 }
173 else
174 {
175 status_cstr = "(???)";
176 }
177
178 // Scope for pthread_cancel_disabler
179 {
180 ScopedPThreadCancelDisabler pthread_cancel_disabler;
181
Caroline Tice926060e2010-10-29 21:48:37 +0000182 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000183 if (log)
184 log->Printf ("%s ::wait4 (pid = %i, &status, options = %i, rusage = %p) => pid = %i, status = 0x%8.8x (%s), signal = %i, exit_state = %i",
185 function,
186 wait_pid,
187 options,
188 rusage,
189 pid,
190 status,
191 status_cstr,
192 signal,
193 exit_status);
194
195 if (exited || (signal != 0 && monitor_signals))
196 {
197 bool callback_return = callback (callback_baton, pid, signal, exit_status);
198
199 // If our process exited, then this thread should exit
200 if (exited)
201 break;
202 // If the callback returns true, it means this process should
203 // exit
204 if (callback_return)
205 break;
206 }
207 }
208 }
209 }
210
Caroline Tice926060e2010-10-29 21:48:37 +0000211 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000212 if (log)
213 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
214
215 return NULL;
216}
217
218size_t
219Host::GetPageSize()
220{
221 return ::getpagesize();
222}
223
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000224const ArchSpec &
Greg Clayton395fc332011-02-15 21:59:32 +0000225Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000226{
Greg Clayton395fc332011-02-15 21:59:32 +0000227 static bool g_supports_32 = false;
228 static bool g_supports_64 = false;
229 static ArchSpec g_host_arch_32;
230 static ArchSpec g_host_arch_64;
231
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000232#if defined (__APPLE__)
Greg Clayton395fc332011-02-15 21:59:32 +0000233
234 // Apple is different in that it can support both 32 and 64 bit executables
235 // in the same operating system running concurrently. Here we detect the
236 // correct host architectures for both 32 and 64 bit including if 64 bit
237 // executables are supported on the system.
238
239 if (g_supports_32 == false && g_supports_64 == false)
240 {
241 // All apple systems support 32 bit execution.
242 g_supports_32 = true;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000243 uint32_t cputype, cpusubtype;
Greg Clayton395fc332011-02-15 21:59:32 +0000244 uint32_t is_64_bit_capable = false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000245 size_t len = sizeof(cputype);
Greg Clayton395fc332011-02-15 21:59:32 +0000246 ArchSpec host_arch;
247 // These will tell us about the kernel architecture, which even on a 64
248 // bit machine can be 32 bit...
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000249 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
250 {
Greg Clayton395fc332011-02-15 21:59:32 +0000251 len = sizeof (cpusubtype);
252 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
253 cpusubtype = CPU_TYPE_ANY;
254
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000255 len = sizeof (is_64_bit_capable);
256 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
257 {
258 if (is_64_bit_capable)
Greg Clayton395fc332011-02-15 21:59:32 +0000259 g_supports_64 = true;
260 }
261
262 if (is_64_bit_capable)
263 {
Greg Clayton75c703d2011-02-16 04:46:07 +0000264#if defined (__i386__) || defined (__x86_64__)
265 if (cpusubtype == CPU_SUBTYPE_486)
266 cpusubtype = CPU_SUBTYPE_I386_ALL;
267#endif
Greg Clayton395fc332011-02-15 21:59:32 +0000268 if (cputype & CPU_ARCH_ABI64)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000269 {
Greg Clayton395fc332011-02-15 21:59:32 +0000270 // We have a 64 bit kernel on a 64 bit system
Greg Clayton75c703d2011-02-16 04:46:07 +0000271 g_host_arch_32.SetMachOArch (~(CPU_ARCH_MASK) & cputype, cpusubtype);
Greg Clayton395fc332011-02-15 21:59:32 +0000272 g_host_arch_64.SetMachOArch (cputype, cpusubtype);
273 }
274 else
275 {
276 // We have a 32 bit kernel on a 64 bit system
277 g_host_arch_32.SetMachOArch (cputype, cpusubtype);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000278 cputype |= CPU_ARCH_ABI64;
Greg Clayton395fc332011-02-15 21:59:32 +0000279 g_host_arch_64.SetMachOArch (cputype, cpusubtype);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000280 }
281 }
Greg Clayton395fc332011-02-15 21:59:32 +0000282 else
283 {
284 g_host_arch_32.SetMachOArch (cputype, cpusubtype);
285 g_host_arch_64.Clear();
286 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000287 }
Greg Clayton395fc332011-02-15 21:59:32 +0000288 }
289
290#else // #if defined (__APPLE__)
291
292 if (g_supports_32 == false && g_supports_64 == false)
293 {
294#if defined (__x86_64__)
295
296 g_host_arch_64.SetArch ("x86_64");
Greg Clayton395fc332011-02-15 21:59:32 +0000297
298#elif defined (__i386__)
299
Greg Clayton4fefe322011-02-17 02:05:38 +0000300 g_host_arch_32.SetArch ("i386");
Greg Clayton395fc332011-02-15 21:59:32 +0000301
302#elif defined (__arm__)
303
Greg Clayton4fefe322011-02-17 02:05:38 +0000304 g_host_arch_32.SetArch ("arm");
Greg Clayton395fc332011-02-15 21:59:32 +0000305
306#elif defined (__ppc64__)
307
Greg Clayton4fefe322011-02-17 02:05:38 +0000308 g_host_arch_64.SetArch ("ppc64");
Greg Clayton395fc332011-02-15 21:59:32 +0000309
310#elif defined (__powerpc__) || defined (__ppc__)
Greg Clayton4fefe322011-02-17 02:05:38 +0000311
312 g_host_arch_32.SetArch ("ppc");
Greg Clayton395fc332011-02-15 21:59:32 +0000313
314#else
315
316#error undefined architecture, define your architecture here
317
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000318#endif
Greg Clayton4fefe322011-02-17 02:05:38 +0000319
320 g_supports_32 = g_host_arch_32.IsValid();
321 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000322 }
Greg Clayton395fc332011-02-15 21:59:32 +0000323
324#endif // #else for #if defined (__APPLE__)
325
326 if (arch_kind == eSystemDefaultArchitecture32)
327 return g_host_arch_32;
328 else if (arch_kind == eSystemDefaultArchitecture64)
329 return g_host_arch_64;
330
331 if (g_supports_64)
332 return g_host_arch_64;
333
334 return g_host_arch_32;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000335}
336
337const ConstString &
338Host::GetVendorString()
339{
340 static ConstString g_vendor;
341 if (!g_vendor)
342 {
343#if defined (__APPLE__)
344 char ostype[64];
345 size_t len = sizeof(ostype);
346 if (::sysctlbyname("kern.ostype", &ostype, &len, NULL, 0) == 0)
347 g_vendor.SetCString (ostype);
348 else
349 g_vendor.SetCString("apple");
350#elif defined (__linux__)
351 g_vendor.SetCString("gnu");
352#endif
353 }
354 return g_vendor;
355}
356
357const ConstString &
358Host::GetOSString()
359{
360 static ConstString g_os_string;
361 if (!g_os_string)
362 {
363#if defined (__APPLE__)
364 g_os_string.SetCString("darwin");
365#elif defined (__linux__)
366 g_os_string.SetCString("linux");
367#endif
368 }
369 return g_os_string;
370}
371
372const ConstString &
373Host::GetTargetTriple()
374{
375 static ConstString g_host_triple;
376 if (!(g_host_triple))
377 {
378 StreamString triple;
379 triple.Printf("%s-%s-%s",
380 GetArchitecture().AsCString(),
381 GetVendorString().AsCString(),
382 GetOSString().AsCString());
383
384 std::transform (triple.GetString().begin(),
385 triple.GetString().end(),
386 triple.GetString().begin(),
387 ::tolower);
388
389 g_host_triple.SetCString(triple.GetString().c_str());
390 }
391 return g_host_triple;
392}
393
394lldb::pid_t
395Host::GetCurrentProcessID()
396{
397 return ::getpid();
398}
399
400lldb::tid_t
401Host::GetCurrentThreadID()
402{
403#if defined (__APPLE__)
404 return ::mach_thread_self();
405#else
406 return lldb::tid_t(pthread_self());
407#endif
408}
409
410const char *
411Host::GetSignalAsCString (int signo)
412{
413 switch (signo)
414 {
415 case SIGHUP: return "SIGHUP"; // 1 hangup
416 case SIGINT: return "SIGINT"; // 2 interrupt
417 case SIGQUIT: return "SIGQUIT"; // 3 quit
418 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
419 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
420 case SIGABRT: return "SIGABRT"; // 6 abort()
421#if defined(_POSIX_C_SOURCE)
422 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
423#else // !_POSIX_C_SOURCE
424 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
425#endif // !_POSIX_C_SOURCE
426 case SIGFPE: return "SIGFPE"; // 8 floating point exception
427 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
428 case SIGBUS: return "SIGBUS"; // 10 bus error
429 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
430 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
431 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
432 case SIGALRM: return "SIGALRM"; // 14 alarm clock
433 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
434 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
435 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
436 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
437 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
438 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
439 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
440 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
441#if !defined(_POSIX_C_SOURCE)
442 case SIGIO: return "SIGIO"; // 23 input/output possible signal
443#endif
444 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
445 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
446 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
447 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
448#if !defined(_POSIX_C_SOURCE)
449 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
450 case SIGINFO: return "SIGINFO"; // 29 information request
451#endif
452 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
453 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
454 default:
455 break;
456 }
457 return NULL;
458}
459
460void
461Host::WillTerminate ()
462{
463}
464
465#if !defined (__APPLE__) // see macosx/Host.mm
466void
467Host::ThreadCreated (const char *thread_name)
468{
469}
Greg Claytonb749a262010-12-03 06:02:24 +0000470
471void
472Host::Backtrace (Stream &strm, uint32_t max_frames)
473{
Greg Clayton52fd9842011-02-02 02:24:04 +0000474 // TODO: Is there a way to backtrace the current process on linux? Other systems?
Greg Claytonb749a262010-12-03 06:02:24 +0000475}
476
Greg Clayton638351a2010-12-04 00:10:17 +0000477
478size_t
479Host::GetEnvironment (StringList &env)
480{
Greg Clayton52fd9842011-02-02 02:24:04 +0000481 // TODO: Is there a way to the host environment for this process on linux? Other systems?
Greg Clayton638351a2010-12-04 00:10:17 +0000482 return 0;
483}
484
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000485#endif
486
487struct HostThreadCreateInfo
488{
489 std::string thread_name;
490 thread_func_t thread_fptr;
491 thread_arg_t thread_arg;
492
493 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
494 thread_name (name ? name : ""),
495 thread_fptr (fptr),
496 thread_arg (arg)
497 {
498 }
499};
500
501static thread_result_t
502ThreadCreateTrampoline (thread_arg_t arg)
503{
504 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
505 Host::ThreadCreated (info->thread_name.c_str());
506 thread_func_t thread_fptr = info->thread_fptr;
507 thread_arg_t thread_arg = info->thread_arg;
508
Greg Claytone005f2c2010-11-06 01:53:30 +0000509 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000510 if (log)
511 log->Printf("thread created");
512
513 delete info;
514 return thread_fptr (thread_arg);
515}
516
517lldb::thread_t
518Host::ThreadCreate
519(
520 const char *thread_name,
521 thread_func_t thread_fptr,
522 thread_arg_t thread_arg,
523 Error *error
524)
525{
526 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
527
528 // Host::ThreadCreateTrampoline will delete this pointer for us.
529 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
530
531 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
532 if (err == 0)
533 {
534 if (error)
535 error->Clear();
536 return thread;
537 }
538
539 if (error)
540 error->SetError (err, eErrorTypePOSIX);
541
542 return LLDB_INVALID_HOST_THREAD;
543}
544
545bool
546Host::ThreadCancel (lldb::thread_t thread, Error *error)
547{
548 int err = ::pthread_cancel (thread);
549 if (error)
550 error->SetError(err, eErrorTypePOSIX);
551 return err == 0;
552}
553
554bool
555Host::ThreadDetach (lldb::thread_t thread, Error *error)
556{
557 int err = ::pthread_detach (thread);
558 if (error)
559 error->SetError(err, eErrorTypePOSIX);
560 return err == 0;
561}
562
563bool
564Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
565{
566 int err = ::pthread_join (thread, thread_result_ptr);
567 if (error)
568 error->SetError(err, eErrorTypePOSIX);
569 return err == 0;
570}
571
572//------------------------------------------------------------------
573// Control access to a static file thread name map using a single
574// static function to avoid a static constructor.
575//------------------------------------------------------------------
576static const char *
577ThreadNameAccessor (bool get, lldb::pid_t pid, lldb::tid_t tid, const char *name)
578{
579 uint64_t pid_tid = ((uint64_t)pid << 32) | (uint64_t)tid;
580
581 static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
582 Mutex::Locker locker(&g_mutex);
583
584 typedef std::map<uint64_t, std::string> thread_name_map;
585 // rdar://problem/8153284
586 // Fixed a crasher where during shutdown, loggings attempted to access the
587 // thread name but the static map instance had already been destructed.
588 // Another approach is to introduce a static guard object which monitors its
589 // own destruction and raises a flag, but this incurs more overhead.
590 static thread_name_map *g_thread_names_ptr = new thread_name_map();
591 thread_name_map &g_thread_names = *g_thread_names_ptr;
592
593 if (get)
594 {
595 // See if the thread name exists in our thread name pool
596 thread_name_map::iterator pos = g_thread_names.find(pid_tid);
597 if (pos != g_thread_names.end())
598 return pos->second.c_str();
599 }
600 else
601 {
602 // Set the thread name
603 g_thread_names[pid_tid] = name;
604 }
605 return NULL;
606}
607
608const char *
609Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
610{
611 const char *name = ThreadNameAccessor (true, pid, tid, NULL);
612 if (name == NULL)
613 {
614#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
615 // We currently can only get the name of a thread in the current process.
616 if (pid == Host::GetCurrentProcessID())
617 {
618 char pthread_name[1024];
619 if (::pthread_getname_np (::pthread_from_mach_thread_np (tid), pthread_name, sizeof(pthread_name)) == 0)
620 {
621 if (pthread_name[0])
622 {
623 // Set the thread in our string pool
624 ThreadNameAccessor (false, pid, tid, pthread_name);
625 // Get our copy of the thread name string
626 name = ThreadNameAccessor (true, pid, tid, NULL);
627 }
628 }
Greg Clayton49ce6822010-10-31 03:01:06 +0000629
630 if (name == NULL)
631 {
632 dispatch_queue_t current_queue = ::dispatch_get_current_queue ();
633 if (current_queue != NULL)
634 name = dispatch_queue_get_label (current_queue);
635 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000636 }
637#endif
638 }
639 return name;
640}
641
642void
643Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
644{
645 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
646 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
647 if (pid == LLDB_INVALID_PROCESS_ID)
648 pid = curr_pid;
649
650 if (tid == LLDB_INVALID_THREAD_ID)
651 tid = curr_tid;
652
653#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
654 // Set the pthread name if possible
655 if (pid == curr_pid && tid == curr_tid)
656 {
657 ::pthread_setname_np (name);
658 }
659#endif
660 ThreadNameAccessor (false, pid, tid, name);
661}
662
663FileSpec
664Host::GetProgramFileSpec ()
665{
666 static FileSpec g_program_filespec;
667 if (!g_program_filespec)
668 {
669#if defined (__APPLE__)
670 char program_fullpath[PATH_MAX];
671 // If DST is NULL, then return the number of bytes needed.
672 uint32_t len = sizeof(program_fullpath);
673 int err = _NSGetExecutablePath (program_fullpath, &len);
674 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000675 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000676 else if (err == -1)
677 {
678 char *large_program_fullpath = (char *)::malloc (len + 1);
679
680 err = _NSGetExecutablePath (large_program_fullpath, &len);
681 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000682 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000683
684 ::free (large_program_fullpath);
685 }
686#elif defined (__linux__)
687 char exe_path[PATH_MAX];
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000688 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
689 if (len > 0) {
690 exe_path[len] = 0;
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000691 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000692 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000693#elif defined (__FreeBSD__)
694 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
695 size_t exe_path_size;
696 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
697 {
Greg Clayton366795e2011-01-13 01:27:55 +0000698 char *exe_path = new char[exe_path_size];
699 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
700 g_program_filespec.SetFile(exe_path, false);
701 delete[] exe_path;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000702 }
703#endif
704 }
705 return g_program_filespec;
706}
707
708FileSpec
709Host::GetModuleFileSpecForHostAddress (const void *host_addr)
710{
711 FileSpec module_filespec;
712 Dl_info info;
713 if (::dladdr (host_addr, &info))
714 {
715 if (info.dli_fname)
Greg Clayton537a7a82010-10-20 20:54:39 +0000716 module_filespec.SetFile(info.dli_fname, true);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000717 }
718 return module_filespec;
719}
720
721#if !defined (__APPLE__) // see Host.mm
722bool
Greg Clayton24b48ff2010-10-17 22:03:32 +0000723Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000724{
Greg Clayton24b48ff2010-10-17 22:03:32 +0000725 return false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000726}
727#endif
728
Greg Clayton14ef59f2011-02-08 00:35:34 +0000729// Opaque info that tracks a dynamic library that was loaded
730struct DynamicLibraryInfo
Greg Clayton52fd9842011-02-02 02:24:04 +0000731{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000732 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
733 file_spec (fs),
734 open_options (o),
735 handle (h)
736 {
737 }
738
739 const FileSpec file_spec;
740 uint32_t open_options;
741 void * handle;
742};
743
744void *
745Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
746{
Greg Clayton52fd9842011-02-02 02:24:04 +0000747 char path[PATH_MAX];
748 if (file_spec.GetPath(path, sizeof(path)))
749 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000750 int mode = 0;
751
752 if (options & eDynamicLibraryOpenOptionLazy)
753 mode |= RTLD_LAZY;
Greg Claytonbf467b02011-02-08 05:24:57 +0000754 else
755 mode |= RTLD_NOW;
756
Greg Clayton14ef59f2011-02-08 00:35:34 +0000757
758 if (options & eDynamicLibraryOpenOptionLocal)
759 mode |= RTLD_LOCAL;
760 else
761 mode |= RTLD_GLOBAL;
762
763#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
764 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
765 mode |= RTLD_FIRST;
Greg Clayton0f577c22011-02-07 17:43:47 +0000766#endif
Greg Clayton14ef59f2011-02-08 00:35:34 +0000767
768 void * opaque = ::dlopen (path, mode);
769
770 if (opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000771 {
772 error.Clear();
Greg Clayton14ef59f2011-02-08 00:35:34 +0000773 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton52fd9842011-02-02 02:24:04 +0000774 }
775 else
776 {
777 error.SetErrorString(::dlerror());
778 }
779 }
780 else
781 {
782 error.SetErrorString("failed to extract path");
783 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000784 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000785}
786
787Error
Greg Clayton14ef59f2011-02-08 00:35:34 +0000788Host::DynamicLibraryClose (void *opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000789{
790 Error error;
Greg Clayton14ef59f2011-02-08 00:35:34 +0000791 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000792 {
793 error.SetErrorString ("invalid dynamic library handle");
794 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000795 else
Greg Clayton52fd9842011-02-02 02:24:04 +0000796 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000797 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
798 if (::dlclose (dylib_info->handle) != 0)
799 {
800 error.SetErrorString(::dlerror());
801 }
802
803 dylib_info->open_options = 0;
804 dylib_info->handle = 0;
805 delete dylib_info;
Greg Clayton52fd9842011-02-02 02:24:04 +0000806 }
807 return error;
808}
809
810void *
Greg Clayton14ef59f2011-02-08 00:35:34 +0000811Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton52fd9842011-02-02 02:24:04 +0000812{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000813 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000814 {
815 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton52fd9842011-02-02 02:24:04 +0000816 }
Greg Clayton52fd9842011-02-02 02:24:04 +0000817 else
Greg Clayton14ef59f2011-02-08 00:35:34 +0000818 {
819 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
820
821 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
822 if (symbol_addr)
823 {
824#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
825 // This host doesn't support limiting searches to this shared library
826 // so we need to verify that the match came from this shared library
827 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonbf467b02011-02-08 05:24:57 +0000828 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton14ef59f2011-02-08 00:35:34 +0000829 {
830 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
831 if (match_dylib_spec != dylib_info->file_spec)
832 {
833 char dylib_path[PATH_MAX];
834 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
835 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
836 else
837 error.SetErrorString ("symbol not found");
838 return NULL;
839 }
840 }
841#endif
842 error.Clear();
843 return symbol_addr;
844 }
845 else
846 {
847 error.SetErrorString(::dlerror());
848 }
849 }
850 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000851}
Greg Clayton24b48ff2010-10-17 22:03:32 +0000852
853bool
854Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
855{
Greg Clayton5d187e52011-01-08 20:28:42 +0000856 // To get paths related to LLDB we get the path to the executable that
Greg Clayton24b48ff2010-10-17 22:03:32 +0000857 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
858 // on linux this is assumed to be the "lldb" main executable. If LLDB on
859 // linux is actually in a shared library (lldb.so??) then this function will
860 // need to be modified to "do the right thing".
861
862 switch (path_type)
863 {
864 case ePathTypeLLDBShlibDir:
865 {
866 static ConstString g_lldb_so_dir;
867 if (!g_lldb_so_dir)
868 {
869 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
870 g_lldb_so_dir = lldb_file_spec.GetDirectory();
871 }
872 file_spec.GetDirectory() = g_lldb_so_dir;
873 return file_spec.GetDirectory();
874 }
875 break;
876
877 case ePathTypeSupportExecutableDir:
878 {
879 static ConstString g_lldb_support_exe_dir;
880 if (!g_lldb_support_exe_dir)
881 {
882 FileSpec lldb_file_spec;
883 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
884 {
885 char raw_path[PATH_MAX];
886 char resolved_path[PATH_MAX];
887 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
888
889#if defined (__APPLE__)
890 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
891 if (framework_pos)
892 {
893 framework_pos += strlen("LLDB.framework");
894 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
895 }
896#endif
897 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
898 g_lldb_support_exe_dir.SetCString(resolved_path);
899 }
900 }
901 file_spec.GetDirectory() = g_lldb_support_exe_dir;
902 return file_spec.GetDirectory();
903 }
904 break;
905
906 case ePathTypeHeaderDir:
907 {
908 static ConstString g_lldb_headers_dir;
909 if (!g_lldb_headers_dir)
910 {
911#if defined (__APPLE__)
912 FileSpec lldb_file_spec;
913 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
914 {
915 char raw_path[PATH_MAX];
916 char resolved_path[PATH_MAX];
917 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
918
919 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
920 if (framework_pos)
921 {
922 framework_pos += strlen("LLDB.framework");
923 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
924 }
925 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
926 g_lldb_headers_dir.SetCString(resolved_path);
927 }
928#else
Greg Clayton52fd9842011-02-02 02:24:04 +0000929 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Clayton24b48ff2010-10-17 22:03:32 +0000930 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
931#endif
932 }
933 file_spec.GetDirectory() = g_lldb_headers_dir;
934 return file_spec.GetDirectory();
935 }
936 break;
937
938 case ePathTypePythonDir:
939 {
Greg Clayton52fd9842011-02-02 02:24:04 +0000940 // TODO: Anyone know how we can determine this for linux? Other systems?
Greg Clayton24b48ff2010-10-17 22:03:32 +0000941 // For linux we are currently assuming the location of the lldb
942 // binary that contains this function is the directory that will
943 // contain lldb.so, lldb.py and embedded_interpreter.py...
944
945 static ConstString g_lldb_python_dir;
946 if (!g_lldb_python_dir)
947 {
948 FileSpec lldb_file_spec;
949 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
950 {
951 char raw_path[PATH_MAX];
952 char resolved_path[PATH_MAX];
953 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
954
955#if defined (__APPLE__)
956 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
957 if (framework_pos)
958 {
959 framework_pos += strlen("LLDB.framework");
960 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
961 }
962#endif
963 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
964 g_lldb_python_dir.SetCString(resolved_path);
965 }
966 }
967 file_spec.GetDirectory() = g_lldb_python_dir;
968 return file_spec.GetDirectory();
969 }
970 break;
971
Greg Clayton52fd9842011-02-02 02:24:04 +0000972 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
973 {
974#if defined (__APPLE__)
975 static ConstString g_lldb_system_plugin_dir;
976 if (!g_lldb_system_plugin_dir)
977 {
978 FileSpec lldb_file_spec;
979 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
980 {
981 char raw_path[PATH_MAX];
982 char resolved_path[PATH_MAX];
983 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
984
985 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
986 if (framework_pos)
987 {
988 framework_pos += strlen("LLDB.framework");
989 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
990 }
991 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
992 g_lldb_system_plugin_dir.SetCString(resolved_path);
993 }
994 }
995 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
996 return file_spec.GetDirectory();
997#endif
998 // TODO: where would system LLDB plug-ins be located on linux? Other systems?
999 return false;
1000 }
1001 break;
1002
1003 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1004 {
1005#if defined (__APPLE__)
1006 static ConstString g_lldb_user_plugin_dir;
1007 if (!g_lldb_user_plugin_dir)
1008 {
1009 char user_plugin_path[PATH_MAX];
1010 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1011 user_plugin_path,
1012 sizeof(user_plugin_path)))
1013 {
1014 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1015 }
1016 }
1017 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1018 return file_spec.GetDirectory();
1019#endif
1020 // TODO: where would user LLDB plug-ins be located on linux? Other systems?
1021 return false;
1022 }
Greg Clayton24b48ff2010-10-17 22:03:32 +00001023 default:
1024 assert (!"Unhandled PathType");
1025 break;
1026 }
1027
1028 return false;
1029}
1030
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001031uint32_t
1032Host::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
1033{
1034 uint32_t num_matches = 0;
1035
1036#if defined (__APPLE__)
1037 int num_pids;
1038 int size_of_pids;
Greg Claytonfb8876d2010-10-10 22:07:18 +00001039 std::vector<int> pid_list;
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001040
1041 size_of_pids = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
1042 if (size_of_pids == -1)
1043 return 0;
1044
1045 num_pids = size_of_pids/sizeof(int);
Greg Claytonfb8876d2010-10-10 22:07:18 +00001046
1047 pid_list.resize (size_of_pids);
1048 size_of_pids = proc_listpids(PROC_ALL_PIDS, 0, &pid_list[0], size_of_pids);
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001049 if (size_of_pids == -1)
1050 return 0;
1051
1052 lldb::pid_t our_pid = getpid();
1053
1054 for (int i = 0; i < num_pids; i++)
1055 {
1056 struct proc_bsdinfo bsd_info;
1057 int error = proc_pidinfo (pid_list[i], PROC_PIDTBSDINFO, (uint64_t) 0, &bsd_info, PROC_PIDTBSDINFO_SIZE);
1058 if (error == 0)
1059 continue;
1060
1061 // Don't offer to attach to zombie processes, already traced or exiting
1062 // processes, and of course, ourselves... It looks like passing the second arg of
1063 // 0 to proc_listpids will exclude zombies anyway, but that's not documented so...
1064 if (((bsd_info.pbi_flags & (PROC_FLAG_TRACED | PROC_FLAG_INEXIT)) != 0)
1065 || (bsd_info.pbi_status == SZOMB)
1066 || (bsd_info.pbi_pid == our_pid))
1067 continue;
1068 char pid_name[MAXCOMLEN * 2 + 1];
1069 int name_len;
1070 name_len = proc_name(bsd_info.pbi_pid, pid_name, MAXCOMLEN * 2);
1071 if (name_len == 0)
1072 continue;
1073
1074 if (strstr(pid_name, name) != pid_name)
1075 continue;
1076 matches.AppendString (pid_name);
1077 pids.push_back (bsd_info.pbi_pid);
1078 num_matches++;
1079 }
1080#endif
1081
1082 return num_matches;
1083}
1084
1085ArchSpec
1086Host::GetArchSpecForExistingProcess (lldb::pid_t pid)
1087{
1088 ArchSpec return_spec;
1089
1090#if defined (__APPLE__)
1091 struct proc_bsdinfo bsd_info;
1092 int error = proc_pidinfo (pid, PROC_PIDTBSDINFO, (uint64_t) 0, &bsd_info, PROC_PIDTBSDINFO_SIZE);
1093 if (error == 0)
1094 return return_spec;
1095 if (bsd_info.pbi_flags & PROC_FLAG_LP64)
1096 return_spec.SetArch(LLDB_ARCH_DEFAULT_64BIT);
1097 else
1098 return_spec.SetArch(LLDB_ARCH_DEFAULT_32BIT);
1099#endif
1100
1101 return return_spec;
1102}
1103
1104ArchSpec
1105Host::GetArchSpecForExistingProcess (const char *process_name)
1106{
1107 ArchSpec returnSpec;
1108 StringList matches;
1109 std::vector<lldb::pid_t> pids;
1110 if (ListProcessesMatchingName(process_name, matches, pids))
1111 {
1112 if (matches.GetSize() == 1)
1113 {
1114 return GetArchSpecForExistingProcess(pids[0]);
1115 }
1116 }
1117 return returnSpec;
1118}
1119
1120#if !defined (__APPLE__) // see macosx/Host.mm
1121bool
Greg Claytonb73620c2010-12-18 01:54:34 +00001122Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001123{
1124 return false;
1125}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001126
Greg Claytone98ac252010-11-10 04:57:04 +00001127void
1128Host::SetCrashDescriptionWithFormat (const char *format, ...)
1129{
1130}
1131
1132void
1133Host::SetCrashDescription (const char *description)
1134{
1135}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001136
1137lldb::pid_t
1138LaunchApplication (const FileSpec &app_file_spec)
1139{
1140 return LLDB_INVALID_PROCESS_ID;
1141}
1142
1143lldb::pid_t
1144Host::LaunchInNewTerminal
1145(
Greg Claytonb73620c2010-12-18 01:54:34 +00001146 const char *tty_name,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001147 const char **argv,
1148 const char **envp,
Greg Claytonde915be2011-01-23 05:56:20 +00001149 const char *working_dir,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001150 const ArchSpec *arch_spec,
1151 bool stop_at_entry,
1152 bool disable_aslr
1153)
1154{
1155 return LLDB_INVALID_PROCESS_ID;
1156}
1157
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001158#endif