blob: 20709ded465088b4dd2d6bf17b7c9aac33839fa8 [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");
297 g_supports_32 = false;
298 g_supports_64 = true;
299
300#elif defined (__i386__)
301
302 g_host_arch.SetArch ("i386");
303 g_supports_32 = true;
304 g_supports_64 = false;
305
306#elif defined (__arm__)
307
308 g_host_arch.SetArch ("arm");
309 g_supports_32 = true;
310 g_supports_64 = false;
311
312#elif defined (__ppc64__)
313
314 g_host_arch.SetArch ("ppc64");
315 g_supports_32 = false;
316 g_supports_64 = true;
317
318#elif defined (__powerpc__) || defined (__ppc__)
319 g_host_arch.SetArch ("ppc");
320 g_supports_32 = true;
321 g_supports_64 = false;
322
323#else
324
325#error undefined architecture, define your architecture here
326
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000327#endif
328 }
Greg Clayton395fc332011-02-15 21:59:32 +0000329
330#endif // #else for #if defined (__APPLE__)
331
332 if (arch_kind == eSystemDefaultArchitecture32)
333 return g_host_arch_32;
334 else if (arch_kind == eSystemDefaultArchitecture64)
335 return g_host_arch_64;
336
337 if (g_supports_64)
338 return g_host_arch_64;
339
340 return g_host_arch_32;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000341}
342
343const ConstString &
344Host::GetVendorString()
345{
346 static ConstString g_vendor;
347 if (!g_vendor)
348 {
349#if defined (__APPLE__)
350 char ostype[64];
351 size_t len = sizeof(ostype);
352 if (::sysctlbyname("kern.ostype", &ostype, &len, NULL, 0) == 0)
353 g_vendor.SetCString (ostype);
354 else
355 g_vendor.SetCString("apple");
356#elif defined (__linux__)
357 g_vendor.SetCString("gnu");
358#endif
359 }
360 return g_vendor;
361}
362
363const ConstString &
364Host::GetOSString()
365{
366 static ConstString g_os_string;
367 if (!g_os_string)
368 {
369#if defined (__APPLE__)
370 g_os_string.SetCString("darwin");
371#elif defined (__linux__)
372 g_os_string.SetCString("linux");
373#endif
374 }
375 return g_os_string;
376}
377
378const ConstString &
379Host::GetTargetTriple()
380{
381 static ConstString g_host_triple;
382 if (!(g_host_triple))
383 {
384 StreamString triple;
385 triple.Printf("%s-%s-%s",
386 GetArchitecture().AsCString(),
387 GetVendorString().AsCString(),
388 GetOSString().AsCString());
389
390 std::transform (triple.GetString().begin(),
391 triple.GetString().end(),
392 triple.GetString().begin(),
393 ::tolower);
394
395 g_host_triple.SetCString(triple.GetString().c_str());
396 }
397 return g_host_triple;
398}
399
400lldb::pid_t
401Host::GetCurrentProcessID()
402{
403 return ::getpid();
404}
405
406lldb::tid_t
407Host::GetCurrentThreadID()
408{
409#if defined (__APPLE__)
410 return ::mach_thread_self();
411#else
412 return lldb::tid_t(pthread_self());
413#endif
414}
415
416const char *
417Host::GetSignalAsCString (int signo)
418{
419 switch (signo)
420 {
421 case SIGHUP: return "SIGHUP"; // 1 hangup
422 case SIGINT: return "SIGINT"; // 2 interrupt
423 case SIGQUIT: return "SIGQUIT"; // 3 quit
424 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
425 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
426 case SIGABRT: return "SIGABRT"; // 6 abort()
427#if defined(_POSIX_C_SOURCE)
428 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
429#else // !_POSIX_C_SOURCE
430 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
431#endif // !_POSIX_C_SOURCE
432 case SIGFPE: return "SIGFPE"; // 8 floating point exception
433 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
434 case SIGBUS: return "SIGBUS"; // 10 bus error
435 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
436 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
437 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
438 case SIGALRM: return "SIGALRM"; // 14 alarm clock
439 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
440 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
441 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
442 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
443 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
444 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
445 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
446 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
447#if !defined(_POSIX_C_SOURCE)
448 case SIGIO: return "SIGIO"; // 23 input/output possible signal
449#endif
450 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
451 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
452 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
453 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
454#if !defined(_POSIX_C_SOURCE)
455 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
456 case SIGINFO: return "SIGINFO"; // 29 information request
457#endif
458 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
459 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
460 default:
461 break;
462 }
463 return NULL;
464}
465
466void
467Host::WillTerminate ()
468{
469}
470
471#if !defined (__APPLE__) // see macosx/Host.mm
472void
473Host::ThreadCreated (const char *thread_name)
474{
475}
Greg Claytonb749a262010-12-03 06:02:24 +0000476
477void
478Host::Backtrace (Stream &strm, uint32_t max_frames)
479{
Greg Clayton52fd9842011-02-02 02:24:04 +0000480 // TODO: Is there a way to backtrace the current process on linux? Other systems?
Greg Claytonb749a262010-12-03 06:02:24 +0000481}
482
Greg Clayton638351a2010-12-04 00:10:17 +0000483
484size_t
485Host::GetEnvironment (StringList &env)
486{
Greg Clayton52fd9842011-02-02 02:24:04 +0000487 // TODO: Is there a way to the host environment for this process on linux? Other systems?
Greg Clayton638351a2010-12-04 00:10:17 +0000488 return 0;
489}
490
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000491#endif
492
493struct HostThreadCreateInfo
494{
495 std::string thread_name;
496 thread_func_t thread_fptr;
497 thread_arg_t thread_arg;
498
499 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
500 thread_name (name ? name : ""),
501 thread_fptr (fptr),
502 thread_arg (arg)
503 {
504 }
505};
506
507static thread_result_t
508ThreadCreateTrampoline (thread_arg_t arg)
509{
510 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
511 Host::ThreadCreated (info->thread_name.c_str());
512 thread_func_t thread_fptr = info->thread_fptr;
513 thread_arg_t thread_arg = info->thread_arg;
514
Greg Claytone005f2c2010-11-06 01:53:30 +0000515 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000516 if (log)
517 log->Printf("thread created");
518
519 delete info;
520 return thread_fptr (thread_arg);
521}
522
523lldb::thread_t
524Host::ThreadCreate
525(
526 const char *thread_name,
527 thread_func_t thread_fptr,
528 thread_arg_t thread_arg,
529 Error *error
530)
531{
532 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
533
534 // Host::ThreadCreateTrampoline will delete this pointer for us.
535 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
536
537 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
538 if (err == 0)
539 {
540 if (error)
541 error->Clear();
542 return thread;
543 }
544
545 if (error)
546 error->SetError (err, eErrorTypePOSIX);
547
548 return LLDB_INVALID_HOST_THREAD;
549}
550
551bool
552Host::ThreadCancel (lldb::thread_t thread, Error *error)
553{
554 int err = ::pthread_cancel (thread);
555 if (error)
556 error->SetError(err, eErrorTypePOSIX);
557 return err == 0;
558}
559
560bool
561Host::ThreadDetach (lldb::thread_t thread, Error *error)
562{
563 int err = ::pthread_detach (thread);
564 if (error)
565 error->SetError(err, eErrorTypePOSIX);
566 return err == 0;
567}
568
569bool
570Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
571{
572 int err = ::pthread_join (thread, thread_result_ptr);
573 if (error)
574 error->SetError(err, eErrorTypePOSIX);
575 return err == 0;
576}
577
578//------------------------------------------------------------------
579// Control access to a static file thread name map using a single
580// static function to avoid a static constructor.
581//------------------------------------------------------------------
582static const char *
583ThreadNameAccessor (bool get, lldb::pid_t pid, lldb::tid_t tid, const char *name)
584{
585 uint64_t pid_tid = ((uint64_t)pid << 32) | (uint64_t)tid;
586
587 static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
588 Mutex::Locker locker(&g_mutex);
589
590 typedef std::map<uint64_t, std::string> thread_name_map;
591 // rdar://problem/8153284
592 // Fixed a crasher where during shutdown, loggings attempted to access the
593 // thread name but the static map instance had already been destructed.
594 // Another approach is to introduce a static guard object which monitors its
595 // own destruction and raises a flag, but this incurs more overhead.
596 static thread_name_map *g_thread_names_ptr = new thread_name_map();
597 thread_name_map &g_thread_names = *g_thread_names_ptr;
598
599 if (get)
600 {
601 // See if the thread name exists in our thread name pool
602 thread_name_map::iterator pos = g_thread_names.find(pid_tid);
603 if (pos != g_thread_names.end())
604 return pos->second.c_str();
605 }
606 else
607 {
608 // Set the thread name
609 g_thread_names[pid_tid] = name;
610 }
611 return NULL;
612}
613
614const char *
615Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
616{
617 const char *name = ThreadNameAccessor (true, pid, tid, NULL);
618 if (name == NULL)
619 {
620#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
621 // We currently can only get the name of a thread in the current process.
622 if (pid == Host::GetCurrentProcessID())
623 {
624 char pthread_name[1024];
625 if (::pthread_getname_np (::pthread_from_mach_thread_np (tid), pthread_name, sizeof(pthread_name)) == 0)
626 {
627 if (pthread_name[0])
628 {
629 // Set the thread in our string pool
630 ThreadNameAccessor (false, pid, tid, pthread_name);
631 // Get our copy of the thread name string
632 name = ThreadNameAccessor (true, pid, tid, NULL);
633 }
634 }
Greg Clayton49ce6822010-10-31 03:01:06 +0000635
636 if (name == NULL)
637 {
638 dispatch_queue_t current_queue = ::dispatch_get_current_queue ();
639 if (current_queue != NULL)
640 name = dispatch_queue_get_label (current_queue);
641 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000642 }
643#endif
644 }
645 return name;
646}
647
648void
649Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
650{
651 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
652 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
653 if (pid == LLDB_INVALID_PROCESS_ID)
654 pid = curr_pid;
655
656 if (tid == LLDB_INVALID_THREAD_ID)
657 tid = curr_tid;
658
659#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
660 // Set the pthread name if possible
661 if (pid == curr_pid && tid == curr_tid)
662 {
663 ::pthread_setname_np (name);
664 }
665#endif
666 ThreadNameAccessor (false, pid, tid, name);
667}
668
669FileSpec
670Host::GetProgramFileSpec ()
671{
672 static FileSpec g_program_filespec;
673 if (!g_program_filespec)
674 {
675#if defined (__APPLE__)
676 char program_fullpath[PATH_MAX];
677 // If DST is NULL, then return the number of bytes needed.
678 uint32_t len = sizeof(program_fullpath);
679 int err = _NSGetExecutablePath (program_fullpath, &len);
680 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000681 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000682 else if (err == -1)
683 {
684 char *large_program_fullpath = (char *)::malloc (len + 1);
685
686 err = _NSGetExecutablePath (large_program_fullpath, &len);
687 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000688 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000689
690 ::free (large_program_fullpath);
691 }
692#elif defined (__linux__)
693 char exe_path[PATH_MAX];
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000694 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
695 if (len > 0) {
696 exe_path[len] = 0;
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000697 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000698 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000699#elif defined (__FreeBSD__)
700 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
701 size_t exe_path_size;
702 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
703 {
Greg Clayton366795e2011-01-13 01:27:55 +0000704 char *exe_path = new char[exe_path_size];
705 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
706 g_program_filespec.SetFile(exe_path, false);
707 delete[] exe_path;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000708 }
709#endif
710 }
711 return g_program_filespec;
712}
713
714FileSpec
715Host::GetModuleFileSpecForHostAddress (const void *host_addr)
716{
717 FileSpec module_filespec;
718 Dl_info info;
719 if (::dladdr (host_addr, &info))
720 {
721 if (info.dli_fname)
Greg Clayton537a7a82010-10-20 20:54:39 +0000722 module_filespec.SetFile(info.dli_fname, true);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000723 }
724 return module_filespec;
725}
726
727#if !defined (__APPLE__) // see Host.mm
728bool
Greg Clayton24b48ff2010-10-17 22:03:32 +0000729Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000730{
Greg Clayton24b48ff2010-10-17 22:03:32 +0000731 return false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000732}
733#endif
734
Greg Clayton14ef59f2011-02-08 00:35:34 +0000735// Opaque info that tracks a dynamic library that was loaded
736struct DynamicLibraryInfo
Greg Clayton52fd9842011-02-02 02:24:04 +0000737{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000738 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
739 file_spec (fs),
740 open_options (o),
741 handle (h)
742 {
743 }
744
745 const FileSpec file_spec;
746 uint32_t open_options;
747 void * handle;
748};
749
750void *
751Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
752{
Greg Clayton52fd9842011-02-02 02:24:04 +0000753 char path[PATH_MAX];
754 if (file_spec.GetPath(path, sizeof(path)))
755 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000756 int mode = 0;
757
758 if (options & eDynamicLibraryOpenOptionLazy)
759 mode |= RTLD_LAZY;
Greg Claytonbf467b02011-02-08 05:24:57 +0000760 else
761 mode |= RTLD_NOW;
762
Greg Clayton14ef59f2011-02-08 00:35:34 +0000763
764 if (options & eDynamicLibraryOpenOptionLocal)
765 mode |= RTLD_LOCAL;
766 else
767 mode |= RTLD_GLOBAL;
768
769#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
770 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
771 mode |= RTLD_FIRST;
Greg Clayton0f577c22011-02-07 17:43:47 +0000772#endif
Greg Clayton14ef59f2011-02-08 00:35:34 +0000773
774 void * opaque = ::dlopen (path, mode);
775
776 if (opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000777 {
778 error.Clear();
Greg Clayton14ef59f2011-02-08 00:35:34 +0000779 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton52fd9842011-02-02 02:24:04 +0000780 }
781 else
782 {
783 error.SetErrorString(::dlerror());
784 }
785 }
786 else
787 {
788 error.SetErrorString("failed to extract path");
789 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000790 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000791}
792
793Error
Greg Clayton14ef59f2011-02-08 00:35:34 +0000794Host::DynamicLibraryClose (void *opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000795{
796 Error error;
Greg Clayton14ef59f2011-02-08 00:35:34 +0000797 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000798 {
799 error.SetErrorString ("invalid dynamic library handle");
800 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000801 else
Greg Clayton52fd9842011-02-02 02:24:04 +0000802 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000803 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
804 if (::dlclose (dylib_info->handle) != 0)
805 {
806 error.SetErrorString(::dlerror());
807 }
808
809 dylib_info->open_options = 0;
810 dylib_info->handle = 0;
811 delete dylib_info;
Greg Clayton52fd9842011-02-02 02:24:04 +0000812 }
813 return error;
814}
815
816void *
Greg Clayton14ef59f2011-02-08 00:35:34 +0000817Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton52fd9842011-02-02 02:24:04 +0000818{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000819 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000820 {
821 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton52fd9842011-02-02 02:24:04 +0000822 }
Greg Clayton52fd9842011-02-02 02:24:04 +0000823 else
Greg Clayton14ef59f2011-02-08 00:35:34 +0000824 {
825 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
826
827 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
828 if (symbol_addr)
829 {
830#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
831 // This host doesn't support limiting searches to this shared library
832 // so we need to verify that the match came from this shared library
833 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonbf467b02011-02-08 05:24:57 +0000834 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton14ef59f2011-02-08 00:35:34 +0000835 {
836 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
837 if (match_dylib_spec != dylib_info->file_spec)
838 {
839 char dylib_path[PATH_MAX];
840 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
841 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
842 else
843 error.SetErrorString ("symbol not found");
844 return NULL;
845 }
846 }
847#endif
848 error.Clear();
849 return symbol_addr;
850 }
851 else
852 {
853 error.SetErrorString(::dlerror());
854 }
855 }
856 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000857}
Greg Clayton24b48ff2010-10-17 22:03:32 +0000858
859bool
860Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
861{
Greg Clayton5d187e52011-01-08 20:28:42 +0000862 // To get paths related to LLDB we get the path to the executable that
Greg Clayton24b48ff2010-10-17 22:03:32 +0000863 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
864 // on linux this is assumed to be the "lldb" main executable. If LLDB on
865 // linux is actually in a shared library (lldb.so??) then this function will
866 // need to be modified to "do the right thing".
867
868 switch (path_type)
869 {
870 case ePathTypeLLDBShlibDir:
871 {
872 static ConstString g_lldb_so_dir;
873 if (!g_lldb_so_dir)
874 {
875 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
876 g_lldb_so_dir = lldb_file_spec.GetDirectory();
877 }
878 file_spec.GetDirectory() = g_lldb_so_dir;
879 return file_spec.GetDirectory();
880 }
881 break;
882
883 case ePathTypeSupportExecutableDir:
884 {
885 static ConstString g_lldb_support_exe_dir;
886 if (!g_lldb_support_exe_dir)
887 {
888 FileSpec lldb_file_spec;
889 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
890 {
891 char raw_path[PATH_MAX];
892 char resolved_path[PATH_MAX];
893 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
894
895#if defined (__APPLE__)
896 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
897 if (framework_pos)
898 {
899 framework_pos += strlen("LLDB.framework");
900 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
901 }
902#endif
903 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
904 g_lldb_support_exe_dir.SetCString(resolved_path);
905 }
906 }
907 file_spec.GetDirectory() = g_lldb_support_exe_dir;
908 return file_spec.GetDirectory();
909 }
910 break;
911
912 case ePathTypeHeaderDir:
913 {
914 static ConstString g_lldb_headers_dir;
915 if (!g_lldb_headers_dir)
916 {
917#if defined (__APPLE__)
918 FileSpec lldb_file_spec;
919 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
920 {
921 char raw_path[PATH_MAX];
922 char resolved_path[PATH_MAX];
923 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
924
925 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
926 if (framework_pos)
927 {
928 framework_pos += strlen("LLDB.framework");
929 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
930 }
931 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
932 g_lldb_headers_dir.SetCString(resolved_path);
933 }
934#else
Greg Clayton52fd9842011-02-02 02:24:04 +0000935 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Clayton24b48ff2010-10-17 22:03:32 +0000936 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
937#endif
938 }
939 file_spec.GetDirectory() = g_lldb_headers_dir;
940 return file_spec.GetDirectory();
941 }
942 break;
943
944 case ePathTypePythonDir:
945 {
Greg Clayton52fd9842011-02-02 02:24:04 +0000946 // TODO: Anyone know how we can determine this for linux? Other systems?
Greg Clayton24b48ff2010-10-17 22:03:32 +0000947 // For linux we are currently assuming the location of the lldb
948 // binary that contains this function is the directory that will
949 // contain lldb.so, lldb.py and embedded_interpreter.py...
950
951 static ConstString g_lldb_python_dir;
952 if (!g_lldb_python_dir)
953 {
954 FileSpec lldb_file_spec;
955 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
956 {
957 char raw_path[PATH_MAX];
958 char resolved_path[PATH_MAX];
959 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
960
961#if defined (__APPLE__)
962 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
963 if (framework_pos)
964 {
965 framework_pos += strlen("LLDB.framework");
966 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
967 }
968#endif
969 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
970 g_lldb_python_dir.SetCString(resolved_path);
971 }
972 }
973 file_spec.GetDirectory() = g_lldb_python_dir;
974 return file_spec.GetDirectory();
975 }
976 break;
977
Greg Clayton52fd9842011-02-02 02:24:04 +0000978 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
979 {
980#if defined (__APPLE__)
981 static ConstString g_lldb_system_plugin_dir;
982 if (!g_lldb_system_plugin_dir)
983 {
984 FileSpec lldb_file_spec;
985 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
986 {
987 char raw_path[PATH_MAX];
988 char resolved_path[PATH_MAX];
989 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
990
991 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
992 if (framework_pos)
993 {
994 framework_pos += strlen("LLDB.framework");
995 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
996 }
997 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
998 g_lldb_system_plugin_dir.SetCString(resolved_path);
999 }
1000 }
1001 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1002 return file_spec.GetDirectory();
1003#endif
1004 // TODO: where would system LLDB plug-ins be located on linux? Other systems?
1005 return false;
1006 }
1007 break;
1008
1009 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1010 {
1011#if defined (__APPLE__)
1012 static ConstString g_lldb_user_plugin_dir;
1013 if (!g_lldb_user_plugin_dir)
1014 {
1015 char user_plugin_path[PATH_MAX];
1016 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1017 user_plugin_path,
1018 sizeof(user_plugin_path)))
1019 {
1020 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1021 }
1022 }
1023 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1024 return file_spec.GetDirectory();
1025#endif
1026 // TODO: where would user LLDB plug-ins be located on linux? Other systems?
1027 return false;
1028 }
Greg Clayton24b48ff2010-10-17 22:03:32 +00001029 default:
1030 assert (!"Unhandled PathType");
1031 break;
1032 }
1033
1034 return false;
1035}
1036
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001037uint32_t
1038Host::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
1039{
1040 uint32_t num_matches = 0;
1041
1042#if defined (__APPLE__)
1043 int num_pids;
1044 int size_of_pids;
Greg Claytonfb8876d2010-10-10 22:07:18 +00001045 std::vector<int> pid_list;
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001046
1047 size_of_pids = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
1048 if (size_of_pids == -1)
1049 return 0;
1050
1051 num_pids = size_of_pids/sizeof(int);
Greg Claytonfb8876d2010-10-10 22:07:18 +00001052
1053 pid_list.resize (size_of_pids);
1054 size_of_pids = proc_listpids(PROC_ALL_PIDS, 0, &pid_list[0], size_of_pids);
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001055 if (size_of_pids == -1)
1056 return 0;
1057
1058 lldb::pid_t our_pid = getpid();
1059
1060 for (int i = 0; i < num_pids; i++)
1061 {
1062 struct proc_bsdinfo bsd_info;
1063 int error = proc_pidinfo (pid_list[i], PROC_PIDTBSDINFO, (uint64_t) 0, &bsd_info, PROC_PIDTBSDINFO_SIZE);
1064 if (error == 0)
1065 continue;
1066
1067 // Don't offer to attach to zombie processes, already traced or exiting
1068 // processes, and of course, ourselves... It looks like passing the second arg of
1069 // 0 to proc_listpids will exclude zombies anyway, but that's not documented so...
1070 if (((bsd_info.pbi_flags & (PROC_FLAG_TRACED | PROC_FLAG_INEXIT)) != 0)
1071 || (bsd_info.pbi_status == SZOMB)
1072 || (bsd_info.pbi_pid == our_pid))
1073 continue;
1074 char pid_name[MAXCOMLEN * 2 + 1];
1075 int name_len;
1076 name_len = proc_name(bsd_info.pbi_pid, pid_name, MAXCOMLEN * 2);
1077 if (name_len == 0)
1078 continue;
1079
1080 if (strstr(pid_name, name) != pid_name)
1081 continue;
1082 matches.AppendString (pid_name);
1083 pids.push_back (bsd_info.pbi_pid);
1084 num_matches++;
1085 }
1086#endif
1087
1088 return num_matches;
1089}
1090
1091ArchSpec
1092Host::GetArchSpecForExistingProcess (lldb::pid_t pid)
1093{
1094 ArchSpec return_spec;
1095
1096#if defined (__APPLE__)
1097 struct proc_bsdinfo bsd_info;
1098 int error = proc_pidinfo (pid, PROC_PIDTBSDINFO, (uint64_t) 0, &bsd_info, PROC_PIDTBSDINFO_SIZE);
1099 if (error == 0)
1100 return return_spec;
1101 if (bsd_info.pbi_flags & PROC_FLAG_LP64)
1102 return_spec.SetArch(LLDB_ARCH_DEFAULT_64BIT);
1103 else
1104 return_spec.SetArch(LLDB_ARCH_DEFAULT_32BIT);
1105#endif
1106
1107 return return_spec;
1108}
1109
1110ArchSpec
1111Host::GetArchSpecForExistingProcess (const char *process_name)
1112{
1113 ArchSpec returnSpec;
1114 StringList matches;
1115 std::vector<lldb::pid_t> pids;
1116 if (ListProcessesMatchingName(process_name, matches, pids))
1117 {
1118 if (matches.GetSize() == 1)
1119 {
1120 return GetArchSpecForExistingProcess(pids[0]);
1121 }
1122 }
1123 return returnSpec;
1124}
1125
1126#if !defined (__APPLE__) // see macosx/Host.mm
1127bool
Greg Claytonb73620c2010-12-18 01:54:34 +00001128Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001129{
1130 return false;
1131}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001132
Greg Claytone98ac252010-11-10 04:57:04 +00001133void
1134Host::SetCrashDescriptionWithFormat (const char *format, ...)
1135{
1136}
1137
1138void
1139Host::SetCrashDescription (const char *description)
1140{
1141}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001142
1143lldb::pid_t
1144LaunchApplication (const FileSpec &app_file_spec)
1145{
1146 return LLDB_INVALID_PROCESS_ID;
1147}
1148
1149lldb::pid_t
1150Host::LaunchInNewTerminal
1151(
Greg Claytonb73620c2010-12-18 01:54:34 +00001152 const char *tty_name,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001153 const char **argv,
1154 const char **envp,
Greg Claytonde915be2011-01-23 05:56:20 +00001155 const char *working_dir,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001156 const ArchSpec *arch_spec,
1157 bool stop_at_entry,
1158 bool disable_aslr
1159)
1160{
1161 return LLDB_INVALID_PROCESS_ID;
1162}
1163
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001164#endif