blob: efe97237d42819c95961d4270f729abaeca70aea [file] [log] [blame]
Greg Clayton2bddd342010-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 Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Greg Claytone3e3fee2013-02-17 20:46:30 +000012// C includes
Greg Claytone3e3fee2013-02-17 20:46:30 +000013#include <errno.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000014#include <limits.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#include <sys/types.h>
16#include <unistd.h>
17#ifdef _WIN32
18#include "lldb/Host/windows/windows.h"
19#include <winsock2.h>
20#include <WS2tcpip.h>
21#else
22#include <dlfcn.h>
23#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000024#include <netdb.h>
25#include <pwd.h>
Ed Mastef2b01622013-06-28 12:35:08 +000026#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000027#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000028
29#if defined (__APPLE__)
30
31#include <dispatch/dispatch.h>
32#include <libproc.h>
33#include <mach-o/dyld.h>
34#include <mach/mach_port.h>
35
Ed Maste8b006c62013-06-25 18:58:11 +000036#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000037
Ed Maste8b006c62013-06-25 18:58:11 +000038#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000039#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000040#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000041#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000042
Ed Maste8b006c62013-06-25 18:58:11 +000043#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000044#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000045#endif
46
Greg Clayton2bddd342010-09-07 20:11:56 +000047#include "lldb/Host/Host.h"
48#include "lldb/Core/ArchSpec.h"
49#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000050#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000051#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000052#include "lldb/Core/Log.h"
53#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000054#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000055#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000056#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000057#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000059#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000060#include "lldb/Target/TargetList.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000061
Daniel Maleafa7425d2013-08-06 21:40:08 +000062#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000063#include "llvm/Support/Host.h"
Greg Claytone996fd32011-03-08 22:40:15 +000064#include "llvm/Support/MachO.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000065#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000066
Greg Clayton32e0a752011-03-30 18:16:51 +000067
Greg Clayton2bddd342010-09-07 20:11:56 +000068
Greg Clayton45319462011-02-08 00:35:34 +000069
Greg Clayton2bddd342010-09-07 20:11:56 +000070
71using namespace lldb;
72using namespace lldb_private;
73
Greg Claytone4e45922011-11-16 05:37:56 +000074
Virgile Bellob2f1fb22013-08-23 12:44:05 +000075#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000076struct MonitorInfo
77{
78 lldb::pid_t pid; // The process ID to monitor
79 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
80 void *callback_baton; // The callback baton for the callback function
81 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
82};
83
Virgile Bellob2f1fb22013-08-23 12:44:05 +000084static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000085MonitorChildProcessThreadFunction (void *arg);
86
87lldb::thread_t
88Host::StartMonitoringChildProcess
89(
90 Host::MonitorChildProcessCallback callback,
91 void *callback_baton,
92 lldb::pid_t pid,
93 bool monitor_signals
94)
95{
96 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +000097 MonitorInfo * info_ptr = new MonitorInfo();
Greg Clayton2bddd342010-09-07 20:11:56 +000098
Greg Claytone4e45922011-11-16 05:37:56 +000099 info_ptr->pid = pid;
100 info_ptr->callback = callback;
101 info_ptr->callback_baton = callback_baton;
102 info_ptr->monitor_signals = monitor_signals;
103
104 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000105 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000106 thread = ThreadCreate (thread_name,
107 MonitorChildProcessThreadFunction,
108 info_ptr,
109 NULL);
110
Greg Clayton2bddd342010-09-07 20:11:56 +0000111 return thread;
112}
113
114//------------------------------------------------------------------
115// Scoped class that will disable thread canceling when it is
116// constructed, and exception safely restore the previous value it
117// when it goes out of scope.
118//------------------------------------------------------------------
119class ScopedPThreadCancelDisabler
120{
121public:
122 ScopedPThreadCancelDisabler()
123 {
124 // Disable the ability for this thread to be cancelled
125 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
126 if (err != 0)
127 m_old_state = -1;
128
129 }
130
131 ~ScopedPThreadCancelDisabler()
132 {
133 // Restore the ability for this thread to be cancelled to what it
134 // previously was.
135 if (m_old_state != -1)
136 ::pthread_setcancelstate (m_old_state, 0);
137 }
138private:
139 int m_old_state; // Save the old cancelability state.
140};
141
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000142static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000143MonitorChildProcessThreadFunction (void *arg)
144{
Greg Clayton5160ce52013-03-27 23:08:40 +0000145 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000146 const char *function = __FUNCTION__;
147 if (log)
148 log->Printf ("%s (arg = %p) thread starting...", function, arg);
149
150 MonitorInfo *info = (MonitorInfo *)arg;
151
152 const Host::MonitorChildProcessCallback callback = info->callback;
153 void * const callback_baton = info->callback_baton;
154 const lldb::pid_t pid = info->pid;
155 const bool monitor_signals = info->monitor_signals;
156
157 delete info;
158
159 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000160#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000161 #define __WALL 0
162#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000163 const int options = __WALL;
164
Greg Clayton2bddd342010-09-07 20:11:56 +0000165 while (1)
166 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000167 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000168 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000169 log->Printf("%s ::wait_pid (pid = %" PRIu64 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000170
171 // Wait for all child processes
172 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000173 // Get signals from all children with same process group of pid
174 const lldb::pid_t wait_pid = ::waitpid (-1*pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000175 ::pthread_testcancel ();
176
177 if (wait_pid == -1)
178 {
179 if (errno == EINTR)
180 continue;
181 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000182 {
183 if (log)
184 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000185 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000186 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000187 }
Matt Kopec650648f2013-01-08 16:30:18 +0000188 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000189 {
190 bool exited = false;
191 int signal = 0;
192 int exit_status = 0;
193 const char *status_cstr = NULL;
194 if (WIFSTOPPED(status))
195 {
196 signal = WSTOPSIG(status);
197 status_cstr = "STOPPED";
198 }
199 else if (WIFEXITED(status))
200 {
201 exit_status = WEXITSTATUS(status);
202 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000203 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000204 }
205 else if (WIFSIGNALED(status))
206 {
207 signal = WTERMSIG(status);
208 status_cstr = "SIGNALED";
Matt Kopec650648f2013-01-08 16:30:18 +0000209 if (wait_pid == pid) {
210 exited = true;
211 exit_status = -1;
212 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000213 }
214 else
215 {
Johnny Chen44805302011-07-19 19:48:13 +0000216 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000217 }
218
219 // Scope for pthread_cancel_disabler
220 {
221 ScopedPThreadCancelDisabler pthread_cancel_disabler;
222
Caroline Tice20ad3c42010-10-29 21:48:37 +0000223 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000224 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000225 log->Printf ("%s ::waitpid (pid = %" PRIu64 ", &status, options = %i) => pid = %" PRIu64 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Greg Clayton2bddd342010-09-07 20:11:56 +0000226 function,
227 wait_pid,
228 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000229 pid,
230 status,
231 status_cstr,
232 signal,
233 exit_status);
234
235 if (exited || (signal != 0 && monitor_signals))
236 {
Greg Claytone4e45922011-11-16 05:37:56 +0000237 bool callback_return = false;
238 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000239 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000240
241 // If our process exited, then this thread should exit
Andrew Kaylor93132f52013-05-28 23:04:25 +0000242 if (exited && wait_pid == pid)
243 {
244 if (log)
245 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000246 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000247 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000248 // If the callback returns true, it means this process should
249 // exit
250 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000251 {
252 if (log)
253 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000254 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000255 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000256 }
257 }
258 }
259 }
260
Caroline Tice20ad3c42010-10-29 21:48:37 +0000261 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000262 if (log)
263 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
264
265 return NULL;
266}
267
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000268#endif // #if !defined (__APPLE__) && !defined (_WIN32)
269
270#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000271
272void
273Host::SystemLog (SystemLogType type, const char *format, va_list args)
274{
275 vfprintf (stderr, format, args);
276}
277
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000278#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000279
Greg Claytone38a5ed2012-01-05 03:57:59 +0000280void
281Host::SystemLog (SystemLogType type, const char *format, ...)
282{
283 va_list args;
284 va_start (args, format);
285 SystemLog (type, format, args);
286 va_end (args);
287}
288
Greg Clayton2bddd342010-09-07 20:11:56 +0000289const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000290Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000291{
Greg Clayton514487e2011-02-15 21:59:32 +0000292 static bool g_supports_32 = false;
293 static bool g_supports_64 = false;
294 static ArchSpec g_host_arch_32;
295 static ArchSpec g_host_arch_64;
296
Greg Clayton2bddd342010-09-07 20:11:56 +0000297#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000298
299 // Apple is different in that it can support both 32 and 64 bit executables
300 // in the same operating system running concurrently. Here we detect the
301 // correct host architectures for both 32 and 64 bit including if 64 bit
302 // executables are supported on the system.
303
304 if (g_supports_32 == false && g_supports_64 == false)
305 {
306 // All apple systems support 32 bit execution.
307 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000308 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000309 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000310 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000311 ArchSpec host_arch;
312 // These will tell us about the kernel architecture, which even on a 64
313 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000314 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
315 {
Greg Clayton514487e2011-02-15 21:59:32 +0000316 len = sizeof (cpusubtype);
317 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
318 cpusubtype = CPU_TYPE_ANY;
319
Greg Clayton2bddd342010-09-07 20:11:56 +0000320 len = sizeof (is_64_bit_capable);
321 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
322 {
323 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000324 g_supports_64 = true;
325 }
326
327 if (is_64_bit_capable)
328 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000329#if defined (__i386__) || defined (__x86_64__)
330 if (cpusubtype == CPU_SUBTYPE_486)
331 cpusubtype = CPU_SUBTYPE_I386_ALL;
332#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000333 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000334 {
Greg Clayton514487e2011-02-15 21:59:32 +0000335 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000336 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
337 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000338 }
339 else
340 {
341 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000342 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000343 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000344 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000345 }
346 }
Greg Clayton514487e2011-02-15 21:59:32 +0000347 else
348 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000349 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000350 g_host_arch_64.Clear();
351 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000352 }
Greg Clayton514487e2011-02-15 21:59:32 +0000353 }
354
355#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000356
Greg Clayton514487e2011-02-15 21:59:32 +0000357 if (g_supports_32 == false && g_supports_64 == false)
358 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000359 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000360
Stephen Wilsonbd588712011-02-24 19:15:09 +0000361 g_host_arch_32.Clear();
362 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000363
Greg Claytonb29e6c62012-10-11 17:38:58 +0000364 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
365 // for the default triple. It's probably an artifact of config.guess.
366 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
367 triple.setVendorName("");
368
Stephen Wilsonbd588712011-02-24 19:15:09 +0000369 switch (triple.getArch())
370 {
371 default:
372 g_host_arch_32.SetTriple(triple);
373 g_supports_32 = true;
374 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000375
Stephen Wilsonbd588712011-02-24 19:15:09 +0000376 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000377 g_host_arch_64.SetTriple(triple);
378 g_supports_64 = true;
379 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
380 g_supports_32 = true;
381 break;
382
Stephen Wilsonbd588712011-02-24 19:15:09 +0000383 case llvm::Triple::sparcv9:
384 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000385 g_host_arch_64.SetTriple(triple);
386 g_supports_64 = true;
387 break;
388 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000389
390 g_supports_32 = g_host_arch_32.IsValid();
391 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000392 }
Greg Clayton514487e2011-02-15 21:59:32 +0000393
394#endif // #else for #if defined (__APPLE__)
395
396 if (arch_kind == eSystemDefaultArchitecture32)
397 return g_host_arch_32;
398 else if (arch_kind == eSystemDefaultArchitecture64)
399 return g_host_arch_64;
400
401 if (g_supports_64)
402 return g_host_arch_64;
403
404 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000405}
406
407const ConstString &
408Host::GetVendorString()
409{
410 static ConstString g_vendor;
411 if (!g_vendor)
412 {
Greg Clayton950971f2012-05-12 00:01:21 +0000413 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
414 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
415 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000416 }
417 return g_vendor;
418}
419
420const ConstString &
421Host::GetOSString()
422{
423 static ConstString g_os_string;
424 if (!g_os_string)
425 {
Greg Clayton950971f2012-05-12 00:01:21 +0000426 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
427 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
428 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000429 }
430 return g_os_string;
431}
432
433const ConstString &
434Host::GetTargetTriple()
435{
436 static ConstString g_host_triple;
437 if (!(g_host_triple))
438 {
Greg Clayton950971f2012-05-12 00:01:21 +0000439 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
440 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000441 }
442 return g_host_triple;
443}
444
445lldb::pid_t
446Host::GetCurrentProcessID()
447{
448 return ::getpid();
449}
450
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000451#ifndef _WIN32
452
Greg Clayton2bddd342010-09-07 20:11:56 +0000453lldb::tid_t
454Host::GetCurrentThreadID()
455{
456#if defined (__APPLE__)
Greg Clayton813ddfc2012-09-18 18:19:49 +0000457 // Calling "mach_port_deallocate()" bumps the reference count on the thread
458 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
459 // count.
460 thread_port_t thread_self = mach_thread_self();
461 mach_port_deallocate(mach_task_self(), thread_self);
462 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000463#elif defined(__FreeBSD__)
464 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000465#elif defined(__linux__)
466 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000467#else
468 return lldb::tid_t(pthread_self());
469#endif
470}
471
Jim Ingham372787f2012-04-07 00:00:41 +0000472lldb::thread_t
473Host::GetCurrentThread ()
474{
475 return lldb::thread_t(pthread_self());
476}
477
Greg Clayton2bddd342010-09-07 20:11:56 +0000478const char *
479Host::GetSignalAsCString (int signo)
480{
481 switch (signo)
482 {
483 case SIGHUP: return "SIGHUP"; // 1 hangup
484 case SIGINT: return "SIGINT"; // 2 interrupt
485 case SIGQUIT: return "SIGQUIT"; // 3 quit
486 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
487 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
488 case SIGABRT: return "SIGABRT"; // 6 abort()
Greg Clayton0ddf6be2011-11-04 03:42:38 +0000489#if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE))
Greg Clayton2bddd342010-09-07 20:11:56 +0000490 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000491#endif
492#if !defined(_POSIX_C_SOURCE)
Greg Clayton2bddd342010-09-07 20:11:56 +0000493 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000494#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000495 case SIGFPE: return "SIGFPE"; // 8 floating point exception
496 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
497 case SIGBUS: return "SIGBUS"; // 10 bus error
498 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
499 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
500 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
501 case SIGALRM: return "SIGALRM"; // 14 alarm clock
502 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
503 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
504 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
505 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
506 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
507 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
508 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
509 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
510#if !defined(_POSIX_C_SOURCE)
511 case SIGIO: return "SIGIO"; // 23 input/output possible signal
512#endif
513 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
514 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
515 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
516 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
517#if !defined(_POSIX_C_SOURCE)
518 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
519 case SIGINFO: return "SIGINFO"; // 29 information request
520#endif
521 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
522 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
523 default:
524 break;
525 }
526 return NULL;
527}
528
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000529#endif
530
Greg Clayton2bddd342010-09-07 20:11:56 +0000531void
532Host::WillTerminate ()
533{
534}
535
Sylvestre Ledru59405832013-07-01 08:21:36 +0000536#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000537
Greg Clayton2bddd342010-09-07 20:11:56 +0000538void
539Host::ThreadCreated (const char *thread_name)
540{
541}
Greg Claytone5219662010-12-03 06:02:24 +0000542
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000543void
Greg Claytone5219662010-12-03 06:02:24 +0000544Host::Backtrace (Stream &strm, uint32_t max_frames)
545{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000546 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000547}
548
Greg Clayton85851dd2010-12-04 00:10:17 +0000549size_t
550Host::GetEnvironment (StringList &env)
551{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000552 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000553 return 0;
554}
555
Sylvestre Ledru59405832013-07-01 08:21:36 +0000556#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000557
558struct HostThreadCreateInfo
559{
560 std::string thread_name;
561 thread_func_t thread_fptr;
562 thread_arg_t thread_arg;
563
564 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
565 thread_name (name ? name : ""),
566 thread_fptr (fptr),
567 thread_arg (arg)
568 {
569 }
570};
571
572static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000573#ifdef _WIN32
574__stdcall
575#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000576ThreadCreateTrampoline (thread_arg_t arg)
577{
578 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
579 Host::ThreadCreated (info->thread_name.c_str());
580 thread_func_t thread_fptr = info->thread_fptr;
581 thread_arg_t thread_arg = info->thread_arg;
582
Greg Clayton5160ce52013-03-27 23:08:40 +0000583 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000584 if (log)
585 log->Printf("thread created");
586
587 delete info;
588 return thread_fptr (thread_arg);
589}
590
591lldb::thread_t
592Host::ThreadCreate
593(
594 const char *thread_name,
595 thread_func_t thread_fptr,
596 thread_arg_t thread_arg,
597 Error *error
598)
599{
600 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
601
602 // Host::ThreadCreateTrampoline will delete this pointer for us.
603 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
604
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000605#ifdef _WIN32
606 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
607 int err = thread <= 0 ? GetLastError() : 0;
608#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000609 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000610#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000611 if (err == 0)
612 {
613 if (error)
614 error->Clear();
615 return thread;
616 }
617
618 if (error)
619 error->SetError (err, eErrorTypePOSIX);
620
621 return LLDB_INVALID_HOST_THREAD;
622}
623
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000624#ifndef _WIN32
625
Greg Clayton2bddd342010-09-07 20:11:56 +0000626bool
627Host::ThreadCancel (lldb::thread_t thread, Error *error)
628{
629 int err = ::pthread_cancel (thread);
630 if (error)
631 error->SetError(err, eErrorTypePOSIX);
632 return err == 0;
633}
634
635bool
636Host::ThreadDetach (lldb::thread_t thread, Error *error)
637{
638 int err = ::pthread_detach (thread);
639 if (error)
640 error->SetError(err, eErrorTypePOSIX);
641 return err == 0;
642}
643
644bool
645Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
646{
647 int err = ::pthread_join (thread, thread_result_ptr);
648 if (error)
649 error->SetError(err, eErrorTypePOSIX);
650 return err == 0;
651}
652
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000653lldb::thread_key_t
654Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
655{
656 pthread_key_t key;
657 ::pthread_key_create (&key, callback);
658 return key;
659}
660
661void*
662Host::ThreadLocalStorageGet(lldb::thread_key_t key)
663{
664 return ::pthread_getspecific (key);
665}
666
667void
668Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
669{
670 ::pthread_setspecific (key, value);
671}
672
Matt Kopec62502c62013-05-13 19:33:58 +0000673bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000674Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
675{
Greg Clayton85719632013-02-27 22:51:58 +0000676#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000677 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
678 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
679 if (pid == LLDB_INVALID_PROCESS_ID)
680 pid = curr_pid;
681
682 if (tid == LLDB_INVALID_THREAD_ID)
683 tid = curr_tid;
684
Greg Clayton2bddd342010-09-07 20:11:56 +0000685 // Set the pthread name if possible
686 if (pid == curr_pid && tid == curr_tid)
687 {
Matt Kopec62502c62013-05-13 19:33:58 +0000688 if (::pthread_setname_np (name) == 0)
689 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000690 }
Matt Kopec62502c62013-05-13 19:33:58 +0000691 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000692#elif defined (__FreeBSD__)
693 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
694 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
695 if (pid == LLDB_INVALID_PROCESS_ID)
696 pid = curr_pid;
697
698 if (tid == LLDB_INVALID_THREAD_ID)
699 tid = curr_tid;
700
701 // Set the pthread name if possible
702 if (pid == curr_pid && tid == curr_tid)
703 {
Michael Sartainc2052432013-08-01 18:51:08 +0000704 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000705 return true;
706 }
707 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000708#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000709 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
710 if (fn)
711 {
Matt Kopec62502c62013-05-13 19:33:58 +0000712 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
713 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000714 if (pid == LLDB_INVALID_PROCESS_ID)
715 pid = curr_pid;
716
717 if (tid == LLDB_INVALID_THREAD_ID)
718 tid = curr_tid;
719
Michael Sartainc2052432013-08-01 18:51:08 +0000720 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000721 {
Michael Sartainc2052432013-08-01 18:51:08 +0000722 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
723 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
724
725 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000726 return true;
727 }
728 }
729 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000730#else
731 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000732#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000733}
734
Ed Maste02983be2013-07-25 19:10:32 +0000735bool
736Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
737 const char *thread_name, size_t len)
738{
739 char *namebuf = (char *)::malloc (len + 1);
740
741 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
742 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
743 // off leads to a lot of similar named threads. Go through the thread name
744 // and search for the last dot and use that.
745 const char *lastdot = ::strrchr (thread_name, '.');
746
747 if (lastdot && lastdot != thread_name)
748 thread_name = lastdot + 1;
749 ::strncpy (namebuf, thread_name, len);
750 namebuf[len] = 0;
751
752 int namebuflen = strlen(namebuf);
753 if (namebuflen > 0)
754 {
755 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
756 {
757 // Trim off trailing '(' and '>' characters for a bit more cleanup.
758 namebuflen--;
759 namebuf[namebuflen] = 0;
760 }
761 return Host::SetThreadName (pid, tid, namebuf);
762 }
763 return false;
764}
765
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000766#endif
767
Greg Clayton2bddd342010-09-07 20:11:56 +0000768FileSpec
769Host::GetProgramFileSpec ()
770{
771 static FileSpec g_program_filespec;
772 if (!g_program_filespec)
773 {
774#if defined (__APPLE__)
775 char program_fullpath[PATH_MAX];
776 // If DST is NULL, then return the number of bytes needed.
777 uint32_t len = sizeof(program_fullpath);
778 int err = _NSGetExecutablePath (program_fullpath, &len);
779 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000780 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000781 else if (err == -1)
782 {
783 char *large_program_fullpath = (char *)::malloc (len + 1);
784
785 err = _NSGetExecutablePath (large_program_fullpath, &len);
786 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000787 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000788
789 ::free (large_program_fullpath);
790 }
791#elif defined (__linux__)
792 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000793 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
794 if (len > 0) {
795 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000796 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000797 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000798#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000799 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
800 size_t exe_path_size;
801 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
802 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000803 char *exe_path = new char[exe_path_size];
804 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
805 g_program_filespec.SetFile(exe_path, false);
806 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000807 }
808#endif
809 }
810 return g_program_filespec;
811}
812
Greg Clayton2bddd342010-09-07 20:11:56 +0000813#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000814
815bool
816Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
817{
818 bundle.Clear();
819 return false;
820}
821
Greg Clayton2bddd342010-09-07 20:11:56 +0000822bool
Greg Claytondd36def2010-10-17 22:03:32 +0000823Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000824{
Greg Claytondd36def2010-10-17 22:03:32 +0000825 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000826}
827#endif
828
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000829#ifndef _WIN32
830
Greg Clayton45319462011-02-08 00:35:34 +0000831// Opaque info that tracks a dynamic library that was loaded
832struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000833{
Greg Clayton45319462011-02-08 00:35:34 +0000834 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
835 file_spec (fs),
836 open_options (o),
837 handle (h)
838 {
839 }
840
841 const FileSpec file_spec;
842 uint32_t open_options;
843 void * handle;
844};
845
846void *
847Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
848{
Greg Clayton4272cc72011-02-02 02:24:04 +0000849 char path[PATH_MAX];
850 if (file_spec.GetPath(path, sizeof(path)))
851 {
Greg Clayton45319462011-02-08 00:35:34 +0000852 int mode = 0;
853
854 if (options & eDynamicLibraryOpenOptionLazy)
855 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000856 else
857 mode |= RTLD_NOW;
858
Greg Clayton45319462011-02-08 00:35:34 +0000859
860 if (options & eDynamicLibraryOpenOptionLocal)
861 mode |= RTLD_LOCAL;
862 else
863 mode |= RTLD_GLOBAL;
864
865#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
866 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
867 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000868#endif
Greg Clayton45319462011-02-08 00:35:34 +0000869
870 void * opaque = ::dlopen (path, mode);
871
872 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000873 {
874 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000875 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000876 }
877 else
878 {
879 error.SetErrorString(::dlerror());
880 }
881 }
882 else
883 {
884 error.SetErrorString("failed to extract path");
885 }
Greg Clayton45319462011-02-08 00:35:34 +0000886 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000887}
888
889Error
Greg Clayton45319462011-02-08 00:35:34 +0000890Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000891{
892 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000893 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000894 {
895 error.SetErrorString ("invalid dynamic library handle");
896 }
Greg Clayton45319462011-02-08 00:35:34 +0000897 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000898 {
Greg Clayton45319462011-02-08 00:35:34 +0000899 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
900 if (::dlclose (dylib_info->handle) != 0)
901 {
902 error.SetErrorString(::dlerror());
903 }
904
905 dylib_info->open_options = 0;
906 dylib_info->handle = 0;
907 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000908 }
909 return error;
910}
911
912void *
Greg Clayton45319462011-02-08 00:35:34 +0000913Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000914{
Greg Clayton45319462011-02-08 00:35:34 +0000915 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000916 {
917 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000918 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000919 else
Greg Clayton45319462011-02-08 00:35:34 +0000920 {
921 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
922
923 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
924 if (symbol_addr)
925 {
926#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
927 // This host doesn't support limiting searches to this shared library
928 // so we need to verify that the match came from this shared library
929 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000930 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000931 {
932 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
933 if (match_dylib_spec != dylib_info->file_spec)
934 {
935 char dylib_path[PATH_MAX];
936 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
937 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
938 else
939 error.SetErrorString ("symbol not found");
940 return NULL;
941 }
942 }
943#endif
944 error.Clear();
945 return symbol_addr;
946 }
947 else
948 {
949 error.SetErrorString(::dlerror());
950 }
951 }
952 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000953}
Greg Claytondd36def2010-10-17 22:03:32 +0000954
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000955FileSpec
956Host::GetModuleFileSpecForHostAddress (const void *host_addr)
957{
958 FileSpec module_filespec;
959 Dl_info info;
960 if (::dladdr (host_addr, &info))
961 {
962 if (info.dli_fname)
963 module_filespec.SetFile(info.dli_fname, true);
964 }
965 return module_filespec;
966}
967
968#endif
969
Greg Claytondd36def2010-10-17 22:03:32 +0000970bool
971Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
972{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000973 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000974 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
975 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000976 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000977 // need to be modified to "do the right thing".
978
979 switch (path_type)
980 {
981 case ePathTypeLLDBShlibDir:
982 {
983 static ConstString g_lldb_so_dir;
984 if (!g_lldb_so_dir)
985 {
986 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
987 g_lldb_so_dir = lldb_file_spec.GetDirectory();
988 }
989 file_spec.GetDirectory() = g_lldb_so_dir;
990 return file_spec.GetDirectory();
991 }
992 break;
993
994 case ePathTypeSupportExecutableDir:
995 {
996 static ConstString g_lldb_support_exe_dir;
997 if (!g_lldb_support_exe_dir)
998 {
999 FileSpec lldb_file_spec;
1000 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1001 {
1002 char raw_path[PATH_MAX];
1003 char resolved_path[PATH_MAX];
1004 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1005
1006#if defined (__APPLE__)
1007 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1008 if (framework_pos)
1009 {
1010 framework_pos += strlen("LLDB.framework");
Greg Claytondce502e2011-11-04 03:34:56 +00001011#if !defined (__arm__)
Greg Claytondd36def2010-10-17 22:03:32 +00001012 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001013#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001014 }
1015#endif
1016 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1017 g_lldb_support_exe_dir.SetCString(resolved_path);
1018 }
1019 }
1020 file_spec.GetDirectory() = g_lldb_support_exe_dir;
1021 return file_spec.GetDirectory();
1022 }
1023 break;
1024
1025 case ePathTypeHeaderDir:
1026 {
1027 static ConstString g_lldb_headers_dir;
1028 if (!g_lldb_headers_dir)
1029 {
1030#if defined (__APPLE__)
1031 FileSpec lldb_file_spec;
1032 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1033 {
1034 char raw_path[PATH_MAX];
1035 char resolved_path[PATH_MAX];
1036 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1037
1038 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1039 if (framework_pos)
1040 {
1041 framework_pos += strlen("LLDB.framework");
1042 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1043 }
1044 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1045 g_lldb_headers_dir.SetCString(resolved_path);
1046 }
1047#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001048 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001049 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1050#endif
1051 }
1052 file_spec.GetDirectory() = g_lldb_headers_dir;
1053 return file_spec.GetDirectory();
1054 }
1055 break;
1056
Ed Mastea85d3642013-07-02 19:30:52 +00001057#ifndef LLDB_DISABLE_PYTHON
Greg Claytondd36def2010-10-17 22:03:32 +00001058 case ePathTypePythonDir:
1059 {
Greg Claytondd36def2010-10-17 22:03:32 +00001060 static ConstString g_lldb_python_dir;
1061 if (!g_lldb_python_dir)
1062 {
1063 FileSpec lldb_file_spec;
1064 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1065 {
1066 char raw_path[PATH_MAX];
1067 char resolved_path[PATH_MAX];
1068 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1069
1070#if defined (__APPLE__)
1071 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1072 if (framework_pos)
1073 {
1074 framework_pos += strlen("LLDB.framework");
1075 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1076 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001077#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001078 llvm::SmallString<256> python_version_dir;
1079 llvm::raw_svector_ostream os(python_version_dir);
1080 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1081 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001082
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001083 // We may get our string truncated. Should we protect
1084 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001085
Daniel Maleafa7425d2013-08-06 21:40:08 +00001086 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001087 sizeof(raw_path) - strlen(raw_path) - 1);
1088
Greg Claytondd36def2010-10-17 22:03:32 +00001089#endif
1090 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1091 g_lldb_python_dir.SetCString(resolved_path);
1092 }
1093 }
1094 file_spec.GetDirectory() = g_lldb_python_dir;
1095 return file_spec.GetDirectory();
1096 }
1097 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001098#endif
1099
Greg Clayton4272cc72011-02-02 02:24:04 +00001100 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1101 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001102#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001103 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001104 static bool g_lldb_system_plugin_dir_located = false;
1105 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001106 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001107 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001108#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001109 FileSpec lldb_file_spec;
1110 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1111 {
1112 char raw_path[PATH_MAX];
1113 char resolved_path[PATH_MAX];
1114 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1115
1116 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1117 if (framework_pos)
1118 {
1119 framework_pos += strlen("LLDB.framework");
1120 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001121 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1122 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001123 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001124 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001125 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001126#elif defined (__linux__)
1127 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1128 if (lldb_file_spec.Exists())
1129 {
1130 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1131 }
1132#endif // __APPLE__ || __linux__
Greg Clayton4272cc72011-02-02 02:24:04 +00001133 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001134
1135 if (g_lldb_system_plugin_dir)
1136 {
1137 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1138 return true;
1139 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001140#else
1141 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001142 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001143#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001144 }
1145 break;
1146
1147 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1148 {
1149#if defined (__APPLE__)
1150 static ConstString g_lldb_user_plugin_dir;
1151 if (!g_lldb_user_plugin_dir)
1152 {
1153 char user_plugin_path[PATH_MAX];
1154 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1155 user_plugin_path,
1156 sizeof(user_plugin_path)))
1157 {
1158 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1159 }
1160 }
1161 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1162 return file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001163#elif defined (__linux__)
1164 static ConstString g_lldb_user_plugin_dir;
1165 if (!g_lldb_user_plugin_dir)
1166 {
1167 // XDG Base Directory Specification
1168 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1169 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1170 FileSpec lldb_file_spec;
1171 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1172 if (xdg_data_home && xdg_data_home[0])
1173 {
1174 std::string user_plugin_dir (xdg_data_home);
1175 user_plugin_dir += "/lldb";
1176 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1177 }
1178 else
1179 {
1180 const char *home_dir = getenv("HOME");
1181 if (home_dir && home_dir[0])
1182 {
1183 std::string user_plugin_dir (home_dir);
1184 user_plugin_dir += "/.local/share/lldb";
1185 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1186 }
1187 }
1188
1189 if (lldb_file_spec.Exists())
1190 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1191 }
1192 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1193 return file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001194#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001195 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001196 return false;
1197 }
Greg Claytondd36def2010-10-17 22:03:32 +00001198 }
1199
1200 return false;
1201}
1202
Greg Clayton1cb64962011-03-24 04:28:38 +00001203
1204bool
1205Host::GetHostname (std::string &s)
1206{
1207 char hostname[PATH_MAX];
1208 hostname[sizeof(hostname) - 1] = '\0';
1209 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1210 {
1211 struct hostent* h = ::gethostbyname (hostname);
1212 if (h)
1213 s.assign (h->h_name);
1214 else
1215 s.assign (hostname);
1216 return true;
1217 }
1218 return false;
1219}
1220
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001221#ifndef _WIN32
1222
Greg Clayton32e0a752011-03-30 18:16:51 +00001223const char *
1224Host::GetUserName (uint32_t uid, std::string &user_name)
1225{
1226 struct passwd user_info;
1227 struct passwd *user_info_ptr = &user_info;
1228 char user_buffer[PATH_MAX];
1229 size_t user_buffer_size = sizeof(user_buffer);
1230 if (::getpwuid_r (uid,
1231 &user_info,
1232 user_buffer,
1233 user_buffer_size,
1234 &user_info_ptr) == 0)
1235 {
1236 if (user_info_ptr)
1237 {
1238 user_name.assign (user_info_ptr->pw_name);
1239 return user_name.c_str();
1240 }
1241 }
1242 user_name.clear();
1243 return NULL;
1244}
1245
1246const char *
1247Host::GetGroupName (uint32_t gid, std::string &group_name)
1248{
1249 char group_buffer[PATH_MAX];
1250 size_t group_buffer_size = sizeof(group_buffer);
1251 struct group group_info;
1252 struct group *group_info_ptr = &group_info;
1253 // Try the threadsafe version first
1254 if (::getgrgid_r (gid,
1255 &group_info,
1256 group_buffer,
1257 group_buffer_size,
1258 &group_info_ptr) == 0)
1259 {
1260 if (group_info_ptr)
1261 {
1262 group_name.assign (group_info_ptr->gr_name);
1263 return group_name.c_str();
1264 }
1265 }
1266 else
1267 {
1268 // The threadsafe version isn't currently working
1269 // for me on darwin, but the non-threadsafe version
1270 // is, so I am calling it below.
1271 group_info_ptr = ::getgrgid (gid);
1272 if (group_info_ptr)
1273 {
1274 group_name.assign (group_info_ptr->gr_name);
1275 return group_name.c_str();
1276 }
1277 }
1278 group_name.clear();
1279 return NULL;
1280}
1281
Han Ming Ong84647042012-02-25 01:07:38 +00001282uint32_t
1283Host::GetUserID ()
1284{
1285 return getuid();
1286}
1287
1288uint32_t
1289Host::GetGroupID ()
1290{
1291 return getgid();
1292}
1293
1294uint32_t
1295Host::GetEffectiveUserID ()
1296{
1297 return geteuid();
1298}
1299
1300uint32_t
1301Host::GetEffectiveGroupID ()
1302{
1303 return getegid();
1304}
1305
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001306#endif
1307
1308#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1309bool
1310Host::GetOSBuildString (std::string &s)
1311{
1312 s.clear();
1313 return false;
1314}
1315
1316bool
1317Host::GetOSKernelDescription (std::string &s)
1318{
1319 s.clear();
1320 return false;
1321}
1322#endif
1323
Daniel Malea25d7eb02013-05-15 17:54:07 +00001324#if !defined (__APPLE__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001325uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001326Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001327{
1328 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001329 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001330}
Daniel Malea25d7eb02013-05-15 17:54:07 +00001331#endif // #if !defined (__APPLE__) && !defined(__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001332
Sylvestre Ledru59405832013-07-01 08:21:36 +00001333#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001334bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001335Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001336{
Greg Claytone996fd32011-03-08 22:40:15 +00001337 process_info.Clear();
1338 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001339}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001340#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001341
Matt Kopec085d6ce2013-05-31 22:00:07 +00001342#if !defined(__linux__)
1343bool
1344Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1345{
1346 return false;
1347}
1348#endif
1349
Sean Callananc0a6e062011-10-27 21:22:25 +00001350lldb::TargetSP
1351Host::GetDummyTarget (lldb_private::Debugger &debugger)
1352{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001353 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001354
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001355 // FIXME: Maybe the dummy target should be per-Debugger
1356 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1357 {
1358 ArchSpec arch(Target::GetDefaultArchitecture());
1359 if (!arch.IsValid())
1360 arch = Host::GetArchitecture ();
1361 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001362 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001363 arch.GetTriple().getTriple().c_str(),
1364 false,
1365 NULL,
1366 g_dummy_target_sp);
1367 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001368
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001369 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001370}
1371
Greg Claytond1cf11a2012-04-14 01:42:46 +00001372struct ShellInfo
1373{
1374 ShellInfo () :
1375 process_reaped (false),
1376 can_delete (false),
1377 pid (LLDB_INVALID_PROCESS_ID),
1378 signo(-1),
1379 status(-1)
1380 {
1381 }
1382
1383 lldb_private::Predicate<bool> process_reaped;
1384 lldb_private::Predicate<bool> can_delete;
1385 lldb::pid_t pid;
1386 int signo;
1387 int status;
1388};
1389
1390static bool
1391MonitorShellCommand (void *callback_baton,
1392 lldb::pid_t pid,
1393 bool exited, // True if the process did exit
1394 int signo, // Zero for no signal
1395 int status) // Exit value of process if signal is zero
1396{
1397 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1398 shell_info->pid = pid;
1399 shell_info->signo = signo;
1400 shell_info->status = status;
1401 // Let the thread running Host::RunShellCommand() know that the process
1402 // exited and that ShellInfo has been filled in by broadcasting to it
1403 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1404 // Now wait for a handshake back from that thread running Host::RunShellCommand
1405 // so we know that we can delete shell_info_ptr
1406 shell_info->can_delete.WaitForValueEqualTo(true);
1407 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1408 usleep(1000);
1409 // Now delete the shell info that was passed into this function
1410 delete shell_info;
1411 return true;
1412}
1413
1414Error
1415Host::RunShellCommand (const char *command,
1416 const char *working_dir,
1417 int *status_ptr,
1418 int *signo_ptr,
1419 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001420 uint32_t timeout_sec,
1421 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001422{
1423 Error error;
1424 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001425 if (shell && shell[0])
1426 {
1427 // Run the command in a shell
1428 launch_info.SetShell(shell);
1429 launch_info.GetArguments().AppendArgument(command);
1430 const bool localhost = true;
1431 const bool will_debug = false;
1432 const bool first_arg_is_full_shell_command = true;
1433 launch_info.ConvertArgumentsForLaunchingInShell (error,
1434 localhost,
1435 will_debug,
1436 first_arg_is_full_shell_command);
1437 }
1438 else
1439 {
1440 // No shell, just run it
1441 Args args (command);
1442 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001443 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001444 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001445
1446 if (working_dir)
1447 launch_info.SetWorkingDirectory(working_dir);
1448 char output_file_path_buffer[L_tmpnam];
1449 const char *output_file_path = NULL;
1450 if (command_output_ptr)
1451 {
1452 // Create a temporary file to get the stdout/stderr and redirect the
1453 // output of the command into this file. We will later read this file
1454 // if all goes well and fill the data into "command_output_ptr"
1455 output_file_path = ::tmpnam(output_file_path_buffer);
1456 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1457 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001458 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001459 }
1460 else
1461 {
1462 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1463 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1464 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1465 }
1466
1467 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001468 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001469
1470 const bool monitor_signals = false;
1471 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1472
1473 error = LaunchProcess (launch_info);
1474 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001475
1476 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1477 error.SetErrorString("failed to get process ID");
1478
1479 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001480 {
1481 // The process successfully launched, so we can defer ownership of
1482 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001483 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001484 // doesn't need to delete the ShellInfo anymore.
1485 ShellInfo *shell_info = shell_info_ap.release();
1486 TimeValue timeout_time(TimeValue::Now());
1487 timeout_time.OffsetWithSeconds(timeout_sec);
1488 bool timed_out = false;
1489 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1490 if (timed_out)
1491 {
1492 error.SetErrorString("timed out waiting for shell command to complete");
1493
1494 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001495 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001496 // Wait for the monitor callback to get the message
1497 timeout_time = TimeValue::Now();
1498 timeout_time.OffsetWithSeconds(1);
1499 timed_out = false;
1500 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1501 }
1502 else
1503 {
1504 if (status_ptr)
1505 *status_ptr = shell_info->status;
1506
1507 if (signo_ptr)
1508 *signo_ptr = shell_info->signo;
1509
1510 if (command_output_ptr)
1511 {
1512 command_output_ptr->clear();
1513 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1514 uint64_t file_size = file_spec.GetByteSize();
1515 if (file_size > 0)
1516 {
1517 if (file_size > command_output_ptr->max_size())
1518 {
1519 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1520 }
1521 else
1522 {
1523 command_output_ptr->resize(file_size);
1524 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1525 }
1526 }
1527 }
1528 }
1529 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1530 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001531
1532 if (output_file_path)
1533 ::unlink (output_file_path);
1534 // Handshake with the monitor thread, or just let it know in advance that
1535 // it can delete "shell_info" in case we timed out and were not able to kill
1536 // the process...
1537 return error;
1538}
1539
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001540#ifndef _WIN32
1541
1542size_t
1543Host::GetPageSize()
1544{
1545 return ::getpagesize();
1546}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001547
Greg Claytone3e3fee2013-02-17 20:46:30 +00001548uint32_t
1549Host::GetNumberCPUS ()
1550{
1551 static uint32_t g_num_cores = UINT32_MAX;
1552 if (g_num_cores == UINT32_MAX)
1553 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001554#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001555
1556 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001557
Greg Claytone3e3fee2013-02-17 20:46:30 +00001558#else
1559
1560 // Assume POSIX support if a host specific case has not been supplied above
1561 g_num_cores = 0;
1562 int num_cores = 0;
1563 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001564#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001565 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001566#else
1567 int mib[] = { CTL_HW, HW_NCPU };
1568#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001569
1570 /* get the number of CPUs from the system */
1571 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1572 {
1573 g_num_cores = num_cores;
1574 }
1575 else
1576 {
1577 mib[1] = HW_NCPU;
1578 num_cores_len = sizeof(num_cores);
1579 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1580 {
1581 if (num_cores > 0)
1582 g_num_cores = num_cores;
1583 }
1584 }
1585#endif
1586 }
1587 return g_num_cores;
1588}
1589
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001590void
1591Host::Kill(lldb::pid_t pid, int signo)
1592{
1593 ::kill(pid, signo);
1594}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001595
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001596#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001597
Johnny Chen8f3d8382011-08-02 20:52:42 +00001598#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001599bool
Greg Clayton3b147632010-12-18 01:54:34 +00001600Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001601{
1602 return false;
1603}
Greg Claytondd36def2010-10-17 22:03:32 +00001604
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001605void
1606Host::SetCrashDescriptionWithFormat (const char *format, ...)
1607{
1608}
1609
1610void
1611Host::SetCrashDescription (const char *description)
1612{
1613}
Greg Claytondd36def2010-10-17 22:03:32 +00001614
1615lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001616Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001617{
1618 return LLDB_INVALID_PROCESS_ID;
1619}
1620
Daniel Maleae0f8f572013-08-26 23:57:52 +00001621uint32_t
1622Host::MakeDirectory (const char* path, mode_t mode)
1623{
1624 return UINT32_MAX;
1625}
Greg Clayton2bddd342010-09-07 20:11:56 +00001626#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00001627
1628typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
1629FDToFileMap& GetFDToFileMap()
1630{
1631 static FDToFileMap g_fd2filemap;
1632 return g_fd2filemap;
1633}
1634
1635lldb::user_id_t
1636Host::OpenFile (const FileSpec& file_spec,
1637 uint32_t flags,
1638 mode_t mode,
1639 Error &error)
1640{
1641 std::string path (file_spec.GetPath());
1642 if (path.empty())
1643 {
1644 error.SetErrorString("empty path");
1645 return UINT64_MAX;
1646 }
1647 FileSP file_sp(new File());
1648 error = file_sp->Open(path.c_str(),flags,mode);
1649 if (file_sp->IsValid() == false)
1650 return UINT64_MAX;
1651 lldb::user_id_t fd = file_sp->GetDescriptor();
1652 GetFDToFileMap()[fd] = file_sp;
1653 return fd;
1654}
1655
1656bool
1657Host::CloseFile (lldb::user_id_t fd, Error &error)
1658{
1659 if (fd == UINT64_MAX)
1660 {
1661 error.SetErrorString ("invalid file descriptor");
1662 return false;
1663 }
1664 FDToFileMap& file_map = GetFDToFileMap();
1665 FDToFileMap::iterator pos = file_map.find(fd);
1666 if (pos == file_map.end())
1667 {
1668 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1669 return false;
1670 }
1671 FileSP file_sp = pos->second;
1672 if (!file_sp)
1673 {
1674 error.SetErrorString ("invalid host backing file");
1675 return false;
1676 }
1677 error = file_sp->Close();
1678 file_map.erase(pos);
1679 return error.Success();
1680}
1681
1682uint64_t
1683Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
1684{
1685 if (fd == UINT64_MAX)
1686 {
1687 error.SetErrorString ("invalid file descriptor");
1688 return UINT64_MAX;
1689 }
1690 FDToFileMap& file_map = GetFDToFileMap();
1691 FDToFileMap::iterator pos = file_map.find(fd);
1692 if (pos == file_map.end())
1693 {
1694 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
1695 return false;
1696 }
1697 FileSP file_sp = pos->second;
1698 if (!file_sp)
1699 {
1700 error.SetErrorString ("invalid host backing file");
1701 return UINT64_MAX;
1702 }
1703 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
1704 return UINT64_MAX;
1705 size_t bytes_written = src_len;
1706 error = file_sp->Write(src, bytes_written);
1707 if (error.Fail())
1708 return UINT64_MAX;
1709 return bytes_written;
1710}
1711
1712uint64_t
1713Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
1714{
1715 if (fd == UINT64_MAX)
1716 {
1717 error.SetErrorString ("invalid file descriptor");
1718 return UINT64_MAX;
1719 }
1720 FDToFileMap& file_map = GetFDToFileMap();
1721 FDToFileMap::iterator pos = file_map.find(fd);
1722 if (pos == file_map.end())
1723 {
1724 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1725 return false;
1726 }
1727 FileSP file_sp = pos->second;
1728 if (!file_sp)
1729 {
1730 error.SetErrorString ("invalid host backing file");
1731 return UINT64_MAX;
1732 }
1733 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
1734 return UINT64_MAX;
1735 size_t bytes_read = dst_len;
1736 error = file_sp->Read(dst ,bytes_read);
1737 if (error.Fail())
1738 return UINT64_MAX;
1739 return bytes_read;
1740}
1741
1742lldb::user_id_t
1743Host::GetFileSize (const FileSpec& file_spec)
1744{
1745 return file_spec.GetByteSize();
1746}
1747
1748bool
1749Host::GetFileExists (const FileSpec& file_spec)
1750{
1751 return file_spec.Exists();
1752}
1753
1754bool
1755Host::CalculateMD5 (const FileSpec& file_spec,
1756 uint64_t &low,
1757 uint64_t &high)
1758{
1759#if defined (__APPLE__)
1760 StreamString md5_cmd_line;
1761 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
1762 std::string hash_string;
1763 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
1764 if (err.Fail())
1765 return false;
1766 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
1767 // if the output is any other length it is probably wrong
1768 if (hash_string.size() != 32)
1769 return false;
1770 std::string part1(hash_string,0,16);
1771 std::string part2(hash_string,16);
1772 const char* part1_cstr = part1.c_str();
1773 const char* part2_cstr = part2.c_str();
1774 high = ::strtoull(part1_cstr, NULL, 16);
1775 low = ::strtoull(part2_cstr, NULL, 16);
1776 return true;
1777#else
1778 // your own MD5 implementation here
1779 return false;
1780#endif
1781}