blob: ae0537bd1be011d9437c628d06d6155e5f2cd323 [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 &
225Host::GetArchitecture ()
226{
227 static ArchSpec g_host_arch;
228 if (!g_host_arch.IsValid())
229 {
230#if defined (__APPLE__)
231 uint32_t cputype, cpusubtype;
232 uint32_t is_64_bit_capable;
233 size_t len = sizeof(cputype);
234 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
235 {
236 len = sizeof(cpusubtype);
237 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) == 0)
Greg Claytone71e2582011-02-04 01:58:07 +0000238 g_host_arch.SetMachOArch (cputype, cpusubtype);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000239
240 len = sizeof (is_64_bit_capable);
241 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
242 {
243 if (is_64_bit_capable)
244 {
245 if (cputype == CPU_TYPE_I386 && cpusubtype == CPU_SUBTYPE_486)
246 cpusubtype = CPU_SUBTYPE_I386_ALL;
247
248 cputype |= CPU_ARCH_ABI64;
249 }
250 }
251 }
252#elif defined (__linux__)
Greg Clayton0f577c22011-02-07 17:43:47 +0000253 g_host_arch.SetElfArch(7u, 144u);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000254#endif
255 }
256 return g_host_arch;
257}
258
259const ConstString &
260Host::GetVendorString()
261{
262 static ConstString g_vendor;
263 if (!g_vendor)
264 {
265#if defined (__APPLE__)
266 char ostype[64];
267 size_t len = sizeof(ostype);
268 if (::sysctlbyname("kern.ostype", &ostype, &len, NULL, 0) == 0)
269 g_vendor.SetCString (ostype);
270 else
271 g_vendor.SetCString("apple");
272#elif defined (__linux__)
273 g_vendor.SetCString("gnu");
274#endif
275 }
276 return g_vendor;
277}
278
279const ConstString &
280Host::GetOSString()
281{
282 static ConstString g_os_string;
283 if (!g_os_string)
284 {
285#if defined (__APPLE__)
286 g_os_string.SetCString("darwin");
287#elif defined (__linux__)
288 g_os_string.SetCString("linux");
289#endif
290 }
291 return g_os_string;
292}
293
294const ConstString &
295Host::GetTargetTriple()
296{
297 static ConstString g_host_triple;
298 if (!(g_host_triple))
299 {
300 StreamString triple;
301 triple.Printf("%s-%s-%s",
302 GetArchitecture().AsCString(),
303 GetVendorString().AsCString(),
304 GetOSString().AsCString());
305
306 std::transform (triple.GetString().begin(),
307 triple.GetString().end(),
308 triple.GetString().begin(),
309 ::tolower);
310
311 g_host_triple.SetCString(triple.GetString().c_str());
312 }
313 return g_host_triple;
314}
315
316lldb::pid_t
317Host::GetCurrentProcessID()
318{
319 return ::getpid();
320}
321
322lldb::tid_t
323Host::GetCurrentThreadID()
324{
325#if defined (__APPLE__)
326 return ::mach_thread_self();
327#else
328 return lldb::tid_t(pthread_self());
329#endif
330}
331
332const char *
333Host::GetSignalAsCString (int signo)
334{
335 switch (signo)
336 {
337 case SIGHUP: return "SIGHUP"; // 1 hangup
338 case SIGINT: return "SIGINT"; // 2 interrupt
339 case SIGQUIT: return "SIGQUIT"; // 3 quit
340 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
341 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
342 case SIGABRT: return "SIGABRT"; // 6 abort()
343#if defined(_POSIX_C_SOURCE)
344 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
345#else // !_POSIX_C_SOURCE
346 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
347#endif // !_POSIX_C_SOURCE
348 case SIGFPE: return "SIGFPE"; // 8 floating point exception
349 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
350 case SIGBUS: return "SIGBUS"; // 10 bus error
351 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
352 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
353 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
354 case SIGALRM: return "SIGALRM"; // 14 alarm clock
355 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
356 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
357 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
358 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
359 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
360 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
361 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
362 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
363#if !defined(_POSIX_C_SOURCE)
364 case SIGIO: return "SIGIO"; // 23 input/output possible signal
365#endif
366 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
367 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
368 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
369 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
370#if !defined(_POSIX_C_SOURCE)
371 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
372 case SIGINFO: return "SIGINFO"; // 29 information request
373#endif
374 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
375 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
376 default:
377 break;
378 }
379 return NULL;
380}
381
382void
383Host::WillTerminate ()
384{
385}
386
387#if !defined (__APPLE__) // see macosx/Host.mm
388void
389Host::ThreadCreated (const char *thread_name)
390{
391}
Greg Claytonb749a262010-12-03 06:02:24 +0000392
393void
394Host::Backtrace (Stream &strm, uint32_t max_frames)
395{
Greg Clayton52fd9842011-02-02 02:24:04 +0000396 // TODO: Is there a way to backtrace the current process on linux? Other systems?
Greg Claytonb749a262010-12-03 06:02:24 +0000397}
398
Greg Clayton638351a2010-12-04 00:10:17 +0000399
400size_t
401Host::GetEnvironment (StringList &env)
402{
Greg Clayton52fd9842011-02-02 02:24:04 +0000403 // TODO: Is there a way to the host environment for this process on linux? Other systems?
Greg Clayton638351a2010-12-04 00:10:17 +0000404 return 0;
405}
406
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000407#endif
408
409struct HostThreadCreateInfo
410{
411 std::string thread_name;
412 thread_func_t thread_fptr;
413 thread_arg_t thread_arg;
414
415 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
416 thread_name (name ? name : ""),
417 thread_fptr (fptr),
418 thread_arg (arg)
419 {
420 }
421};
422
423static thread_result_t
424ThreadCreateTrampoline (thread_arg_t arg)
425{
426 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
427 Host::ThreadCreated (info->thread_name.c_str());
428 thread_func_t thread_fptr = info->thread_fptr;
429 thread_arg_t thread_arg = info->thread_arg;
430
Greg Claytone005f2c2010-11-06 01:53:30 +0000431 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000432 if (log)
433 log->Printf("thread created");
434
435 delete info;
436 return thread_fptr (thread_arg);
437}
438
439lldb::thread_t
440Host::ThreadCreate
441(
442 const char *thread_name,
443 thread_func_t thread_fptr,
444 thread_arg_t thread_arg,
445 Error *error
446)
447{
448 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
449
450 // Host::ThreadCreateTrampoline will delete this pointer for us.
451 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
452
453 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
454 if (err == 0)
455 {
456 if (error)
457 error->Clear();
458 return thread;
459 }
460
461 if (error)
462 error->SetError (err, eErrorTypePOSIX);
463
464 return LLDB_INVALID_HOST_THREAD;
465}
466
467bool
468Host::ThreadCancel (lldb::thread_t thread, Error *error)
469{
470 int err = ::pthread_cancel (thread);
471 if (error)
472 error->SetError(err, eErrorTypePOSIX);
473 return err == 0;
474}
475
476bool
477Host::ThreadDetach (lldb::thread_t thread, Error *error)
478{
479 int err = ::pthread_detach (thread);
480 if (error)
481 error->SetError(err, eErrorTypePOSIX);
482 return err == 0;
483}
484
485bool
486Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
487{
488 int err = ::pthread_join (thread, thread_result_ptr);
489 if (error)
490 error->SetError(err, eErrorTypePOSIX);
491 return err == 0;
492}
493
494//------------------------------------------------------------------
495// Control access to a static file thread name map using a single
496// static function to avoid a static constructor.
497//------------------------------------------------------------------
498static const char *
499ThreadNameAccessor (bool get, lldb::pid_t pid, lldb::tid_t tid, const char *name)
500{
501 uint64_t pid_tid = ((uint64_t)pid << 32) | (uint64_t)tid;
502
503 static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
504 Mutex::Locker locker(&g_mutex);
505
506 typedef std::map<uint64_t, std::string> thread_name_map;
507 // rdar://problem/8153284
508 // Fixed a crasher where during shutdown, loggings attempted to access the
509 // thread name but the static map instance had already been destructed.
510 // Another approach is to introduce a static guard object which monitors its
511 // own destruction and raises a flag, but this incurs more overhead.
512 static thread_name_map *g_thread_names_ptr = new thread_name_map();
513 thread_name_map &g_thread_names = *g_thread_names_ptr;
514
515 if (get)
516 {
517 // See if the thread name exists in our thread name pool
518 thread_name_map::iterator pos = g_thread_names.find(pid_tid);
519 if (pos != g_thread_names.end())
520 return pos->second.c_str();
521 }
522 else
523 {
524 // Set the thread name
525 g_thread_names[pid_tid] = name;
526 }
527 return NULL;
528}
529
530const char *
531Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
532{
533 const char *name = ThreadNameAccessor (true, pid, tid, NULL);
534 if (name == NULL)
535 {
536#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
537 // We currently can only get the name of a thread in the current process.
538 if (pid == Host::GetCurrentProcessID())
539 {
540 char pthread_name[1024];
541 if (::pthread_getname_np (::pthread_from_mach_thread_np (tid), pthread_name, sizeof(pthread_name)) == 0)
542 {
543 if (pthread_name[0])
544 {
545 // Set the thread in our string pool
546 ThreadNameAccessor (false, pid, tid, pthread_name);
547 // Get our copy of the thread name string
548 name = ThreadNameAccessor (true, pid, tid, NULL);
549 }
550 }
Greg Clayton49ce6822010-10-31 03:01:06 +0000551
552 if (name == NULL)
553 {
554 dispatch_queue_t current_queue = ::dispatch_get_current_queue ();
555 if (current_queue != NULL)
556 name = dispatch_queue_get_label (current_queue);
557 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000558 }
559#endif
560 }
561 return name;
562}
563
564void
565Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
566{
567 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
568 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
569 if (pid == LLDB_INVALID_PROCESS_ID)
570 pid = curr_pid;
571
572 if (tid == LLDB_INVALID_THREAD_ID)
573 tid = curr_tid;
574
575#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
576 // Set the pthread name if possible
577 if (pid == curr_pid && tid == curr_tid)
578 {
579 ::pthread_setname_np (name);
580 }
581#endif
582 ThreadNameAccessor (false, pid, tid, name);
583}
584
585FileSpec
586Host::GetProgramFileSpec ()
587{
588 static FileSpec g_program_filespec;
589 if (!g_program_filespec)
590 {
591#if defined (__APPLE__)
592 char program_fullpath[PATH_MAX];
593 // If DST is NULL, then return the number of bytes needed.
594 uint32_t len = sizeof(program_fullpath);
595 int err = _NSGetExecutablePath (program_fullpath, &len);
596 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000597 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000598 else if (err == -1)
599 {
600 char *large_program_fullpath = (char *)::malloc (len + 1);
601
602 err = _NSGetExecutablePath (large_program_fullpath, &len);
603 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000604 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000605
606 ::free (large_program_fullpath);
607 }
608#elif defined (__linux__)
609 char exe_path[PATH_MAX];
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000610 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
611 if (len > 0) {
612 exe_path[len] = 0;
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000613 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000614 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000615#elif defined (__FreeBSD__)
616 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
617 size_t exe_path_size;
618 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
619 {
Greg Clayton366795e2011-01-13 01:27:55 +0000620 char *exe_path = new char[exe_path_size];
621 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
622 g_program_filespec.SetFile(exe_path, false);
623 delete[] exe_path;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000624 }
625#endif
626 }
627 return g_program_filespec;
628}
629
630FileSpec
631Host::GetModuleFileSpecForHostAddress (const void *host_addr)
632{
633 FileSpec module_filespec;
634 Dl_info info;
635 if (::dladdr (host_addr, &info))
636 {
637 if (info.dli_fname)
Greg Clayton537a7a82010-10-20 20:54:39 +0000638 module_filespec.SetFile(info.dli_fname, true);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000639 }
640 return module_filespec;
641}
642
643#if !defined (__APPLE__) // see Host.mm
644bool
Greg Clayton24b48ff2010-10-17 22:03:32 +0000645Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000646{
Greg Clayton24b48ff2010-10-17 22:03:32 +0000647 return false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000648}
649#endif
650
Greg Clayton14ef59f2011-02-08 00:35:34 +0000651// Opaque info that tracks a dynamic library that was loaded
652struct DynamicLibraryInfo
Greg Clayton52fd9842011-02-02 02:24:04 +0000653{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000654 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
655 file_spec (fs),
656 open_options (o),
657 handle (h)
658 {
659 }
660
661 const FileSpec file_spec;
662 uint32_t open_options;
663 void * handle;
664};
665
666void *
667Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
668{
Greg Clayton52fd9842011-02-02 02:24:04 +0000669 char path[PATH_MAX];
670 if (file_spec.GetPath(path, sizeof(path)))
671 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000672 int mode = 0;
673
674 if (options & eDynamicLibraryOpenOptionLazy)
675 mode |= RTLD_LAZY;
Greg Claytonbf467b02011-02-08 05:24:57 +0000676 else
677 mode |= RTLD_NOW;
678
Greg Clayton14ef59f2011-02-08 00:35:34 +0000679
680 if (options & eDynamicLibraryOpenOptionLocal)
681 mode |= RTLD_LOCAL;
682 else
683 mode |= RTLD_GLOBAL;
684
685#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
686 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
687 mode |= RTLD_FIRST;
Greg Clayton0f577c22011-02-07 17:43:47 +0000688#endif
Greg Clayton14ef59f2011-02-08 00:35:34 +0000689
690 void * opaque = ::dlopen (path, mode);
691
692 if (opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000693 {
694 error.Clear();
Greg Clayton14ef59f2011-02-08 00:35:34 +0000695 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton52fd9842011-02-02 02:24:04 +0000696 }
697 else
698 {
699 error.SetErrorString(::dlerror());
700 }
701 }
702 else
703 {
704 error.SetErrorString("failed to extract path");
705 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000706 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000707}
708
709Error
Greg Clayton14ef59f2011-02-08 00:35:34 +0000710Host::DynamicLibraryClose (void *opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000711{
712 Error error;
Greg Clayton14ef59f2011-02-08 00:35:34 +0000713 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000714 {
715 error.SetErrorString ("invalid dynamic library handle");
716 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000717 else
Greg Clayton52fd9842011-02-02 02:24:04 +0000718 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000719 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
720 if (::dlclose (dylib_info->handle) != 0)
721 {
722 error.SetErrorString(::dlerror());
723 }
724
725 dylib_info->open_options = 0;
726 dylib_info->handle = 0;
727 delete dylib_info;
Greg Clayton52fd9842011-02-02 02:24:04 +0000728 }
729 return error;
730}
731
732void *
Greg Clayton14ef59f2011-02-08 00:35:34 +0000733Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton52fd9842011-02-02 02:24:04 +0000734{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000735 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000736 {
737 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton52fd9842011-02-02 02:24:04 +0000738 }
Greg Clayton52fd9842011-02-02 02:24:04 +0000739 else
Greg Clayton14ef59f2011-02-08 00:35:34 +0000740 {
741 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
742
743 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
744 if (symbol_addr)
745 {
746#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
747 // This host doesn't support limiting searches to this shared library
748 // so we need to verify that the match came from this shared library
749 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonbf467b02011-02-08 05:24:57 +0000750 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton14ef59f2011-02-08 00:35:34 +0000751 {
752 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
753 if (match_dylib_spec != dylib_info->file_spec)
754 {
755 char dylib_path[PATH_MAX];
756 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
757 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
758 else
759 error.SetErrorString ("symbol not found");
760 return NULL;
761 }
762 }
763#endif
764 error.Clear();
765 return symbol_addr;
766 }
767 else
768 {
769 error.SetErrorString(::dlerror());
770 }
771 }
772 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000773}
Greg Clayton24b48ff2010-10-17 22:03:32 +0000774
775bool
776Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
777{
Greg Clayton5d187e52011-01-08 20:28:42 +0000778 // To get paths related to LLDB we get the path to the executable that
Greg Clayton24b48ff2010-10-17 22:03:32 +0000779 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
780 // on linux this is assumed to be the "lldb" main executable. If LLDB on
781 // linux is actually in a shared library (lldb.so??) then this function will
782 // need to be modified to "do the right thing".
783
784 switch (path_type)
785 {
786 case ePathTypeLLDBShlibDir:
787 {
788 static ConstString g_lldb_so_dir;
789 if (!g_lldb_so_dir)
790 {
791 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
792 g_lldb_so_dir = lldb_file_spec.GetDirectory();
793 }
794 file_spec.GetDirectory() = g_lldb_so_dir;
795 return file_spec.GetDirectory();
796 }
797 break;
798
799 case ePathTypeSupportExecutableDir:
800 {
801 static ConstString g_lldb_support_exe_dir;
802 if (!g_lldb_support_exe_dir)
803 {
804 FileSpec lldb_file_spec;
805 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
806 {
807 char raw_path[PATH_MAX];
808 char resolved_path[PATH_MAX];
809 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
810
811#if defined (__APPLE__)
812 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
813 if (framework_pos)
814 {
815 framework_pos += strlen("LLDB.framework");
816 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
817 }
818#endif
819 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
820 g_lldb_support_exe_dir.SetCString(resolved_path);
821 }
822 }
823 file_spec.GetDirectory() = g_lldb_support_exe_dir;
824 return file_spec.GetDirectory();
825 }
826 break;
827
828 case ePathTypeHeaderDir:
829 {
830 static ConstString g_lldb_headers_dir;
831 if (!g_lldb_headers_dir)
832 {
833#if defined (__APPLE__)
834 FileSpec lldb_file_spec;
835 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
836 {
837 char raw_path[PATH_MAX];
838 char resolved_path[PATH_MAX];
839 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
840
841 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
842 if (framework_pos)
843 {
844 framework_pos += strlen("LLDB.framework");
845 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
846 }
847 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
848 g_lldb_headers_dir.SetCString(resolved_path);
849 }
850#else
Greg Clayton52fd9842011-02-02 02:24:04 +0000851 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Clayton24b48ff2010-10-17 22:03:32 +0000852 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
853#endif
854 }
855 file_spec.GetDirectory() = g_lldb_headers_dir;
856 return file_spec.GetDirectory();
857 }
858 break;
859
860 case ePathTypePythonDir:
861 {
Greg Clayton52fd9842011-02-02 02:24:04 +0000862 // TODO: Anyone know how we can determine this for linux? Other systems?
Greg Clayton24b48ff2010-10-17 22:03:32 +0000863 // For linux we are currently assuming the location of the lldb
864 // binary that contains this function is the directory that will
865 // contain lldb.so, lldb.py and embedded_interpreter.py...
866
867 static ConstString g_lldb_python_dir;
868 if (!g_lldb_python_dir)
869 {
870 FileSpec lldb_file_spec;
871 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
872 {
873 char raw_path[PATH_MAX];
874 char resolved_path[PATH_MAX];
875 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
876
877#if defined (__APPLE__)
878 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
879 if (framework_pos)
880 {
881 framework_pos += strlen("LLDB.framework");
882 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
883 }
884#endif
885 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
886 g_lldb_python_dir.SetCString(resolved_path);
887 }
888 }
889 file_spec.GetDirectory() = g_lldb_python_dir;
890 return file_spec.GetDirectory();
891 }
892 break;
893
Greg Clayton52fd9842011-02-02 02:24:04 +0000894 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
895 {
896#if defined (__APPLE__)
897 static ConstString g_lldb_system_plugin_dir;
898 if (!g_lldb_system_plugin_dir)
899 {
900 FileSpec lldb_file_spec;
901 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
902 {
903 char raw_path[PATH_MAX];
904 char resolved_path[PATH_MAX];
905 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
906
907 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
908 if (framework_pos)
909 {
910 framework_pos += strlen("LLDB.framework");
911 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
912 }
913 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
914 g_lldb_system_plugin_dir.SetCString(resolved_path);
915 }
916 }
917 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
918 return file_spec.GetDirectory();
919#endif
920 // TODO: where would system LLDB plug-ins be located on linux? Other systems?
921 return false;
922 }
923 break;
924
925 case ePathTypeLLDBUserPlugins: // User plug-ins directory
926 {
927#if defined (__APPLE__)
928 static ConstString g_lldb_user_plugin_dir;
929 if (!g_lldb_user_plugin_dir)
930 {
931 char user_plugin_path[PATH_MAX];
932 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
933 user_plugin_path,
934 sizeof(user_plugin_path)))
935 {
936 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
937 }
938 }
939 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
940 return file_spec.GetDirectory();
941#endif
942 // TODO: where would user LLDB plug-ins be located on linux? Other systems?
943 return false;
944 }
Greg Clayton24b48ff2010-10-17 22:03:32 +0000945 default:
946 assert (!"Unhandled PathType");
947 break;
948 }
949
950 return false;
951}
952
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000953uint32_t
954Host::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
955{
956 uint32_t num_matches = 0;
957
958#if defined (__APPLE__)
959 int num_pids;
960 int size_of_pids;
Greg Claytonfb8876d2010-10-10 22:07:18 +0000961 std::vector<int> pid_list;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000962
963 size_of_pids = proc_listpids(PROC_ALL_PIDS, 0, NULL, 0);
964 if (size_of_pids == -1)
965 return 0;
966
967 num_pids = size_of_pids/sizeof(int);
Greg Claytonfb8876d2010-10-10 22:07:18 +0000968
969 pid_list.resize (size_of_pids);
970 size_of_pids = proc_listpids(PROC_ALL_PIDS, 0, &pid_list[0], size_of_pids);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000971 if (size_of_pids == -1)
972 return 0;
973
974 lldb::pid_t our_pid = getpid();
975
976 for (int i = 0; i < num_pids; i++)
977 {
978 struct proc_bsdinfo bsd_info;
979 int error = proc_pidinfo (pid_list[i], PROC_PIDTBSDINFO, (uint64_t) 0, &bsd_info, PROC_PIDTBSDINFO_SIZE);
980 if (error == 0)
981 continue;
982
983 // Don't offer to attach to zombie processes, already traced or exiting
984 // processes, and of course, ourselves... It looks like passing the second arg of
985 // 0 to proc_listpids will exclude zombies anyway, but that's not documented so...
986 if (((bsd_info.pbi_flags & (PROC_FLAG_TRACED | PROC_FLAG_INEXIT)) != 0)
987 || (bsd_info.pbi_status == SZOMB)
988 || (bsd_info.pbi_pid == our_pid))
989 continue;
990 char pid_name[MAXCOMLEN * 2 + 1];
991 int name_len;
992 name_len = proc_name(bsd_info.pbi_pid, pid_name, MAXCOMLEN * 2);
993 if (name_len == 0)
994 continue;
995
996 if (strstr(pid_name, name) != pid_name)
997 continue;
998 matches.AppendString (pid_name);
999 pids.push_back (bsd_info.pbi_pid);
1000 num_matches++;
1001 }
1002#endif
1003
1004 return num_matches;
1005}
1006
1007ArchSpec
1008Host::GetArchSpecForExistingProcess (lldb::pid_t pid)
1009{
1010 ArchSpec return_spec;
1011
1012#if defined (__APPLE__)
1013 struct proc_bsdinfo bsd_info;
1014 int error = proc_pidinfo (pid, PROC_PIDTBSDINFO, (uint64_t) 0, &bsd_info, PROC_PIDTBSDINFO_SIZE);
1015 if (error == 0)
1016 return return_spec;
1017 if (bsd_info.pbi_flags & PROC_FLAG_LP64)
1018 return_spec.SetArch(LLDB_ARCH_DEFAULT_64BIT);
1019 else
1020 return_spec.SetArch(LLDB_ARCH_DEFAULT_32BIT);
1021#endif
1022
1023 return return_spec;
1024}
1025
1026ArchSpec
1027Host::GetArchSpecForExistingProcess (const char *process_name)
1028{
1029 ArchSpec returnSpec;
1030 StringList matches;
1031 std::vector<lldb::pid_t> pids;
1032 if (ListProcessesMatchingName(process_name, matches, pids))
1033 {
1034 if (matches.GetSize() == 1)
1035 {
1036 return GetArchSpecForExistingProcess(pids[0]);
1037 }
1038 }
1039 return returnSpec;
1040}
1041
1042#if !defined (__APPLE__) // see macosx/Host.mm
1043bool
Greg Claytonb73620c2010-12-18 01:54:34 +00001044Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001045{
1046 return false;
1047}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001048
Greg Claytone98ac252010-11-10 04:57:04 +00001049void
1050Host::SetCrashDescriptionWithFormat (const char *format, ...)
1051{
1052}
1053
1054void
1055Host::SetCrashDescription (const char *description)
1056{
1057}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001058
1059lldb::pid_t
1060LaunchApplication (const FileSpec &app_file_spec)
1061{
1062 return LLDB_INVALID_PROCESS_ID;
1063}
1064
1065lldb::pid_t
1066Host::LaunchInNewTerminal
1067(
Greg Claytonb73620c2010-12-18 01:54:34 +00001068 const char *tty_name,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001069 const char **argv,
1070 const char **envp,
Greg Claytonde915be2011-01-23 05:56:20 +00001071 const char *working_dir,
Greg Clayton24b48ff2010-10-17 22:03:32 +00001072 const ArchSpec *arch_spec,
1073 bool stop_at_entry,
1074 bool disable_aslr
1075)
1076{
1077 return LLDB_INVALID_PROCESS_ID;
1078}
1079
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001080#endif