blob: edd64c678b68610b989fa97b22bc4e2ffa3722fa [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>
Greg Clayton23f8c952014-03-24 23:10:19 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#include <sys/types.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000017#ifdef _WIN32
18#include "lldb/Host/windows/windows.h"
19#include <winsock2.h>
Hafiz Abid Qadeera6678752014-03-10 22:31:39 +000020#include <ws2tcpip.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000021#else
Deepak Panickalb36da432014-01-13 14:55:15 +000022#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000023#include <dlfcn.h>
24#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000025#include <netdb.h>
26#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000027#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000028#endif
29
30#if !defined (__GNU__) && !defined (_WIN32)
31// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000032#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000033#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000034
35#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000036#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000037#include <mach/mach_init.h>
38#include <mach-o/dyld.h>
Jim Ingham1a7ee702013-11-22 00:51:36 +000039#include <AvailabilityMacros.h>
Ed Maste8b006c62013-06-25 18:58:11 +000040#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000041
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +000042#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000043#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000044#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000045#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000046#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000047
Ed Maste8b006c62013-06-25 18:58:11 +000048#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000050#endif
51
Greg Clayton2bddd342010-09-07 20:11:56 +000052#include "lldb/Host/Host.h"
53#include "lldb/Core/ArchSpec.h"
54#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000055#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000057#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000058#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000059#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000060#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000061#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000062#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000063#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000064#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000065#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000066#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000067#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000068
Saleem Abdulrasool28606952014-06-27 05:17:41 +000069#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000070#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000071#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000072#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000073
Todd Fiala76747122014-01-23 00:52:28 +000074#if defined (__APPLE__)
75#ifndef _POSIX_SPAWN_DISABLE_ASLR
76#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
77#endif
78
79extern "C"
80{
81 int __pthread_chdir(const char *path);
82 int __pthread_fchdir (int fildes);
83}
84
85#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000086
Greg Clayton2bddd342010-09-07 20:11:56 +000087using namespace lldb;
88using namespace lldb_private;
89
Greg Claytone4e45922011-11-16 05:37:56 +000090
Virgile Bellob2f1fb22013-08-23 12:44:05 +000091#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000092struct MonitorInfo
93{
94 lldb::pid_t pid; // The process ID to monitor
95 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
96 void *callback_baton; // The callback baton for the callback function
97 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
98};
99
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000100static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000101MonitorChildProcessThreadFunction (void *arg);
102
103lldb::thread_t
104Host::StartMonitoringChildProcess
105(
106 Host::MonitorChildProcessCallback callback,
107 void *callback_baton,
108 lldb::pid_t pid,
109 bool monitor_signals
110)
111{
112 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000113 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000114
Greg Claytone4e45922011-11-16 05:37:56 +0000115 info_ptr->pid = pid;
116 info_ptr->callback = callback;
117 info_ptr->callback_baton = callback_baton;
118 info_ptr->monitor_signals = monitor_signals;
119
120 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000121 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000122 thread = ThreadCreate (thread_name,
123 MonitorChildProcessThreadFunction,
124 info_ptr,
125 NULL);
126
Greg Clayton2bddd342010-09-07 20:11:56 +0000127 return thread;
128}
129
130//------------------------------------------------------------------
131// Scoped class that will disable thread canceling when it is
132// constructed, and exception safely restore the previous value it
133// when it goes out of scope.
134//------------------------------------------------------------------
135class ScopedPThreadCancelDisabler
136{
137public:
138 ScopedPThreadCancelDisabler()
139 {
140 // Disable the ability for this thread to be cancelled
141 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
142 if (err != 0)
143 m_old_state = -1;
144
145 }
146
147 ~ScopedPThreadCancelDisabler()
148 {
149 // Restore the ability for this thread to be cancelled to what it
150 // previously was.
151 if (m_old_state != -1)
152 ::pthread_setcancelstate (m_old_state, 0);
153 }
154private:
155 int m_old_state; // Save the old cancelability state.
156};
157
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000158static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000159MonitorChildProcessThreadFunction (void *arg)
160{
Greg Clayton5160ce52013-03-27 23:08:40 +0000161 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000162 const char *function = __FUNCTION__;
163 if (log)
164 log->Printf ("%s (arg = %p) thread starting...", function, arg);
165
166 MonitorInfo *info = (MonitorInfo *)arg;
167
168 const Host::MonitorChildProcessCallback callback = info->callback;
169 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000170 const bool monitor_signals = info->monitor_signals;
171
Daniel Malea4244cbd2013-08-27 20:58:59 +0000172 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000173 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000174
Greg Clayton2bddd342010-09-07 20:11:56 +0000175 delete info;
176
177 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000178#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000179 #define __WALL 0
180#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000181 const int options = __WALL;
182
Greg Clayton2bddd342010-09-07 20:11:56 +0000183 while (1)
184 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000185 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000186 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000187 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000188
189 // Wait for all child processes
190 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000191 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000192 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000193 ::pthread_testcancel ();
194
195 if (wait_pid == -1)
196 {
197 if (errno == EINTR)
198 continue;
199 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000200 {
201 if (log)
202 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000203 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000204 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000205 }
Matt Kopec650648f2013-01-08 16:30:18 +0000206 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000207 {
208 bool exited = false;
209 int signal = 0;
210 int exit_status = 0;
211 const char *status_cstr = NULL;
212 if (WIFSTOPPED(status))
213 {
214 signal = WSTOPSIG(status);
215 status_cstr = "STOPPED";
216 }
217 else if (WIFEXITED(status))
218 {
219 exit_status = WEXITSTATUS(status);
220 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000221 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000222 }
223 else if (WIFSIGNALED(status))
224 {
225 signal = WTERMSIG(status);
226 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000227 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000228 exited = true;
229 exit_status = -1;
230 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000231 }
232 else
233 {
Johnny Chen44805302011-07-19 19:48:13 +0000234 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000235 }
236
237 // Scope for pthread_cancel_disabler
238 {
239 ScopedPThreadCancelDisabler pthread_cancel_disabler;
240
Caroline Tice20ad3c42010-10-29 21:48:37 +0000241 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000242 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000243 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 +0000244 function,
245 wait_pid,
246 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000247 pid,
248 status,
249 status_cstr,
250 signal,
251 exit_status);
252
253 if (exited || (signal != 0 && monitor_signals))
254 {
Greg Claytone4e45922011-11-16 05:37:56 +0000255 bool callback_return = false;
256 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000257 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000258
259 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000260 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000261 {
262 if (log)
263 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000264 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000265 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000266 // If the callback returns true, it means this process should
267 // exit
268 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000269 {
270 if (log)
271 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000272 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000273 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000274 }
275 }
276 }
277 }
278
Caroline Tice20ad3c42010-10-29 21:48:37 +0000279 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000280 if (log)
281 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
282
283 return NULL;
284}
285
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000286#endif // #if !defined (__APPLE__) && !defined (_WIN32)
287
288#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000289
290void
291Host::SystemLog (SystemLogType type, const char *format, va_list args)
292{
293 vfprintf (stderr, format, args);
294}
295
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000296#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000297
Greg Claytone38a5ed2012-01-05 03:57:59 +0000298void
299Host::SystemLog (SystemLogType type, const char *format, ...)
300{
301 va_list args;
302 va_start (args, format);
303 SystemLog (type, format, args);
304 va_end (args);
305}
306
Greg Clayton2bddd342010-09-07 20:11:56 +0000307const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000308Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000309{
Greg Clayton514487e2011-02-15 21:59:32 +0000310 static bool g_supports_32 = false;
311 static bool g_supports_64 = false;
312 static ArchSpec g_host_arch_32;
313 static ArchSpec g_host_arch_64;
314
Greg Clayton2bddd342010-09-07 20:11:56 +0000315#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000316
317 // Apple is different in that it can support both 32 and 64 bit executables
318 // in the same operating system running concurrently. Here we detect the
319 // correct host architectures for both 32 and 64 bit including if 64 bit
320 // executables are supported on the system.
321
322 if (g_supports_32 == false && g_supports_64 == false)
323 {
324 // All apple systems support 32 bit execution.
325 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000326 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000327 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000328 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000329 ArchSpec host_arch;
330 // These will tell us about the kernel architecture, which even on a 64
331 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000332 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
333 {
Greg Clayton514487e2011-02-15 21:59:32 +0000334 len = sizeof (cpusubtype);
335 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
336 cpusubtype = CPU_TYPE_ANY;
337
Greg Clayton2bddd342010-09-07 20:11:56 +0000338 len = sizeof (is_64_bit_capable);
339 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
340 {
341 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000342 g_supports_64 = true;
343 }
344
345 if (is_64_bit_capable)
346 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000347#if defined (__i386__) || defined (__x86_64__)
348 if (cpusubtype == CPU_SUBTYPE_486)
349 cpusubtype = CPU_SUBTYPE_I386_ALL;
350#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000351 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000352 {
Greg Clayton514487e2011-02-15 21:59:32 +0000353 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000354 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
355 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000356 }
357 else
358 {
359 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000360 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000361 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000362 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000363 }
364 }
Greg Clayton514487e2011-02-15 21:59:32 +0000365 else
366 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000367 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000368 g_host_arch_64.Clear();
369 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000370 }
Greg Clayton514487e2011-02-15 21:59:32 +0000371 }
372
373#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000374
Greg Clayton514487e2011-02-15 21:59:32 +0000375 if (g_supports_32 == false && g_supports_64 == false)
376 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000377 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000378
Stephen Wilsonbd588712011-02-24 19:15:09 +0000379 g_host_arch_32.Clear();
380 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000381
Greg Claytonb29e6c62012-10-11 17:38:58 +0000382 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
383 // for the default triple. It's probably an artifact of config.guess.
384 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000385 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000386
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000387 const char* distribution_id = GetDistributionId ().AsCString();
388
Stephen Wilsonbd588712011-02-24 19:15:09 +0000389 switch (triple.getArch())
390 {
391 default:
392 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000393 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000394 g_supports_32 = true;
395 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000396
Stephen Wilsonbd588712011-02-24 19:15:09 +0000397 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000398 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000399 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000400 g_supports_64 = true;
401 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000402 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000403 g_supports_32 = true;
404 break;
405
Ed Mastea8375762014-04-01 18:06:45 +0000406 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000407 case llvm::Triple::sparcv9:
408 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000409 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000410 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000411 g_supports_64 = true;
412 break;
413 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000414
415 g_supports_32 = g_host_arch_32.IsValid();
416 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000417 }
Greg Clayton514487e2011-02-15 21:59:32 +0000418
419#endif // #else for #if defined (__APPLE__)
420
421 if (arch_kind == eSystemDefaultArchitecture32)
422 return g_host_arch_32;
423 else if (arch_kind == eSystemDefaultArchitecture64)
424 return g_host_arch_64;
425
426 if (g_supports_64)
427 return g_host_arch_64;
428
429 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000430}
431
432const ConstString &
433Host::GetVendorString()
434{
435 static ConstString g_vendor;
436 if (!g_vendor)
437 {
Greg Clayton950971f2012-05-12 00:01:21 +0000438 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
439 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
440 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000441 }
442 return g_vendor;
443}
444
445const ConstString &
446Host::GetOSString()
447{
448 static ConstString g_os_string;
449 if (!g_os_string)
450 {
Greg Clayton950971f2012-05-12 00:01:21 +0000451 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
452 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
453 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000454 }
455 return g_os_string;
456}
457
458const ConstString &
459Host::GetTargetTriple()
460{
461 static ConstString g_host_triple;
462 if (!(g_host_triple))
463 {
Greg Clayton950971f2012-05-12 00:01:21 +0000464 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
465 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000466 }
467 return g_host_triple;
468}
469
Todd Fialaf3d61de2014-01-17 20:18:59 +0000470// See linux/Host.cpp for Linux-based implementations of this.
471// Add your platform-specific implementation to the appropriate host file.
472#if !defined(__linux__)
473
474const ConstString &
475 Host::GetDistributionId ()
476{
477 static ConstString s_distribution_id;
478 return s_distribution_id;
479}
480
481#endif // #if !defined(__linux__)
482
Greg Clayton2bddd342010-09-07 20:11:56 +0000483lldb::pid_t
484Host::GetCurrentProcessID()
485{
486 return ::getpid();
487}
488
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000489#ifndef _WIN32
490
Greg Clayton2bddd342010-09-07 20:11:56 +0000491lldb::tid_t
492Host::GetCurrentThreadID()
493{
494#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000495 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000496 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
497 // count.
498 thread_port_t thread_self = mach_thread_self();
499 mach_port_deallocate(mach_task_self(), thread_self);
500 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000501#elif defined(__FreeBSD__)
502 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000503#elif defined(__linux__)
504 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000505#else
506 return lldb::tid_t(pthread_self());
507#endif
508}
509
Jim Ingham372787f2012-04-07 00:00:41 +0000510lldb::thread_t
511Host::GetCurrentThread ()
512{
513 return lldb::thread_t(pthread_self());
514}
515
Greg Clayton2bddd342010-09-07 20:11:56 +0000516const char *
517Host::GetSignalAsCString (int signo)
518{
519 switch (signo)
520 {
521 case SIGHUP: return "SIGHUP"; // 1 hangup
522 case SIGINT: return "SIGINT"; // 2 interrupt
523 case SIGQUIT: return "SIGQUIT"; // 3 quit
524 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
525 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
526 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000527#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000528#if !defined(SIGIO) || (SIGPOLL != SIGIO)
529// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
530// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000531 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000532#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000533#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000534#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000535 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000536#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000537 case SIGFPE: return "SIGFPE"; // 8 floating point exception
538 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
539 case SIGBUS: return "SIGBUS"; // 10 bus error
540 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
541 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
542 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
543 case SIGALRM: return "SIGALRM"; // 14 alarm clock
544 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
545 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
546 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
547 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
548 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
549 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
550 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
551 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000552#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000553 case SIGIO: return "SIGIO"; // 23 input/output possible signal
554#endif
555 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
556 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
557 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
558 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000559#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000560 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000561#endif
562#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000563 case SIGINFO: return "SIGINFO"; // 29 information request
564#endif
565 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
566 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
567 default:
568 break;
569 }
570 return NULL;
571}
572
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000573#endif
574
Greg Clayton2bddd342010-09-07 20:11:56 +0000575void
576Host::WillTerminate ()
577{
578}
579
Sylvestre Ledru59405832013-07-01 08:21:36 +0000580#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000581
Greg Clayton2bddd342010-09-07 20:11:56 +0000582void
583Host::ThreadCreated (const char *thread_name)
584{
585}
Greg Claytone5219662010-12-03 06:02:24 +0000586
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000587void
Greg Claytone5219662010-12-03 06:02:24 +0000588Host::Backtrace (Stream &strm, uint32_t max_frames)
589{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000590 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000591}
592
Greg Clayton85851dd2010-12-04 00:10:17 +0000593size_t
594Host::GetEnvironment (StringList &env)
595{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000596 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000597 return 0;
598}
599
Sylvestre Ledru59405832013-07-01 08:21:36 +0000600#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000601
602struct HostThreadCreateInfo
603{
604 std::string thread_name;
605 thread_func_t thread_fptr;
606 thread_arg_t thread_arg;
607
608 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
609 thread_name (name ? name : ""),
610 thread_fptr (fptr),
611 thread_arg (arg)
612 {
613 }
614};
615
616static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000617#ifdef _WIN32
618__stdcall
619#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000620ThreadCreateTrampoline (thread_arg_t arg)
621{
622 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
623 Host::ThreadCreated (info->thread_name.c_str());
624 thread_func_t thread_fptr = info->thread_fptr;
625 thread_arg_t thread_arg = info->thread_arg;
626
Greg Clayton5160ce52013-03-27 23:08:40 +0000627 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000628 if (log)
629 log->Printf("thread created");
630
631 delete info;
632 return thread_fptr (thread_arg);
633}
634
635lldb::thread_t
636Host::ThreadCreate
637(
638 const char *thread_name,
639 thread_func_t thread_fptr,
640 thread_arg_t thread_arg,
641 Error *error
642)
643{
644 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
645
646 // Host::ThreadCreateTrampoline will delete this pointer for us.
647 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
648
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000649#ifdef _WIN32
650 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
651 int err = thread <= 0 ? GetLastError() : 0;
652#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000653 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000654#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000655 if (err == 0)
656 {
657 if (error)
658 error->Clear();
659 return thread;
660 }
661
662 if (error)
663 error->SetError (err, eErrorTypePOSIX);
664
665 return LLDB_INVALID_HOST_THREAD;
666}
667
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000668#ifndef _WIN32
669
Greg Clayton2bddd342010-09-07 20:11:56 +0000670bool
671Host::ThreadCancel (lldb::thread_t thread, Error *error)
672{
673 int err = ::pthread_cancel (thread);
674 if (error)
675 error->SetError(err, eErrorTypePOSIX);
676 return err == 0;
677}
678
679bool
680Host::ThreadDetach (lldb::thread_t thread, Error *error)
681{
682 int err = ::pthread_detach (thread);
683 if (error)
684 error->SetError(err, eErrorTypePOSIX);
685 return err == 0;
686}
687
688bool
689Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
690{
691 int err = ::pthread_join (thread, thread_result_ptr);
692 if (error)
693 error->SetError(err, eErrorTypePOSIX);
694 return err == 0;
695}
696
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000697lldb::thread_key_t
698Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
699{
700 pthread_key_t key;
701 ::pthread_key_create (&key, callback);
702 return key;
703}
704
705void*
706Host::ThreadLocalStorageGet(lldb::thread_key_t key)
707{
708 return ::pthread_getspecific (key);
709}
710
711void
712Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
713{
714 ::pthread_setspecific (key, value);
715}
716
Matt Kopec62502c62013-05-13 19:33:58 +0000717bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000718Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
719{
Greg Clayton85719632013-02-27 22:51:58 +0000720#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000721 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
722 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
723 if (pid == LLDB_INVALID_PROCESS_ID)
724 pid = curr_pid;
725
726 if (tid == LLDB_INVALID_THREAD_ID)
727 tid = curr_tid;
728
Greg Clayton2bddd342010-09-07 20:11:56 +0000729 // Set the pthread name if possible
730 if (pid == curr_pid && tid == curr_tid)
731 {
Matt Kopec62502c62013-05-13 19:33:58 +0000732 if (::pthread_setname_np (name) == 0)
733 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000734 }
Matt Kopec62502c62013-05-13 19:33:58 +0000735 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000736#elif defined (__FreeBSD__)
737 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
738 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
739 if (pid == LLDB_INVALID_PROCESS_ID)
740 pid = curr_pid;
741
742 if (tid == LLDB_INVALID_THREAD_ID)
743 tid = curr_tid;
744
745 // Set the pthread name if possible
746 if (pid == curr_pid && tid == curr_tid)
747 {
Michael Sartainc2052432013-08-01 18:51:08 +0000748 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000749 return true;
750 }
751 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000752#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000753 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
754 if (fn)
755 {
Matt Kopec62502c62013-05-13 19:33:58 +0000756 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
757 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000758 if (pid == LLDB_INVALID_PROCESS_ID)
759 pid = curr_pid;
760
761 if (tid == LLDB_INVALID_THREAD_ID)
762 tid = curr_tid;
763
Michael Sartainc2052432013-08-01 18:51:08 +0000764 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000765 {
Michael Sartainc2052432013-08-01 18:51:08 +0000766 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
767 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
768
769 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000770 return true;
771 }
772 }
773 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000774#else
775 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000776#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000777}
778
Ed Maste02983be2013-07-25 19:10:32 +0000779bool
780Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
781 const char *thread_name, size_t len)
782{
Enrico Granata67530b62014-02-12 03:37:33 +0000783 std::unique_ptr<char[]> namebuf(new char[len+1]);
784
Ed Maste02983be2013-07-25 19:10:32 +0000785 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
786 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
787 // off leads to a lot of similar named threads. Go through the thread name
788 // and search for the last dot and use that.
789 const char *lastdot = ::strrchr (thread_name, '.');
790
791 if (lastdot && lastdot != thread_name)
792 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000793 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000794 namebuf[len] = 0;
795
Enrico Granata67530b62014-02-12 03:37:33 +0000796 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000797 if (namebuflen > 0)
798 {
799 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
800 {
801 // Trim off trailing '(' and '>' characters for a bit more cleanup.
802 namebuflen--;
803 namebuf[namebuflen] = 0;
804 }
Enrico Granata67530b62014-02-12 03:37:33 +0000805 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000806 }
807 return false;
808}
809
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000810#endif
811
Greg Clayton2bddd342010-09-07 20:11:56 +0000812FileSpec
813Host::GetProgramFileSpec ()
814{
815 static FileSpec g_program_filespec;
816 if (!g_program_filespec)
817 {
818#if defined (__APPLE__)
819 char program_fullpath[PATH_MAX];
820 // If DST is NULL, then return the number of bytes needed.
821 uint32_t len = sizeof(program_fullpath);
822 int err = _NSGetExecutablePath (program_fullpath, &len);
823 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000824 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000825 else if (err == -1)
826 {
827 char *large_program_fullpath = (char *)::malloc (len + 1);
828
829 err = _NSGetExecutablePath (large_program_fullpath, &len);
830 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000831 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000832
833 ::free (large_program_fullpath);
834 }
835#elif defined (__linux__)
836 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000837 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
838 if (len > 0) {
839 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000840 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000841 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000842#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000843 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
844 size_t exe_path_size;
845 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
846 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000847 char *exe_path = new char[exe_path_size];
848 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
849 g_program_filespec.SetFile(exe_path, false);
850 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000851 }
852#endif
853 }
854 return g_program_filespec;
855}
856
Greg Clayton2bddd342010-09-07 20:11:56 +0000857#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000858
859bool
860Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
861{
862 bundle.Clear();
863 return false;
864}
865
Greg Clayton2bddd342010-09-07 20:11:56 +0000866bool
Greg Claytondd36def2010-10-17 22:03:32 +0000867Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000868{
Greg Claytondd36def2010-10-17 22:03:32 +0000869 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000870}
871#endif
872
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000873#ifndef _WIN32
874
Greg Clayton45319462011-02-08 00:35:34 +0000875// Opaque info that tracks a dynamic library that was loaded
876struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000877{
Greg Clayton45319462011-02-08 00:35:34 +0000878 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
879 file_spec (fs),
880 open_options (o),
881 handle (h)
882 {
883 }
884
885 const FileSpec file_spec;
886 uint32_t open_options;
887 void * handle;
888};
889
890void *
891Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
892{
Greg Clayton4272cc72011-02-02 02:24:04 +0000893 char path[PATH_MAX];
894 if (file_spec.GetPath(path, sizeof(path)))
895 {
Greg Clayton45319462011-02-08 00:35:34 +0000896 int mode = 0;
897
898 if (options & eDynamicLibraryOpenOptionLazy)
899 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000900 else
901 mode |= RTLD_NOW;
902
Greg Clayton45319462011-02-08 00:35:34 +0000903
904 if (options & eDynamicLibraryOpenOptionLocal)
905 mode |= RTLD_LOCAL;
906 else
907 mode |= RTLD_GLOBAL;
908
909#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
910 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
911 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000912#endif
Greg Clayton45319462011-02-08 00:35:34 +0000913
914 void * opaque = ::dlopen (path, mode);
915
916 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000917 {
918 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000919 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000920 }
921 else
922 {
923 error.SetErrorString(::dlerror());
924 }
925 }
926 else
927 {
928 error.SetErrorString("failed to extract path");
929 }
Greg Clayton45319462011-02-08 00:35:34 +0000930 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000931}
932
933Error
Greg Clayton45319462011-02-08 00:35:34 +0000934Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000935{
936 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000937 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000938 {
939 error.SetErrorString ("invalid dynamic library handle");
940 }
Greg Clayton45319462011-02-08 00:35:34 +0000941 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000942 {
Greg Clayton45319462011-02-08 00:35:34 +0000943 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
944 if (::dlclose (dylib_info->handle) != 0)
945 {
946 error.SetErrorString(::dlerror());
947 }
948
949 dylib_info->open_options = 0;
950 dylib_info->handle = 0;
951 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000952 }
953 return error;
954}
955
956void *
Greg Clayton45319462011-02-08 00:35:34 +0000957Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000958{
Greg Clayton45319462011-02-08 00:35:34 +0000959 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000960 {
961 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000962 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000963 else
Greg Clayton45319462011-02-08 00:35:34 +0000964 {
965 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
966
967 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
968 if (symbol_addr)
969 {
970#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
971 // This host doesn't support limiting searches to this shared library
972 // so we need to verify that the match came from this shared library
973 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000974 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000975 {
976 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
977 if (match_dylib_spec != dylib_info->file_spec)
978 {
979 char dylib_path[PATH_MAX];
980 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
981 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
982 else
983 error.SetErrorString ("symbol not found");
984 return NULL;
985 }
986 }
987#endif
988 error.Clear();
989 return symbol_addr;
990 }
991 else
992 {
993 error.SetErrorString(::dlerror());
994 }
995 }
996 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000997}
Greg Claytondd36def2010-10-17 22:03:32 +0000998
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000999FileSpec
1000Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1001{
1002 FileSpec module_filespec;
1003 Dl_info info;
1004 if (::dladdr (host_addr, &info))
1005 {
1006 if (info.dli_fname)
1007 module_filespec.SetFile(info.dli_fname, true);
1008 }
1009 return module_filespec;
1010}
1011
1012#endif
1013
Greg Clayton23f8c952014-03-24 23:10:19 +00001014
1015static void CleanupProcessSpecificLLDBTempDir ()
1016{
1017 // Get the process specific LLDB temporary directory and delete it.
1018 FileSpec tmpdir_file_spec;
1019 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1020 {
1021 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1022 // true to all files that were created for the LLDB process can be cleaned up.
1023 const bool recurse = true;
1024 Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1025 }
1026}
1027
Greg Claytondd36def2010-10-17 22:03:32 +00001028bool
1029Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1030{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001031 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001032 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1033 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001034 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001035 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001036 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001037
1038 switch (path_type)
1039 {
1040 case ePathTypeLLDBShlibDir:
1041 {
1042 static ConstString g_lldb_so_dir;
1043 if (!g_lldb_so_dir)
1044 {
1045 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
1046 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001047 if (log)
1048 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001049 }
1050 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001051 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001052 }
1053 break;
1054
1055 case ePathTypeSupportExecutableDir:
1056 {
1057 static ConstString g_lldb_support_exe_dir;
1058 if (!g_lldb_support_exe_dir)
1059 {
1060 FileSpec lldb_file_spec;
1061 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1062 {
1063 char raw_path[PATH_MAX];
1064 char resolved_path[PATH_MAX];
1065 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1066
1067#if defined (__APPLE__)
1068 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1069 if (framework_pos)
1070 {
1071 framework_pos += strlen("LLDB.framework");
Jason Molendaa3329782014-03-29 18:54:20 +00001072#if defined (__arm__) || defined (__arm64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001073 // Shallow bundle
1074 *framework_pos = '\0';
1075#else
1076 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001077 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001078#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001079 }
Jason Molendaa3329782014-03-29 18:54:20 +00001080#endif // #if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001081 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1082 g_lldb_support_exe_dir.SetCString(resolved_path);
1083 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001084 if (log)
1085 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001086 }
1087 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001088 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001089 }
1090 break;
1091
1092 case ePathTypeHeaderDir:
1093 {
1094 static ConstString g_lldb_headers_dir;
1095 if (!g_lldb_headers_dir)
1096 {
1097#if defined (__APPLE__)
1098 FileSpec lldb_file_spec;
1099 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1100 {
1101 char raw_path[PATH_MAX];
1102 char resolved_path[PATH_MAX];
1103 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1104
1105 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1106 if (framework_pos)
1107 {
1108 framework_pos += strlen("LLDB.framework");
1109 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1110 }
1111 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1112 g_lldb_headers_dir.SetCString(resolved_path);
1113 }
1114#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001115 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001116 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1117#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001118 if (log)
1119 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001120 }
1121 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001122 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001123 }
1124 break;
1125
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001126#ifdef LLDB_DISABLE_PYTHON
1127 case ePathTypePythonDir:
1128 return false;
1129#else
1130 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001131 {
Greg Claytondd36def2010-10-17 22:03:32 +00001132 static ConstString g_lldb_python_dir;
1133 if (!g_lldb_python_dir)
1134 {
1135 FileSpec lldb_file_spec;
1136 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1137 {
1138 char raw_path[PATH_MAX];
1139 char resolved_path[PATH_MAX];
1140 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1141
1142#if defined (__APPLE__)
1143 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1144 if (framework_pos)
1145 {
1146 framework_pos += strlen("LLDB.framework");
1147 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001148 }
1149 else
1150 {
1151#endif
1152 llvm::SmallString<256> python_version_dir;
1153 llvm::raw_svector_ostream os(python_version_dir);
1154 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1155 os.flush();
1156
1157 // We may get our string truncated. Should we protect
1158 // this with an assert?
1159
1160 ::strncat(raw_path, python_version_dir.c_str(),
1161 sizeof(raw_path) - strlen(raw_path) - 1);
1162
1163#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001164 }
1165#endif
1166 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1167 g_lldb_python_dir.SetCString(resolved_path);
1168 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001169
1170 if (log)
1171 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1172
Greg Claytondd36def2010-10-17 22:03:32 +00001173 }
1174 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001175 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001176 }
1177 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001178#endif
1179
Greg Clayton4272cc72011-02-02 02:24:04 +00001180 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1181 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001182#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001183 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001184 static bool g_lldb_system_plugin_dir_located = false;
1185 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001186 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001187 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001188#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001189 FileSpec lldb_file_spec;
1190 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1191 {
1192 char raw_path[PATH_MAX];
1193 char resolved_path[PATH_MAX];
1194 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1195
1196 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1197 if (framework_pos)
1198 {
1199 framework_pos += strlen("LLDB.framework");
1200 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001201 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1202 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001203 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001204 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001205 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001206#elif defined (__linux__)
1207 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1208 if (lldb_file_spec.Exists())
1209 {
1210 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1211 }
1212#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001213
1214 if (log)
1215 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1216
Greg Clayton4272cc72011-02-02 02:24:04 +00001217 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001218
1219 if (g_lldb_system_plugin_dir)
1220 {
1221 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1222 return true;
1223 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001224#else
1225 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001226 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001227#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001228 }
1229 break;
1230
1231 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1232 {
1233#if defined (__APPLE__)
1234 static ConstString g_lldb_user_plugin_dir;
1235 if (!g_lldb_user_plugin_dir)
1236 {
1237 char user_plugin_path[PATH_MAX];
1238 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1239 user_plugin_path,
1240 sizeof(user_plugin_path)))
1241 {
1242 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1243 }
1244 }
1245 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001246 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001247#elif defined (__linux__)
1248 static ConstString g_lldb_user_plugin_dir;
1249 if (!g_lldb_user_plugin_dir)
1250 {
1251 // XDG Base Directory Specification
1252 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1253 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1254 FileSpec lldb_file_spec;
1255 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1256 if (xdg_data_home && xdg_data_home[0])
1257 {
1258 std::string user_plugin_dir (xdg_data_home);
1259 user_plugin_dir += "/lldb";
1260 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1261 }
1262 else
1263 {
1264 const char *home_dir = getenv("HOME");
1265 if (home_dir && home_dir[0])
1266 {
1267 std::string user_plugin_dir (home_dir);
1268 user_plugin_dir += "/.local/share/lldb";
1269 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1270 }
1271 }
1272
1273 if (lldb_file_spec.Exists())
1274 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001275 if (log)
1276 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001277 }
1278 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001279 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001280#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001281 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001282 return false;
1283 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001284
1285 case ePathTypeLLDBTempSystemDir:
1286 {
1287 static ConstString g_lldb_tmp_dir;
1288 if (!g_lldb_tmp_dir)
1289 {
1290 const char *tmpdir_cstr = getenv("TMPDIR");
1291 if (tmpdir_cstr == NULL)
1292 {
1293 tmpdir_cstr = getenv("TMP");
1294 if (tmpdir_cstr == NULL)
1295 tmpdir_cstr = getenv("TEMP");
1296 }
1297 if (tmpdir_cstr)
1298 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001299 StreamString pid_tmpdir;
1300 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1301 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1302 {
1303 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1304 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1305 {
1306 // Make an atexit handler to clean up the process specify LLDB temp dir
1307 // and all of its contents.
1308 ::atexit (CleanupProcessSpecificLLDBTempDir);
1309 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1310 if (log)
1311 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1312
1313 }
1314 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001315 }
1316 }
1317 file_spec.GetDirectory() = g_lldb_tmp_dir;
1318 return (bool)file_spec.GetDirectory();
1319 }
Greg Claytondd36def2010-10-17 22:03:32 +00001320 }
1321
1322 return false;
1323}
1324
Greg Clayton1cb64962011-03-24 04:28:38 +00001325
1326bool
1327Host::GetHostname (std::string &s)
1328{
1329 char hostname[PATH_MAX];
1330 hostname[sizeof(hostname) - 1] = '\0';
1331 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1332 {
1333 struct hostent* h = ::gethostbyname (hostname);
1334 if (h)
1335 s.assign (h->h_name);
1336 else
1337 s.assign (hostname);
1338 return true;
1339 }
1340 return false;
1341}
1342
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001343#ifndef _WIN32
1344
Greg Clayton32e0a752011-03-30 18:16:51 +00001345const char *
1346Host::GetUserName (uint32_t uid, std::string &user_name)
1347{
1348 struct passwd user_info;
1349 struct passwd *user_info_ptr = &user_info;
1350 char user_buffer[PATH_MAX];
1351 size_t user_buffer_size = sizeof(user_buffer);
1352 if (::getpwuid_r (uid,
1353 &user_info,
1354 user_buffer,
1355 user_buffer_size,
1356 &user_info_ptr) == 0)
1357 {
1358 if (user_info_ptr)
1359 {
1360 user_name.assign (user_info_ptr->pw_name);
1361 return user_name.c_str();
1362 }
1363 }
1364 user_name.clear();
1365 return NULL;
1366}
1367
1368const char *
1369Host::GetGroupName (uint32_t gid, std::string &group_name)
1370{
1371 char group_buffer[PATH_MAX];
1372 size_t group_buffer_size = sizeof(group_buffer);
1373 struct group group_info;
1374 struct group *group_info_ptr = &group_info;
1375 // Try the threadsafe version first
1376 if (::getgrgid_r (gid,
1377 &group_info,
1378 group_buffer,
1379 group_buffer_size,
1380 &group_info_ptr) == 0)
1381 {
1382 if (group_info_ptr)
1383 {
1384 group_name.assign (group_info_ptr->gr_name);
1385 return group_name.c_str();
1386 }
1387 }
1388 else
1389 {
1390 // The threadsafe version isn't currently working
1391 // for me on darwin, but the non-threadsafe version
1392 // is, so I am calling it below.
1393 group_info_ptr = ::getgrgid (gid);
1394 if (group_info_ptr)
1395 {
1396 group_name.assign (group_info_ptr->gr_name);
1397 return group_name.c_str();
1398 }
1399 }
1400 group_name.clear();
1401 return NULL;
1402}
1403
Han Ming Ong84647042012-02-25 01:07:38 +00001404uint32_t
1405Host::GetUserID ()
1406{
1407 return getuid();
1408}
1409
1410uint32_t
1411Host::GetGroupID ()
1412{
1413 return getgid();
1414}
1415
1416uint32_t
1417Host::GetEffectiveUserID ()
1418{
1419 return geteuid();
1420}
1421
1422uint32_t
1423Host::GetEffectiveGroupID ()
1424{
1425 return getegid();
1426}
1427
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001428#endif
1429
1430#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1431bool
1432Host::GetOSBuildString (std::string &s)
1433{
1434 s.clear();
1435 return false;
1436}
1437
1438bool
1439Host::GetOSKernelDescription (std::string &s)
1440{
1441 s.clear();
1442 return false;
1443}
1444#endif
1445
Ed Maste47e575e2013-08-29 18:44:27 +00001446#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001447uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001448Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001449{
1450 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001451 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001452}
1453
Greg Claytone996fd32011-03-08 22:40:15 +00001454bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001455Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001456{
Greg Claytone996fd32011-03-08 22:40:15 +00001457 process_info.Clear();
1458 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001459}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001460#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001461
Matt Kopec085d6ce2013-05-31 22:00:07 +00001462#if !defined(__linux__)
1463bool
1464Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1465{
1466 return false;
1467}
1468#endif
1469
Sean Callananc0a6e062011-10-27 21:22:25 +00001470lldb::TargetSP
1471Host::GetDummyTarget (lldb_private::Debugger &debugger)
1472{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001473 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001474
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001475 // FIXME: Maybe the dummy target should be per-Debugger
1476 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1477 {
1478 ArchSpec arch(Target::GetDefaultArchitecture());
1479 if (!arch.IsValid())
1480 arch = Host::GetArchitecture ();
1481 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001482 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001483 arch.GetTriple().getTriple().c_str(),
1484 false,
1485 NULL,
1486 g_dummy_target_sp);
1487 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001488
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001489 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001490}
1491
Greg Claytond1cf11a2012-04-14 01:42:46 +00001492struct ShellInfo
1493{
1494 ShellInfo () :
1495 process_reaped (false),
1496 can_delete (false),
1497 pid (LLDB_INVALID_PROCESS_ID),
1498 signo(-1),
1499 status(-1)
1500 {
1501 }
1502
1503 lldb_private::Predicate<bool> process_reaped;
1504 lldb_private::Predicate<bool> can_delete;
1505 lldb::pid_t pid;
1506 int signo;
1507 int status;
1508};
1509
1510static bool
1511MonitorShellCommand (void *callback_baton,
1512 lldb::pid_t pid,
1513 bool exited, // True if the process did exit
1514 int signo, // Zero for no signal
1515 int status) // Exit value of process if signal is zero
1516{
1517 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1518 shell_info->pid = pid;
1519 shell_info->signo = signo;
1520 shell_info->status = status;
1521 // Let the thread running Host::RunShellCommand() know that the process
1522 // exited and that ShellInfo has been filled in by broadcasting to it
1523 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1524 // Now wait for a handshake back from that thread running Host::RunShellCommand
1525 // so we know that we can delete shell_info_ptr
1526 shell_info->can_delete.WaitForValueEqualTo(true);
1527 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1528 usleep(1000);
1529 // Now delete the shell info that was passed into this function
1530 delete shell_info;
1531 return true;
1532}
1533
1534Error
1535Host::RunShellCommand (const char *command,
1536 const char *working_dir,
1537 int *status_ptr,
1538 int *signo_ptr,
1539 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001540 uint32_t timeout_sec,
1541 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001542{
1543 Error error;
1544 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001545 if (shell && shell[0])
1546 {
1547 // Run the command in a shell
1548 launch_info.SetShell(shell);
1549 launch_info.GetArguments().AppendArgument(command);
1550 const bool localhost = true;
1551 const bool will_debug = false;
1552 const bool first_arg_is_full_shell_command = true;
1553 launch_info.ConvertArgumentsForLaunchingInShell (error,
1554 localhost,
1555 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001556 first_arg_is_full_shell_command,
1557 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001558 }
1559 else
1560 {
1561 // No shell, just run it
1562 Args args (command);
1563 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001564 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001565 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001566
1567 if (working_dir)
1568 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001569 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001570 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001571
Greg Claytond1cf11a2012-04-14 01:42:46 +00001572 if (command_output_ptr)
1573 {
1574 // Create a temporary file to get the stdout/stderr and redirect the
1575 // output of the command into this file. We will later read this file
1576 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001577 FileSpec tmpdir_file_spec;
1578 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1579 {
1580 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1581 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1582 }
1583 else
1584 {
1585 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1586 }
1587
1588 output_file_path = ::mktemp(output_file_path_buffer);
1589 }
1590
1591 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1592 if (output_file_path)
1593 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001594 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001595 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001596 }
1597 else
1598 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001599 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1600 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1601 }
1602
1603 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001604 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001605
1606 const bool monitor_signals = false;
1607 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1608
1609 error = LaunchProcess (launch_info);
1610 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001611
1612 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1613 error.SetErrorString("failed to get process ID");
1614
1615 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001616 {
1617 // The process successfully launched, so we can defer ownership of
1618 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001619 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001620 // doesn't need to delete the ShellInfo anymore.
1621 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001622 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001623 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001624 if (timeout_sec > 0) {
1625 timeout_time.OffsetWithSeconds(timeout_sec);
1626 timeout_ptr = &timeout_time;
1627 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001628 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001629 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001630 if (timed_out)
1631 {
1632 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001633
Greg Claytond1cf11a2012-04-14 01:42:46 +00001634 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001635 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001636 // Wait for the monitor callback to get the message
1637 timeout_time = TimeValue::Now();
1638 timeout_time.OffsetWithSeconds(1);
1639 timed_out = false;
1640 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1641 }
1642 else
1643 {
1644 if (status_ptr)
1645 *status_ptr = shell_info->status;
1646
1647 if (signo_ptr)
1648 *signo_ptr = shell_info->signo;
1649
1650 if (command_output_ptr)
1651 {
1652 command_output_ptr->clear();
1653 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1654 uint64_t file_size = file_spec.GetByteSize();
1655 if (file_size > 0)
1656 {
1657 if (file_size > command_output_ptr->max_size())
1658 {
1659 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1660 }
1661 else
1662 {
1663 command_output_ptr->resize(file_size);
1664 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1665 }
1666 }
1667 }
1668 }
1669 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1670 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001671
1672 if (output_file_path)
1673 ::unlink (output_file_path);
1674 // Handshake with the monitor thread, or just let it know in advance that
1675 // it can delete "shell_info" in case we timed out and were not able to kill
1676 // the process...
1677 return error;
1678}
1679
Daniel Malea4244cbd2013-08-27 20:58:59 +00001680
Todd Fiala76747122014-01-23 00:52:28 +00001681// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1682// systems
1683
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001684#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001685
1686// this method needs to be visible to macosx/Host.cpp and
1687// common/Host.cpp.
1688
1689short
1690Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1691{
1692 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1693
1694#if defined (__APPLE__)
1695 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1696 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1697
1698 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1699 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1700
1701 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1702 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1703
1704 if (launch_info.GetLaunchInSeparateProcessGroup())
1705 flags |= POSIX_SPAWN_SETPGROUP;
1706
1707#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1708#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1709 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1710 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1711 {
1712 g_use_close_on_exec_flag = eLazyBoolNo;
1713
1714 uint32_t major, minor, update;
1715 if (Host::GetOSVersion(major, minor, update))
1716 {
1717 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1718 if (major > 10 || (major == 10 && minor > 7))
1719 {
1720 // Only enable for 10.8 and later OS versions
1721 g_use_close_on_exec_flag = eLazyBoolYes;
1722 }
1723 }
1724 }
1725#else
1726 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1727#endif
1728 // Close all files exception those with file actions if this is supported.
1729 if (g_use_close_on_exec_flag == eLazyBoolYes)
1730 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1731#endif
1732#endif // #if defined (__APPLE__)
1733 return flags;
1734}
1735
1736Error
1737Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001738{
1739 Error error;
1740 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1741
Daniel Malea4244cbd2013-08-27 20:58:59 +00001742 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001743 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001744
1745 if (error.Fail() || log)
1746 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001747 if (error.Fail())
1748 return error;
1749
1750 // Make a quick class that will cleanup the posix spawn attributes in case
1751 // we return in the middle of this function.
1752 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1753
1754 sigset_t no_signals;
1755 sigset_t all_signals;
1756 sigemptyset (&no_signals);
1757 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001758 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001759#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001760 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001761#else
1762 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1763#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001764
Todd Fiala76747122014-01-23 00:52:28 +00001765 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001766
1767 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001768 if (error.Fail() || log)
1769 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001770 if (error.Fail())
1771 return error;
1772
Todd Fiala76747122014-01-23 00:52:28 +00001773 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1774 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1775#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001776
1777 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1778 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1779 // to do that job on OSX.
1780
1781 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001782 {
Jim Ingham90331d52014-02-21 01:25:21 +00001783 // We don't need to do this for ARM, and we really shouldn't now that we
1784 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1785 // to set which CPU subtype to launch...
1786 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1787 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1788 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1789 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001790 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1791 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001792 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1793 {
1794 size_t ocount = 0;
1795 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1796 if (error.Fail() || log)
1797 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu, (uint64_t)ocount);
Todd Fiala76747122014-01-23 00:52:28 +00001798
Jim Ingham90331d52014-02-21 01:25:21 +00001799 if (error.Fail() || ocount != 1)
1800 return error;
1801 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001802 }
1803
Todd Fiala76747122014-01-23 00:52:28 +00001804#endif
1805
1806 const char *tmp_argv[2];
1807 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1808 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1809 if (argv == NULL)
1810 {
1811 // posix_spawn gets very unhappy if it doesn't have at least the program
1812 // name in argv[0]. One of the side affects I have noticed is the environment
1813 // variables don't make it into the child process if "argv == NULL"!!!
1814 tmp_argv[0] = exe_path;
1815 tmp_argv[1] = NULL;
1816 argv = (char * const*)tmp_argv;
1817 }
1818
1819#if !defined (__APPLE__)
1820 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001821 char current_dir[PATH_MAX];
1822 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001823#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001824
1825 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001826 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001827 {
Todd Fiala76747122014-01-23 00:52:28 +00001828#if defined (__APPLE__)
1829 // Set the working directory on this thread only
1830 if (__pthread_chdir (working_dir) < 0) {
1831 if (errno == ENOENT) {
1832 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1833 } else if (errno == ENOTDIR) {
1834 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1835 } else {
1836 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1837 }
1838 return error;
1839 }
1840#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001841 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1842 {
1843 error.SetError(errno, eErrorTypePOSIX);
1844 error.LogIfError(log, "unable to save the current directory");
1845 return error;
1846 }
1847
1848 if (::chdir(working_dir) == -1)
1849 {
1850 error.SetError(errno, eErrorTypePOSIX);
1851 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1852 return error;
1853 }
Todd Fiala76747122014-01-23 00:52:28 +00001854#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001855 }
1856
Todd Fiala76747122014-01-23 00:52:28 +00001857 const size_t num_file_actions = launch_info.GetNumFileActions ();
1858 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001859 {
Todd Fiala76747122014-01-23 00:52:28 +00001860 posix_spawn_file_actions_t file_actions;
1861 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1862 if (error.Fail() || log)
1863 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1864 if (error.Fail())
1865 return error;
1866
1867 // Make a quick class that will cleanup the posix spawn attributes in case
1868 // we return in the middle of this function.
1869 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1870
1871 for (size_t i=0; i<num_file_actions; ++i)
1872 {
1873 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1874 if (launch_file_action)
1875 {
1876 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1877 launch_file_action,
1878 log,
1879 error))
1880 return error;
1881 }
1882 }
1883
1884 error.SetError (::posix_spawnp (&pid,
1885 exe_path,
1886 &file_actions,
1887 &attr,
1888 argv,
1889 envp),
1890 eErrorTypePOSIX);
1891
1892 if (error.Fail() || log)
1893 {
1894 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001895 pid, exe_path, static_cast<void*>(&file_actions),
1896 static_cast<void*>(&attr),
1897 reinterpret_cast<const void*>(argv),
1898 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001899 if (log)
1900 {
1901 for (int ii=0; argv[ii]; ++ii)
1902 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1903 }
1904 }
1905
1906 }
1907 else
1908 {
1909 error.SetError (::posix_spawnp (&pid,
1910 exe_path,
1911 NULL,
1912 &attr,
1913 argv,
1914 envp),
1915 eErrorTypePOSIX);
1916
1917 if (error.Fail() || log)
1918 {
1919 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001920 pid, exe_path, static_cast<void*>(&attr),
1921 reinterpret_cast<const void*>(argv),
1922 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001923 if (log)
1924 {
1925 for (int ii=0; argv[ii]; ++ii)
1926 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1927 }
1928 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001929 }
1930
Todd Fiala76747122014-01-23 00:52:28 +00001931 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001932 {
Todd Fiala76747122014-01-23 00:52:28 +00001933#if defined (__APPLE__)
1934 // No more thread specific current working directory
1935 __pthread_fchdir (-1);
1936#else
1937 if (::chdir(current_dir) == -1 && error.Success())
1938 {
1939 error.SetError(errno, eErrorTypePOSIX);
1940 error.LogIfError(log, "unable to change current directory back to %s",
1941 current_dir);
1942 }
1943#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001944 }
1945
1946 return error;
1947}
1948
Todd Fiala76747122014-01-23 00:52:28 +00001949#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1950
1951
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001952#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
1953// The functions below implement process launching via posix_spawn() for Linux,
1954// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001955
1956Error
1957Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1958{
1959 Error error;
1960 char exe_path[PATH_MAX];
1961
1962 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1963
1964 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1965
1966 FileSpec exe_spec(launch_info.GetExecutableFile());
1967
1968 FileSpec::FileType file_type = exe_spec.GetFileType();
1969 if (file_type != FileSpec::eFileTypeRegular)
1970 {
1971 lldb::ModuleSP exe_module_sp;
1972 error = host_platform_sp->ResolveExecutable (exe_spec,
1973 arch_spec,
1974 exe_module_sp,
1975 NULL);
1976
1977 if (error.Fail())
1978 return error;
1979
1980 if (exe_module_sp)
1981 exe_spec = exe_module_sp->GetFileSpec();
1982 }
1983
1984 if (exe_spec.Exists())
1985 {
1986 exe_spec.GetPath (exe_path, sizeof(exe_path));
1987 }
1988 else
1989 {
1990 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1991 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1992 return error;
1993 }
1994
1995 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1996
1997 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1998
1999 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2000
2001 if (pid != LLDB_INVALID_PROCESS_ID)
2002 {
2003 // If all went well, then set the process ID into the launch info
2004 launch_info.SetProcessID(pid);
2005
Todd Fiala76747122014-01-23 00:52:28 +00002006 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2007
Daniel Malea4244cbd2013-08-27 20:58:59 +00002008 // Make sure we reap any processes we spawn or we will have zombies.
2009 if (!launch_info.MonitorProcess())
2010 {
2011 const bool monitor_signals = false;
2012 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2013 NULL,
2014 pid,
2015 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002016 if (log)
2017 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2018 }
2019 else
2020 {
2021 if (log)
2022 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002023 }
2024 }
2025 else
2026 {
2027 // Invalid process ID, something didn't go well
2028 if (error.Success())
2029 error.SetErrorString ("process launch failed for unknown reasons");
2030 }
2031 return error;
2032}
2033
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002034#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002035
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002036#ifndef _WIN32
2037
2038size_t
2039Host::GetPageSize()
2040{
2041 return ::getpagesize();
2042}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002043
Greg Claytone3e3fee2013-02-17 20:46:30 +00002044uint32_t
2045Host::GetNumberCPUS ()
2046{
2047 static uint32_t g_num_cores = UINT32_MAX;
2048 if (g_num_cores == UINT32_MAX)
2049 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002050#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002051
2052 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002053
Greg Claytone3e3fee2013-02-17 20:46:30 +00002054#else
2055
2056 // Assume POSIX support if a host specific case has not been supplied above
2057 g_num_cores = 0;
2058 int num_cores = 0;
2059 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002060#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002061 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002062#else
2063 int mib[] = { CTL_HW, HW_NCPU };
2064#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002065
2066 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002067 if (sysctl(mib, llvm::array_lengthof(mib), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
Greg Claytone3e3fee2013-02-17 20:46:30 +00002068 {
2069 g_num_cores = num_cores;
2070 }
2071 else
2072 {
2073 mib[1] = HW_NCPU;
2074 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002075 if (sysctl(mib, llvm::array_lengthof(mib), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
Greg Claytone3e3fee2013-02-17 20:46:30 +00002076 {
2077 if (num_cores > 0)
2078 g_num_cores = num_cores;
2079 }
2080 }
2081#endif
2082 }
2083 return g_num_cores;
2084}
2085
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002086void
2087Host::Kill(lldb::pid_t pid, int signo)
2088{
2089 ::kill(pid, signo);
2090}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002091
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002092#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002093
Johnny Chen8f3d8382011-08-02 20:52:42 +00002094#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002095bool
Greg Clayton3b147632010-12-18 01:54:34 +00002096Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002097{
2098 return false;
2099}
Greg Claytondd36def2010-10-17 22:03:32 +00002100
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002101void
2102Host::SetCrashDescriptionWithFormat (const char *format, ...)
2103{
2104}
2105
2106void
2107Host::SetCrashDescription (const char *description)
2108{
2109}
Greg Claytondd36def2010-10-17 22:03:32 +00002110
2111lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002112Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002113{
2114 return LLDB_INVALID_PROCESS_ID;
2115}
2116
Greg Claytonfbb76342013-11-20 21:07:01 +00002117#endif
2118
2119
2120#ifdef LLDB_DISABLE_POSIX
2121
2122Error
2123Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002124{
Greg Claytonfbb76342013-11-20 21:07:01 +00002125 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002126 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002127 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002128}
Greg Claytonfbb76342013-11-20 21:07:01 +00002129
2130Error
2131Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2132{
2133 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002134 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002135 return error;
2136}
2137
2138Error
2139Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2140{
2141 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002142 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002143 return error;
2144}
2145
2146Error
2147Host::Symlink (const char *src, const char *dst)
2148{
2149 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002150 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002151 return error;
2152}
2153
2154Error
2155Host::Readlink (const char *path, char *buf, size_t buf_len)
2156{
2157 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002158 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002159 return error;
2160}
2161
2162Error
2163Host::Unlink (const char *path)
2164{
2165 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002166 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002167 return error;
2168}
2169
Greg Clayton23f8c952014-03-24 23:10:19 +00002170Error
2171Host::RemoveDirectory (const char* path, bool recurse)
2172{
2173 Error error;
2174 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2175 return error;
2176}
2177
Greg Claytonfbb76342013-11-20 21:07:01 +00002178#else
2179
2180Error
2181Host::MakeDirectory (const char* path, uint32_t file_permissions)
2182{
2183 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002184 if (path && path[0])
2185 {
Greg Claytonfb909312013-11-23 01:58:15 +00002186 if (::mkdir(path, file_permissions) != 0)
2187 {
2188 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002189 switch (error.GetError())
2190 {
2191 case ENOENT:
2192 {
2193 // Parent directory doesn't exist, so lets make it if we can
2194 FileSpec spec(path, false);
2195 if (spec.GetDirectory() && spec.GetFilename())
2196 {
2197 // Make the parent directory and try again
2198 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2199 if (error2.Success())
2200 {
2201 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002202 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002203 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002204 else
Greg Claytonfb909312013-11-23 01:58:15 +00002205 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002206 }
2207 }
2208 }
2209 break;
2210 case EEXIST:
2211 {
2212 FileSpec path_spec(path, false);
2213 if (path_spec.IsDirectory())
2214 error.Clear(); // It is a directory and it already exists
2215 }
2216 break;
2217 }
2218 }
Greg Claytonfb909312013-11-23 01:58:15 +00002219 }
2220 else
2221 {
2222 error.SetErrorString("empty path");
2223 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002224 return error;
2225}
Greg Clayton23f8c952014-03-24 23:10:19 +00002226
2227Error
2228Host::RemoveDirectory (const char* path, bool recurse)
2229{
2230 Error error;
2231 if (path && path[0])
2232 {
2233 if (recurse)
2234 {
2235 StreamString command;
2236 command.Printf("rm -rf \"%s\"", path);
2237 int status = ::system(command.GetString().c_str());
2238 if (status != 0)
2239 error.SetError(status, eErrorTypeGeneric);
2240 }
2241 else
2242 {
2243 if (::rmdir(path) != 0)
2244 error.SetErrorToErrno();
2245 }
2246 }
2247 else
2248 {
2249 error.SetErrorString("empty path");
2250 }
2251 return error;
2252}
Greg Claytonfbb76342013-11-20 21:07:01 +00002253
2254Error
2255Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2256{
2257 Error error;
2258 struct stat file_stats;
2259 if (::stat (path, &file_stats) == 0)
2260 {
2261 // The bits in "st_mode" currently match the definitions
2262 // for the file mode bits in unix.
2263 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2264 }
2265 else
2266 {
2267 error.SetErrorToErrno();
2268 }
2269 return error;
2270}
2271
2272Error
2273Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2274{
2275 Error error;
2276 if (::chmod(path, file_permissions) != 0)
2277 error.SetErrorToErrno();
2278 return error;
2279}
2280
2281Error
2282Host::Symlink (const char *src, const char *dst)
2283{
2284 Error error;
2285 if (::symlink(dst, src) == -1)
2286 error.SetErrorToErrno();
2287 return error;
2288}
2289
2290Error
2291Host::Unlink (const char *path)
2292{
2293 Error error;
2294 if (::unlink(path) == -1)
2295 error.SetErrorToErrno();
2296 return error;
2297}
2298
2299Error
2300Host::Readlink (const char *path, char *buf, size_t buf_len)
2301{
2302 Error error;
2303 ssize_t count = ::readlink(path, buf, buf_len);
2304 if (count < 0)
2305 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002306 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002307 buf[count] = '\0'; // Success
2308 else
2309 error.SetErrorString("'buf' buffer is too small to contain link contents");
2310 return error;
2311}
2312
2313
Greg Clayton2bddd342010-09-07 20:11:56 +00002314#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002315
2316typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2317FDToFileMap& GetFDToFileMap()
2318{
2319 static FDToFileMap g_fd2filemap;
2320 return g_fd2filemap;
2321}
2322
2323lldb::user_id_t
2324Host::OpenFile (const FileSpec& file_spec,
2325 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002326 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002327 Error &error)
2328{
2329 std::string path (file_spec.GetPath());
2330 if (path.empty())
2331 {
2332 error.SetErrorString("empty path");
2333 return UINT64_MAX;
2334 }
2335 FileSP file_sp(new File());
2336 error = file_sp->Open(path.c_str(),flags,mode);
2337 if (file_sp->IsValid() == false)
2338 return UINT64_MAX;
2339 lldb::user_id_t fd = file_sp->GetDescriptor();
2340 GetFDToFileMap()[fd] = file_sp;
2341 return fd;
2342}
2343
2344bool
2345Host::CloseFile (lldb::user_id_t fd, Error &error)
2346{
2347 if (fd == UINT64_MAX)
2348 {
2349 error.SetErrorString ("invalid file descriptor");
2350 return false;
2351 }
2352 FDToFileMap& file_map = GetFDToFileMap();
2353 FDToFileMap::iterator pos = file_map.find(fd);
2354 if (pos == file_map.end())
2355 {
2356 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2357 return false;
2358 }
2359 FileSP file_sp = pos->second;
2360 if (!file_sp)
2361 {
2362 error.SetErrorString ("invalid host backing file");
2363 return false;
2364 }
2365 error = file_sp->Close();
2366 file_map.erase(pos);
2367 return error.Success();
2368}
2369
2370uint64_t
2371Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2372{
2373 if (fd == UINT64_MAX)
2374 {
2375 error.SetErrorString ("invalid file descriptor");
2376 return UINT64_MAX;
2377 }
2378 FDToFileMap& file_map = GetFDToFileMap();
2379 FDToFileMap::iterator pos = file_map.find(fd);
2380 if (pos == file_map.end())
2381 {
2382 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2383 return false;
2384 }
2385 FileSP file_sp = pos->second;
2386 if (!file_sp)
2387 {
2388 error.SetErrorString ("invalid host backing file");
2389 return UINT64_MAX;
2390 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002391 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2392 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002393 return UINT64_MAX;
2394 size_t bytes_written = src_len;
2395 error = file_sp->Write(src, bytes_written);
2396 if (error.Fail())
2397 return UINT64_MAX;
2398 return bytes_written;
2399}
2400
2401uint64_t
2402Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2403{
2404 if (fd == UINT64_MAX)
2405 {
2406 error.SetErrorString ("invalid file descriptor");
2407 return UINT64_MAX;
2408 }
2409 FDToFileMap& file_map = GetFDToFileMap();
2410 FDToFileMap::iterator pos = file_map.find(fd);
2411 if (pos == file_map.end())
2412 {
2413 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2414 return false;
2415 }
2416 FileSP file_sp = pos->second;
2417 if (!file_sp)
2418 {
2419 error.SetErrorString ("invalid host backing file");
2420 return UINT64_MAX;
2421 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002422 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2423 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002424 return UINT64_MAX;
2425 size_t bytes_read = dst_len;
2426 error = file_sp->Read(dst ,bytes_read);
2427 if (error.Fail())
2428 return UINT64_MAX;
2429 return bytes_read;
2430}
2431
2432lldb::user_id_t
2433Host::GetFileSize (const FileSpec& file_spec)
2434{
2435 return file_spec.GetByteSize();
2436}
2437
2438bool
2439Host::GetFileExists (const FileSpec& file_spec)
2440{
2441 return file_spec.Exists();
2442}
2443
2444bool
2445Host::CalculateMD5 (const FileSpec& file_spec,
2446 uint64_t &low,
2447 uint64_t &high)
2448{
2449#if defined (__APPLE__)
2450 StreamString md5_cmd_line;
2451 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2452 std::string hash_string;
2453 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2454 if (err.Fail())
2455 return false;
2456 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2457 // if the output is any other length it is probably wrong
2458 if (hash_string.size() != 32)
2459 return false;
2460 std::string part1(hash_string,0,16);
2461 std::string part2(hash_string,16);
2462 const char* part1_cstr = part1.c_str();
2463 const char* part2_cstr = part2.c_str();
2464 high = ::strtoull(part1_cstr, NULL, 16);
2465 low = ::strtoull(part2_cstr, NULL, 16);
2466 return true;
2467#else
2468 // your own MD5 implementation here
2469 return false;
2470#endif
2471}