blob: 18a8fbabee5dfd63d2512741d889fc238f6b2268 [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
Daniel Malead891f9b2012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Greg Clayton132c49a2013-02-17 20:46:30 +000012// C includes
13#include <dlfcn.h>
14#include <errno.h>
15#include <grp.h>
16#include <limits.h>
17#include <netdb.h>
18#include <pwd.h>
19#include <sys/sysctl.h>
20#include <sys/types.h>
21#include <unistd.h>
22
23#if defined (__APPLE__)
24
25#include <dispatch/dispatch.h>
26#include <libproc.h>
27#include <mach-o/dyld.h>
28#include <mach/mach_port.h>
29
30#elif defined (__linux__)
31
32#include <sys/wait.h>
33
34#elif defined (__FreeBSD__)
35
36#include <sys/wait.h>
37#include <pthread_np.h>
38
39#endif
40
Greg Clayton8f3b21d2010-09-07 20:11:56 +000041#include "lldb/Host/Host.h"
42#include "lldb/Core/ArchSpec.h"
43#include "lldb/Core/ConstString.h"
Sean Callananf35a96c2011-10-27 21:22:25 +000044#include "lldb/Core/Debugger.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000045#include "lldb/Core/Error.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000046#include "lldb/Core/Log.h"
47#include "lldb/Core/StreamString.h"
Jim Ingham35dd4962012-05-04 19:24:49 +000048#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton14ef59f2011-02-08 00:35:34 +000049#include "lldb/Host/Config.h"
Greg Claytoncd548032011-02-01 01:31:41 +000050#include "lldb/Host/Endian.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000051#include "lldb/Host/FileSpec.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000052#include "lldb/Host/Mutex.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000053#include "lldb/Target/Process.h"
Sean Callananf35a96c2011-10-27 21:22:25 +000054#include "lldb/Target/TargetList.h"
Greg Clayton8f3b21d2010-09-07 20:11:56 +000055
Stephen Wilson7f513ba2011-02-24 19:15:09 +000056#include "llvm/Support/Host.h"
Greg Claytone4b9c1f2011-03-08 22:40:15 +000057#include "llvm/Support/MachO.h"
Daniel Malea21e32a62013-01-04 23:35:13 +000058#include "llvm/ADT/Twine.h"
Stephen Wilson7f513ba2011-02-24 19:15:09 +000059
Greg Clayton24bc5d92011-03-30 18:16:51 +000060
Greg Clayton8f3b21d2010-09-07 20:11:56 +000061
Greg Clayton14ef59f2011-02-08 00:35:34 +000062
Greg Clayton8f3b21d2010-09-07 20:11:56 +000063
64using namespace lldb;
65using namespace lldb_private;
66
Greg Clayton1c4642c2011-11-16 05:37:56 +000067
Greg Claytonc518fe72011-11-17 19:41:57 +000068#if !defined (__APPLE__)
Greg Clayton8f3b21d2010-09-07 20:11:56 +000069struct MonitorInfo
70{
71 lldb::pid_t pid; // The process ID to monitor
72 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
73 void *callback_baton; // The callback baton for the callback function
74 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
75};
76
77static void *
78MonitorChildProcessThreadFunction (void *arg);
79
80lldb::thread_t
81Host::StartMonitoringChildProcess
82(
83 Host::MonitorChildProcessCallback callback,
84 void *callback_baton,
85 lldb::pid_t pid,
86 bool monitor_signals
87)
88{
89 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Clayton1c4642c2011-11-16 05:37:56 +000090 MonitorInfo * info_ptr = new MonitorInfo();
Greg Clayton8f3b21d2010-09-07 20:11:56 +000091
Greg Clayton1c4642c2011-11-16 05:37:56 +000092 info_ptr->pid = pid;
93 info_ptr->callback = callback;
94 info_ptr->callback_baton = callback_baton;
95 info_ptr->monitor_signals = monitor_signals;
96
97 char thread_name[256];
Daniel Malea5f35a4b2012-11-29 21:49:15 +000098 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Clayton1c4642c2011-11-16 05:37:56 +000099 thread = ThreadCreate (thread_name,
100 MonitorChildProcessThreadFunction,
101 info_ptr,
102 NULL);
103
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000104 return thread;
105}
106
107//------------------------------------------------------------------
108// Scoped class that will disable thread canceling when it is
109// constructed, and exception safely restore the previous value it
110// when it goes out of scope.
111//------------------------------------------------------------------
112class ScopedPThreadCancelDisabler
113{
114public:
115 ScopedPThreadCancelDisabler()
116 {
117 // Disable the ability for this thread to be cancelled
118 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
119 if (err != 0)
120 m_old_state = -1;
121
122 }
123
124 ~ScopedPThreadCancelDisabler()
125 {
126 // Restore the ability for this thread to be cancelled to what it
127 // previously was.
128 if (m_old_state != -1)
129 ::pthread_setcancelstate (m_old_state, 0);
130 }
131private:
132 int m_old_state; // Save the old cancelability state.
133};
134
135static void *
136MonitorChildProcessThreadFunction (void *arg)
137{
Greg Claytone005f2c2010-11-06 01:53:30 +0000138 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000139 const char *function = __FUNCTION__;
140 if (log)
141 log->Printf ("%s (arg = %p) thread starting...", function, arg);
142
143 MonitorInfo *info = (MonitorInfo *)arg;
144
145 const Host::MonitorChildProcessCallback callback = info->callback;
146 void * const callback_baton = info->callback_baton;
147 const lldb::pid_t pid = info->pid;
148 const bool monitor_signals = info->monitor_signals;
149
150 delete info;
151
152 int status = -1;
Matt Kopecf1fda372013-01-08 16:30:18 +0000153 const int options = __WALL;
154
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000155 while (1)
156 {
Caroline Tice926060e2010-10-29 21:48:37 +0000157 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000158 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000159 log->Printf("%s ::wait_pid (pid = %" PRIu64 ", &status, options = %i)...", function, pid, options);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000160
161 // Wait for all child processes
162 ::pthread_testcancel ();
Matt Kopecf1fda372013-01-08 16:30:18 +0000163 // Get signals from all children with same process group of pid
164 const lldb::pid_t wait_pid = ::waitpid (-1*pid, &status, options);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000165 ::pthread_testcancel ();
166
167 if (wait_pid == -1)
168 {
169 if (errno == EINTR)
170 continue;
171 else
172 break;
173 }
Matt Kopecf1fda372013-01-08 16:30:18 +0000174 else if (wait_pid > 0)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000175 {
176 bool exited = false;
177 int signal = 0;
178 int exit_status = 0;
179 const char *status_cstr = NULL;
180 if (WIFSTOPPED(status))
181 {
182 signal = WSTOPSIG(status);
183 status_cstr = "STOPPED";
184 }
185 else if (WIFEXITED(status))
186 {
187 exit_status = WEXITSTATUS(status);
188 status_cstr = "EXITED";
Matt Kopecf1fda372013-01-08 16:30:18 +0000189 if (wait_pid == pid)
190 exited = true;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000191 }
192 else if (WIFSIGNALED(status))
193 {
194 signal = WTERMSIG(status);
195 status_cstr = "SIGNALED";
Matt Kopecf1fda372013-01-08 16:30:18 +0000196 if (wait_pid == pid) {
197 exited = true;
198 exit_status = -1;
199 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000200 }
201 else
202 {
Johnny Chen2bc9eb32011-07-19 19:48:13 +0000203 status_cstr = "(\?\?\?)";
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000204 }
205
206 // Scope for pthread_cancel_disabler
207 {
208 ScopedPThreadCancelDisabler pthread_cancel_disabler;
209
Caroline Tice926060e2010-10-29 21:48:37 +0000210 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000211 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000212 log->Printf ("%s ::waitpid (pid = %" PRIu64 ", &status, options = %i) => pid = %" PRIu64 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000213 function,
214 wait_pid,
215 options,
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000216 pid,
217 status,
218 status_cstr,
219 signal,
220 exit_status);
221
222 if (exited || (signal != 0 && monitor_signals))
223 {
Greg Clayton1c4642c2011-11-16 05:37:56 +0000224 bool callback_return = false;
225 if (callback)
Matt Kopecf1fda372013-01-08 16:30:18 +0000226 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000227
228 // If our process exited, then this thread should exit
229 if (exited)
230 break;
231 // If the callback returns true, it means this process should
232 // exit
233 if (callback_return)
234 break;
235 }
236 }
237 }
238 }
239
Caroline Tice926060e2010-10-29 21:48:37 +0000240 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000241 if (log)
242 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
243
244 return NULL;
245}
246
Greg Claytondf6dc882012-01-05 03:57:59 +0000247
248void
249Host::SystemLog (SystemLogType type, const char *format, va_list args)
250{
251 vfprintf (stderr, format, args);
252}
253
Greg Clayton1c4642c2011-11-16 05:37:56 +0000254#endif // #if !defined (__APPLE__)
255
Greg Claytondf6dc882012-01-05 03:57:59 +0000256void
257Host::SystemLog (SystemLogType type, const char *format, ...)
258{
259 va_list args;
260 va_start (args, format);
261 SystemLog (type, format, args);
262 va_end (args);
263}
264
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000265size_t
266Host::GetPageSize()
267{
268 return ::getpagesize();
269}
270
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000271const ArchSpec &
Greg Clayton395fc332011-02-15 21:59:32 +0000272Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000273{
Greg Clayton395fc332011-02-15 21:59:32 +0000274 static bool g_supports_32 = false;
275 static bool g_supports_64 = false;
276 static ArchSpec g_host_arch_32;
277 static ArchSpec g_host_arch_64;
278
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000279#if defined (__APPLE__)
Greg Clayton395fc332011-02-15 21:59:32 +0000280
281 // Apple is different in that it can support both 32 and 64 bit executables
282 // in the same operating system running concurrently. Here we detect the
283 // correct host architectures for both 32 and 64 bit including if 64 bit
284 // executables are supported on the system.
285
286 if (g_supports_32 == false && g_supports_64 == false)
287 {
288 // All apple systems support 32 bit execution.
289 g_supports_32 = true;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000290 uint32_t cputype, cpusubtype;
Greg Clayton395fc332011-02-15 21:59:32 +0000291 uint32_t is_64_bit_capable = false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000292 size_t len = sizeof(cputype);
Greg Clayton395fc332011-02-15 21:59:32 +0000293 ArchSpec host_arch;
294 // These will tell us about the kernel architecture, which even on a 64
295 // bit machine can be 32 bit...
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000296 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
297 {
Greg Clayton395fc332011-02-15 21:59:32 +0000298 len = sizeof (cpusubtype);
299 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
300 cpusubtype = CPU_TYPE_ANY;
301
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000302 len = sizeof (is_64_bit_capable);
303 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
304 {
305 if (is_64_bit_capable)
Greg Clayton395fc332011-02-15 21:59:32 +0000306 g_supports_64 = true;
307 }
308
309 if (is_64_bit_capable)
310 {
Greg Clayton75c703d2011-02-16 04:46:07 +0000311#if defined (__i386__) || defined (__x86_64__)
312 if (cpusubtype == CPU_SUBTYPE_486)
313 cpusubtype = CPU_SUBTYPE_I386_ALL;
314#endif
Greg Clayton395fc332011-02-15 21:59:32 +0000315 if (cputype & CPU_ARCH_ABI64)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000316 {
Greg Clayton395fc332011-02-15 21:59:32 +0000317 // We have a 64 bit kernel on a 64 bit system
Greg Claytonb3448432011-03-24 21:19:54 +0000318 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
319 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton395fc332011-02-15 21:59:32 +0000320 }
321 else
322 {
323 // We have a 32 bit kernel on a 64 bit system
Greg Claytonb3448432011-03-24 21:19:54 +0000324 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000325 cputype |= CPU_ARCH_ABI64;
Greg Claytonb3448432011-03-24 21:19:54 +0000326 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000327 }
328 }
Greg Clayton395fc332011-02-15 21:59:32 +0000329 else
330 {
Greg Claytonb3448432011-03-24 21:19:54 +0000331 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton395fc332011-02-15 21:59:32 +0000332 g_host_arch_64.Clear();
333 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000334 }
Greg Clayton395fc332011-02-15 21:59:32 +0000335 }
336
337#else // #if defined (__APPLE__)
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000338
Greg Clayton395fc332011-02-15 21:59:32 +0000339 if (g_supports_32 == false && g_supports_64 == false)
340 {
Peter Collingbourneb47c9982011-11-05 01:35:31 +0000341 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton395fc332011-02-15 21:59:32 +0000342
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000343 g_host_arch_32.Clear();
344 g_host_arch_64.Clear();
Greg Clayton395fc332011-02-15 21:59:32 +0000345
Greg Clayton7971a032012-10-11 17:38:58 +0000346 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
347 // for the default triple. It's probably an artifact of config.guess.
348 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
349 triple.setVendorName("");
350
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000351 switch (triple.getArch())
352 {
353 default:
354 g_host_arch_32.SetTriple(triple);
355 g_supports_32 = true;
356 break;
Greg Clayton395fc332011-02-15 21:59:32 +0000357
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000358 case llvm::Triple::x86_64:
Greg Clayton1a450cd2012-09-07 17:49:29 +0000359 g_host_arch_64.SetTriple(triple);
360 g_supports_64 = true;
361 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
362 g_supports_32 = true;
363 break;
364
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000365 case llvm::Triple::sparcv9:
366 case llvm::Triple::ppc64:
Stephen Wilson7f513ba2011-02-24 19:15:09 +0000367 g_host_arch_64.SetTriple(triple);
368 g_supports_64 = true;
369 break;
370 }
Greg Clayton4fefe322011-02-17 02:05:38 +0000371
372 g_supports_32 = g_host_arch_32.IsValid();
373 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000374 }
Greg Clayton395fc332011-02-15 21:59:32 +0000375
376#endif // #else for #if defined (__APPLE__)
377
378 if (arch_kind == eSystemDefaultArchitecture32)
379 return g_host_arch_32;
380 else if (arch_kind == eSystemDefaultArchitecture64)
381 return g_host_arch_64;
382
383 if (g_supports_64)
384 return g_host_arch_64;
385
386 return g_host_arch_32;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000387}
388
389const ConstString &
390Host::GetVendorString()
391{
392 static ConstString g_vendor;
393 if (!g_vendor)
394 {
Greg Clayton5b0025f2012-05-12 00:01:21 +0000395 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
396 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
397 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000398 }
399 return g_vendor;
400}
401
402const ConstString &
403Host::GetOSString()
404{
405 static ConstString g_os_string;
406 if (!g_os_string)
407 {
Greg Clayton5b0025f2012-05-12 00:01:21 +0000408 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
409 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
410 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000411 }
412 return g_os_string;
413}
414
415const ConstString &
416Host::GetTargetTriple()
417{
418 static ConstString g_host_triple;
419 if (!(g_host_triple))
420 {
Greg Clayton5b0025f2012-05-12 00:01:21 +0000421 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
422 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000423 }
424 return g_host_triple;
425}
426
427lldb::pid_t
428Host::GetCurrentProcessID()
429{
430 return ::getpid();
431}
432
433lldb::tid_t
434Host::GetCurrentThreadID()
435{
436#if defined (__APPLE__)
Greg Claytone93725b2012-09-18 18:19:49 +0000437 // Calling "mach_port_deallocate()" bumps the reference count on the thread
438 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
439 // count.
440 thread_port_t thread_self = mach_thread_self();
441 mach_port_deallocate(mach_task_self(), thread_self);
442 return thread_self;
Johnny Chen4b663292011-08-02 20:52:42 +0000443#elif defined(__FreeBSD__)
444 return lldb::tid_t(pthread_getthreadid_np());
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000445#else
446 return lldb::tid_t(pthread_self());
447#endif
448}
449
Jim Ingham1831e782012-04-07 00:00:41 +0000450lldb::thread_t
451Host::GetCurrentThread ()
452{
453 return lldb::thread_t(pthread_self());
454}
455
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000456const char *
457Host::GetSignalAsCString (int signo)
458{
459 switch (signo)
460 {
461 case SIGHUP: return "SIGHUP"; // 1 hangup
462 case SIGINT: return "SIGINT"; // 2 interrupt
463 case SIGQUIT: return "SIGQUIT"; // 3 quit
464 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
465 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
466 case SIGABRT: return "SIGABRT"; // 6 abort()
Greg Clayton193cc832011-11-04 03:42:38 +0000467#if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE))
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000468 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer06c306c2011-11-04 16:06:40 +0000469#endif
470#if !defined(_POSIX_C_SOURCE)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000471 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer06c306c2011-11-04 16:06:40 +0000472#endif
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000473 case SIGFPE: return "SIGFPE"; // 8 floating point exception
474 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
475 case SIGBUS: return "SIGBUS"; // 10 bus error
476 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
477 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
478 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
479 case SIGALRM: return "SIGALRM"; // 14 alarm clock
480 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
481 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
482 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
483 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
484 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
485 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
486 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
487 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
488#if !defined(_POSIX_C_SOURCE)
489 case SIGIO: return "SIGIO"; // 23 input/output possible signal
490#endif
491 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
492 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
493 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
494 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
495#if !defined(_POSIX_C_SOURCE)
496 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
497 case SIGINFO: return "SIGINFO"; // 29 information request
498#endif
499 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
500 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
501 default:
502 break;
503 }
504 return NULL;
505}
506
507void
508Host::WillTerminate ()
509{
510}
511
Johnny Chen4b663292011-08-02 20:52:42 +0000512#if !defined (__APPLE__) && !defined (__FreeBSD__) // see macosx/Host.mm
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000513void
514Host::ThreadCreated (const char *thread_name)
515{
516}
Greg Claytonb749a262010-12-03 06:02:24 +0000517
Peter Collingbourne5f0559d2011-08-05 00:35:43 +0000518void
Greg Claytonb749a262010-12-03 06:02:24 +0000519Host::Backtrace (Stream &strm, uint32_t max_frames)
520{
Greg Clayton52fd9842011-02-02 02:24:04 +0000521 // TODO: Is there a way to backtrace the current process on linux? Other systems?
Greg Claytonb749a262010-12-03 06:02:24 +0000522}
523
Greg Clayton638351a2010-12-04 00:10:17 +0000524size_t
525Host::GetEnvironment (StringList &env)
526{
Greg Clayton52fd9842011-02-02 02:24:04 +0000527 // TODO: Is there a way to the host environment for this process on linux? Other systems?
Greg Clayton638351a2010-12-04 00:10:17 +0000528 return 0;
529}
530
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000531#endif
532
533struct HostThreadCreateInfo
534{
535 std::string thread_name;
536 thread_func_t thread_fptr;
537 thread_arg_t thread_arg;
538
539 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
540 thread_name (name ? name : ""),
541 thread_fptr (fptr),
542 thread_arg (arg)
543 {
544 }
545};
546
547static thread_result_t
548ThreadCreateTrampoline (thread_arg_t arg)
549{
550 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
551 Host::ThreadCreated (info->thread_name.c_str());
552 thread_func_t thread_fptr = info->thread_fptr;
553 thread_arg_t thread_arg = info->thread_arg;
554
Greg Claytone005f2c2010-11-06 01:53:30 +0000555 LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000556 if (log)
557 log->Printf("thread created");
558
559 delete info;
560 return thread_fptr (thread_arg);
561}
562
563lldb::thread_t
564Host::ThreadCreate
565(
566 const char *thread_name,
567 thread_func_t thread_fptr,
568 thread_arg_t thread_arg,
569 Error *error
570)
571{
572 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
573
574 // Host::ThreadCreateTrampoline will delete this pointer for us.
575 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
576
577 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
578 if (err == 0)
579 {
580 if (error)
581 error->Clear();
582 return thread;
583 }
584
585 if (error)
586 error->SetError (err, eErrorTypePOSIX);
587
588 return LLDB_INVALID_HOST_THREAD;
589}
590
591bool
592Host::ThreadCancel (lldb::thread_t thread, Error *error)
593{
594 int err = ::pthread_cancel (thread);
595 if (error)
596 error->SetError(err, eErrorTypePOSIX);
597 return err == 0;
598}
599
600bool
601Host::ThreadDetach (lldb::thread_t thread, Error *error)
602{
603 int err = ::pthread_detach (thread);
604 if (error)
605 error->SetError(err, eErrorTypePOSIX);
606 return err == 0;
607}
608
609bool
610Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
611{
612 int err = ::pthread_join (thread, thread_result_ptr);
613 if (error)
614 error->SetError(err, eErrorTypePOSIX);
615 return err == 0;
616}
617
Jim Ingham35dd4962012-05-04 19:24:49 +0000618// rdar://problem/8153284
619// Fixed a crasher where during shutdown, loggings attempted to access the
620// thread name but the static map instance had already been destructed.
621// So we are using a ThreadSafeSTLMap POINTER, initializing it with a
622// pthread_once action. That map will get leaked.
623//
624// Another approach is to introduce a static guard object which monitors its
625// own destruction and raises a flag, but this incurs more overhead.
626
627static pthread_once_t g_thread_map_once = PTHREAD_ONCE_INIT;
628static ThreadSafeSTLMap<uint64_t, std::string> *g_thread_names_map_ptr;
629
630static void
631InitThreadNamesMap()
632{
633 g_thread_names_map_ptr = new ThreadSafeSTLMap<uint64_t, std::string>();
634}
635
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000636//------------------------------------------------------------------
637// Control access to a static file thread name map using a single
638// static function to avoid a static constructor.
639//------------------------------------------------------------------
640static const char *
641ThreadNameAccessor (bool get, lldb::pid_t pid, lldb::tid_t tid, const char *name)
642{
Jim Ingham35dd4962012-05-04 19:24:49 +0000643 int success = ::pthread_once (&g_thread_map_once, InitThreadNamesMap);
644 if (success != 0)
645 return NULL;
646
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000647 uint64_t pid_tid = ((uint64_t)pid << 32) | (uint64_t)tid;
648
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000649 if (get)
650 {
651 // See if the thread name exists in our thread name pool
Jim Ingham35dd4962012-05-04 19:24:49 +0000652 std::string value;
653 bool found_it = g_thread_names_map_ptr->GetValueForKey (pid_tid, value);
654 if (found_it)
655 return value.c_str();
656 else
657 return NULL;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000658 }
Jim Ingham35dd4962012-05-04 19:24:49 +0000659 else if (name)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000660 {
661 // Set the thread name
Jim Ingham35dd4962012-05-04 19:24:49 +0000662 g_thread_names_map_ptr->SetValueForKey (pid_tid, std::string(name));
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000663 }
664 return NULL;
665}
666
667const char *
668Host::GetThreadName (lldb::pid_t pid, lldb::tid_t tid)
669{
670 const char *name = ThreadNameAccessor (true, pid, tid, NULL);
671 if (name == NULL)
672 {
673#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
674 // We currently can only get the name of a thread in the current process.
675 if (pid == Host::GetCurrentProcessID())
676 {
677 char pthread_name[1024];
678 if (::pthread_getname_np (::pthread_from_mach_thread_np (tid), pthread_name, sizeof(pthread_name)) == 0)
679 {
680 if (pthread_name[0])
681 {
682 // Set the thread in our string pool
683 ThreadNameAccessor (false, pid, tid, pthread_name);
684 // Get our copy of the thread name string
685 name = ThreadNameAccessor (true, pid, tid, NULL);
686 }
687 }
Greg Clayton49ce6822010-10-31 03:01:06 +0000688
689 if (name == NULL)
690 {
691 dispatch_queue_t current_queue = ::dispatch_get_current_queue ();
692 if (current_queue != NULL)
693 name = dispatch_queue_get_label (current_queue);
694 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000695 }
696#endif
697 }
698 return name;
699}
700
701void
702Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
703{
704 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
705 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
706 if (pid == LLDB_INVALID_PROCESS_ID)
707 pid = curr_pid;
708
709 if (tid == LLDB_INVALID_THREAD_ID)
710 tid = curr_tid;
711
712#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
713 // Set the pthread name if possible
714 if (pid == curr_pid && tid == curr_tid)
715 {
716 ::pthread_setname_np (name);
717 }
718#endif
719 ThreadNameAccessor (false, pid, tid, name);
720}
721
722FileSpec
723Host::GetProgramFileSpec ()
724{
725 static FileSpec g_program_filespec;
726 if (!g_program_filespec)
727 {
728#if defined (__APPLE__)
729 char program_fullpath[PATH_MAX];
730 // If DST is NULL, then return the number of bytes needed.
731 uint32_t len = sizeof(program_fullpath);
732 int err = _NSGetExecutablePath (program_fullpath, &len);
733 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000734 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000735 else if (err == -1)
736 {
737 char *large_program_fullpath = (char *)::malloc (len + 1);
738
739 err = _NSGetExecutablePath (large_program_fullpath, &len);
740 if (err == 0)
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000741 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000742
743 ::free (large_program_fullpath);
744 }
745#elif defined (__linux__)
746 char exe_path[PATH_MAX];
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000747 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
748 if (len > 0) {
749 exe_path[len] = 0;
Greg Clayton20fbf8d2011-01-13 01:23:43 +0000750 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsonf302a9e2011-01-12 04:21:21 +0000751 }
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000752#elif defined (__FreeBSD__)
753 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
754 size_t exe_path_size;
755 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
756 {
Greg Clayton366795e2011-01-13 01:27:55 +0000757 char *exe_path = new char[exe_path_size];
758 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
759 g_program_filespec.SetFile(exe_path, false);
760 delete[] exe_path;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000761 }
762#endif
763 }
764 return g_program_filespec;
765}
766
767FileSpec
768Host::GetModuleFileSpecForHostAddress (const void *host_addr)
769{
770 FileSpec module_filespec;
771 Dl_info info;
772 if (::dladdr (host_addr, &info))
773 {
774 if (info.dli_fname)
Greg Clayton537a7a82010-10-20 20:54:39 +0000775 module_filespec.SetFile(info.dli_fname, true);
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000776 }
777 return module_filespec;
778}
779
780#if !defined (__APPLE__) // see Host.mm
Greg Clayton9ce95382012-02-13 23:10:39 +0000781
782bool
783Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
784{
785 bundle.Clear();
786 return false;
787}
788
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000789bool
Greg Clayton24b48ff2010-10-17 22:03:32 +0000790Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000791{
Greg Clayton24b48ff2010-10-17 22:03:32 +0000792 return false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +0000793}
794#endif
795
Greg Clayton14ef59f2011-02-08 00:35:34 +0000796// Opaque info that tracks a dynamic library that was loaded
797struct DynamicLibraryInfo
Greg Clayton52fd9842011-02-02 02:24:04 +0000798{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000799 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
800 file_spec (fs),
801 open_options (o),
802 handle (h)
803 {
804 }
805
806 const FileSpec file_spec;
807 uint32_t open_options;
808 void * handle;
809};
810
811void *
812Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
813{
Greg Clayton52fd9842011-02-02 02:24:04 +0000814 char path[PATH_MAX];
815 if (file_spec.GetPath(path, sizeof(path)))
816 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000817 int mode = 0;
818
819 if (options & eDynamicLibraryOpenOptionLazy)
820 mode |= RTLD_LAZY;
Greg Claytonbf467b02011-02-08 05:24:57 +0000821 else
822 mode |= RTLD_NOW;
823
Greg Clayton14ef59f2011-02-08 00:35:34 +0000824
825 if (options & eDynamicLibraryOpenOptionLocal)
826 mode |= RTLD_LOCAL;
827 else
828 mode |= RTLD_GLOBAL;
829
830#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
831 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
832 mode |= RTLD_FIRST;
Greg Clayton0f577c22011-02-07 17:43:47 +0000833#endif
Greg Clayton14ef59f2011-02-08 00:35:34 +0000834
835 void * opaque = ::dlopen (path, mode);
836
837 if (opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000838 {
839 error.Clear();
Greg Clayton14ef59f2011-02-08 00:35:34 +0000840 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton52fd9842011-02-02 02:24:04 +0000841 }
842 else
843 {
844 error.SetErrorString(::dlerror());
845 }
846 }
847 else
848 {
849 error.SetErrorString("failed to extract path");
850 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000851 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000852}
853
854Error
Greg Clayton14ef59f2011-02-08 00:35:34 +0000855Host::DynamicLibraryClose (void *opaque)
Greg Clayton52fd9842011-02-02 02:24:04 +0000856{
857 Error error;
Greg Clayton14ef59f2011-02-08 00:35:34 +0000858 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000859 {
860 error.SetErrorString ("invalid dynamic library handle");
861 }
Greg Clayton14ef59f2011-02-08 00:35:34 +0000862 else
Greg Clayton52fd9842011-02-02 02:24:04 +0000863 {
Greg Clayton14ef59f2011-02-08 00:35:34 +0000864 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
865 if (::dlclose (dylib_info->handle) != 0)
866 {
867 error.SetErrorString(::dlerror());
868 }
869
870 dylib_info->open_options = 0;
871 dylib_info->handle = 0;
872 delete dylib_info;
Greg Clayton52fd9842011-02-02 02:24:04 +0000873 }
874 return error;
875}
876
877void *
Greg Clayton14ef59f2011-02-08 00:35:34 +0000878Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton52fd9842011-02-02 02:24:04 +0000879{
Greg Clayton14ef59f2011-02-08 00:35:34 +0000880 if (opaque == NULL)
Greg Clayton52fd9842011-02-02 02:24:04 +0000881 {
882 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton52fd9842011-02-02 02:24:04 +0000883 }
Greg Clayton52fd9842011-02-02 02:24:04 +0000884 else
Greg Clayton14ef59f2011-02-08 00:35:34 +0000885 {
886 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
887
888 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
889 if (symbol_addr)
890 {
891#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
892 // This host doesn't support limiting searches to this shared library
893 // so we need to verify that the match came from this shared library
894 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonbf467b02011-02-08 05:24:57 +0000895 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton14ef59f2011-02-08 00:35:34 +0000896 {
897 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
898 if (match_dylib_spec != dylib_info->file_spec)
899 {
900 char dylib_path[PATH_MAX];
901 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
902 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
903 else
904 error.SetErrorString ("symbol not found");
905 return NULL;
906 }
907 }
908#endif
909 error.Clear();
910 return symbol_addr;
911 }
912 else
913 {
914 error.SetErrorString(::dlerror());
915 }
916 }
917 return NULL;
Greg Clayton52fd9842011-02-02 02:24:04 +0000918}
Greg Clayton24b48ff2010-10-17 22:03:32 +0000919
920bool
921Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
922{
Greg Clayton5d187e52011-01-08 20:28:42 +0000923 // To get paths related to LLDB we get the path to the executable that
Greg Clayton24b48ff2010-10-17 22:03:32 +0000924 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
925 // on linux this is assumed to be the "lldb" main executable. If LLDB on
926 // linux is actually in a shared library (lldb.so??) then this function will
927 // need to be modified to "do the right thing".
928
929 switch (path_type)
930 {
931 case ePathTypeLLDBShlibDir:
932 {
933 static ConstString g_lldb_so_dir;
934 if (!g_lldb_so_dir)
935 {
936 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
937 g_lldb_so_dir = lldb_file_spec.GetDirectory();
938 }
939 file_spec.GetDirectory() = g_lldb_so_dir;
940 return file_spec.GetDirectory();
941 }
942 break;
943
944 case ePathTypeSupportExecutableDir:
945 {
946 static ConstString g_lldb_support_exe_dir;
947 if (!g_lldb_support_exe_dir)
948 {
949 FileSpec lldb_file_spec;
950 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
951 {
952 char raw_path[PATH_MAX];
953 char resolved_path[PATH_MAX];
954 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
955
956#if defined (__APPLE__)
957 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
958 if (framework_pos)
959 {
960 framework_pos += strlen("LLDB.framework");
Greg Clayton3e4238d2011-11-04 03:34:56 +0000961#if !defined (__arm__)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000962 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Clayton3e4238d2011-11-04 03:34:56 +0000963#endif
Greg Clayton24b48ff2010-10-17 22:03:32 +0000964 }
965#endif
966 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
967 g_lldb_support_exe_dir.SetCString(resolved_path);
968 }
969 }
970 file_spec.GetDirectory() = g_lldb_support_exe_dir;
971 return file_spec.GetDirectory();
972 }
973 break;
974
975 case ePathTypeHeaderDir:
976 {
977 static ConstString g_lldb_headers_dir;
978 if (!g_lldb_headers_dir)
979 {
980#if defined (__APPLE__)
981 FileSpec lldb_file_spec;
982 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
983 {
984 char raw_path[PATH_MAX];
985 char resolved_path[PATH_MAX];
986 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
987
988 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
989 if (framework_pos)
990 {
991 framework_pos += strlen("LLDB.framework");
992 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
993 }
994 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
995 g_lldb_headers_dir.SetCString(resolved_path);
996 }
997#else
Greg Clayton52fd9842011-02-02 02:24:04 +0000998 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Clayton24b48ff2010-10-17 22:03:32 +0000999 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1000#endif
1001 }
1002 file_spec.GetDirectory() = g_lldb_headers_dir;
1003 return file_spec.GetDirectory();
1004 }
1005 break;
1006
1007 case ePathTypePythonDir:
1008 {
Greg Clayton24b48ff2010-10-17 22:03:32 +00001009 static ConstString g_lldb_python_dir;
1010 if (!g_lldb_python_dir)
1011 {
1012 FileSpec lldb_file_spec;
1013 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1014 {
1015 char raw_path[PATH_MAX];
1016 char resolved_path[PATH_MAX];
1017 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1018
1019#if defined (__APPLE__)
1020 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1021 if (framework_pos)
1022 {
1023 framework_pos += strlen("LLDB.framework");
1024 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1025 }
Filipe Cabecinhasdf802722012-07-30 16:46:32 +00001026#else
Daniel Malea21e32a62013-01-04 23:35:13 +00001027 llvm::Twine python_version_dir;
1028 python_version_dir = "/python"
1029 + llvm::Twine(PY_MAJOR_VERSION)
1030 + "."
1031 + llvm::Twine(PY_MINOR_VERSION)
1032 + "/site-packages";
1033
Filipe Cabecinhas67aa5b62012-07-30 18:56:10 +00001034 // We may get our string truncated. Should we protect
1035 // this with an assert?
Daniel Malea21e32a62013-01-04 23:35:13 +00001036
1037 ::strncat(raw_path, python_version_dir.str().c_str(),
1038 sizeof(raw_path) - strlen(raw_path) - 1);
1039
Greg Clayton24b48ff2010-10-17 22:03:32 +00001040#endif
1041 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1042 g_lldb_python_dir.SetCString(resolved_path);
1043 }
1044 }
1045 file_spec.GetDirectory() = g_lldb_python_dir;
1046 return file_spec.GetDirectory();
1047 }
1048 break;
1049
Greg Clayton52fd9842011-02-02 02:24:04 +00001050 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1051 {
1052#if defined (__APPLE__)
1053 static ConstString g_lldb_system_plugin_dir;
Greg Clayton58e26e02011-03-24 04:28:38 +00001054 static bool g_lldb_system_plugin_dir_located = false;
1055 if (!g_lldb_system_plugin_dir_located)
Greg Clayton52fd9842011-02-02 02:24:04 +00001056 {
Greg Clayton58e26e02011-03-24 04:28:38 +00001057 g_lldb_system_plugin_dir_located = true;
Greg Clayton52fd9842011-02-02 02:24:04 +00001058 FileSpec lldb_file_spec;
1059 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1060 {
1061 char raw_path[PATH_MAX];
1062 char resolved_path[PATH_MAX];
1063 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1064
1065 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1066 if (framework_pos)
1067 {
1068 framework_pos += strlen("LLDB.framework");
1069 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton58e26e02011-03-24 04:28:38 +00001070 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1071 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton52fd9842011-02-02 02:24:04 +00001072 }
Greg Clayton58e26e02011-03-24 04:28:38 +00001073 return false;
Greg Clayton52fd9842011-02-02 02:24:04 +00001074 }
1075 }
Greg Clayton58e26e02011-03-24 04:28:38 +00001076
1077 if (g_lldb_system_plugin_dir)
1078 {
1079 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1080 return true;
1081 }
Greg Clayton52fd9842011-02-02 02:24:04 +00001082#endif
1083 // TODO: where would system LLDB plug-ins be located on linux? Other systems?
1084 return false;
1085 }
1086 break;
1087
1088 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1089 {
1090#if defined (__APPLE__)
1091 static ConstString g_lldb_user_plugin_dir;
1092 if (!g_lldb_user_plugin_dir)
1093 {
1094 char user_plugin_path[PATH_MAX];
1095 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1096 user_plugin_path,
1097 sizeof(user_plugin_path)))
1098 {
1099 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1100 }
1101 }
1102 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1103 return file_spec.GetDirectory();
1104#endif
1105 // TODO: where would user LLDB plug-ins be located on linux? Other systems?
1106 return false;
1107 }
Greg Clayton24b48ff2010-10-17 22:03:32 +00001108 }
1109
1110 return false;
1111}
1112
Greg Clayton58e26e02011-03-24 04:28:38 +00001113
1114bool
1115Host::GetHostname (std::string &s)
1116{
1117 char hostname[PATH_MAX];
1118 hostname[sizeof(hostname) - 1] = '\0';
1119 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1120 {
1121 struct hostent* h = ::gethostbyname (hostname);
1122 if (h)
1123 s.assign (h->h_name);
1124 else
1125 s.assign (hostname);
1126 return true;
1127 }
1128 return false;
1129}
1130
Greg Clayton24bc5d92011-03-30 18:16:51 +00001131const char *
1132Host::GetUserName (uint32_t uid, std::string &user_name)
1133{
1134 struct passwd user_info;
1135 struct passwd *user_info_ptr = &user_info;
1136 char user_buffer[PATH_MAX];
1137 size_t user_buffer_size = sizeof(user_buffer);
1138 if (::getpwuid_r (uid,
1139 &user_info,
1140 user_buffer,
1141 user_buffer_size,
1142 &user_info_ptr) == 0)
1143 {
1144 if (user_info_ptr)
1145 {
1146 user_name.assign (user_info_ptr->pw_name);
1147 return user_name.c_str();
1148 }
1149 }
1150 user_name.clear();
1151 return NULL;
1152}
1153
1154const char *
1155Host::GetGroupName (uint32_t gid, std::string &group_name)
1156{
1157 char group_buffer[PATH_MAX];
1158 size_t group_buffer_size = sizeof(group_buffer);
1159 struct group group_info;
1160 struct group *group_info_ptr = &group_info;
1161 // Try the threadsafe version first
1162 if (::getgrgid_r (gid,
1163 &group_info,
1164 group_buffer,
1165 group_buffer_size,
1166 &group_info_ptr) == 0)
1167 {
1168 if (group_info_ptr)
1169 {
1170 group_name.assign (group_info_ptr->gr_name);
1171 return group_name.c_str();
1172 }
1173 }
1174 else
1175 {
1176 // The threadsafe version isn't currently working
1177 // for me on darwin, but the non-threadsafe version
1178 // is, so I am calling it below.
1179 group_info_ptr = ::getgrgid (gid);
1180 if (group_info_ptr)
1181 {
1182 group_name.assign (group_info_ptr->gr_name);
1183 return group_name.c_str();
1184 }
1185 }
1186 group_name.clear();
1187 return NULL;
1188}
1189
Johnny Chen4b663292011-08-02 20:52:42 +00001190#if !defined (__APPLE__) && !defined (__FreeBSD__) // see macosx/Host.mm
Greg Clayton58e26e02011-03-24 04:28:38 +00001191bool
1192Host::GetOSBuildString (std::string &s)
1193{
1194 s.clear();
1195 return false;
1196}
1197
1198bool
1199Host::GetOSKernelDescription (std::string &s)
1200{
1201 s.clear();
1202 return false;
1203}
Johnny Chen4b663292011-08-02 20:52:42 +00001204#endif
Greg Clayton58e26e02011-03-24 04:28:38 +00001205
Han Ming Ongd1040dd2012-02-25 01:07:38 +00001206uint32_t
1207Host::GetUserID ()
1208{
1209 return getuid();
1210}
1211
1212uint32_t
1213Host::GetGroupID ()
1214{
1215 return getgid();
1216}
1217
1218uint32_t
1219Host::GetEffectiveUserID ()
1220{
1221 return geteuid();
1222}
1223
1224uint32_t
1225Host::GetEffectiveGroupID ()
1226{
1227 return getegid();
1228}
1229
1230#if !defined (__APPLE__)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001231uint32_t
Greg Claytonb72d0f02011-04-12 05:54:46 +00001232Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001233{
1234 process_infos.Clear();
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001235 return process_infos.GetSize();
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001236}
Johnny Chen4b663292011-08-02 20:52:42 +00001237#endif
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001238
Johnny Chen4b663292011-08-02 20:52:42 +00001239#if !defined (__APPLE__) && !defined (__FreeBSD__)
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001240bool
Greg Claytonb72d0f02011-04-12 05:54:46 +00001241Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001242{
Greg Claytone4b9c1f2011-03-08 22:40:15 +00001243 process_info.Clear();
1244 return false;
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001245}
Johnny Chen4b663292011-08-02 20:52:42 +00001246#endif
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001247
Sean Callananf35a96c2011-10-27 21:22:25 +00001248lldb::TargetSP
1249Host::GetDummyTarget (lldb_private::Debugger &debugger)
1250{
Filipe Cabecinhasf7d782b2012-05-19 09:59:08 +00001251 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasf42d3f62012-05-17 15:48:02 +00001252
Filipe Cabecinhasf7d782b2012-05-19 09:59:08 +00001253 // FIXME: Maybe the dummy target should be per-Debugger
1254 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1255 {
1256 ArchSpec arch(Target::GetDefaultArchitecture());
1257 if (!arch.IsValid())
1258 arch = Host::GetArchitecture ();
1259 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytoned0a0fb2012-10-18 16:33:33 +00001260 NULL,
Filipe Cabecinhasf7d782b2012-05-19 09:59:08 +00001261 arch.GetTriple().getTriple().c_str(),
1262 false,
1263 NULL,
1264 g_dummy_target_sp);
1265 }
Filipe Cabecinhasf42d3f62012-05-17 15:48:02 +00001266
Filipe Cabecinhasf7d782b2012-05-19 09:59:08 +00001267 return g_dummy_target_sp;
Sean Callananf35a96c2011-10-27 21:22:25 +00001268}
1269
Greg Clayton97471182012-04-14 01:42:46 +00001270struct ShellInfo
1271{
1272 ShellInfo () :
1273 process_reaped (false),
1274 can_delete (false),
1275 pid (LLDB_INVALID_PROCESS_ID),
1276 signo(-1),
1277 status(-1)
1278 {
1279 }
1280
1281 lldb_private::Predicate<bool> process_reaped;
1282 lldb_private::Predicate<bool> can_delete;
1283 lldb::pid_t pid;
1284 int signo;
1285 int status;
1286};
1287
1288static bool
1289MonitorShellCommand (void *callback_baton,
1290 lldb::pid_t pid,
1291 bool exited, // True if the process did exit
1292 int signo, // Zero for no signal
1293 int status) // Exit value of process if signal is zero
1294{
1295 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1296 shell_info->pid = pid;
1297 shell_info->signo = signo;
1298 shell_info->status = status;
1299 // Let the thread running Host::RunShellCommand() know that the process
1300 // exited and that ShellInfo has been filled in by broadcasting to it
1301 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1302 // Now wait for a handshake back from that thread running Host::RunShellCommand
1303 // so we know that we can delete shell_info_ptr
1304 shell_info->can_delete.WaitForValueEqualTo(true);
1305 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1306 usleep(1000);
1307 // Now delete the shell info that was passed into this function
1308 delete shell_info;
1309 return true;
1310}
1311
1312Error
1313Host::RunShellCommand (const char *command,
1314 const char *working_dir,
1315 int *status_ptr,
1316 int *signo_ptr,
1317 std::string *command_output_ptr,
Greg Claytonb924eb62012-09-27 03:13:55 +00001318 uint32_t timeout_sec,
1319 const char *shell)
Greg Clayton97471182012-04-14 01:42:46 +00001320{
1321 Error error;
1322 ProcessLaunchInfo launch_info;
Greg Claytonb924eb62012-09-27 03:13:55 +00001323 if (shell && shell[0])
1324 {
1325 // Run the command in a shell
1326 launch_info.SetShell(shell);
1327 launch_info.GetArguments().AppendArgument(command);
1328 const bool localhost = true;
1329 const bool will_debug = false;
1330 const bool first_arg_is_full_shell_command = true;
1331 launch_info.ConvertArgumentsForLaunchingInShell (error,
1332 localhost,
1333 will_debug,
1334 first_arg_is_full_shell_command);
1335 }
1336 else
1337 {
1338 // No shell, just run it
1339 Args args (command);
1340 const bool first_arg_is_executable = true;
Greg Clayton0c8446c2012-10-17 22:57:12 +00001341 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonb924eb62012-09-27 03:13:55 +00001342 }
Greg Clayton97471182012-04-14 01:42:46 +00001343
1344 if (working_dir)
1345 launch_info.SetWorkingDirectory(working_dir);
1346 char output_file_path_buffer[L_tmpnam];
1347 const char *output_file_path = NULL;
1348 if (command_output_ptr)
1349 {
1350 // Create a temporary file to get the stdout/stderr and redirect the
1351 // output of the command into this file. We will later read this file
1352 // if all goes well and fill the data into "command_output_ptr"
1353 output_file_path = ::tmpnam(output_file_path_buffer);
1354 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1355 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonb924eb62012-09-27 03:13:55 +00001356 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Clayton97471182012-04-14 01:42:46 +00001357 }
1358 else
1359 {
1360 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1361 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1362 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1363 }
1364
1365 // The process monitor callback will delete the 'shell_info_ptr' below...
1366 std::auto_ptr<ShellInfo> shell_info_ap (new ShellInfo());
1367
1368 const bool monitor_signals = false;
1369 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1370
1371 error = LaunchProcess (launch_info);
1372 const lldb::pid_t pid = launch_info.GetProcessID();
1373 if (pid != LLDB_INVALID_PROCESS_ID)
1374 {
1375 // The process successfully launched, so we can defer ownership of
1376 // "shell_info" to the MonitorShellCommand callback function that will
1377 // get called when the process dies. We release the std::auto_ptr as it
1378 // doesn't need to delete the ShellInfo anymore.
1379 ShellInfo *shell_info = shell_info_ap.release();
1380 TimeValue timeout_time(TimeValue::Now());
1381 timeout_time.OffsetWithSeconds(timeout_sec);
1382 bool timed_out = false;
1383 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1384 if (timed_out)
1385 {
1386 error.SetErrorString("timed out waiting for shell command to complete");
1387
1388 // Kill the process since it didn't complete withint the timeout specified
1389 ::kill (pid, SIGKILL);
1390 // Wait for the monitor callback to get the message
1391 timeout_time = TimeValue::Now();
1392 timeout_time.OffsetWithSeconds(1);
1393 timed_out = false;
1394 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1395 }
1396 else
1397 {
1398 if (status_ptr)
1399 *status_ptr = shell_info->status;
1400
1401 if (signo_ptr)
1402 *signo_ptr = shell_info->signo;
1403
1404 if (command_output_ptr)
1405 {
1406 command_output_ptr->clear();
1407 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1408 uint64_t file_size = file_spec.GetByteSize();
1409 if (file_size > 0)
1410 {
1411 if (file_size > command_output_ptr->max_size())
1412 {
1413 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1414 }
1415 else
1416 {
1417 command_output_ptr->resize(file_size);
1418 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1419 }
1420 }
1421 }
1422 }
1423 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1424 }
1425 else
1426 {
1427 error.SetErrorString("failed to get process ID");
1428 }
1429
1430 if (output_file_path)
1431 ::unlink (output_file_path);
1432 // Handshake with the monitor thread, or just let it know in advance that
1433 // it can delete "shell_info" in case we timed out and were not able to kill
1434 // the process...
1435 return error;
1436}
1437
1438
Greg Clayton132c49a2013-02-17 20:46:30 +00001439uint32_t
1440Host::GetNumberCPUS ()
1441{
1442 static uint32_t g_num_cores = UINT32_MAX;
1443 if (g_num_cores == UINT32_MAX)
1444 {
1445#if defined(__APPLE__) or defined (__linux__)
1446
1447 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
1448
1449#elif defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
1450
1451 // Header file for this might need to be included at the top of this file
1452 SYSTEM_INFO system_info;
1453 ::GetSystemInfo (&system_info);
1454 g_num_cores = system_info.dwNumberOfProcessors;
1455
1456#else
1457
1458 // Assume POSIX support if a host specific case has not been supplied above
1459 g_num_cores = 0;
1460 int num_cores = 0;
1461 size_t num_cores_len = sizeof(num_cores);
1462 int mib[] = { CTL_HW, HW_AVAILCPU };
1463
1464 /* get the number of CPUs from the system */
1465 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1466 {
1467 g_num_cores = num_cores;
1468 }
1469 else
1470 {
1471 mib[1] = HW_NCPU;
1472 num_cores_len = sizeof(num_cores);
1473 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1474 {
1475 if (num_cores > 0)
1476 g_num_cores = num_cores;
1477 }
1478 }
1479#endif
1480 }
1481 return g_num_cores;
1482}
1483
1484
Greg Clayton97471182012-04-14 01:42:46 +00001485
Johnny Chen4b663292011-08-02 20:52:42 +00001486#if !defined (__APPLE__)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001487bool
Greg Claytonb73620c2010-12-18 01:54:34 +00001488Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001489{
1490 return false;
1491}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001492
Greg Claytone98ac252010-11-10 04:57:04 +00001493void
1494Host::SetCrashDescriptionWithFormat (const char *format, ...)
1495{
1496}
1497
1498void
1499Host::SetCrashDescription (const char *description)
1500{
1501}
Greg Clayton24b48ff2010-10-17 22:03:32 +00001502
1503lldb::pid_t
1504LaunchApplication (const FileSpec &app_file_spec)
1505{
1506 return LLDB_INVALID_PROCESS_ID;
1507}
1508
Greg Clayton8f3b21d2010-09-07 20:11:56 +00001509#endif