blob: 4161559f4e64b8ccf396f1b45f792de27b1a7ad8 [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>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifdef _WIN32
17#include "lldb/Host/windows/windows.h"
18#include <winsock2.h>
19#include <WS2tcpip.h>
20#else
21#include <dlfcn.h>
22#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000023#include <netdb.h>
24#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000025#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000026#endif
27
28#if !defined (__GNU__) && !defined (_WIN32)
29// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000030#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000031#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000032
33#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000034#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000035#include <mach/mach_init.h>
36#include <mach-o/dyld.h>
Ed Maste8b006c62013-06-25 18:58:11 +000037#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000038
Ed Maste8b006c62013-06-25 18:58:11 +000039#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000040#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000041#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000042#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000043#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000044
Ed Maste8b006c62013-06-25 18:58:11 +000045#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000046#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000047#endif
48
Greg Clayton2bddd342010-09-07 20:11:56 +000049#include "lldb/Host/Host.h"
50#include "lldb/Core/ArchSpec.h"
51#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000052#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000053#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000054#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000055#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000057#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000058#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000059#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000060#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000061#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000062#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000063#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000064#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000065
Daniel Maleafa7425d2013-08-06 21:40:08 +000066#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000067#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000068#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000069
Greg Clayton32e0a752011-03-30 18:16:51 +000070
Greg Clayton2bddd342010-09-07 20:11:56 +000071using 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();
Daniel Malea4244cbd2013-08-27 20:58:59 +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;
Greg Clayton2bddd342010-09-07 20:11:56 +0000154 const bool monitor_signals = info->monitor_signals;
155
Daniel Malea4244cbd2013-08-27 20:58:59 +0000156 assert (info->pid <= UINT32_MAX);
157 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
158
Greg Clayton2bddd342010-09-07 20:11:56 +0000159 delete info;
160
161 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000162#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000163 #define __WALL 0
164#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000165 const int options = __WALL;
166
Greg Clayton2bddd342010-09-07 20:11:56 +0000167 while (1)
168 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000169 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000170 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000171 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000172
173 // Wait for all child processes
174 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000175 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000176 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000177 ::pthread_testcancel ();
178
179 if (wait_pid == -1)
180 {
181 if (errno == EINTR)
182 continue;
183 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000184 {
185 if (log)
186 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000187 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000188 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000189 }
Matt Kopec650648f2013-01-08 16:30:18 +0000190 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000191 {
192 bool exited = false;
193 int signal = 0;
194 int exit_status = 0;
195 const char *status_cstr = NULL;
196 if (WIFSTOPPED(status))
197 {
198 signal = WSTOPSIG(status);
199 status_cstr = "STOPPED";
200 }
201 else if (WIFEXITED(status))
202 {
203 exit_status = WEXITSTATUS(status);
204 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000205 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000206 }
207 else if (WIFSIGNALED(status))
208 {
209 signal = WTERMSIG(status);
210 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000211 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000212 exited = true;
213 exit_status = -1;
214 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000215 }
216 else
217 {
Johnny Chen44805302011-07-19 19:48:13 +0000218 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000219 }
220
221 // Scope for pthread_cancel_disabler
222 {
223 ScopedPThreadCancelDisabler pthread_cancel_disabler;
224
Caroline Tice20ad3c42010-10-29 21:48:37 +0000225 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000226 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000227 log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Greg Clayton2bddd342010-09-07 20:11:56 +0000228 function,
229 wait_pid,
230 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000231 pid,
232 status,
233 status_cstr,
234 signal,
235 exit_status);
236
237 if (exited || (signal != 0 && monitor_signals))
238 {
Greg Claytone4e45922011-11-16 05:37:56 +0000239 bool callback_return = false;
240 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000241 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000242
243 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000244 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000245 {
246 if (log)
247 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000248 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000249 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000250 // If the callback returns true, it means this process should
251 // exit
252 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000253 {
254 if (log)
255 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000256 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000257 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 }
259 }
260 }
261 }
262
Caroline Tice20ad3c42010-10-29 21:48:37 +0000263 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000264 if (log)
265 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
266
267 return NULL;
268}
269
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000270#endif // #if !defined (__APPLE__) && !defined (_WIN32)
271
272#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000273
274void
275Host::SystemLog (SystemLogType type, const char *format, va_list args)
276{
277 vfprintf (stderr, format, args);
278}
279
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000280#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000281
Greg Claytone38a5ed2012-01-05 03:57:59 +0000282void
283Host::SystemLog (SystemLogType type, const char *format, ...)
284{
285 va_list args;
286 va_start (args, format);
287 SystemLog (type, format, args);
288 va_end (args);
289}
290
Greg Clayton2bddd342010-09-07 20:11:56 +0000291const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000292Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000293{
Greg Clayton514487e2011-02-15 21:59:32 +0000294 static bool g_supports_32 = false;
295 static bool g_supports_64 = false;
296 static ArchSpec g_host_arch_32;
297 static ArchSpec g_host_arch_64;
298
Greg Clayton2bddd342010-09-07 20:11:56 +0000299#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000300
301 // Apple is different in that it can support both 32 and 64 bit executables
302 // in the same operating system running concurrently. Here we detect the
303 // correct host architectures for both 32 and 64 bit including if 64 bit
304 // executables are supported on the system.
305
306 if (g_supports_32 == false && g_supports_64 == false)
307 {
308 // All apple systems support 32 bit execution.
309 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000310 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000311 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000312 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000313 ArchSpec host_arch;
314 // These will tell us about the kernel architecture, which even on a 64
315 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000316 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
317 {
Greg Clayton514487e2011-02-15 21:59:32 +0000318 len = sizeof (cpusubtype);
319 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
320 cpusubtype = CPU_TYPE_ANY;
321
Greg Clayton2bddd342010-09-07 20:11:56 +0000322 len = sizeof (is_64_bit_capable);
323 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
324 {
325 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000326 g_supports_64 = true;
327 }
328
329 if (is_64_bit_capable)
330 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000331#if defined (__i386__) || defined (__x86_64__)
332 if (cpusubtype == CPU_SUBTYPE_486)
333 cpusubtype = CPU_SUBTYPE_I386_ALL;
334#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000335 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000336 {
Greg Clayton514487e2011-02-15 21:59:32 +0000337 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000338 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
339 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000340 }
341 else
342 {
343 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000344 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000345 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000346 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000347 }
348 }
Greg Clayton514487e2011-02-15 21:59:32 +0000349 else
350 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000351 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000352 g_host_arch_64.Clear();
353 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000354 }
Greg Clayton514487e2011-02-15 21:59:32 +0000355 }
356
357#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000358
Greg Clayton514487e2011-02-15 21:59:32 +0000359 if (g_supports_32 == false && g_supports_64 == false)
360 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000361 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000362
Stephen Wilsonbd588712011-02-24 19:15:09 +0000363 g_host_arch_32.Clear();
364 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000365
Greg Claytonb29e6c62012-10-11 17:38:58 +0000366 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
367 // for the default triple. It's probably an artifact of config.guess.
368 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
369 triple.setVendorName("");
370
Stephen Wilsonbd588712011-02-24 19:15:09 +0000371 switch (triple.getArch())
372 {
373 default:
374 g_host_arch_32.SetTriple(triple);
375 g_supports_32 = true;
376 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000377
Stephen Wilsonbd588712011-02-24 19:15:09 +0000378 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000379 g_host_arch_64.SetTriple(triple);
380 g_supports_64 = true;
381 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
382 g_supports_32 = true;
383 break;
384
Stephen Wilsonbd588712011-02-24 19:15:09 +0000385 case llvm::Triple::sparcv9:
386 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000387 g_host_arch_64.SetTriple(triple);
388 g_supports_64 = true;
389 break;
390 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000391
392 g_supports_32 = g_host_arch_32.IsValid();
393 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000394 }
Greg Clayton514487e2011-02-15 21:59:32 +0000395
396#endif // #else for #if defined (__APPLE__)
397
398 if (arch_kind == eSystemDefaultArchitecture32)
399 return g_host_arch_32;
400 else if (arch_kind == eSystemDefaultArchitecture64)
401 return g_host_arch_64;
402
403 if (g_supports_64)
404 return g_host_arch_64;
405
406 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000407}
408
409const ConstString &
410Host::GetVendorString()
411{
412 static ConstString g_vendor;
413 if (!g_vendor)
414 {
Greg Clayton950971f2012-05-12 00:01:21 +0000415 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
416 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
417 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000418 }
419 return g_vendor;
420}
421
422const ConstString &
423Host::GetOSString()
424{
425 static ConstString g_os_string;
426 if (!g_os_string)
427 {
Greg Clayton950971f2012-05-12 00:01:21 +0000428 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
429 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
430 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000431 }
432 return g_os_string;
433}
434
435const ConstString &
436Host::GetTargetTriple()
437{
438 static ConstString g_host_triple;
439 if (!(g_host_triple))
440 {
Greg Clayton950971f2012-05-12 00:01:21 +0000441 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
442 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000443 }
444 return g_host_triple;
445}
446
447lldb::pid_t
448Host::GetCurrentProcessID()
449{
450 return ::getpid();
451}
452
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000453#ifndef _WIN32
454
Greg Clayton2bddd342010-09-07 20:11:56 +0000455lldb::tid_t
456Host::GetCurrentThreadID()
457{
458#if defined (__APPLE__)
Greg Clayton813ddfc2012-09-18 18:19:49 +0000459 // Calling "mach_port_deallocate()" bumps the reference count on the thread
460 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
461 // count.
462 thread_port_t thread_self = mach_thread_self();
463 mach_port_deallocate(mach_task_self(), thread_self);
464 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000465#elif defined(__FreeBSD__)
466 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000467#elif defined(__linux__)
468 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000469#else
470 return lldb::tid_t(pthread_self());
471#endif
472}
473
Jim Ingham372787f2012-04-07 00:00:41 +0000474lldb::thread_t
475Host::GetCurrentThread ()
476{
477 return lldb::thread_t(pthread_self());
478}
479
Greg Clayton2bddd342010-09-07 20:11:56 +0000480const char *
481Host::GetSignalAsCString (int signo)
482{
483 switch (signo)
484 {
485 case SIGHUP: return "SIGHUP"; // 1 hangup
486 case SIGINT: return "SIGINT"; // 2 interrupt
487 case SIGQUIT: return "SIGQUIT"; // 3 quit
488 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
489 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
490 case SIGABRT: return "SIGABRT"; // 6 abort()
Greg Clayton0ddf6be2011-11-04 03:42:38 +0000491#if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE))
Greg Clayton2bddd342010-09-07 20:11:56 +0000492 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000493#endif
494#if !defined(_POSIX_C_SOURCE)
Greg Clayton2bddd342010-09-07 20:11:56 +0000495 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000496#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000497 case SIGFPE: return "SIGFPE"; // 8 floating point exception
498 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
499 case SIGBUS: return "SIGBUS"; // 10 bus error
500 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
501 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
502 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
503 case SIGALRM: return "SIGALRM"; // 14 alarm clock
504 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
505 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
506 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
507 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
508 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
509 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
510 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
511 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
512#if !defined(_POSIX_C_SOURCE)
513 case SIGIO: return "SIGIO"; // 23 input/output possible signal
514#endif
515 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
516 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
517 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
518 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
519#if !defined(_POSIX_C_SOURCE)
520 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
521 case SIGINFO: return "SIGINFO"; // 29 information request
522#endif
523 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
524 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
525 default:
526 break;
527 }
528 return NULL;
529}
530
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000531#endif
532
Greg Clayton2bddd342010-09-07 20:11:56 +0000533void
534Host::WillTerminate ()
535{
536}
537
Sylvestre Ledru59405832013-07-01 08:21:36 +0000538#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000539
Greg Clayton2bddd342010-09-07 20:11:56 +0000540void
541Host::ThreadCreated (const char *thread_name)
542{
543}
Greg Claytone5219662010-12-03 06:02:24 +0000544
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000545void
Greg Claytone5219662010-12-03 06:02:24 +0000546Host::Backtrace (Stream &strm, uint32_t max_frames)
547{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000548 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000549}
550
Greg Clayton85851dd2010-12-04 00:10:17 +0000551size_t
552Host::GetEnvironment (StringList &env)
553{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000554 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000555 return 0;
556}
557
Sylvestre Ledru59405832013-07-01 08:21:36 +0000558#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000559
560struct HostThreadCreateInfo
561{
562 std::string thread_name;
563 thread_func_t thread_fptr;
564 thread_arg_t thread_arg;
565
566 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
567 thread_name (name ? name : ""),
568 thread_fptr (fptr),
569 thread_arg (arg)
570 {
571 }
572};
573
574static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000575#ifdef _WIN32
576__stdcall
577#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000578ThreadCreateTrampoline (thread_arg_t arg)
579{
580 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
581 Host::ThreadCreated (info->thread_name.c_str());
582 thread_func_t thread_fptr = info->thread_fptr;
583 thread_arg_t thread_arg = info->thread_arg;
584
Greg Clayton5160ce52013-03-27 23:08:40 +0000585 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000586 if (log)
587 log->Printf("thread created");
588
589 delete info;
590 return thread_fptr (thread_arg);
591}
592
593lldb::thread_t
594Host::ThreadCreate
595(
596 const char *thread_name,
597 thread_func_t thread_fptr,
598 thread_arg_t thread_arg,
599 Error *error
600)
601{
602 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
603
604 // Host::ThreadCreateTrampoline will delete this pointer for us.
605 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
606
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000607#ifdef _WIN32
608 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
609 int err = thread <= 0 ? GetLastError() : 0;
610#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000611 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000612#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000613 if (err == 0)
614 {
615 if (error)
616 error->Clear();
617 return thread;
618 }
619
620 if (error)
621 error->SetError (err, eErrorTypePOSIX);
622
623 return LLDB_INVALID_HOST_THREAD;
624}
625
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000626#ifndef _WIN32
627
Greg Clayton2bddd342010-09-07 20:11:56 +0000628bool
629Host::ThreadCancel (lldb::thread_t thread, Error *error)
630{
631 int err = ::pthread_cancel (thread);
632 if (error)
633 error->SetError(err, eErrorTypePOSIX);
634 return err == 0;
635}
636
637bool
638Host::ThreadDetach (lldb::thread_t thread, Error *error)
639{
640 int err = ::pthread_detach (thread);
641 if (error)
642 error->SetError(err, eErrorTypePOSIX);
643 return err == 0;
644}
645
646bool
647Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
648{
649 int err = ::pthread_join (thread, thread_result_ptr);
650 if (error)
651 error->SetError(err, eErrorTypePOSIX);
652 return err == 0;
653}
654
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000655lldb::thread_key_t
656Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
657{
658 pthread_key_t key;
659 ::pthread_key_create (&key, callback);
660 return key;
661}
662
663void*
664Host::ThreadLocalStorageGet(lldb::thread_key_t key)
665{
666 return ::pthread_getspecific (key);
667}
668
669void
670Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
671{
672 ::pthread_setspecific (key, value);
673}
674
Matt Kopec62502c62013-05-13 19:33:58 +0000675bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000676Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
677{
Greg Clayton85719632013-02-27 22:51:58 +0000678#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000679 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
680 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
681 if (pid == LLDB_INVALID_PROCESS_ID)
682 pid = curr_pid;
683
684 if (tid == LLDB_INVALID_THREAD_ID)
685 tid = curr_tid;
686
Greg Clayton2bddd342010-09-07 20:11:56 +0000687 // Set the pthread name if possible
688 if (pid == curr_pid && tid == curr_tid)
689 {
Matt Kopec62502c62013-05-13 19:33:58 +0000690 if (::pthread_setname_np (name) == 0)
691 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000692 }
Matt Kopec62502c62013-05-13 19:33:58 +0000693 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000694#elif defined (__FreeBSD__)
695 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
696 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
697 if (pid == LLDB_INVALID_PROCESS_ID)
698 pid = curr_pid;
699
700 if (tid == LLDB_INVALID_THREAD_ID)
701 tid = curr_tid;
702
703 // Set the pthread name if possible
704 if (pid == curr_pid && tid == curr_tid)
705 {
Michael Sartainc2052432013-08-01 18:51:08 +0000706 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000707 return true;
708 }
709 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000710#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000711 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
712 if (fn)
713 {
Matt Kopec62502c62013-05-13 19:33:58 +0000714 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
715 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000716 if (pid == LLDB_INVALID_PROCESS_ID)
717 pid = curr_pid;
718
719 if (tid == LLDB_INVALID_THREAD_ID)
720 tid = curr_tid;
721
Michael Sartainc2052432013-08-01 18:51:08 +0000722 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000723 {
Michael Sartainc2052432013-08-01 18:51:08 +0000724 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
725 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
726
727 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000728 return true;
729 }
730 }
731 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000732#else
733 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000734#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000735}
736
Ed Maste02983be2013-07-25 19:10:32 +0000737bool
738Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
739 const char *thread_name, size_t len)
740{
741 char *namebuf = (char *)::malloc (len + 1);
742
743 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
744 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
745 // off leads to a lot of similar named threads. Go through the thread name
746 // and search for the last dot and use that.
747 const char *lastdot = ::strrchr (thread_name, '.');
748
749 if (lastdot && lastdot != thread_name)
750 thread_name = lastdot + 1;
751 ::strncpy (namebuf, thread_name, len);
752 namebuf[len] = 0;
753
754 int namebuflen = strlen(namebuf);
755 if (namebuflen > 0)
756 {
757 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
758 {
759 // Trim off trailing '(' and '>' characters for a bit more cleanup.
760 namebuflen--;
761 namebuf[namebuflen] = 0;
762 }
763 return Host::SetThreadName (pid, tid, namebuf);
764 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000765
766 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000767 return false;
768}
769
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000770#endif
771
Greg Clayton2bddd342010-09-07 20:11:56 +0000772FileSpec
773Host::GetProgramFileSpec ()
774{
775 static FileSpec g_program_filespec;
776 if (!g_program_filespec)
777 {
778#if defined (__APPLE__)
779 char program_fullpath[PATH_MAX];
780 // If DST is NULL, then return the number of bytes needed.
781 uint32_t len = sizeof(program_fullpath);
782 int err = _NSGetExecutablePath (program_fullpath, &len);
783 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000784 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000785 else if (err == -1)
786 {
787 char *large_program_fullpath = (char *)::malloc (len + 1);
788
789 err = _NSGetExecutablePath (large_program_fullpath, &len);
790 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000791 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000792
793 ::free (large_program_fullpath);
794 }
795#elif defined (__linux__)
796 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000797 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
798 if (len > 0) {
799 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000800 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000801 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000802#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000803 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
804 size_t exe_path_size;
805 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
806 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000807 char *exe_path = new char[exe_path_size];
808 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
809 g_program_filespec.SetFile(exe_path, false);
810 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000811 }
812#endif
813 }
814 return g_program_filespec;
815}
816
Greg Clayton2bddd342010-09-07 20:11:56 +0000817#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000818
819bool
820Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
821{
822 bundle.Clear();
823 return false;
824}
825
Greg Clayton2bddd342010-09-07 20:11:56 +0000826bool
Greg Claytondd36def2010-10-17 22:03:32 +0000827Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000828{
Greg Claytondd36def2010-10-17 22:03:32 +0000829 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000830}
831#endif
832
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000833#ifndef _WIN32
834
Greg Clayton45319462011-02-08 00:35:34 +0000835// Opaque info that tracks a dynamic library that was loaded
836struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000837{
Greg Clayton45319462011-02-08 00:35:34 +0000838 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
839 file_spec (fs),
840 open_options (o),
841 handle (h)
842 {
843 }
844
845 const FileSpec file_spec;
846 uint32_t open_options;
847 void * handle;
848};
849
850void *
851Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
852{
Greg Clayton4272cc72011-02-02 02:24:04 +0000853 char path[PATH_MAX];
854 if (file_spec.GetPath(path, sizeof(path)))
855 {
Greg Clayton45319462011-02-08 00:35:34 +0000856 int mode = 0;
857
858 if (options & eDynamicLibraryOpenOptionLazy)
859 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000860 else
861 mode |= RTLD_NOW;
862
Greg Clayton45319462011-02-08 00:35:34 +0000863
864 if (options & eDynamicLibraryOpenOptionLocal)
865 mode |= RTLD_LOCAL;
866 else
867 mode |= RTLD_GLOBAL;
868
869#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
870 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
871 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000872#endif
Greg Clayton45319462011-02-08 00:35:34 +0000873
874 void * opaque = ::dlopen (path, mode);
875
876 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000877 {
878 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000879 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000880 }
881 else
882 {
883 error.SetErrorString(::dlerror());
884 }
885 }
886 else
887 {
888 error.SetErrorString("failed to extract path");
889 }
Greg Clayton45319462011-02-08 00:35:34 +0000890 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000891}
892
893Error
Greg Clayton45319462011-02-08 00:35:34 +0000894Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000895{
896 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000897 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000898 {
899 error.SetErrorString ("invalid dynamic library handle");
900 }
Greg Clayton45319462011-02-08 00:35:34 +0000901 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000902 {
Greg Clayton45319462011-02-08 00:35:34 +0000903 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
904 if (::dlclose (dylib_info->handle) != 0)
905 {
906 error.SetErrorString(::dlerror());
907 }
908
909 dylib_info->open_options = 0;
910 dylib_info->handle = 0;
911 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000912 }
913 return error;
914}
915
916void *
Greg Clayton45319462011-02-08 00:35:34 +0000917Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000918{
Greg Clayton45319462011-02-08 00:35:34 +0000919 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000920 {
921 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000922 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000923 else
Greg Clayton45319462011-02-08 00:35:34 +0000924 {
925 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
926
927 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
928 if (symbol_addr)
929 {
930#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
931 // This host doesn't support limiting searches to this shared library
932 // so we need to verify that the match came from this shared library
933 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000934 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000935 {
936 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
937 if (match_dylib_spec != dylib_info->file_spec)
938 {
939 char dylib_path[PATH_MAX];
940 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
941 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
942 else
943 error.SetErrorString ("symbol not found");
944 return NULL;
945 }
946 }
947#endif
948 error.Clear();
949 return symbol_addr;
950 }
951 else
952 {
953 error.SetErrorString(::dlerror());
954 }
955 }
956 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000957}
Greg Claytondd36def2010-10-17 22:03:32 +0000958
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000959FileSpec
960Host::GetModuleFileSpecForHostAddress (const void *host_addr)
961{
962 FileSpec module_filespec;
963 Dl_info info;
964 if (::dladdr (host_addr, &info))
965 {
966 if (info.dli_fname)
967 module_filespec.SetFile(info.dli_fname, true);
968 }
969 return module_filespec;
970}
971
972#endif
973
Greg Claytondd36def2010-10-17 22:03:32 +0000974bool
975Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
976{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000977 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000978 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
979 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000980 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000981 // need to be modified to "do the right thing".
982
983 switch (path_type)
984 {
985 case ePathTypeLLDBShlibDir:
986 {
987 static ConstString g_lldb_so_dir;
988 if (!g_lldb_so_dir)
989 {
990 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
991 g_lldb_so_dir = lldb_file_spec.GetDirectory();
992 }
993 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +0000994 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +0000995 }
996 break;
997
998 case ePathTypeSupportExecutableDir:
999 {
1000 static ConstString g_lldb_support_exe_dir;
1001 if (!g_lldb_support_exe_dir)
1002 {
1003 FileSpec lldb_file_spec;
1004 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1005 {
1006 char raw_path[PATH_MAX];
1007 char resolved_path[PATH_MAX];
1008 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1009
1010#if defined (__APPLE__)
1011 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1012 if (framework_pos)
1013 {
1014 framework_pos += strlen("LLDB.framework");
Greg Claytondce502e2011-11-04 03:34:56 +00001015#if !defined (__arm__)
Greg Claytondd36def2010-10-17 22:03:32 +00001016 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001017#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001018 }
1019#endif
1020 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1021 g_lldb_support_exe_dir.SetCString(resolved_path);
1022 }
1023 }
1024 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001025 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001026 }
1027 break;
1028
1029 case ePathTypeHeaderDir:
1030 {
1031 static ConstString g_lldb_headers_dir;
1032 if (!g_lldb_headers_dir)
1033 {
1034#if defined (__APPLE__)
1035 FileSpec lldb_file_spec;
1036 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1037 {
1038 char raw_path[PATH_MAX];
1039 char resolved_path[PATH_MAX];
1040 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1041
1042 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1043 if (framework_pos)
1044 {
1045 framework_pos += strlen("LLDB.framework");
1046 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1047 }
1048 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1049 g_lldb_headers_dir.SetCString(resolved_path);
1050 }
1051#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001052 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001053 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1054#endif
1055 }
1056 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001057 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001058 }
1059 break;
1060
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001061#ifdef LLDB_DISABLE_PYTHON
1062 case ePathTypePythonDir:
1063 return false;
1064#else
1065 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001066 {
Greg Claytondd36def2010-10-17 22:03:32 +00001067 static ConstString g_lldb_python_dir;
1068 if (!g_lldb_python_dir)
1069 {
1070 FileSpec lldb_file_spec;
1071 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1072 {
1073 char raw_path[PATH_MAX];
1074 char resolved_path[PATH_MAX];
1075 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1076
1077#if defined (__APPLE__)
1078 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1079 if (framework_pos)
1080 {
1081 framework_pos += strlen("LLDB.framework");
1082 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1083 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001084#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001085 llvm::SmallString<256> python_version_dir;
1086 llvm::raw_svector_ostream os(python_version_dir);
1087 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1088 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001089
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001090 // We may get our string truncated. Should we protect
1091 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001092
Daniel Maleafa7425d2013-08-06 21:40:08 +00001093 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001094 sizeof(raw_path) - strlen(raw_path) - 1);
1095
Greg Claytondd36def2010-10-17 22:03:32 +00001096#endif
1097 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1098 g_lldb_python_dir.SetCString(resolved_path);
1099 }
1100 }
1101 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001102 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001103 }
1104 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001105#endif
1106
Greg Clayton4272cc72011-02-02 02:24:04 +00001107 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1108 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001109#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001110 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001111 static bool g_lldb_system_plugin_dir_located = false;
1112 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001113 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001114 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001115#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001116 FileSpec lldb_file_spec;
1117 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1118 {
1119 char raw_path[PATH_MAX];
1120 char resolved_path[PATH_MAX];
1121 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1122
1123 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1124 if (framework_pos)
1125 {
1126 framework_pos += strlen("LLDB.framework");
1127 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001128 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1129 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001130 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001131 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001132 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001133#elif defined (__linux__)
1134 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1135 if (lldb_file_spec.Exists())
1136 {
1137 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1138 }
1139#endif // __APPLE__ || __linux__
Greg Clayton4272cc72011-02-02 02:24:04 +00001140 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001141
1142 if (g_lldb_system_plugin_dir)
1143 {
1144 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1145 return true;
1146 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001147#else
1148 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001149 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001150#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001151 }
1152 break;
1153
1154 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1155 {
1156#if defined (__APPLE__)
1157 static ConstString g_lldb_user_plugin_dir;
1158 if (!g_lldb_user_plugin_dir)
1159 {
1160 char user_plugin_path[PATH_MAX];
1161 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1162 user_plugin_path,
1163 sizeof(user_plugin_path)))
1164 {
1165 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1166 }
1167 }
1168 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001169 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001170#elif defined (__linux__)
1171 static ConstString g_lldb_user_plugin_dir;
1172 if (!g_lldb_user_plugin_dir)
1173 {
1174 // XDG Base Directory Specification
1175 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1176 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1177 FileSpec lldb_file_spec;
1178 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1179 if (xdg_data_home && xdg_data_home[0])
1180 {
1181 std::string user_plugin_dir (xdg_data_home);
1182 user_plugin_dir += "/lldb";
1183 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1184 }
1185 else
1186 {
1187 const char *home_dir = getenv("HOME");
1188 if (home_dir && home_dir[0])
1189 {
1190 std::string user_plugin_dir (home_dir);
1191 user_plugin_dir += "/.local/share/lldb";
1192 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1193 }
1194 }
1195
1196 if (lldb_file_spec.Exists())
1197 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1198 }
1199 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001200 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001201#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001202 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001203 return false;
1204 }
Greg Claytondd36def2010-10-17 22:03:32 +00001205 }
1206
1207 return false;
1208}
1209
Greg Clayton1cb64962011-03-24 04:28:38 +00001210
1211bool
1212Host::GetHostname (std::string &s)
1213{
1214 char hostname[PATH_MAX];
1215 hostname[sizeof(hostname) - 1] = '\0';
1216 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1217 {
1218 struct hostent* h = ::gethostbyname (hostname);
1219 if (h)
1220 s.assign (h->h_name);
1221 else
1222 s.assign (hostname);
1223 return true;
1224 }
1225 return false;
1226}
1227
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001228#ifndef _WIN32
1229
Greg Clayton32e0a752011-03-30 18:16:51 +00001230const char *
1231Host::GetUserName (uint32_t uid, std::string &user_name)
1232{
1233 struct passwd user_info;
1234 struct passwd *user_info_ptr = &user_info;
1235 char user_buffer[PATH_MAX];
1236 size_t user_buffer_size = sizeof(user_buffer);
1237 if (::getpwuid_r (uid,
1238 &user_info,
1239 user_buffer,
1240 user_buffer_size,
1241 &user_info_ptr) == 0)
1242 {
1243 if (user_info_ptr)
1244 {
1245 user_name.assign (user_info_ptr->pw_name);
1246 return user_name.c_str();
1247 }
1248 }
1249 user_name.clear();
1250 return NULL;
1251}
1252
1253const char *
1254Host::GetGroupName (uint32_t gid, std::string &group_name)
1255{
1256 char group_buffer[PATH_MAX];
1257 size_t group_buffer_size = sizeof(group_buffer);
1258 struct group group_info;
1259 struct group *group_info_ptr = &group_info;
1260 // Try the threadsafe version first
1261 if (::getgrgid_r (gid,
1262 &group_info,
1263 group_buffer,
1264 group_buffer_size,
1265 &group_info_ptr) == 0)
1266 {
1267 if (group_info_ptr)
1268 {
1269 group_name.assign (group_info_ptr->gr_name);
1270 return group_name.c_str();
1271 }
1272 }
1273 else
1274 {
1275 // The threadsafe version isn't currently working
1276 // for me on darwin, but the non-threadsafe version
1277 // is, so I am calling it below.
1278 group_info_ptr = ::getgrgid (gid);
1279 if (group_info_ptr)
1280 {
1281 group_name.assign (group_info_ptr->gr_name);
1282 return group_name.c_str();
1283 }
1284 }
1285 group_name.clear();
1286 return NULL;
1287}
1288
Han Ming Ong84647042012-02-25 01:07:38 +00001289uint32_t
1290Host::GetUserID ()
1291{
1292 return getuid();
1293}
1294
1295uint32_t
1296Host::GetGroupID ()
1297{
1298 return getgid();
1299}
1300
1301uint32_t
1302Host::GetEffectiveUserID ()
1303{
1304 return geteuid();
1305}
1306
1307uint32_t
1308Host::GetEffectiveGroupID ()
1309{
1310 return getegid();
1311}
1312
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001313#endif
1314
1315#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1316bool
1317Host::GetOSBuildString (std::string &s)
1318{
1319 s.clear();
1320 return false;
1321}
1322
1323bool
1324Host::GetOSKernelDescription (std::string &s)
1325{
1326 s.clear();
1327 return false;
1328}
1329#endif
1330
Ed Maste47e575e2013-08-29 18:44:27 +00001331#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001332uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001333Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001334{
1335 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001336 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001337}
1338
Greg Claytone996fd32011-03-08 22:40:15 +00001339bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001340Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001341{
Greg Claytone996fd32011-03-08 22:40:15 +00001342 process_info.Clear();
1343 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001344}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001345#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001346
Matt Kopec085d6ce2013-05-31 22:00:07 +00001347#if !defined(__linux__)
1348bool
1349Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1350{
1351 return false;
1352}
1353#endif
1354
Sean Callananc0a6e062011-10-27 21:22:25 +00001355lldb::TargetSP
1356Host::GetDummyTarget (lldb_private::Debugger &debugger)
1357{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001358 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001359
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001360 // FIXME: Maybe the dummy target should be per-Debugger
1361 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1362 {
1363 ArchSpec arch(Target::GetDefaultArchitecture());
1364 if (!arch.IsValid())
1365 arch = Host::GetArchitecture ();
1366 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001367 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001368 arch.GetTriple().getTriple().c_str(),
1369 false,
1370 NULL,
1371 g_dummy_target_sp);
1372 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001373
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001374 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001375}
1376
Greg Claytond1cf11a2012-04-14 01:42:46 +00001377struct ShellInfo
1378{
1379 ShellInfo () :
1380 process_reaped (false),
1381 can_delete (false),
1382 pid (LLDB_INVALID_PROCESS_ID),
1383 signo(-1),
1384 status(-1)
1385 {
1386 }
1387
1388 lldb_private::Predicate<bool> process_reaped;
1389 lldb_private::Predicate<bool> can_delete;
1390 lldb::pid_t pid;
1391 int signo;
1392 int status;
1393};
1394
1395static bool
1396MonitorShellCommand (void *callback_baton,
1397 lldb::pid_t pid,
1398 bool exited, // True if the process did exit
1399 int signo, // Zero for no signal
1400 int status) // Exit value of process if signal is zero
1401{
1402 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1403 shell_info->pid = pid;
1404 shell_info->signo = signo;
1405 shell_info->status = status;
1406 // Let the thread running Host::RunShellCommand() know that the process
1407 // exited and that ShellInfo has been filled in by broadcasting to it
1408 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1409 // Now wait for a handshake back from that thread running Host::RunShellCommand
1410 // so we know that we can delete shell_info_ptr
1411 shell_info->can_delete.WaitForValueEqualTo(true);
1412 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1413 usleep(1000);
1414 // Now delete the shell info that was passed into this function
1415 delete shell_info;
1416 return true;
1417}
1418
1419Error
1420Host::RunShellCommand (const char *command,
1421 const char *working_dir,
1422 int *status_ptr,
1423 int *signo_ptr,
1424 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001425 uint32_t timeout_sec,
1426 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001427{
1428 Error error;
1429 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001430 if (shell && shell[0])
1431 {
1432 // Run the command in a shell
1433 launch_info.SetShell(shell);
1434 launch_info.GetArguments().AppendArgument(command);
1435 const bool localhost = true;
1436 const bool will_debug = false;
1437 const bool first_arg_is_full_shell_command = true;
1438 launch_info.ConvertArgumentsForLaunchingInShell (error,
1439 localhost,
1440 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001441 first_arg_is_full_shell_command,
1442 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001443 }
1444 else
1445 {
1446 // No shell, just run it
1447 Args args (command);
1448 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001449 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001450 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001451
1452 if (working_dir)
1453 launch_info.SetWorkingDirectory(working_dir);
1454 char output_file_path_buffer[L_tmpnam];
1455 const char *output_file_path = NULL;
1456 if (command_output_ptr)
1457 {
1458 // Create a temporary file to get the stdout/stderr and redirect the
1459 // output of the command into this file. We will later read this file
1460 // if all goes well and fill the data into "command_output_ptr"
1461 output_file_path = ::tmpnam(output_file_path_buffer);
1462 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1463 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001464 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001465 }
1466 else
1467 {
1468 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1469 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1470 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1471 }
1472
1473 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001474 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001475
1476 const bool monitor_signals = false;
1477 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1478
1479 error = LaunchProcess (launch_info);
1480 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001481
1482 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1483 error.SetErrorString("failed to get process ID");
1484
1485 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001486 {
1487 // The process successfully launched, so we can defer ownership of
1488 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001489 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001490 // doesn't need to delete the ShellInfo anymore.
1491 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001492 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001493 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001494 if (timeout_sec > 0) {
1495 timeout_time.OffsetWithSeconds(timeout_sec);
1496 timeout_ptr = &timeout_time;
1497 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001498 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001499 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001500 if (timed_out)
1501 {
1502 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001503
Greg Claytond1cf11a2012-04-14 01:42:46 +00001504 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001505 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001506 // Wait for the monitor callback to get the message
1507 timeout_time = TimeValue::Now();
1508 timeout_time.OffsetWithSeconds(1);
1509 timed_out = false;
1510 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1511 }
1512 else
1513 {
1514 if (status_ptr)
1515 *status_ptr = shell_info->status;
1516
1517 if (signo_ptr)
1518 *signo_ptr = shell_info->signo;
1519
1520 if (command_output_ptr)
1521 {
1522 command_output_ptr->clear();
1523 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1524 uint64_t file_size = file_spec.GetByteSize();
1525 if (file_size > 0)
1526 {
1527 if (file_size > command_output_ptr->max_size())
1528 {
1529 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1530 }
1531 else
1532 {
1533 command_output_ptr->resize(file_size);
1534 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1535 }
1536 }
1537 }
1538 }
1539 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1540 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001541
1542 if (output_file_path)
1543 ::unlink (output_file_path);
1544 // Handshake with the monitor thread, or just let it know in advance that
1545 // it can delete "shell_info" in case we timed out and were not able to kill
1546 // the process...
1547 return error;
1548}
1549
Daniel Malea4244cbd2013-08-27 20:58:59 +00001550#if defined(__linux__) or defined(__FreeBSD__)
1551// The functions below implement process launching via posix_spawn() for Linux
1552// and FreeBSD.
1553
1554// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1555static Error
1556LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1557{
1558 Error error;
1559 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1560
1561 assert(exe_path);
1562 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1563
1564 posix_spawnattr_t attr;
1565
1566 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1567 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1568 if (error.Fail())
1569 return error;
1570
1571 // Make a quick class that will cleanup the posix spawn attributes in case
1572 // we return in the middle of this function.
1573 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1574
1575 sigset_t no_signals;
1576 sigset_t all_signals;
1577 sigemptyset (&no_signals);
1578 sigfillset (&all_signals);
1579 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1580 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1581
1582 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1583
1584 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1585 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1586 if (error.Fail())
1587 return error;
1588
1589 const size_t num_file_actions = launch_info.GetNumFileActions ();
1590 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1591 // Make a quick class that will cleanup the posix spawn attributes in case
1592 // we return in the middle of this function.
1593 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1594 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1595
1596 if (num_file_actions > 0)
1597 {
1598 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1599 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1600 if (error.Fail())
1601 return error;
1602
1603 file_action_ptr = &file_actions;
1604 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1605
1606 for (size_t i = 0; i < num_file_actions; ++i)
1607 {
1608 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1609 if (launch_file_action &&
1610 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1611 launch_file_action,
1612 log,
1613 error))
1614 return error;
1615 }
1616 }
1617
1618 // Change working directory if neccessary.
1619 char current_dir[PATH_MAX];
1620 current_dir[0] = '\0';
1621
1622 const char *working_dir = launch_info.GetWorkingDirectory();
1623 if (working_dir != NULL)
1624 {
1625 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1626 {
1627 error.SetError(errno, eErrorTypePOSIX);
1628 error.LogIfError(log, "unable to save the current directory");
1629 return error;
1630 }
1631
1632 if (::chdir(working_dir) == -1)
1633 {
1634 error.SetError(errno, eErrorTypePOSIX);
1635 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1636 return error;
1637 }
1638 }
1639
1640 const char *tmp_argv[2];
1641 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1642 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1643
1644 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1645 // We must pass argv into posix_spawnp and it must contain at least two items -
1646 // pointer to an executable and NULL.
1647 if (argv == NULL)
1648 {
1649 tmp_argv[0] = exe_path;
1650 tmp_argv[1] = NULL;
1651 argv = (char * const*)tmp_argv;
1652 }
1653
1654 error.SetError (::posix_spawnp (&pid,
1655 exe_path,
1656 (num_file_actions > 0) ? &file_actions : NULL,
1657 &attr,
1658 argv,
1659 envp),
1660 eErrorTypePOSIX);
1661
1662 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1663 pid, exe_path, file_action_ptr, &attr, argv, envp);
1664
1665 // Change back the current directory.
1666 // NOTE: do not override previously established error from posix_spawnp.
1667 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1668 {
1669 error.SetError(errno, eErrorTypePOSIX);
1670 error.LogIfError(log, "unable to change current directory back to %s",
1671 current_dir);
1672 }
1673
1674 return error;
1675}
1676
1677
1678Error
1679Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1680{
1681 Error error;
1682 char exe_path[PATH_MAX];
1683
1684 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1685
1686 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1687
1688 FileSpec exe_spec(launch_info.GetExecutableFile());
1689
1690 FileSpec::FileType file_type = exe_spec.GetFileType();
1691 if (file_type != FileSpec::eFileTypeRegular)
1692 {
1693 lldb::ModuleSP exe_module_sp;
1694 error = host_platform_sp->ResolveExecutable (exe_spec,
1695 arch_spec,
1696 exe_module_sp,
1697 NULL);
1698
1699 if (error.Fail())
1700 return error;
1701
1702 if (exe_module_sp)
1703 exe_spec = exe_module_sp->GetFileSpec();
1704 }
1705
1706 if (exe_spec.Exists())
1707 {
1708 exe_spec.GetPath (exe_path, sizeof(exe_path));
1709 }
1710 else
1711 {
1712 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1713 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1714 return error;
1715 }
1716
1717 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1718
1719 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1720
1721 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1722
1723 if (pid != LLDB_INVALID_PROCESS_ID)
1724 {
1725 // If all went well, then set the process ID into the launch info
1726 launch_info.SetProcessID(pid);
1727
1728 // Make sure we reap any processes we spawn or we will have zombies.
1729 if (!launch_info.MonitorProcess())
1730 {
1731 const bool monitor_signals = false;
1732 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1733 NULL,
1734 pid,
1735 monitor_signals);
1736 }
1737 }
1738 else
1739 {
1740 // Invalid process ID, something didn't go well
1741 if (error.Success())
1742 error.SetErrorString ("process launch failed for unknown reasons");
1743 }
1744 return error;
1745}
1746
1747#endif // defined(__linux__) or defined(__FreeBSD__)
1748
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001749#ifndef _WIN32
1750
1751size_t
1752Host::GetPageSize()
1753{
1754 return ::getpagesize();
1755}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001756
Greg Claytone3e3fee2013-02-17 20:46:30 +00001757uint32_t
1758Host::GetNumberCPUS ()
1759{
1760 static uint32_t g_num_cores = UINT32_MAX;
1761 if (g_num_cores == UINT32_MAX)
1762 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001763#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001764
1765 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001766
Greg Claytone3e3fee2013-02-17 20:46:30 +00001767#else
1768
1769 // Assume POSIX support if a host specific case has not been supplied above
1770 g_num_cores = 0;
1771 int num_cores = 0;
1772 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001773#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001774 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001775#else
1776 int mib[] = { CTL_HW, HW_NCPU };
1777#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001778
1779 /* get the number of CPUs from the system */
1780 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1781 {
1782 g_num_cores = num_cores;
1783 }
1784 else
1785 {
1786 mib[1] = HW_NCPU;
1787 num_cores_len = sizeof(num_cores);
1788 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1789 {
1790 if (num_cores > 0)
1791 g_num_cores = num_cores;
1792 }
1793 }
1794#endif
1795 }
1796 return g_num_cores;
1797}
1798
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001799void
1800Host::Kill(lldb::pid_t pid, int signo)
1801{
1802 ::kill(pid, signo);
1803}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001804
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001805#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001806
Johnny Chen8f3d8382011-08-02 20:52:42 +00001807#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001808bool
Greg Clayton3b147632010-12-18 01:54:34 +00001809Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001810{
1811 return false;
1812}
Greg Claytondd36def2010-10-17 22:03:32 +00001813
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001814void
1815Host::SetCrashDescriptionWithFormat (const char *format, ...)
1816{
1817}
1818
1819void
1820Host::SetCrashDescription (const char *description)
1821{
1822}
Greg Claytondd36def2010-10-17 22:03:32 +00001823
1824lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001825Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001826{
1827 return LLDB_INVALID_PROCESS_ID;
1828}
1829
Greg Claytonfbb76342013-11-20 21:07:01 +00001830#endif
1831
1832
1833#ifdef LLDB_DISABLE_POSIX
1834
1835Error
1836Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001837{
Greg Claytonfbb76342013-11-20 21:07:01 +00001838 Error error;
1839 error.SetErrorString("%s in not implemented on this host", __PRETTY_FUNCTION__);
1840 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001841}
Greg Claytonfbb76342013-11-20 21:07:01 +00001842
1843Error
1844Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1845{
1846 Error error;
1847 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1848 return error;
1849}
1850
1851Error
1852Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1853{
1854 Error error;
1855 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1856 return error;
1857}
1858
1859Error
1860Host::Symlink (const char *src, const char *dst)
1861{
1862 Error error;
1863 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1864 return error;
1865}
1866
1867Error
1868Host::Readlink (const char *path, char *buf, size_t buf_len)
1869{
1870 Error error;
1871 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1872 return error;
1873}
1874
1875Error
1876Host::Unlink (const char *path)
1877{
1878 Error error;
1879 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1880 return error;
1881}
1882
1883#else
1884
1885Error
1886Host::MakeDirectory (const char* path, uint32_t file_permissions)
1887{
1888 Error error;
1889 if (::mkdir(path, file_permissions) != 0)
1890 error.SetErrorToErrno();
1891 return error;
1892}
1893
1894Error
1895Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1896{
1897 Error error;
1898 struct stat file_stats;
1899 if (::stat (path, &file_stats) == 0)
1900 {
1901 // The bits in "st_mode" currently match the definitions
1902 // for the file mode bits in unix.
1903 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1904 }
1905 else
1906 {
1907 error.SetErrorToErrno();
1908 }
1909 return error;
1910}
1911
1912Error
1913Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1914{
1915 Error error;
1916 if (::chmod(path, file_permissions) != 0)
1917 error.SetErrorToErrno();
1918 return error;
1919}
1920
1921Error
1922Host::Symlink (const char *src, const char *dst)
1923{
1924 Error error;
1925 if (::symlink(dst, src) == -1)
1926 error.SetErrorToErrno();
1927 return error;
1928}
1929
1930Error
1931Host::Unlink (const char *path)
1932{
1933 Error error;
1934 if (::unlink(path) == -1)
1935 error.SetErrorToErrno();
1936 return error;
1937}
1938
1939Error
1940Host::Readlink (const char *path, char *buf, size_t buf_len)
1941{
1942 Error error;
1943 ssize_t count = ::readlink(path, buf, buf_len);
1944 if (count < 0)
1945 error.SetErrorToErrno();
1946 else if (count < (buf_len-1))
1947 buf[count] = '\0'; // Success
1948 else
1949 error.SetErrorString("'buf' buffer is too small to contain link contents");
1950 return error;
1951}
1952
1953
Greg Clayton2bddd342010-09-07 20:11:56 +00001954#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00001955
1956typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
1957FDToFileMap& GetFDToFileMap()
1958{
1959 static FDToFileMap g_fd2filemap;
1960 return g_fd2filemap;
1961}
1962
1963lldb::user_id_t
1964Host::OpenFile (const FileSpec& file_spec,
1965 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00001966 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00001967 Error &error)
1968{
1969 std::string path (file_spec.GetPath());
1970 if (path.empty())
1971 {
1972 error.SetErrorString("empty path");
1973 return UINT64_MAX;
1974 }
1975 FileSP file_sp(new File());
1976 error = file_sp->Open(path.c_str(),flags,mode);
1977 if (file_sp->IsValid() == false)
1978 return UINT64_MAX;
1979 lldb::user_id_t fd = file_sp->GetDescriptor();
1980 GetFDToFileMap()[fd] = file_sp;
1981 return fd;
1982}
1983
1984bool
1985Host::CloseFile (lldb::user_id_t fd, Error &error)
1986{
1987 if (fd == UINT64_MAX)
1988 {
1989 error.SetErrorString ("invalid file descriptor");
1990 return false;
1991 }
1992 FDToFileMap& file_map = GetFDToFileMap();
1993 FDToFileMap::iterator pos = file_map.find(fd);
1994 if (pos == file_map.end())
1995 {
1996 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1997 return false;
1998 }
1999 FileSP file_sp = pos->second;
2000 if (!file_sp)
2001 {
2002 error.SetErrorString ("invalid host backing file");
2003 return false;
2004 }
2005 error = file_sp->Close();
2006 file_map.erase(pos);
2007 return error.Success();
2008}
2009
2010uint64_t
2011Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2012{
2013 if (fd == UINT64_MAX)
2014 {
2015 error.SetErrorString ("invalid file descriptor");
2016 return UINT64_MAX;
2017 }
2018 FDToFileMap& file_map = GetFDToFileMap();
2019 FDToFileMap::iterator pos = file_map.find(fd);
2020 if (pos == file_map.end())
2021 {
2022 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2023 return false;
2024 }
2025 FileSP file_sp = pos->second;
2026 if (!file_sp)
2027 {
2028 error.SetErrorString ("invalid host backing file");
2029 return UINT64_MAX;
2030 }
2031 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2032 return UINT64_MAX;
2033 size_t bytes_written = src_len;
2034 error = file_sp->Write(src, bytes_written);
2035 if (error.Fail())
2036 return UINT64_MAX;
2037 return bytes_written;
2038}
2039
2040uint64_t
2041Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2042{
2043 if (fd == UINT64_MAX)
2044 {
2045 error.SetErrorString ("invalid file descriptor");
2046 return UINT64_MAX;
2047 }
2048 FDToFileMap& file_map = GetFDToFileMap();
2049 FDToFileMap::iterator pos = file_map.find(fd);
2050 if (pos == file_map.end())
2051 {
2052 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2053 return false;
2054 }
2055 FileSP file_sp = pos->second;
2056 if (!file_sp)
2057 {
2058 error.SetErrorString ("invalid host backing file");
2059 return UINT64_MAX;
2060 }
2061 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2062 return UINT64_MAX;
2063 size_t bytes_read = dst_len;
2064 error = file_sp->Read(dst ,bytes_read);
2065 if (error.Fail())
2066 return UINT64_MAX;
2067 return bytes_read;
2068}
2069
2070lldb::user_id_t
2071Host::GetFileSize (const FileSpec& file_spec)
2072{
2073 return file_spec.GetByteSize();
2074}
2075
2076bool
2077Host::GetFileExists (const FileSpec& file_spec)
2078{
2079 return file_spec.Exists();
2080}
2081
2082bool
2083Host::CalculateMD5 (const FileSpec& file_spec,
2084 uint64_t &low,
2085 uint64_t &high)
2086{
2087#if defined (__APPLE__)
2088 StreamString md5_cmd_line;
2089 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2090 std::string hash_string;
2091 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2092 if (err.Fail())
2093 return false;
2094 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2095 // if the output is any other length it is probably wrong
2096 if (hash_string.size() != 32)
2097 return false;
2098 std::string part1(hash_string,0,16);
2099 std::string part2(hash_string,16);
2100 const char* part1_cstr = part1.c_str();
2101 const char* part2_cstr = part2.c_str();
2102 high = ::strtoull(part1_cstr, NULL, 16);
2103 low = ::strtoull(part2_cstr, NULL, 16);
2104 return true;
2105#else
2106 // your own MD5 implementation here
2107 return false;
2108#endif
2109}