blob: 2a34caa1901ab296c7d0b96f4e6e9a9ea228d2d7 [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>
Jim Ingham1a7ee702013-11-22 00:51:36 +000037#include <AvailabilityMacros.h>
Ed Maste8b006c62013-06-25 18:58:11 +000038#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000039
Ed Maste8b006c62013-06-25 18:58:11 +000040#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000041#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000042#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000043#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000044#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000045
Ed Maste8b006c62013-06-25 18:58:11 +000046#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000047#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000048#endif
49
Greg Clayton2bddd342010-09-07 20:11:56 +000050#include "lldb/Host/Host.h"
51#include "lldb/Core/ArchSpec.h"
52#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000053#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000054#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000055#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000056#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000057#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000058#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000059#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000060#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000061#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000062#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000063#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000064#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000065#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000066
Daniel Maleafa7425d2013-08-06 21:40:08 +000067#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000068#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000069#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000070
Greg Clayton32e0a752011-03-30 18:16:51 +000071
Greg Clayton2bddd342010-09-07 20:11:56 +000072using namespace lldb;
73using namespace lldb_private;
74
Greg Claytone4e45922011-11-16 05:37:56 +000075
Virgile Bellob2f1fb22013-08-23 12:44:05 +000076#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000077struct MonitorInfo
78{
79 lldb::pid_t pid; // The process ID to monitor
80 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
81 void *callback_baton; // The callback baton for the callback function
82 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
83};
84
Virgile Bellob2f1fb22013-08-23 12:44:05 +000085static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000086MonitorChildProcessThreadFunction (void *arg);
87
88lldb::thread_t
89Host::StartMonitoringChildProcess
90(
91 Host::MonitorChildProcessCallback callback,
92 void *callback_baton,
93 lldb::pid_t pid,
94 bool monitor_signals
95)
96{
97 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +000098 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +000099
Greg Claytone4e45922011-11-16 05:37:56 +0000100 info_ptr->pid = pid;
101 info_ptr->callback = callback;
102 info_ptr->callback_baton = callback_baton;
103 info_ptr->monitor_signals = monitor_signals;
104
105 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000106 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000107 thread = ThreadCreate (thread_name,
108 MonitorChildProcessThreadFunction,
109 info_ptr,
110 NULL);
111
Greg Clayton2bddd342010-09-07 20:11:56 +0000112 return thread;
113}
114
115//------------------------------------------------------------------
116// Scoped class that will disable thread canceling when it is
117// constructed, and exception safely restore the previous value it
118// when it goes out of scope.
119//------------------------------------------------------------------
120class ScopedPThreadCancelDisabler
121{
122public:
123 ScopedPThreadCancelDisabler()
124 {
125 // Disable the ability for this thread to be cancelled
126 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
127 if (err != 0)
128 m_old_state = -1;
129
130 }
131
132 ~ScopedPThreadCancelDisabler()
133 {
134 // Restore the ability for this thread to be cancelled to what it
135 // previously was.
136 if (m_old_state != -1)
137 ::pthread_setcancelstate (m_old_state, 0);
138 }
139private:
140 int m_old_state; // Save the old cancelability state.
141};
142
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000143static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000144MonitorChildProcessThreadFunction (void *arg)
145{
Greg Clayton5160ce52013-03-27 23:08:40 +0000146 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000147 const char *function = __FUNCTION__;
148 if (log)
149 log->Printf ("%s (arg = %p) thread starting...", function, arg);
150
151 MonitorInfo *info = (MonitorInfo *)arg;
152
153 const Host::MonitorChildProcessCallback callback = info->callback;
154 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000155 const bool monitor_signals = info->monitor_signals;
156
Daniel Malea4244cbd2013-08-27 20:58:59 +0000157 assert (info->pid <= UINT32_MAX);
158 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
159
Greg Clayton2bddd342010-09-07 20:11:56 +0000160 delete info;
161
162 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000163#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000164 #define __WALL 0
165#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000166 const int options = __WALL;
167
Greg Clayton2bddd342010-09-07 20:11:56 +0000168 while (1)
169 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000170 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000171 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000172 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000173
174 // Wait for all child processes
175 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000176 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000177 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000178 ::pthread_testcancel ();
179
180 if (wait_pid == -1)
181 {
182 if (errno == EINTR)
183 continue;
184 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000185 {
186 if (log)
187 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000188 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000189 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000190 }
Matt Kopec650648f2013-01-08 16:30:18 +0000191 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000192 {
193 bool exited = false;
194 int signal = 0;
195 int exit_status = 0;
196 const char *status_cstr = NULL;
197 if (WIFSTOPPED(status))
198 {
199 signal = WSTOPSIG(status);
200 status_cstr = "STOPPED";
201 }
202 else if (WIFEXITED(status))
203 {
204 exit_status = WEXITSTATUS(status);
205 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000206 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000207 }
208 else if (WIFSIGNALED(status))
209 {
210 signal = WTERMSIG(status);
211 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000212 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000213 exited = true;
214 exit_status = -1;
215 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000216 }
217 else
218 {
Johnny Chen44805302011-07-19 19:48:13 +0000219 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000220 }
221
222 // Scope for pthread_cancel_disabler
223 {
224 ScopedPThreadCancelDisabler pthread_cancel_disabler;
225
Caroline Tice20ad3c42010-10-29 21:48:37 +0000226 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000227 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000228 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 +0000229 function,
230 wait_pid,
231 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000232 pid,
233 status,
234 status_cstr,
235 signal,
236 exit_status);
237
238 if (exited || (signal != 0 && monitor_signals))
239 {
Greg Claytone4e45922011-11-16 05:37:56 +0000240 bool callback_return = false;
241 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000242 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000243
244 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000245 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000246 {
247 if (log)
248 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000249 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000250 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000251 // If the callback returns true, it means this process should
252 // exit
253 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000254 {
255 if (log)
256 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000257 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000258 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000259 }
260 }
261 }
262 }
263
Caroline Tice20ad3c42010-10-29 21:48:37 +0000264 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000265 if (log)
266 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
267
268 return NULL;
269}
270
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000271#endif // #if !defined (__APPLE__) && !defined (_WIN32)
272
273#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000274
275void
276Host::SystemLog (SystemLogType type, const char *format, va_list args)
277{
278 vfprintf (stderr, format, args);
279}
280
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000281#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000282
Greg Claytone38a5ed2012-01-05 03:57:59 +0000283void
284Host::SystemLog (SystemLogType type, const char *format, ...)
285{
286 va_list args;
287 va_start (args, format);
288 SystemLog (type, format, args);
289 va_end (args);
290}
291
Greg Clayton2bddd342010-09-07 20:11:56 +0000292const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000293Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000294{
Greg Clayton514487e2011-02-15 21:59:32 +0000295 static bool g_supports_32 = false;
296 static bool g_supports_64 = false;
297 static ArchSpec g_host_arch_32;
298 static ArchSpec g_host_arch_64;
299
Greg Clayton2bddd342010-09-07 20:11:56 +0000300#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000301
302 // Apple is different in that it can support both 32 and 64 bit executables
303 // in the same operating system running concurrently. Here we detect the
304 // correct host architectures for both 32 and 64 bit including if 64 bit
305 // executables are supported on the system.
306
307 if (g_supports_32 == false && g_supports_64 == false)
308 {
309 // All apple systems support 32 bit execution.
310 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000311 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000312 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000313 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000314 ArchSpec host_arch;
315 // These will tell us about the kernel architecture, which even on a 64
316 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000317 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
318 {
Greg Clayton514487e2011-02-15 21:59:32 +0000319 len = sizeof (cpusubtype);
320 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
321 cpusubtype = CPU_TYPE_ANY;
322
Greg Clayton2bddd342010-09-07 20:11:56 +0000323 len = sizeof (is_64_bit_capable);
324 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
325 {
326 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000327 g_supports_64 = true;
328 }
329
330 if (is_64_bit_capable)
331 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000332#if defined (__i386__) || defined (__x86_64__)
333 if (cpusubtype == CPU_SUBTYPE_486)
334 cpusubtype = CPU_SUBTYPE_I386_ALL;
335#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000336 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000337 {
Greg Clayton514487e2011-02-15 21:59:32 +0000338 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000339 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
340 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000341 }
342 else
343 {
344 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000345 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000346 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000347 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000348 }
349 }
Greg Clayton514487e2011-02-15 21:59:32 +0000350 else
351 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000352 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000353 g_host_arch_64.Clear();
354 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000355 }
Greg Clayton514487e2011-02-15 21:59:32 +0000356 }
357
358#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000359
Greg Clayton514487e2011-02-15 21:59:32 +0000360 if (g_supports_32 == false && g_supports_64 == false)
361 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000362 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000363
Stephen Wilsonbd588712011-02-24 19:15:09 +0000364 g_host_arch_32.Clear();
365 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000366
Greg Claytonb29e6c62012-10-11 17:38:58 +0000367 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
368 // for the default triple. It's probably an artifact of config.guess.
369 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
370 triple.setVendorName("");
371
Stephen Wilsonbd588712011-02-24 19:15:09 +0000372 switch (triple.getArch())
373 {
374 default:
375 g_host_arch_32.SetTriple(triple);
376 g_supports_32 = true;
377 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000378
Stephen Wilsonbd588712011-02-24 19:15:09 +0000379 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000380 g_host_arch_64.SetTriple(triple);
381 g_supports_64 = true;
382 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
383 g_supports_32 = true;
384 break;
385
Stephen Wilsonbd588712011-02-24 19:15:09 +0000386 case llvm::Triple::sparcv9:
387 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000388 g_host_arch_64.SetTriple(triple);
389 g_supports_64 = true;
390 break;
391 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000392
393 g_supports_32 = g_host_arch_32.IsValid();
394 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000395 }
Greg Clayton514487e2011-02-15 21:59:32 +0000396
397#endif // #else for #if defined (__APPLE__)
398
399 if (arch_kind == eSystemDefaultArchitecture32)
400 return g_host_arch_32;
401 else if (arch_kind == eSystemDefaultArchitecture64)
402 return g_host_arch_64;
403
404 if (g_supports_64)
405 return g_host_arch_64;
406
407 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000408}
409
410const ConstString &
411Host::GetVendorString()
412{
413 static ConstString g_vendor;
414 if (!g_vendor)
415 {
Greg Clayton950971f2012-05-12 00:01:21 +0000416 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
417 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
418 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000419 }
420 return g_vendor;
421}
422
423const ConstString &
424Host::GetOSString()
425{
426 static ConstString g_os_string;
427 if (!g_os_string)
428 {
Greg Clayton950971f2012-05-12 00:01:21 +0000429 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
430 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
431 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000432 }
433 return g_os_string;
434}
435
436const ConstString &
437Host::GetTargetTriple()
438{
439 static ConstString g_host_triple;
440 if (!(g_host_triple))
441 {
Greg Clayton950971f2012-05-12 00:01:21 +0000442 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
443 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000444 }
445 return g_host_triple;
446}
447
448lldb::pid_t
449Host::GetCurrentProcessID()
450{
451 return ::getpid();
452}
453
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000454#ifndef _WIN32
455
Greg Clayton2bddd342010-09-07 20:11:56 +0000456lldb::tid_t
457Host::GetCurrentThreadID()
458{
459#if defined (__APPLE__)
Greg Clayton813ddfc2012-09-18 18:19:49 +0000460 // Calling "mach_port_deallocate()" bumps the reference count on the thread
461 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
462 // count.
463 thread_port_t thread_self = mach_thread_self();
464 mach_port_deallocate(mach_task_self(), thread_self);
465 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000466#elif defined(__FreeBSD__)
467 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000468#elif defined(__linux__)
469 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000470#else
471 return lldb::tid_t(pthread_self());
472#endif
473}
474
Jim Ingham372787f2012-04-07 00:00:41 +0000475lldb::thread_t
476Host::GetCurrentThread ()
477{
478 return lldb::thread_t(pthread_self());
479}
480
Greg Clayton2bddd342010-09-07 20:11:56 +0000481const char *
482Host::GetSignalAsCString (int signo)
483{
484 switch (signo)
485 {
486 case SIGHUP: return "SIGHUP"; // 1 hangup
487 case SIGINT: return "SIGINT"; // 2 interrupt
488 case SIGQUIT: return "SIGQUIT"; // 3 quit
489 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
490 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
491 case SIGABRT: return "SIGABRT"; // 6 abort()
Greg Clayton0ddf6be2011-11-04 03:42:38 +0000492#if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE))
Greg Clayton2bddd342010-09-07 20:11:56 +0000493 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000494#endif
495#if !defined(_POSIX_C_SOURCE)
Greg Clayton2bddd342010-09-07 20:11:56 +0000496 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000497#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000498 case SIGFPE: return "SIGFPE"; // 8 floating point exception
499 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
500 case SIGBUS: return "SIGBUS"; // 10 bus error
501 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
502 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
503 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
504 case SIGALRM: return "SIGALRM"; // 14 alarm clock
505 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
506 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
507 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
508 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
509 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
510 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
511 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
512 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
513#if !defined(_POSIX_C_SOURCE)
514 case SIGIO: return "SIGIO"; // 23 input/output possible signal
515#endif
516 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
517 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
518 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
519 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
520#if !defined(_POSIX_C_SOURCE)
521 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
522 case SIGINFO: return "SIGINFO"; // 29 information request
523#endif
524 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
525 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
526 default:
527 break;
528 }
529 return NULL;
530}
531
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000532#endif
533
Greg Clayton2bddd342010-09-07 20:11:56 +0000534void
535Host::WillTerminate ()
536{
537}
538
Sylvestre Ledru59405832013-07-01 08:21:36 +0000539#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000540
Greg Clayton2bddd342010-09-07 20:11:56 +0000541void
542Host::ThreadCreated (const char *thread_name)
543{
544}
Greg Claytone5219662010-12-03 06:02:24 +0000545
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000546void
Greg Claytone5219662010-12-03 06:02:24 +0000547Host::Backtrace (Stream &strm, uint32_t max_frames)
548{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000549 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000550}
551
Greg Clayton85851dd2010-12-04 00:10:17 +0000552size_t
553Host::GetEnvironment (StringList &env)
554{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000555 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000556 return 0;
557}
558
Sylvestre Ledru59405832013-07-01 08:21:36 +0000559#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000560
561struct HostThreadCreateInfo
562{
563 std::string thread_name;
564 thread_func_t thread_fptr;
565 thread_arg_t thread_arg;
566
567 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
568 thread_name (name ? name : ""),
569 thread_fptr (fptr),
570 thread_arg (arg)
571 {
572 }
573};
574
575static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000576#ifdef _WIN32
577__stdcall
578#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000579ThreadCreateTrampoline (thread_arg_t arg)
580{
581 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
582 Host::ThreadCreated (info->thread_name.c_str());
583 thread_func_t thread_fptr = info->thread_fptr;
584 thread_arg_t thread_arg = info->thread_arg;
585
Greg Clayton5160ce52013-03-27 23:08:40 +0000586 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000587 if (log)
588 log->Printf("thread created");
589
590 delete info;
591 return thread_fptr (thread_arg);
592}
593
594lldb::thread_t
595Host::ThreadCreate
596(
597 const char *thread_name,
598 thread_func_t thread_fptr,
599 thread_arg_t thread_arg,
600 Error *error
601)
602{
603 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
604
605 // Host::ThreadCreateTrampoline will delete this pointer for us.
606 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
607
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000608#ifdef _WIN32
609 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
610 int err = thread <= 0 ? GetLastError() : 0;
611#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000612 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000613#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000614 if (err == 0)
615 {
616 if (error)
617 error->Clear();
618 return thread;
619 }
620
621 if (error)
622 error->SetError (err, eErrorTypePOSIX);
623
624 return LLDB_INVALID_HOST_THREAD;
625}
626
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000627#ifndef _WIN32
628
Greg Clayton2bddd342010-09-07 20:11:56 +0000629bool
630Host::ThreadCancel (lldb::thread_t thread, Error *error)
631{
632 int err = ::pthread_cancel (thread);
633 if (error)
634 error->SetError(err, eErrorTypePOSIX);
635 return err == 0;
636}
637
638bool
639Host::ThreadDetach (lldb::thread_t thread, Error *error)
640{
641 int err = ::pthread_detach (thread);
642 if (error)
643 error->SetError(err, eErrorTypePOSIX);
644 return err == 0;
645}
646
647bool
648Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
649{
650 int err = ::pthread_join (thread, thread_result_ptr);
651 if (error)
652 error->SetError(err, eErrorTypePOSIX);
653 return err == 0;
654}
655
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000656lldb::thread_key_t
657Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
658{
659 pthread_key_t key;
660 ::pthread_key_create (&key, callback);
661 return key;
662}
663
664void*
665Host::ThreadLocalStorageGet(lldb::thread_key_t key)
666{
667 return ::pthread_getspecific (key);
668}
669
670void
671Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
672{
673 ::pthread_setspecific (key, value);
674}
675
Matt Kopec62502c62013-05-13 19:33:58 +0000676bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000677Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
678{
Greg Clayton85719632013-02-27 22:51:58 +0000679#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000680 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
681 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
682 if (pid == LLDB_INVALID_PROCESS_ID)
683 pid = curr_pid;
684
685 if (tid == LLDB_INVALID_THREAD_ID)
686 tid = curr_tid;
687
Greg Clayton2bddd342010-09-07 20:11:56 +0000688 // Set the pthread name if possible
689 if (pid == curr_pid && tid == curr_tid)
690 {
Matt Kopec62502c62013-05-13 19:33:58 +0000691 if (::pthread_setname_np (name) == 0)
692 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000693 }
Matt Kopec62502c62013-05-13 19:33:58 +0000694 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000695#elif defined (__FreeBSD__)
696 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
697 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
698 if (pid == LLDB_INVALID_PROCESS_ID)
699 pid = curr_pid;
700
701 if (tid == LLDB_INVALID_THREAD_ID)
702 tid = curr_tid;
703
704 // Set the pthread name if possible
705 if (pid == curr_pid && tid == curr_tid)
706 {
Michael Sartainc2052432013-08-01 18:51:08 +0000707 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000708 return true;
709 }
710 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000711#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000712 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
713 if (fn)
714 {
Matt Kopec62502c62013-05-13 19:33:58 +0000715 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
716 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000717 if (pid == LLDB_INVALID_PROCESS_ID)
718 pid = curr_pid;
719
720 if (tid == LLDB_INVALID_THREAD_ID)
721 tid = curr_tid;
722
Michael Sartainc2052432013-08-01 18:51:08 +0000723 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000724 {
Michael Sartainc2052432013-08-01 18:51:08 +0000725 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
726 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
727
728 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000729 return true;
730 }
731 }
732 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000733#else
734 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000735#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000736}
737
Ed Maste02983be2013-07-25 19:10:32 +0000738bool
739Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
740 const char *thread_name, size_t len)
741{
742 char *namebuf = (char *)::malloc (len + 1);
743
744 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
745 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
746 // off leads to a lot of similar named threads. Go through the thread name
747 // and search for the last dot and use that.
748 const char *lastdot = ::strrchr (thread_name, '.');
749
750 if (lastdot && lastdot != thread_name)
751 thread_name = lastdot + 1;
752 ::strncpy (namebuf, thread_name, len);
753 namebuf[len] = 0;
754
755 int namebuflen = strlen(namebuf);
756 if (namebuflen > 0)
757 {
758 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
759 {
760 // Trim off trailing '(' and '>' characters for a bit more cleanup.
761 namebuflen--;
762 namebuf[namebuflen] = 0;
763 }
764 return Host::SetThreadName (pid, tid, namebuf);
765 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000766
767 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000768 return false;
769}
770
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000771#endif
772
Greg Clayton2bddd342010-09-07 20:11:56 +0000773FileSpec
774Host::GetProgramFileSpec ()
775{
776 static FileSpec g_program_filespec;
777 if (!g_program_filespec)
778 {
779#if defined (__APPLE__)
780 char program_fullpath[PATH_MAX];
781 // If DST is NULL, then return the number of bytes needed.
782 uint32_t len = sizeof(program_fullpath);
783 int err = _NSGetExecutablePath (program_fullpath, &len);
784 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000785 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000786 else if (err == -1)
787 {
788 char *large_program_fullpath = (char *)::malloc (len + 1);
789
790 err = _NSGetExecutablePath (large_program_fullpath, &len);
791 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000792 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000793
794 ::free (large_program_fullpath);
795 }
796#elif defined (__linux__)
797 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000798 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
799 if (len > 0) {
800 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000801 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000802 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000803#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000804 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
805 size_t exe_path_size;
806 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
807 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000808 char *exe_path = new char[exe_path_size];
809 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
810 g_program_filespec.SetFile(exe_path, false);
811 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000812 }
813#endif
814 }
815 return g_program_filespec;
816}
817
Greg Clayton2bddd342010-09-07 20:11:56 +0000818#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000819
820bool
821Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
822{
823 bundle.Clear();
824 return false;
825}
826
Greg Clayton2bddd342010-09-07 20:11:56 +0000827bool
Greg Claytondd36def2010-10-17 22:03:32 +0000828Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000829{
Greg Claytondd36def2010-10-17 22:03:32 +0000830 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000831}
832#endif
833
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000834#ifndef _WIN32
835
Greg Clayton45319462011-02-08 00:35:34 +0000836// Opaque info that tracks a dynamic library that was loaded
837struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000838{
Greg Clayton45319462011-02-08 00:35:34 +0000839 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
840 file_spec (fs),
841 open_options (o),
842 handle (h)
843 {
844 }
845
846 const FileSpec file_spec;
847 uint32_t open_options;
848 void * handle;
849};
850
851void *
852Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
853{
Greg Clayton4272cc72011-02-02 02:24:04 +0000854 char path[PATH_MAX];
855 if (file_spec.GetPath(path, sizeof(path)))
856 {
Greg Clayton45319462011-02-08 00:35:34 +0000857 int mode = 0;
858
859 if (options & eDynamicLibraryOpenOptionLazy)
860 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000861 else
862 mode |= RTLD_NOW;
863
Greg Clayton45319462011-02-08 00:35:34 +0000864
865 if (options & eDynamicLibraryOpenOptionLocal)
866 mode |= RTLD_LOCAL;
867 else
868 mode |= RTLD_GLOBAL;
869
870#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
871 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
872 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000873#endif
Greg Clayton45319462011-02-08 00:35:34 +0000874
875 void * opaque = ::dlopen (path, mode);
876
877 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000878 {
879 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000880 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000881 }
882 else
883 {
884 error.SetErrorString(::dlerror());
885 }
886 }
887 else
888 {
889 error.SetErrorString("failed to extract path");
890 }
Greg Clayton45319462011-02-08 00:35:34 +0000891 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000892}
893
894Error
Greg Clayton45319462011-02-08 00:35:34 +0000895Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000896{
897 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000898 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000899 {
900 error.SetErrorString ("invalid dynamic library handle");
901 }
Greg Clayton45319462011-02-08 00:35:34 +0000902 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000903 {
Greg Clayton45319462011-02-08 00:35:34 +0000904 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
905 if (::dlclose (dylib_info->handle) != 0)
906 {
907 error.SetErrorString(::dlerror());
908 }
909
910 dylib_info->open_options = 0;
911 dylib_info->handle = 0;
912 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000913 }
914 return error;
915}
916
917void *
Greg Clayton45319462011-02-08 00:35:34 +0000918Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000919{
Greg Clayton45319462011-02-08 00:35:34 +0000920 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000921 {
922 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000923 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000924 else
Greg Clayton45319462011-02-08 00:35:34 +0000925 {
926 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
927
928 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
929 if (symbol_addr)
930 {
931#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
932 // This host doesn't support limiting searches to this shared library
933 // so we need to verify that the match came from this shared library
934 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000935 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000936 {
937 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
938 if (match_dylib_spec != dylib_info->file_spec)
939 {
940 char dylib_path[PATH_MAX];
941 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
942 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
943 else
944 error.SetErrorString ("symbol not found");
945 return NULL;
946 }
947 }
948#endif
949 error.Clear();
950 return symbol_addr;
951 }
952 else
953 {
954 error.SetErrorString(::dlerror());
955 }
956 }
957 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000958}
Greg Claytondd36def2010-10-17 22:03:32 +0000959
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000960FileSpec
961Host::GetModuleFileSpecForHostAddress (const void *host_addr)
962{
963 FileSpec module_filespec;
964 Dl_info info;
965 if (::dladdr (host_addr, &info))
966 {
967 if (info.dli_fname)
968 module_filespec.SetFile(info.dli_fname, true);
969 }
970 return module_filespec;
971}
972
973#endif
974
Greg Claytondd36def2010-10-17 22:03:32 +0000975bool
976Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
977{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000978 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000979 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
980 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000981 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000982 // need to be modified to "do the right thing".
983
984 switch (path_type)
985 {
986 case ePathTypeLLDBShlibDir:
987 {
988 static ConstString g_lldb_so_dir;
989 if (!g_lldb_so_dir)
990 {
991 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
992 g_lldb_so_dir = lldb_file_spec.GetDirectory();
993 }
994 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +0000995 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +0000996 }
997 break;
998
999 case ePathTypeSupportExecutableDir:
1000 {
1001 static ConstString g_lldb_support_exe_dir;
1002 if (!g_lldb_support_exe_dir)
1003 {
1004 FileSpec lldb_file_spec;
1005 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1006 {
1007 char raw_path[PATH_MAX];
1008 char resolved_path[PATH_MAX];
1009 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1010
1011#if defined (__APPLE__)
1012 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1013 if (framework_pos)
1014 {
1015 framework_pos += strlen("LLDB.framework");
Greg Claytondce502e2011-11-04 03:34:56 +00001016#if !defined (__arm__)
Greg Claytondd36def2010-10-17 22:03:32 +00001017 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001018#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001019 }
1020#endif
1021 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1022 g_lldb_support_exe_dir.SetCString(resolved_path);
1023 }
1024 }
1025 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001026 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001027 }
1028 break;
1029
1030 case ePathTypeHeaderDir:
1031 {
1032 static ConstString g_lldb_headers_dir;
1033 if (!g_lldb_headers_dir)
1034 {
1035#if defined (__APPLE__)
1036 FileSpec lldb_file_spec;
1037 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1038 {
1039 char raw_path[PATH_MAX];
1040 char resolved_path[PATH_MAX];
1041 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1042
1043 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1044 if (framework_pos)
1045 {
1046 framework_pos += strlen("LLDB.framework");
1047 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1048 }
1049 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1050 g_lldb_headers_dir.SetCString(resolved_path);
1051 }
1052#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001053 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001054 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1055#endif
1056 }
1057 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001058 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001059 }
1060 break;
1061
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001062#ifdef LLDB_DISABLE_PYTHON
1063 case ePathTypePythonDir:
1064 return false;
1065#else
1066 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001067 {
Greg Claytondd36def2010-10-17 22:03:32 +00001068 static ConstString g_lldb_python_dir;
1069 if (!g_lldb_python_dir)
1070 {
1071 FileSpec lldb_file_spec;
1072 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1073 {
1074 char raw_path[PATH_MAX];
1075 char resolved_path[PATH_MAX];
1076 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1077
1078#if defined (__APPLE__)
1079 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1080 if (framework_pos)
1081 {
1082 framework_pos += strlen("LLDB.framework");
1083 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1084 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001085#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001086 llvm::SmallString<256> python_version_dir;
1087 llvm::raw_svector_ostream os(python_version_dir);
1088 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1089 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001090
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001091 // We may get our string truncated. Should we protect
1092 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001093
Daniel Maleafa7425d2013-08-06 21:40:08 +00001094 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001095 sizeof(raw_path) - strlen(raw_path) - 1);
1096
Greg Claytondd36def2010-10-17 22:03:32 +00001097#endif
1098 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1099 g_lldb_python_dir.SetCString(resolved_path);
1100 }
1101 }
1102 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001103 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001104 }
1105 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001106#endif
1107
Greg Clayton4272cc72011-02-02 02:24:04 +00001108 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1109 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001110#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001111 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001112 static bool g_lldb_system_plugin_dir_located = false;
1113 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001114 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001115 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001116#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001117 FileSpec lldb_file_spec;
1118 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1119 {
1120 char raw_path[PATH_MAX];
1121 char resolved_path[PATH_MAX];
1122 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1123
1124 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1125 if (framework_pos)
1126 {
1127 framework_pos += strlen("LLDB.framework");
1128 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001129 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1130 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001131 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001132 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001133 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001134#elif defined (__linux__)
1135 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1136 if (lldb_file_spec.Exists())
1137 {
1138 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1139 }
1140#endif // __APPLE__ || __linux__
Greg Clayton4272cc72011-02-02 02:24:04 +00001141 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001142
1143 if (g_lldb_system_plugin_dir)
1144 {
1145 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1146 return true;
1147 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001148#else
1149 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001150 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001151#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001152 }
1153 break;
1154
1155 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1156 {
1157#if defined (__APPLE__)
1158 static ConstString g_lldb_user_plugin_dir;
1159 if (!g_lldb_user_plugin_dir)
1160 {
1161 char user_plugin_path[PATH_MAX];
1162 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1163 user_plugin_path,
1164 sizeof(user_plugin_path)))
1165 {
1166 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1167 }
1168 }
1169 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001170 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001171#elif defined (__linux__)
1172 static ConstString g_lldb_user_plugin_dir;
1173 if (!g_lldb_user_plugin_dir)
1174 {
1175 // XDG Base Directory Specification
1176 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1177 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1178 FileSpec lldb_file_spec;
1179 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1180 if (xdg_data_home && xdg_data_home[0])
1181 {
1182 std::string user_plugin_dir (xdg_data_home);
1183 user_plugin_dir += "/lldb";
1184 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1185 }
1186 else
1187 {
1188 const char *home_dir = getenv("HOME");
1189 if (home_dir && home_dir[0])
1190 {
1191 std::string user_plugin_dir (home_dir);
1192 user_plugin_dir += "/.local/share/lldb";
1193 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1194 }
1195 }
1196
1197 if (lldb_file_spec.Exists())
1198 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1199 }
1200 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001201 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001202#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001203 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001204 return false;
1205 }
Greg Claytondd36def2010-10-17 22:03:32 +00001206 }
1207
1208 return false;
1209}
1210
Greg Clayton1cb64962011-03-24 04:28:38 +00001211
1212bool
1213Host::GetHostname (std::string &s)
1214{
1215 char hostname[PATH_MAX];
1216 hostname[sizeof(hostname) - 1] = '\0';
1217 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1218 {
1219 struct hostent* h = ::gethostbyname (hostname);
1220 if (h)
1221 s.assign (h->h_name);
1222 else
1223 s.assign (hostname);
1224 return true;
1225 }
1226 return false;
1227}
1228
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001229#ifndef _WIN32
1230
Greg Clayton32e0a752011-03-30 18:16:51 +00001231const char *
1232Host::GetUserName (uint32_t uid, std::string &user_name)
1233{
1234 struct passwd user_info;
1235 struct passwd *user_info_ptr = &user_info;
1236 char user_buffer[PATH_MAX];
1237 size_t user_buffer_size = sizeof(user_buffer);
1238 if (::getpwuid_r (uid,
1239 &user_info,
1240 user_buffer,
1241 user_buffer_size,
1242 &user_info_ptr) == 0)
1243 {
1244 if (user_info_ptr)
1245 {
1246 user_name.assign (user_info_ptr->pw_name);
1247 return user_name.c_str();
1248 }
1249 }
1250 user_name.clear();
1251 return NULL;
1252}
1253
1254const char *
1255Host::GetGroupName (uint32_t gid, std::string &group_name)
1256{
1257 char group_buffer[PATH_MAX];
1258 size_t group_buffer_size = sizeof(group_buffer);
1259 struct group group_info;
1260 struct group *group_info_ptr = &group_info;
1261 // Try the threadsafe version first
1262 if (::getgrgid_r (gid,
1263 &group_info,
1264 group_buffer,
1265 group_buffer_size,
1266 &group_info_ptr) == 0)
1267 {
1268 if (group_info_ptr)
1269 {
1270 group_name.assign (group_info_ptr->gr_name);
1271 return group_name.c_str();
1272 }
1273 }
1274 else
1275 {
1276 // The threadsafe version isn't currently working
1277 // for me on darwin, but the non-threadsafe version
1278 // is, so I am calling it below.
1279 group_info_ptr = ::getgrgid (gid);
1280 if (group_info_ptr)
1281 {
1282 group_name.assign (group_info_ptr->gr_name);
1283 return group_name.c_str();
1284 }
1285 }
1286 group_name.clear();
1287 return NULL;
1288}
1289
Han Ming Ong84647042012-02-25 01:07:38 +00001290uint32_t
1291Host::GetUserID ()
1292{
1293 return getuid();
1294}
1295
1296uint32_t
1297Host::GetGroupID ()
1298{
1299 return getgid();
1300}
1301
1302uint32_t
1303Host::GetEffectiveUserID ()
1304{
1305 return geteuid();
1306}
1307
1308uint32_t
1309Host::GetEffectiveGroupID ()
1310{
1311 return getegid();
1312}
1313
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001314#endif
1315
1316#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1317bool
1318Host::GetOSBuildString (std::string &s)
1319{
1320 s.clear();
1321 return false;
1322}
1323
1324bool
1325Host::GetOSKernelDescription (std::string &s)
1326{
1327 s.clear();
1328 return false;
1329}
1330#endif
1331
Ed Maste47e575e2013-08-29 18:44:27 +00001332#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001333uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001334Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001335{
1336 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001337 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001338}
1339
Greg Claytone996fd32011-03-08 22:40:15 +00001340bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001341Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001342{
Greg Claytone996fd32011-03-08 22:40:15 +00001343 process_info.Clear();
1344 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001345}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001346#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001347
Matt Kopec085d6ce2013-05-31 22:00:07 +00001348#if !defined(__linux__)
1349bool
1350Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1351{
1352 return false;
1353}
1354#endif
1355
Sean Callananc0a6e062011-10-27 21:22:25 +00001356lldb::TargetSP
1357Host::GetDummyTarget (lldb_private::Debugger &debugger)
1358{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001359 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001360
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001361 // FIXME: Maybe the dummy target should be per-Debugger
1362 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1363 {
1364 ArchSpec arch(Target::GetDefaultArchitecture());
1365 if (!arch.IsValid())
1366 arch = Host::GetArchitecture ();
1367 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001368 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001369 arch.GetTriple().getTriple().c_str(),
1370 false,
1371 NULL,
1372 g_dummy_target_sp);
1373 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001374
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001375 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001376}
1377
Greg Claytond1cf11a2012-04-14 01:42:46 +00001378struct ShellInfo
1379{
1380 ShellInfo () :
1381 process_reaped (false),
1382 can_delete (false),
1383 pid (LLDB_INVALID_PROCESS_ID),
1384 signo(-1),
1385 status(-1)
1386 {
1387 }
1388
1389 lldb_private::Predicate<bool> process_reaped;
1390 lldb_private::Predicate<bool> can_delete;
1391 lldb::pid_t pid;
1392 int signo;
1393 int status;
1394};
1395
1396static bool
1397MonitorShellCommand (void *callback_baton,
1398 lldb::pid_t pid,
1399 bool exited, // True if the process did exit
1400 int signo, // Zero for no signal
1401 int status) // Exit value of process if signal is zero
1402{
1403 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1404 shell_info->pid = pid;
1405 shell_info->signo = signo;
1406 shell_info->status = status;
1407 // Let the thread running Host::RunShellCommand() know that the process
1408 // exited and that ShellInfo has been filled in by broadcasting to it
1409 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1410 // Now wait for a handshake back from that thread running Host::RunShellCommand
1411 // so we know that we can delete shell_info_ptr
1412 shell_info->can_delete.WaitForValueEqualTo(true);
1413 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1414 usleep(1000);
1415 // Now delete the shell info that was passed into this function
1416 delete shell_info;
1417 return true;
1418}
1419
1420Error
1421Host::RunShellCommand (const char *command,
1422 const char *working_dir,
1423 int *status_ptr,
1424 int *signo_ptr,
1425 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001426 uint32_t timeout_sec,
1427 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001428{
1429 Error error;
1430 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001431 if (shell && shell[0])
1432 {
1433 // Run the command in a shell
1434 launch_info.SetShell(shell);
1435 launch_info.GetArguments().AppendArgument(command);
1436 const bool localhost = true;
1437 const bool will_debug = false;
1438 const bool first_arg_is_full_shell_command = true;
1439 launch_info.ConvertArgumentsForLaunchingInShell (error,
1440 localhost,
1441 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001442 first_arg_is_full_shell_command,
1443 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001444 }
1445 else
1446 {
1447 // No shell, just run it
1448 Args args (command);
1449 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001450 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001451 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001452
1453 if (working_dir)
1454 launch_info.SetWorkingDirectory(working_dir);
1455 char output_file_path_buffer[L_tmpnam];
1456 const char *output_file_path = NULL;
1457 if (command_output_ptr)
1458 {
1459 // Create a temporary file to get the stdout/stderr and redirect the
1460 // output of the command into this file. We will later read this file
1461 // if all goes well and fill the data into "command_output_ptr"
1462 output_file_path = ::tmpnam(output_file_path_buffer);
1463 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1464 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001465 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001466 }
1467 else
1468 {
1469 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1470 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1471 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1472 }
1473
1474 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001475 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001476
1477 const bool monitor_signals = false;
1478 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1479
1480 error = LaunchProcess (launch_info);
1481 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001482
1483 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1484 error.SetErrorString("failed to get process ID");
1485
1486 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001487 {
1488 // The process successfully launched, so we can defer ownership of
1489 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001490 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001491 // doesn't need to delete the ShellInfo anymore.
1492 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001493 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001494 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001495 if (timeout_sec > 0) {
1496 timeout_time.OffsetWithSeconds(timeout_sec);
1497 timeout_ptr = &timeout_time;
1498 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001499 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001500 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001501 if (timed_out)
1502 {
1503 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001504
Greg Claytond1cf11a2012-04-14 01:42:46 +00001505 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001506 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001507 // Wait for the monitor callback to get the message
1508 timeout_time = TimeValue::Now();
1509 timeout_time.OffsetWithSeconds(1);
1510 timed_out = false;
1511 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1512 }
1513 else
1514 {
1515 if (status_ptr)
1516 *status_ptr = shell_info->status;
1517
1518 if (signo_ptr)
1519 *signo_ptr = shell_info->signo;
1520
1521 if (command_output_ptr)
1522 {
1523 command_output_ptr->clear();
1524 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1525 uint64_t file_size = file_spec.GetByteSize();
1526 if (file_size > 0)
1527 {
1528 if (file_size > command_output_ptr->max_size())
1529 {
1530 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1531 }
1532 else
1533 {
1534 command_output_ptr->resize(file_size);
1535 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1536 }
1537 }
1538 }
1539 }
1540 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1541 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001542
1543 if (output_file_path)
1544 ::unlink (output_file_path);
1545 // Handshake with the monitor thread, or just let it know in advance that
1546 // it can delete "shell_info" in case we timed out and were not able to kill
1547 // the process...
1548 return error;
1549}
1550
Daniel Malea4244cbd2013-08-27 20:58:59 +00001551#if defined(__linux__) or defined(__FreeBSD__)
1552// The functions below implement process launching via posix_spawn() for Linux
1553// and FreeBSD.
1554
1555// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1556static Error
1557LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1558{
1559 Error error;
1560 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1561
1562 assert(exe_path);
1563 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1564
1565 posix_spawnattr_t attr;
1566
1567 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1568 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1569 if (error.Fail())
1570 return error;
1571
1572 // Make a quick class that will cleanup the posix spawn attributes in case
1573 // we return in the middle of this function.
1574 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1575
1576 sigset_t no_signals;
1577 sigset_t all_signals;
1578 sigemptyset (&no_signals);
1579 sigfillset (&all_signals);
1580 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1581 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1582
1583 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1584
1585 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1586 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1587 if (error.Fail())
1588 return error;
1589
1590 const size_t num_file_actions = launch_info.GetNumFileActions ();
1591 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1592 // Make a quick class that will cleanup the posix spawn attributes in case
1593 // we return in the middle of this function.
1594 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1595 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1596
1597 if (num_file_actions > 0)
1598 {
1599 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1600 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1601 if (error.Fail())
1602 return error;
1603
1604 file_action_ptr = &file_actions;
1605 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1606
1607 for (size_t i = 0; i < num_file_actions; ++i)
1608 {
1609 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1610 if (launch_file_action &&
1611 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1612 launch_file_action,
1613 log,
1614 error))
1615 return error;
1616 }
1617 }
1618
1619 // Change working directory if neccessary.
1620 char current_dir[PATH_MAX];
1621 current_dir[0] = '\0';
1622
1623 const char *working_dir = launch_info.GetWorkingDirectory();
1624 if (working_dir != NULL)
1625 {
1626 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1627 {
1628 error.SetError(errno, eErrorTypePOSIX);
1629 error.LogIfError(log, "unable to save the current directory");
1630 return error;
1631 }
1632
1633 if (::chdir(working_dir) == -1)
1634 {
1635 error.SetError(errno, eErrorTypePOSIX);
1636 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1637 return error;
1638 }
1639 }
1640
1641 const char *tmp_argv[2];
1642 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1643 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1644
1645 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1646 // We must pass argv into posix_spawnp and it must contain at least two items -
1647 // pointer to an executable and NULL.
1648 if (argv == NULL)
1649 {
1650 tmp_argv[0] = exe_path;
1651 tmp_argv[1] = NULL;
1652 argv = (char * const*)tmp_argv;
1653 }
1654
1655 error.SetError (::posix_spawnp (&pid,
1656 exe_path,
1657 (num_file_actions > 0) ? &file_actions : NULL,
1658 &attr,
1659 argv,
1660 envp),
1661 eErrorTypePOSIX);
1662
1663 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1664 pid, exe_path, file_action_ptr, &attr, argv, envp);
1665
1666 // Change back the current directory.
1667 // NOTE: do not override previously established error from posix_spawnp.
1668 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1669 {
1670 error.SetError(errno, eErrorTypePOSIX);
1671 error.LogIfError(log, "unable to change current directory back to %s",
1672 current_dir);
1673 }
1674
1675 return error;
1676}
1677
1678
1679Error
1680Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1681{
1682 Error error;
1683 char exe_path[PATH_MAX];
1684
1685 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1686
1687 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1688
1689 FileSpec exe_spec(launch_info.GetExecutableFile());
1690
1691 FileSpec::FileType file_type = exe_spec.GetFileType();
1692 if (file_type != FileSpec::eFileTypeRegular)
1693 {
1694 lldb::ModuleSP exe_module_sp;
1695 error = host_platform_sp->ResolveExecutable (exe_spec,
1696 arch_spec,
1697 exe_module_sp,
1698 NULL);
1699
1700 if (error.Fail())
1701 return error;
1702
1703 if (exe_module_sp)
1704 exe_spec = exe_module_sp->GetFileSpec();
1705 }
1706
1707 if (exe_spec.Exists())
1708 {
1709 exe_spec.GetPath (exe_path, sizeof(exe_path));
1710 }
1711 else
1712 {
1713 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1714 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1715 return error;
1716 }
1717
1718 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1719
1720 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1721
1722 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1723
1724 if (pid != LLDB_INVALID_PROCESS_ID)
1725 {
1726 // If all went well, then set the process ID into the launch info
1727 launch_info.SetProcessID(pid);
1728
1729 // Make sure we reap any processes we spawn or we will have zombies.
1730 if (!launch_info.MonitorProcess())
1731 {
1732 const bool monitor_signals = false;
1733 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1734 NULL,
1735 pid,
1736 monitor_signals);
1737 }
1738 }
1739 else
1740 {
1741 // Invalid process ID, something didn't go well
1742 if (error.Success())
1743 error.SetErrorString ("process launch failed for unknown reasons");
1744 }
1745 return error;
1746}
1747
1748#endif // defined(__linux__) or defined(__FreeBSD__)
1749
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001750#ifndef _WIN32
1751
1752size_t
1753Host::GetPageSize()
1754{
1755 return ::getpagesize();
1756}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001757
Greg Claytone3e3fee2013-02-17 20:46:30 +00001758uint32_t
1759Host::GetNumberCPUS ()
1760{
1761 static uint32_t g_num_cores = UINT32_MAX;
1762 if (g_num_cores == UINT32_MAX)
1763 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001764#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001765
1766 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001767
Greg Claytone3e3fee2013-02-17 20:46:30 +00001768#else
1769
1770 // Assume POSIX support if a host specific case has not been supplied above
1771 g_num_cores = 0;
1772 int num_cores = 0;
1773 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001774#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001775 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001776#else
1777 int mib[] = { CTL_HW, HW_NCPU };
1778#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001779
1780 /* get the number of CPUs from the system */
1781 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1782 {
1783 g_num_cores = num_cores;
1784 }
1785 else
1786 {
1787 mib[1] = HW_NCPU;
1788 num_cores_len = sizeof(num_cores);
1789 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1790 {
1791 if (num_cores > 0)
1792 g_num_cores = num_cores;
1793 }
1794 }
1795#endif
1796 }
1797 return g_num_cores;
1798}
1799
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001800void
1801Host::Kill(lldb::pid_t pid, int signo)
1802{
1803 ::kill(pid, signo);
1804}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001805
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001806#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001807
Johnny Chen8f3d8382011-08-02 20:52:42 +00001808#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001809bool
Greg Clayton3b147632010-12-18 01:54:34 +00001810Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001811{
1812 return false;
1813}
Greg Claytondd36def2010-10-17 22:03:32 +00001814
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001815void
1816Host::SetCrashDescriptionWithFormat (const char *format, ...)
1817{
1818}
1819
1820void
1821Host::SetCrashDescription (const char *description)
1822{
1823}
Greg Claytondd36def2010-10-17 22:03:32 +00001824
1825lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001826Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001827{
1828 return LLDB_INVALID_PROCESS_ID;
1829}
1830
Greg Claytonfbb76342013-11-20 21:07:01 +00001831#endif
1832
1833
1834#ifdef LLDB_DISABLE_POSIX
1835
1836Error
1837Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001838{
Greg Claytonfbb76342013-11-20 21:07:01 +00001839 Error error;
1840 error.SetErrorString("%s in not implemented on this host", __PRETTY_FUNCTION__);
1841 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001842}
Greg Claytonfbb76342013-11-20 21:07:01 +00001843
1844Error
1845Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1846{
1847 Error error;
1848 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1849 return error;
1850}
1851
1852Error
1853Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1854{
1855 Error error;
1856 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1857 return error;
1858}
1859
1860Error
1861Host::Symlink (const char *src, const char *dst)
1862{
1863 Error error;
1864 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1865 return error;
1866}
1867
1868Error
1869Host::Readlink (const char *path, char *buf, size_t buf_len)
1870{
1871 Error error;
1872 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1873 return error;
1874}
1875
1876Error
1877Host::Unlink (const char *path)
1878{
1879 Error error;
1880 error.SetErrorString("%s is not supported on this host", __PRETTY_FUNCTION__);
1881 return error;
1882}
1883
1884#else
1885
1886Error
1887Host::MakeDirectory (const char* path, uint32_t file_permissions)
1888{
1889 Error error;
1890 if (::mkdir(path, file_permissions) != 0)
1891 error.SetErrorToErrno();
1892 return error;
1893}
1894
1895Error
1896Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1897{
1898 Error error;
1899 struct stat file_stats;
1900 if (::stat (path, &file_stats) == 0)
1901 {
1902 // The bits in "st_mode" currently match the definitions
1903 // for the file mode bits in unix.
1904 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
1905 }
1906 else
1907 {
1908 error.SetErrorToErrno();
1909 }
1910 return error;
1911}
1912
1913Error
1914Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1915{
1916 Error error;
1917 if (::chmod(path, file_permissions) != 0)
1918 error.SetErrorToErrno();
1919 return error;
1920}
1921
1922Error
1923Host::Symlink (const char *src, const char *dst)
1924{
1925 Error error;
1926 if (::symlink(dst, src) == -1)
1927 error.SetErrorToErrno();
1928 return error;
1929}
1930
1931Error
1932Host::Unlink (const char *path)
1933{
1934 Error error;
1935 if (::unlink(path) == -1)
1936 error.SetErrorToErrno();
1937 return error;
1938}
1939
1940Error
1941Host::Readlink (const char *path, char *buf, size_t buf_len)
1942{
1943 Error error;
1944 ssize_t count = ::readlink(path, buf, buf_len);
1945 if (count < 0)
1946 error.SetErrorToErrno();
1947 else if (count < (buf_len-1))
1948 buf[count] = '\0'; // Success
1949 else
1950 error.SetErrorString("'buf' buffer is too small to contain link contents");
1951 return error;
1952}
1953
1954
Greg Clayton2bddd342010-09-07 20:11:56 +00001955#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00001956
1957typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
1958FDToFileMap& GetFDToFileMap()
1959{
1960 static FDToFileMap g_fd2filemap;
1961 return g_fd2filemap;
1962}
1963
1964lldb::user_id_t
1965Host::OpenFile (const FileSpec& file_spec,
1966 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00001967 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00001968 Error &error)
1969{
1970 std::string path (file_spec.GetPath());
1971 if (path.empty())
1972 {
1973 error.SetErrorString("empty path");
1974 return UINT64_MAX;
1975 }
1976 FileSP file_sp(new File());
1977 error = file_sp->Open(path.c_str(),flags,mode);
1978 if (file_sp->IsValid() == false)
1979 return UINT64_MAX;
1980 lldb::user_id_t fd = file_sp->GetDescriptor();
1981 GetFDToFileMap()[fd] = file_sp;
1982 return fd;
1983}
1984
1985bool
1986Host::CloseFile (lldb::user_id_t fd, Error &error)
1987{
1988 if (fd == UINT64_MAX)
1989 {
1990 error.SetErrorString ("invalid file descriptor");
1991 return false;
1992 }
1993 FDToFileMap& file_map = GetFDToFileMap();
1994 FDToFileMap::iterator pos = file_map.find(fd);
1995 if (pos == file_map.end())
1996 {
1997 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1998 return false;
1999 }
2000 FileSP file_sp = pos->second;
2001 if (!file_sp)
2002 {
2003 error.SetErrorString ("invalid host backing file");
2004 return false;
2005 }
2006 error = file_sp->Close();
2007 file_map.erase(pos);
2008 return error.Success();
2009}
2010
2011uint64_t
2012Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2013{
2014 if (fd == UINT64_MAX)
2015 {
2016 error.SetErrorString ("invalid file descriptor");
2017 return UINT64_MAX;
2018 }
2019 FDToFileMap& file_map = GetFDToFileMap();
2020 FDToFileMap::iterator pos = file_map.find(fd);
2021 if (pos == file_map.end())
2022 {
2023 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2024 return false;
2025 }
2026 FileSP file_sp = pos->second;
2027 if (!file_sp)
2028 {
2029 error.SetErrorString ("invalid host backing file");
2030 return UINT64_MAX;
2031 }
2032 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2033 return UINT64_MAX;
2034 size_t bytes_written = src_len;
2035 error = file_sp->Write(src, bytes_written);
2036 if (error.Fail())
2037 return UINT64_MAX;
2038 return bytes_written;
2039}
2040
2041uint64_t
2042Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2043{
2044 if (fd == UINT64_MAX)
2045 {
2046 error.SetErrorString ("invalid file descriptor");
2047 return UINT64_MAX;
2048 }
2049 FDToFileMap& file_map = GetFDToFileMap();
2050 FDToFileMap::iterator pos = file_map.find(fd);
2051 if (pos == file_map.end())
2052 {
2053 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2054 return false;
2055 }
2056 FileSP file_sp = pos->second;
2057 if (!file_sp)
2058 {
2059 error.SetErrorString ("invalid host backing file");
2060 return UINT64_MAX;
2061 }
2062 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2063 return UINT64_MAX;
2064 size_t bytes_read = dst_len;
2065 error = file_sp->Read(dst ,bytes_read);
2066 if (error.Fail())
2067 return UINT64_MAX;
2068 return bytes_read;
2069}
2070
2071lldb::user_id_t
2072Host::GetFileSize (const FileSpec& file_spec)
2073{
2074 return file_spec.GetByteSize();
2075}
2076
2077bool
2078Host::GetFileExists (const FileSpec& file_spec)
2079{
2080 return file_spec.Exists();
2081}
2082
2083bool
2084Host::CalculateMD5 (const FileSpec& file_spec,
2085 uint64_t &low,
2086 uint64_t &high)
2087{
2088#if defined (__APPLE__)
2089 StreamString md5_cmd_line;
2090 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2091 std::string hash_string;
2092 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2093 if (err.Fail())
2094 return false;
2095 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2096 // if the output is any other length it is probably wrong
2097 if (hash_string.size() != 32)
2098 return false;
2099 std::string part1(hash_string,0,16);
2100 std::string part2(hash_string,16);
2101 const char* part1_cstr = part1.c_str();
2102 const char* part2_cstr = part2.c_str();
2103 high = ::strtoull(part1_cstr, NULL, 16);
2104 low = ::strtoull(part2_cstr, NULL, 16);
2105 return true;
2106#else
2107 // your own MD5 implementation here
2108 return false;
2109#endif
2110}