blob: 4aa362ecee56fdeb436ea0f8bc66f94dbd28111b [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
Todd Fiala17096d72014-07-16 19:03:16 +000052// C++ includes
53#include <limits>
54
Greg Clayton2bddd342010-09-07 20:11:56 +000055#include "lldb/Host/Host.h"
56#include "lldb/Core/ArchSpec.h"
57#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000058#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000059#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000060#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000061#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000062#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000063#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000064#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000065#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000066#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000067#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000068#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000069#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000070#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000071
Saleem Abdulrasool28606952014-06-27 05:17:41 +000072#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000073#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000074#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000075#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000076
Todd Fiala76747122014-01-23 00:52:28 +000077#if defined (__APPLE__)
78#ifndef _POSIX_SPAWN_DISABLE_ASLR
79#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
80#endif
81
82extern "C"
83{
84 int __pthread_chdir(const char *path);
85 int __pthread_fchdir (int fildes);
86}
87
88#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000089
Greg Clayton2bddd342010-09-07 20:11:56 +000090using namespace lldb;
91using namespace lldb_private;
92
Todd Fiala17096d72014-07-16 19:03:16 +000093// Define maximum thread name length
94#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
95uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
96#else
97uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
98#endif
Greg Claytone4e45922011-11-16 05:37:56 +000099
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000100#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000101struct MonitorInfo
102{
103 lldb::pid_t pid; // The process ID to monitor
104 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
105 void *callback_baton; // The callback baton for the callback function
106 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
107};
108
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000109static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000110MonitorChildProcessThreadFunction (void *arg);
111
112lldb::thread_t
113Host::StartMonitoringChildProcess
114(
115 Host::MonitorChildProcessCallback callback,
116 void *callback_baton,
117 lldb::pid_t pid,
118 bool monitor_signals
119)
120{
121 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000122 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000123
Greg Claytone4e45922011-11-16 05:37:56 +0000124 info_ptr->pid = pid;
125 info_ptr->callback = callback;
126 info_ptr->callback_baton = callback_baton;
127 info_ptr->monitor_signals = monitor_signals;
128
129 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000130 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000131 thread = ThreadCreate (thread_name,
132 MonitorChildProcessThreadFunction,
133 info_ptr,
134 NULL);
135
Greg Clayton2bddd342010-09-07 20:11:56 +0000136 return thread;
137}
138
139//------------------------------------------------------------------
140// Scoped class that will disable thread canceling when it is
141// constructed, and exception safely restore the previous value it
142// when it goes out of scope.
143//------------------------------------------------------------------
144class ScopedPThreadCancelDisabler
145{
146public:
147 ScopedPThreadCancelDisabler()
148 {
149 // Disable the ability for this thread to be cancelled
150 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
151 if (err != 0)
152 m_old_state = -1;
153
154 }
155
156 ~ScopedPThreadCancelDisabler()
157 {
158 // Restore the ability for this thread to be cancelled to what it
159 // previously was.
160 if (m_old_state != -1)
161 ::pthread_setcancelstate (m_old_state, 0);
162 }
163private:
164 int m_old_state; // Save the old cancelability state.
165};
166
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000167static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000168MonitorChildProcessThreadFunction (void *arg)
169{
Greg Clayton5160ce52013-03-27 23:08:40 +0000170 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000171 const char *function = __FUNCTION__;
172 if (log)
173 log->Printf ("%s (arg = %p) thread starting...", function, arg);
174
175 MonitorInfo *info = (MonitorInfo *)arg;
176
177 const Host::MonitorChildProcessCallback callback = info->callback;
178 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000179 const bool monitor_signals = info->monitor_signals;
180
Daniel Malea4244cbd2013-08-27 20:58:59 +0000181 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000182 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000183
Greg Clayton2bddd342010-09-07 20:11:56 +0000184 delete info;
185
186 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000187#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000188 #define __WALL 0
189#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000190 const int options = __WALL;
191
Greg Clayton2bddd342010-09-07 20:11:56 +0000192 while (1)
193 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000194 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000195 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000196 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000197
198 // Wait for all child processes
199 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000200 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000201 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000202 ::pthread_testcancel ();
203
204 if (wait_pid == -1)
205 {
206 if (errno == EINTR)
207 continue;
208 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000209 {
210 if (log)
211 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000212 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000213 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000214 }
Matt Kopec650648f2013-01-08 16:30:18 +0000215 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000216 {
217 bool exited = false;
218 int signal = 0;
219 int exit_status = 0;
220 const char *status_cstr = NULL;
221 if (WIFSTOPPED(status))
222 {
223 signal = WSTOPSIG(status);
224 status_cstr = "STOPPED";
225 }
226 else if (WIFEXITED(status))
227 {
228 exit_status = WEXITSTATUS(status);
229 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000230 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000231 }
232 else if (WIFSIGNALED(status))
233 {
234 signal = WTERMSIG(status);
235 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000236 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000237 exited = true;
238 exit_status = -1;
239 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000240 }
241 else
242 {
Johnny Chen44805302011-07-19 19:48:13 +0000243 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000244 }
245
246 // Scope for pthread_cancel_disabler
247 {
248 ScopedPThreadCancelDisabler pthread_cancel_disabler;
249
Caroline Tice20ad3c42010-10-29 21:48:37 +0000250 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000251 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000252 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 +0000253 function,
254 wait_pid,
255 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000256 pid,
257 status,
258 status_cstr,
259 signal,
260 exit_status);
261
262 if (exited || (signal != 0 && monitor_signals))
263 {
Greg Claytone4e45922011-11-16 05:37:56 +0000264 bool callback_return = false;
265 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000266 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000267
268 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000269 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000270 {
271 if (log)
272 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000273 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000274 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000275 // If the callback returns true, it means this process should
276 // exit
277 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000278 {
279 if (log)
280 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000281 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000282 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000283 }
284 }
285 }
286 }
287
Caroline Tice20ad3c42010-10-29 21:48:37 +0000288 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000289 if (log)
290 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
291
292 return NULL;
293}
294
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000295#endif // #if !defined (__APPLE__) && !defined (_WIN32)
296
297#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000298
299void
300Host::SystemLog (SystemLogType type, const char *format, va_list args)
301{
302 vfprintf (stderr, format, args);
303}
304
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000305#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000306
Greg Claytone38a5ed2012-01-05 03:57:59 +0000307void
308Host::SystemLog (SystemLogType type, const char *format, ...)
309{
310 va_list args;
311 va_start (args, format);
312 SystemLog (type, format, args);
313 va_end (args);
314}
315
Greg Clayton2bddd342010-09-07 20:11:56 +0000316const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000317Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000318{
Greg Clayton514487e2011-02-15 21:59:32 +0000319 static bool g_supports_32 = false;
320 static bool g_supports_64 = false;
321 static ArchSpec g_host_arch_32;
322 static ArchSpec g_host_arch_64;
323
Greg Clayton2bddd342010-09-07 20:11:56 +0000324#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000325
326 // Apple is different in that it can support both 32 and 64 bit executables
327 // in the same operating system running concurrently. Here we detect the
328 // correct host architectures for both 32 and 64 bit including if 64 bit
329 // executables are supported on the system.
330
331 if (g_supports_32 == false && g_supports_64 == false)
332 {
333 // All apple systems support 32 bit execution.
334 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000335 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000336 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000337 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000338 ArchSpec host_arch;
339 // These will tell us about the kernel architecture, which even on a 64
340 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000341 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
342 {
Greg Clayton514487e2011-02-15 21:59:32 +0000343 len = sizeof (cpusubtype);
344 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
345 cpusubtype = CPU_TYPE_ANY;
346
Greg Clayton2bddd342010-09-07 20:11:56 +0000347 len = sizeof (is_64_bit_capable);
348 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
349 {
350 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000351 g_supports_64 = true;
352 }
353
354 if (is_64_bit_capable)
355 {
356 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000357 {
Greg Clayton514487e2011-02-15 21:59:32 +0000358 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000359 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000360 }
361 else
362 {
Greg Clayton52edb362014-07-14 22:53:02 +0000363 // We have a 64 bit kernel that is returning a 32 bit cputype, the
364 // cpusubtype will be correct as if it were for a 64 bit architecture
365 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype | CPU_ARCH_ABI64, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000366 }
Greg Clayton52edb362014-07-14 22:53:02 +0000367
368 // Now we need modify the cpusubtype for the 32 bit slices.
369 uint32_t cpusubtype32 = cpusubtype;
370#if defined (__i386__) || defined (__x86_64__)
371 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
372 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
373#elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
374 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
375 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
376#endif
377 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype & ~(CPU_ARCH_MASK), cpusubtype32);
Greg Clayton2bddd342010-09-07 20:11:56 +0000378 }
Greg Clayton514487e2011-02-15 21:59:32 +0000379 else
380 {
Greg Clayton52edb362014-07-14 22:53:02 +0000381 // We have a 32 bit kernel on a 32 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000382 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000383 g_host_arch_64.Clear();
384 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000385 }
Greg Clayton514487e2011-02-15 21:59:32 +0000386 }
387
388#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000389
Greg Clayton514487e2011-02-15 21:59:32 +0000390 if (g_supports_32 == false && g_supports_64 == false)
391 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000392 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000393
Stephen Wilsonbd588712011-02-24 19:15:09 +0000394 g_host_arch_32.Clear();
395 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000396
Greg Claytonb29e6c62012-10-11 17:38:58 +0000397 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
398 // for the default triple. It's probably an artifact of config.guess.
399 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000400 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000401
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000402 const char* distribution_id = GetDistributionId ().AsCString();
403
Stephen Wilsonbd588712011-02-24 19:15:09 +0000404 switch (triple.getArch())
405 {
406 default:
407 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000408 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000409 g_supports_32 = true;
410 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000411
Stephen Wilsonbd588712011-02-24 19:15:09 +0000412 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000413 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000414 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000415 g_supports_64 = true;
416 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000417 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000418 g_supports_32 = true;
419 break;
420
Ed Mastea8375762014-04-01 18:06:45 +0000421 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000422 case llvm::Triple::sparcv9:
423 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000424 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000425 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000426 g_supports_64 = true;
427 break;
428 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000429
430 g_supports_32 = g_host_arch_32.IsValid();
431 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000432 }
Greg Clayton514487e2011-02-15 21:59:32 +0000433
434#endif // #else for #if defined (__APPLE__)
435
436 if (arch_kind == eSystemDefaultArchitecture32)
437 return g_host_arch_32;
438 else if (arch_kind == eSystemDefaultArchitecture64)
439 return g_host_arch_64;
440
441 if (g_supports_64)
442 return g_host_arch_64;
443
444 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000445}
446
447const ConstString &
448Host::GetVendorString()
449{
450 static ConstString g_vendor;
451 if (!g_vendor)
452 {
Greg Clayton950971f2012-05-12 00:01:21 +0000453 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
454 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
455 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000456 }
457 return g_vendor;
458}
459
460const ConstString &
461Host::GetOSString()
462{
463 static ConstString g_os_string;
464 if (!g_os_string)
465 {
Greg Clayton950971f2012-05-12 00:01:21 +0000466 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
467 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
468 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000469 }
470 return g_os_string;
471}
472
473const ConstString &
474Host::GetTargetTriple()
475{
476 static ConstString g_host_triple;
477 if (!(g_host_triple))
478 {
Greg Clayton950971f2012-05-12 00:01:21 +0000479 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
480 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000481 }
482 return g_host_triple;
483}
484
Todd Fialaf3d61de2014-01-17 20:18:59 +0000485// See linux/Host.cpp for Linux-based implementations of this.
486// Add your platform-specific implementation to the appropriate host file.
487#if !defined(__linux__)
488
489const ConstString &
490 Host::GetDistributionId ()
491{
492 static ConstString s_distribution_id;
493 return s_distribution_id;
494}
495
496#endif // #if !defined(__linux__)
497
Greg Clayton2bddd342010-09-07 20:11:56 +0000498lldb::pid_t
499Host::GetCurrentProcessID()
500{
501 return ::getpid();
502}
503
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000504#ifndef _WIN32
505
Greg Clayton2bddd342010-09-07 20:11:56 +0000506lldb::tid_t
507Host::GetCurrentThreadID()
508{
509#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000510 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000511 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
512 // count.
513 thread_port_t thread_self = mach_thread_self();
514 mach_port_deallocate(mach_task_self(), thread_self);
515 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000516#elif defined(__FreeBSD__)
517 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000518#elif defined(__linux__)
519 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000520#else
521 return lldb::tid_t(pthread_self());
522#endif
523}
524
Jim Ingham372787f2012-04-07 00:00:41 +0000525lldb::thread_t
526Host::GetCurrentThread ()
527{
528 return lldb::thread_t(pthread_self());
529}
530
Greg Clayton2bddd342010-09-07 20:11:56 +0000531const char *
532Host::GetSignalAsCString (int signo)
533{
534 switch (signo)
535 {
536 case SIGHUP: return "SIGHUP"; // 1 hangup
537 case SIGINT: return "SIGINT"; // 2 interrupt
538 case SIGQUIT: return "SIGQUIT"; // 3 quit
539 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
540 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
541 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000542#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000543#if !defined(SIGIO) || (SIGPOLL != SIGIO)
544// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
545// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000546 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000547#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000548#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000549#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000550 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000551#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000552 case SIGFPE: return "SIGFPE"; // 8 floating point exception
553 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
554 case SIGBUS: return "SIGBUS"; // 10 bus error
555 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
556 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
557 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
558 case SIGALRM: return "SIGALRM"; // 14 alarm clock
559 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
560 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
561 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
562 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
563 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
564 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
565 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
566 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000567#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000568 case SIGIO: return "SIGIO"; // 23 input/output possible signal
569#endif
570 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
571 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
572 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
573 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000574#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000575 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000576#endif
577#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000578 case SIGINFO: return "SIGINFO"; // 29 information request
579#endif
580 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
581 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
582 default:
583 break;
584 }
585 return NULL;
586}
587
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000588#endif
589
Greg Clayton2bddd342010-09-07 20:11:56 +0000590void
591Host::WillTerminate ()
592{
593}
594
Sylvestre Ledru59405832013-07-01 08:21:36 +0000595#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000596
Greg Clayton2bddd342010-09-07 20:11:56 +0000597void
598Host::ThreadCreated (const char *thread_name)
599{
600}
Greg Claytone5219662010-12-03 06:02:24 +0000601
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000602void
Greg Claytone5219662010-12-03 06:02:24 +0000603Host::Backtrace (Stream &strm, uint32_t max_frames)
604{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000605 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000606}
607
Greg Clayton85851dd2010-12-04 00:10:17 +0000608size_t
609Host::GetEnvironment (StringList &env)
610{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000611 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000612 return 0;
613}
614
Sylvestre Ledru59405832013-07-01 08:21:36 +0000615#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000616
617struct HostThreadCreateInfo
618{
619 std::string thread_name;
620 thread_func_t thread_fptr;
621 thread_arg_t thread_arg;
622
623 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
624 thread_name (name ? name : ""),
625 thread_fptr (fptr),
626 thread_arg (arg)
627 {
628 }
629};
630
631static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000632#ifdef _WIN32
633__stdcall
634#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000635ThreadCreateTrampoline (thread_arg_t arg)
636{
637 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
638 Host::ThreadCreated (info->thread_name.c_str());
639 thread_func_t thread_fptr = info->thread_fptr;
640 thread_arg_t thread_arg = info->thread_arg;
641
Greg Clayton5160ce52013-03-27 23:08:40 +0000642 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000643 if (log)
644 log->Printf("thread created");
645
646 delete info;
647 return thread_fptr (thread_arg);
648}
649
650lldb::thread_t
651Host::ThreadCreate
652(
653 const char *thread_name,
654 thread_func_t thread_fptr,
655 thread_arg_t thread_arg,
656 Error *error
657)
658{
659 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
660
661 // Host::ThreadCreateTrampoline will delete this pointer for us.
662 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
663
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000664#ifdef _WIN32
665 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
666 int err = thread <= 0 ? GetLastError() : 0;
667#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000668 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000669#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000670 if (err == 0)
671 {
672 if (error)
673 error->Clear();
674 return thread;
675 }
676
677 if (error)
678 error->SetError (err, eErrorTypePOSIX);
679
680 return LLDB_INVALID_HOST_THREAD;
681}
682
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000683#ifndef _WIN32
684
Greg Clayton2bddd342010-09-07 20:11:56 +0000685bool
686Host::ThreadCancel (lldb::thread_t thread, Error *error)
687{
688 int err = ::pthread_cancel (thread);
689 if (error)
690 error->SetError(err, eErrorTypePOSIX);
691 return err == 0;
692}
693
694bool
695Host::ThreadDetach (lldb::thread_t thread, Error *error)
696{
697 int err = ::pthread_detach (thread);
698 if (error)
699 error->SetError(err, eErrorTypePOSIX);
700 return err == 0;
701}
702
703bool
704Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
705{
706 int err = ::pthread_join (thread, thread_result_ptr);
707 if (error)
708 error->SetError(err, eErrorTypePOSIX);
709 return err == 0;
710}
711
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000712lldb::thread_key_t
713Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
714{
715 pthread_key_t key;
716 ::pthread_key_create (&key, callback);
717 return key;
718}
719
720void*
721Host::ThreadLocalStorageGet(lldb::thread_key_t key)
722{
723 return ::pthread_getspecific (key);
724}
725
726void
727Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
728{
729 ::pthread_setspecific (key, value);
730}
731
Matt Kopec62502c62013-05-13 19:33:58 +0000732bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000733Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
734{
Greg Clayton85719632013-02-27 22:51:58 +0000735#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000736 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
737 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
738 if (pid == LLDB_INVALID_PROCESS_ID)
739 pid = curr_pid;
740
741 if (tid == LLDB_INVALID_THREAD_ID)
742 tid = curr_tid;
743
Greg Clayton2bddd342010-09-07 20:11:56 +0000744 // Set the pthread name if possible
745 if (pid == curr_pid && tid == curr_tid)
746 {
Matt Kopec62502c62013-05-13 19:33:58 +0000747 if (::pthread_setname_np (name) == 0)
748 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000749 }
Matt Kopec62502c62013-05-13 19:33:58 +0000750 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000751#elif defined (__FreeBSD__)
752 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
753 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
754 if (pid == LLDB_INVALID_PROCESS_ID)
755 pid = curr_pid;
756
757 if (tid == LLDB_INVALID_THREAD_ID)
758 tid = curr_tid;
759
760 // Set the pthread name if possible
761 if (pid == curr_pid && tid == curr_tid)
762 {
Michael Sartainc2052432013-08-01 18:51:08 +0000763 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000764 return true;
765 }
766 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000767#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000768 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
769 if (fn)
770 {
Matt Kopec62502c62013-05-13 19:33:58 +0000771 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
772 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000773 if (pid == LLDB_INVALID_PROCESS_ID)
774 pid = curr_pid;
775
776 if (tid == LLDB_INVALID_THREAD_ID)
777 tid = curr_tid;
778
Michael Sartainc2052432013-08-01 18:51:08 +0000779 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000780 {
Michael Sartainc2052432013-08-01 18:51:08 +0000781 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
782 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
783
784 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000785 return true;
786 }
787 }
788 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000789#else
790 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000791#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000792}
793
Ed Maste02983be2013-07-25 19:10:32 +0000794bool
795Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
796 const char *thread_name, size_t len)
797{
Enrico Granata67530b62014-02-12 03:37:33 +0000798 std::unique_ptr<char[]> namebuf(new char[len+1]);
799
Ed Maste02983be2013-07-25 19:10:32 +0000800 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
801 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
802 // off leads to a lot of similar named threads. Go through the thread name
803 // and search for the last dot and use that.
804 const char *lastdot = ::strrchr (thread_name, '.');
805
806 if (lastdot && lastdot != thread_name)
807 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000808 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000809 namebuf[len] = 0;
810
Enrico Granata67530b62014-02-12 03:37:33 +0000811 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000812 if (namebuflen > 0)
813 {
814 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
815 {
816 // Trim off trailing '(' and '>' characters for a bit more cleanup.
817 namebuflen--;
818 namebuf[namebuflen] = 0;
819 }
Enrico Granata67530b62014-02-12 03:37:33 +0000820 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000821 }
822 return false;
823}
824
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000825#endif
826
Greg Clayton2bddd342010-09-07 20:11:56 +0000827FileSpec
828Host::GetProgramFileSpec ()
829{
830 static FileSpec g_program_filespec;
831 if (!g_program_filespec)
832 {
833#if defined (__APPLE__)
834 char program_fullpath[PATH_MAX];
835 // If DST is NULL, then return the number of bytes needed.
836 uint32_t len = sizeof(program_fullpath);
837 int err = _NSGetExecutablePath (program_fullpath, &len);
838 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000839 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000840 else if (err == -1)
841 {
842 char *large_program_fullpath = (char *)::malloc (len + 1);
843
844 err = _NSGetExecutablePath (large_program_fullpath, &len);
845 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000846 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000847
848 ::free (large_program_fullpath);
849 }
850#elif defined (__linux__)
851 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000852 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
853 if (len > 0) {
854 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000855 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000856 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000857#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000858 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
859 size_t exe_path_size;
860 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
861 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000862 char *exe_path = new char[exe_path_size];
863 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
864 g_program_filespec.SetFile(exe_path, false);
865 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000866 }
867#endif
868 }
869 return g_program_filespec;
870}
871
Greg Clayton2bddd342010-09-07 20:11:56 +0000872#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000873
874bool
875Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
876{
877 bundle.Clear();
878 return false;
879}
880
Greg Clayton2bddd342010-09-07 20:11:56 +0000881bool
Greg Claytondd36def2010-10-17 22:03:32 +0000882Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000883{
Greg Claytondd36def2010-10-17 22:03:32 +0000884 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000885}
886#endif
887
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000888#ifndef _WIN32
889
Greg Clayton45319462011-02-08 00:35:34 +0000890// Opaque info that tracks a dynamic library that was loaded
891struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000892{
Greg Clayton45319462011-02-08 00:35:34 +0000893 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
894 file_spec (fs),
895 open_options (o),
896 handle (h)
897 {
898 }
899
900 const FileSpec file_spec;
901 uint32_t open_options;
902 void * handle;
903};
904
905void *
906Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
907{
Greg Clayton4272cc72011-02-02 02:24:04 +0000908 char path[PATH_MAX];
909 if (file_spec.GetPath(path, sizeof(path)))
910 {
Greg Clayton45319462011-02-08 00:35:34 +0000911 int mode = 0;
912
913 if (options & eDynamicLibraryOpenOptionLazy)
914 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000915 else
916 mode |= RTLD_NOW;
917
Greg Clayton45319462011-02-08 00:35:34 +0000918
919 if (options & eDynamicLibraryOpenOptionLocal)
920 mode |= RTLD_LOCAL;
921 else
922 mode |= RTLD_GLOBAL;
923
924#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
925 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
926 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000927#endif
Greg Clayton45319462011-02-08 00:35:34 +0000928
929 void * opaque = ::dlopen (path, mode);
930
931 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000932 {
933 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000934 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000935 }
936 else
937 {
938 error.SetErrorString(::dlerror());
939 }
940 }
941 else
942 {
943 error.SetErrorString("failed to extract path");
944 }
Greg Clayton45319462011-02-08 00:35:34 +0000945 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000946}
947
948Error
Greg Clayton45319462011-02-08 00:35:34 +0000949Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000950{
951 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000952 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000953 {
954 error.SetErrorString ("invalid dynamic library handle");
955 }
Greg Clayton45319462011-02-08 00:35:34 +0000956 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000957 {
Greg Clayton45319462011-02-08 00:35:34 +0000958 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
959 if (::dlclose (dylib_info->handle) != 0)
960 {
961 error.SetErrorString(::dlerror());
962 }
963
964 dylib_info->open_options = 0;
965 dylib_info->handle = 0;
966 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000967 }
968 return error;
969}
970
971void *
Greg Clayton45319462011-02-08 00:35:34 +0000972Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000973{
Greg Clayton45319462011-02-08 00:35:34 +0000974 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000975 {
976 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000977 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000978 else
Greg Clayton45319462011-02-08 00:35:34 +0000979 {
980 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
981
982 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
983 if (symbol_addr)
984 {
985#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
986 // This host doesn't support limiting searches to this shared library
987 // so we need to verify that the match came from this shared library
988 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000989 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000990 {
991 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
992 if (match_dylib_spec != dylib_info->file_spec)
993 {
994 char dylib_path[PATH_MAX];
995 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
996 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
997 else
998 error.SetErrorString ("symbol not found");
999 return NULL;
1000 }
1001 }
1002#endif
1003 error.Clear();
1004 return symbol_addr;
1005 }
1006 else
1007 {
1008 error.SetErrorString(::dlerror());
1009 }
1010 }
1011 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +00001012}
Greg Claytondd36def2010-10-17 22:03:32 +00001013
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001014FileSpec
1015Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1016{
1017 FileSpec module_filespec;
1018 Dl_info info;
1019 if (::dladdr (host_addr, &info))
1020 {
1021 if (info.dli_fname)
1022 module_filespec.SetFile(info.dli_fname, true);
1023 }
1024 return module_filespec;
1025}
1026
1027#endif
1028
Greg Clayton23f8c952014-03-24 23:10:19 +00001029
1030static void CleanupProcessSpecificLLDBTempDir ()
1031{
1032 // Get the process specific LLDB temporary directory and delete it.
1033 FileSpec tmpdir_file_spec;
1034 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1035 {
1036 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1037 // true to all files that were created for the LLDB process can be cleaned up.
1038 const bool recurse = true;
1039 Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1040 }
1041}
1042
Greg Claytondd36def2010-10-17 22:03:32 +00001043bool
1044Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1045{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001046 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001047 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1048 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001049 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001050 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001051 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001052
1053 switch (path_type)
1054 {
1055 case ePathTypeLLDBShlibDir:
1056 {
1057 static ConstString g_lldb_so_dir;
1058 if (!g_lldb_so_dir)
1059 {
David Majnemer8490da12014-07-22 22:00:42 +00001060 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1061 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +00001062 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001063 if (log)
1064 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001065 }
1066 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001067 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001068 }
1069 break;
1070
1071 case ePathTypeSupportExecutableDir:
1072 {
1073 static ConstString g_lldb_support_exe_dir;
1074 if (!g_lldb_support_exe_dir)
1075 {
1076 FileSpec lldb_file_spec;
1077 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1078 {
1079 char raw_path[PATH_MAX];
1080 char resolved_path[PATH_MAX];
1081 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1082
1083#if defined (__APPLE__)
1084 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1085 if (framework_pos)
1086 {
1087 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +00001088#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001089 // Shallow bundle
1090 *framework_pos = '\0';
1091#else
1092 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001093 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001094#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001095 }
Jason Molendaa3329782014-03-29 18:54:20 +00001096#endif // #if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001097 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1098 g_lldb_support_exe_dir.SetCString(resolved_path);
1099 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001100 if (log)
1101 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001102 }
1103 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001104 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001105 }
1106 break;
1107
1108 case ePathTypeHeaderDir:
1109 {
1110 static ConstString g_lldb_headers_dir;
1111 if (!g_lldb_headers_dir)
1112 {
1113#if defined (__APPLE__)
1114 FileSpec lldb_file_spec;
1115 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1116 {
1117 char raw_path[PATH_MAX];
1118 char resolved_path[PATH_MAX];
1119 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1120
1121 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1122 if (framework_pos)
1123 {
1124 framework_pos += strlen("LLDB.framework");
1125 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1126 }
1127 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1128 g_lldb_headers_dir.SetCString(resolved_path);
1129 }
1130#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001131 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001132 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1133#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001134 if (log)
1135 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001136 }
1137 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001138 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001139 }
1140 break;
1141
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001142#ifdef LLDB_DISABLE_PYTHON
1143 case ePathTypePythonDir:
1144 return false;
1145#else
1146 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001147 {
Greg Claytondd36def2010-10-17 22:03:32 +00001148 static ConstString g_lldb_python_dir;
1149 if (!g_lldb_python_dir)
1150 {
1151 FileSpec lldb_file_spec;
1152 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1153 {
1154 char raw_path[PATH_MAX];
1155 char resolved_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001156#if defined(_WIN32)
1157 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1158 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1159#else
Greg Claytondd36def2010-10-17 22:03:32 +00001160 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1161
1162#if defined (__APPLE__)
1163 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1164 if (framework_pos)
1165 {
1166 framework_pos += strlen("LLDB.framework");
1167 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001168 }
1169 else
1170 {
1171#endif
1172 llvm::SmallString<256> python_version_dir;
1173 llvm::raw_svector_ostream os(python_version_dir);
1174 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1175 os.flush();
1176
1177 // We may get our string truncated. Should we protect
1178 // this with an assert?
1179
1180 ::strncat(raw_path, python_version_dir.c_str(),
1181 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001182#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001183#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001184 }
1185#endif
1186 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1187 g_lldb_python_dir.SetCString(resolved_path);
1188 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001189
1190 if (log)
1191 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1192
Greg Claytondd36def2010-10-17 22:03:32 +00001193 }
1194 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001195 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001196 }
1197 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001198#endif
1199
Greg Clayton4272cc72011-02-02 02:24:04 +00001200 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1201 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001202#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001203 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001204 static bool g_lldb_system_plugin_dir_located = false;
1205 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001206 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001207 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001208#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001209 FileSpec lldb_file_spec;
1210 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1211 {
1212 char raw_path[PATH_MAX];
1213 char resolved_path[PATH_MAX];
1214 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1215
1216 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1217 if (framework_pos)
1218 {
1219 framework_pos += strlen("LLDB.framework");
1220 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001221 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1222 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001223 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001224 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001225 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001226#elif defined (__linux__)
1227 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1228 if (lldb_file_spec.Exists())
1229 {
1230 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1231 }
1232#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001233
1234 if (log)
1235 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1236
Greg Clayton4272cc72011-02-02 02:24:04 +00001237 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001238
1239 if (g_lldb_system_plugin_dir)
1240 {
1241 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1242 return true;
1243 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001244#else
1245 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001246 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001247#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001248 }
1249 break;
1250
1251 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1252 {
1253#if defined (__APPLE__)
1254 static ConstString g_lldb_user_plugin_dir;
1255 if (!g_lldb_user_plugin_dir)
1256 {
1257 char user_plugin_path[PATH_MAX];
1258 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1259 user_plugin_path,
1260 sizeof(user_plugin_path)))
1261 {
1262 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1263 }
1264 }
1265 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001266 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001267#elif defined (__linux__)
1268 static ConstString g_lldb_user_plugin_dir;
1269 if (!g_lldb_user_plugin_dir)
1270 {
1271 // XDG Base Directory Specification
1272 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1273 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1274 FileSpec lldb_file_spec;
1275 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1276 if (xdg_data_home && xdg_data_home[0])
1277 {
1278 std::string user_plugin_dir (xdg_data_home);
1279 user_plugin_dir += "/lldb";
1280 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1281 }
1282 else
1283 {
1284 const char *home_dir = getenv("HOME");
1285 if (home_dir && home_dir[0])
1286 {
1287 std::string user_plugin_dir (home_dir);
1288 user_plugin_dir += "/.local/share/lldb";
1289 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1290 }
1291 }
1292
1293 if (lldb_file_spec.Exists())
1294 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001295 if (log)
1296 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001297 }
1298 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001299 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001300#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001301 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001302 return false;
1303 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001304
1305 case ePathTypeLLDBTempSystemDir:
1306 {
1307 static ConstString g_lldb_tmp_dir;
1308 if (!g_lldb_tmp_dir)
1309 {
1310 const char *tmpdir_cstr = getenv("TMPDIR");
1311 if (tmpdir_cstr == NULL)
1312 {
1313 tmpdir_cstr = getenv("TMP");
1314 if (tmpdir_cstr == NULL)
1315 tmpdir_cstr = getenv("TEMP");
1316 }
1317 if (tmpdir_cstr)
1318 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001319 StreamString pid_tmpdir;
1320 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1321 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1322 {
1323 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1324 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1325 {
1326 // Make an atexit handler to clean up the process specify LLDB temp dir
1327 // and all of its contents.
1328 ::atexit (CleanupProcessSpecificLLDBTempDir);
1329 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1330 if (log)
1331 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1332
1333 }
1334 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001335 }
1336 }
1337 file_spec.GetDirectory() = g_lldb_tmp_dir;
1338 return (bool)file_spec.GetDirectory();
1339 }
Greg Claytondd36def2010-10-17 22:03:32 +00001340 }
1341
1342 return false;
1343}
1344
Greg Clayton1cb64962011-03-24 04:28:38 +00001345
1346bool
1347Host::GetHostname (std::string &s)
1348{
1349 char hostname[PATH_MAX];
1350 hostname[sizeof(hostname) - 1] = '\0';
1351 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1352 {
1353 struct hostent* h = ::gethostbyname (hostname);
1354 if (h)
1355 s.assign (h->h_name);
1356 else
1357 s.assign (hostname);
1358 return true;
1359 }
1360 return false;
1361}
1362
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001363#ifndef _WIN32
1364
Greg Clayton32e0a752011-03-30 18:16:51 +00001365const char *
1366Host::GetUserName (uint32_t uid, std::string &user_name)
1367{
1368 struct passwd user_info;
1369 struct passwd *user_info_ptr = &user_info;
1370 char user_buffer[PATH_MAX];
1371 size_t user_buffer_size = sizeof(user_buffer);
1372 if (::getpwuid_r (uid,
1373 &user_info,
1374 user_buffer,
1375 user_buffer_size,
1376 &user_info_ptr) == 0)
1377 {
1378 if (user_info_ptr)
1379 {
1380 user_name.assign (user_info_ptr->pw_name);
1381 return user_name.c_str();
1382 }
1383 }
1384 user_name.clear();
1385 return NULL;
1386}
1387
1388const char *
1389Host::GetGroupName (uint32_t gid, std::string &group_name)
1390{
1391 char group_buffer[PATH_MAX];
1392 size_t group_buffer_size = sizeof(group_buffer);
1393 struct group group_info;
1394 struct group *group_info_ptr = &group_info;
1395 // Try the threadsafe version first
1396 if (::getgrgid_r (gid,
1397 &group_info,
1398 group_buffer,
1399 group_buffer_size,
1400 &group_info_ptr) == 0)
1401 {
1402 if (group_info_ptr)
1403 {
1404 group_name.assign (group_info_ptr->gr_name);
1405 return group_name.c_str();
1406 }
1407 }
1408 else
1409 {
1410 // The threadsafe version isn't currently working
1411 // for me on darwin, but the non-threadsafe version
1412 // is, so I am calling it below.
1413 group_info_ptr = ::getgrgid (gid);
1414 if (group_info_ptr)
1415 {
1416 group_name.assign (group_info_ptr->gr_name);
1417 return group_name.c_str();
1418 }
1419 }
1420 group_name.clear();
1421 return NULL;
1422}
1423
Han Ming Ong84647042012-02-25 01:07:38 +00001424uint32_t
1425Host::GetUserID ()
1426{
1427 return getuid();
1428}
1429
1430uint32_t
1431Host::GetGroupID ()
1432{
1433 return getgid();
1434}
1435
1436uint32_t
1437Host::GetEffectiveUserID ()
1438{
1439 return geteuid();
1440}
1441
1442uint32_t
1443Host::GetEffectiveGroupID ()
1444{
1445 return getegid();
1446}
1447
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001448#endif
1449
1450#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1451bool
1452Host::GetOSBuildString (std::string &s)
1453{
1454 s.clear();
1455 return false;
1456}
1457
1458bool
1459Host::GetOSKernelDescription (std::string &s)
1460{
1461 s.clear();
1462 return false;
1463}
1464#endif
1465
Zachary Turner310035a2014-07-08 04:52:15 +00001466#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1467 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001468uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001469Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001470{
1471 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001472 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001473}
1474
Greg Claytone996fd32011-03-08 22:40:15 +00001475bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001476Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001477{
Greg Claytone996fd32011-03-08 22:40:15 +00001478 process_info.Clear();
1479 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001480}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001481#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001482
Matt Kopec085d6ce2013-05-31 22:00:07 +00001483#if !defined(__linux__)
1484bool
1485Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1486{
1487 return false;
1488}
1489#endif
1490
Sean Callananc0a6e062011-10-27 21:22:25 +00001491lldb::TargetSP
1492Host::GetDummyTarget (lldb_private::Debugger &debugger)
1493{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001494 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001495
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001496 // FIXME: Maybe the dummy target should be per-Debugger
1497 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1498 {
1499 ArchSpec arch(Target::GetDefaultArchitecture());
1500 if (!arch.IsValid())
1501 arch = Host::GetArchitecture ();
1502 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001503 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001504 arch.GetTriple().getTriple().c_str(),
1505 false,
1506 NULL,
1507 g_dummy_target_sp);
1508 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001509
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001510 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001511}
1512
Greg Claytond1cf11a2012-04-14 01:42:46 +00001513struct ShellInfo
1514{
1515 ShellInfo () :
1516 process_reaped (false),
1517 can_delete (false),
1518 pid (LLDB_INVALID_PROCESS_ID),
1519 signo(-1),
1520 status(-1)
1521 {
1522 }
1523
1524 lldb_private::Predicate<bool> process_reaped;
1525 lldb_private::Predicate<bool> can_delete;
1526 lldb::pid_t pid;
1527 int signo;
1528 int status;
1529};
1530
1531static bool
1532MonitorShellCommand (void *callback_baton,
1533 lldb::pid_t pid,
1534 bool exited, // True if the process did exit
1535 int signo, // Zero for no signal
1536 int status) // Exit value of process if signal is zero
1537{
1538 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1539 shell_info->pid = pid;
1540 shell_info->signo = signo;
1541 shell_info->status = status;
1542 // Let the thread running Host::RunShellCommand() know that the process
1543 // exited and that ShellInfo has been filled in by broadcasting to it
1544 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1545 // Now wait for a handshake back from that thread running Host::RunShellCommand
1546 // so we know that we can delete shell_info_ptr
1547 shell_info->can_delete.WaitForValueEqualTo(true);
1548 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1549 usleep(1000);
1550 // Now delete the shell info that was passed into this function
1551 delete shell_info;
1552 return true;
1553}
1554
1555Error
1556Host::RunShellCommand (const char *command,
1557 const char *working_dir,
1558 int *status_ptr,
1559 int *signo_ptr,
1560 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001561 uint32_t timeout_sec,
1562 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001563{
1564 Error error;
1565 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001566 if (shell && shell[0])
1567 {
1568 // Run the command in a shell
1569 launch_info.SetShell(shell);
1570 launch_info.GetArguments().AppendArgument(command);
1571 const bool localhost = true;
1572 const bool will_debug = false;
1573 const bool first_arg_is_full_shell_command = true;
1574 launch_info.ConvertArgumentsForLaunchingInShell (error,
1575 localhost,
1576 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001577 first_arg_is_full_shell_command,
1578 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001579 }
1580 else
1581 {
1582 // No shell, just run it
1583 Args args (command);
1584 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001585 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001586 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001587
1588 if (working_dir)
1589 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001590 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001591 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001592
Greg Claytond1cf11a2012-04-14 01:42:46 +00001593 if (command_output_ptr)
1594 {
1595 // Create a temporary file to get the stdout/stderr and redirect the
1596 // output of the command into this file. We will later read this file
1597 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001598 FileSpec tmpdir_file_spec;
1599 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1600 {
1601 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1602 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1603 }
1604 else
1605 {
1606 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1607 }
1608
1609 output_file_path = ::mktemp(output_file_path_buffer);
1610 }
1611
1612 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1613 if (output_file_path)
1614 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001615 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001616 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001617 }
1618 else
1619 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001620 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1621 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1622 }
1623
1624 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001625 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001626
1627 const bool monitor_signals = false;
1628 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1629
1630 error = LaunchProcess (launch_info);
1631 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001632
1633 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1634 error.SetErrorString("failed to get process ID");
1635
1636 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001637 {
1638 // The process successfully launched, so we can defer ownership of
1639 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001640 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001641 // doesn't need to delete the ShellInfo anymore.
1642 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001643 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001644 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001645 if (timeout_sec > 0) {
1646 timeout_time.OffsetWithSeconds(timeout_sec);
1647 timeout_ptr = &timeout_time;
1648 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001649 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001650 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001651 if (timed_out)
1652 {
1653 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001654
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001655 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001656 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001657 // Wait for the monitor callback to get the message
1658 timeout_time = TimeValue::Now();
1659 timeout_time.OffsetWithSeconds(1);
1660 timed_out = false;
1661 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1662 }
1663 else
1664 {
1665 if (status_ptr)
1666 *status_ptr = shell_info->status;
1667
1668 if (signo_ptr)
1669 *signo_ptr = shell_info->signo;
1670
1671 if (command_output_ptr)
1672 {
1673 command_output_ptr->clear();
1674 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1675 uint64_t file_size = file_spec.GetByteSize();
1676 if (file_size > 0)
1677 {
1678 if (file_size > command_output_ptr->max_size())
1679 {
1680 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1681 }
1682 else
1683 {
1684 command_output_ptr->resize(file_size);
1685 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1686 }
1687 }
1688 }
1689 }
1690 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1691 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001692
1693 if (output_file_path)
1694 ::unlink (output_file_path);
1695 // Handshake with the monitor thread, or just let it know in advance that
1696 // it can delete "shell_info" in case we timed out and were not able to kill
1697 // the process...
1698 return error;
1699}
1700
Daniel Malea4244cbd2013-08-27 20:58:59 +00001701
Todd Fiala76747122014-01-23 00:52:28 +00001702// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1703// systems
1704
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001705#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001706
1707// this method needs to be visible to macosx/Host.cpp and
1708// common/Host.cpp.
1709
1710short
1711Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1712{
1713 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1714
1715#if defined (__APPLE__)
1716 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1717 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1718
1719 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1720 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1721
1722 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1723 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1724
1725 if (launch_info.GetLaunchInSeparateProcessGroup())
1726 flags |= POSIX_SPAWN_SETPGROUP;
1727
1728#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1729#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1730 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1731 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1732 {
1733 g_use_close_on_exec_flag = eLazyBoolNo;
1734
1735 uint32_t major, minor, update;
1736 if (Host::GetOSVersion(major, minor, update))
1737 {
1738 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1739 if (major > 10 || (major == 10 && minor > 7))
1740 {
1741 // Only enable for 10.8 and later OS versions
1742 g_use_close_on_exec_flag = eLazyBoolYes;
1743 }
1744 }
1745 }
1746#else
1747 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1748#endif
1749 // Close all files exception those with file actions if this is supported.
1750 if (g_use_close_on_exec_flag == eLazyBoolYes)
1751 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1752#endif
1753#endif // #if defined (__APPLE__)
1754 return flags;
1755}
1756
1757Error
1758Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001759{
1760 Error error;
1761 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1762
Daniel Malea4244cbd2013-08-27 20:58:59 +00001763 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001764 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001765
1766 if (error.Fail() || log)
1767 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001768 if (error.Fail())
1769 return error;
1770
1771 // Make a quick class that will cleanup the posix spawn attributes in case
1772 // we return in the middle of this function.
1773 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1774
1775 sigset_t no_signals;
1776 sigset_t all_signals;
1777 sigemptyset (&no_signals);
1778 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001779 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001780#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001781 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001782#else
1783 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1784#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001785
Todd Fiala76747122014-01-23 00:52:28 +00001786 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001787
1788 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001789 if (error.Fail() || log)
1790 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001791 if (error.Fail())
1792 return error;
1793
Todd Fiala76747122014-01-23 00:52:28 +00001794 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1795 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1796#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001797
1798 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1799 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1800 // to do that job on OSX.
1801
1802 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001803 {
Jim Ingham90331d52014-02-21 01:25:21 +00001804 // We don't need to do this for ARM, and we really shouldn't now that we
1805 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1806 // to set which CPU subtype to launch...
1807 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1808 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1809 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1810 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001811 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1812 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001813 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1814 {
1815 size_t ocount = 0;
1816 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1817 if (error.Fail() || log)
1818 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 +00001819
Jim Ingham90331d52014-02-21 01:25:21 +00001820 if (error.Fail() || ocount != 1)
1821 return error;
1822 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001823 }
1824
Todd Fiala76747122014-01-23 00:52:28 +00001825#endif
1826
1827 const char *tmp_argv[2];
1828 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1829 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1830 if (argv == NULL)
1831 {
1832 // posix_spawn gets very unhappy if it doesn't have at least the program
1833 // name in argv[0]. One of the side affects I have noticed is the environment
1834 // variables don't make it into the child process if "argv == NULL"!!!
1835 tmp_argv[0] = exe_path;
1836 tmp_argv[1] = NULL;
1837 argv = (char * const*)tmp_argv;
1838 }
1839
1840#if !defined (__APPLE__)
1841 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001842 char current_dir[PATH_MAX];
1843 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001844#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001845
1846 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001847 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001848 {
Todd Fiala76747122014-01-23 00:52:28 +00001849#if defined (__APPLE__)
1850 // Set the working directory on this thread only
1851 if (__pthread_chdir (working_dir) < 0) {
1852 if (errno == ENOENT) {
1853 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1854 } else if (errno == ENOTDIR) {
1855 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1856 } else {
1857 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1858 }
1859 return error;
1860 }
1861#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001862 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1863 {
1864 error.SetError(errno, eErrorTypePOSIX);
1865 error.LogIfError(log, "unable to save the current directory");
1866 return error;
1867 }
1868
1869 if (::chdir(working_dir) == -1)
1870 {
1871 error.SetError(errno, eErrorTypePOSIX);
1872 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1873 return error;
1874 }
Todd Fiala76747122014-01-23 00:52:28 +00001875#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001876 }
1877
Todd Fiala76747122014-01-23 00:52:28 +00001878 const size_t num_file_actions = launch_info.GetNumFileActions ();
1879 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001880 {
Todd Fiala76747122014-01-23 00:52:28 +00001881 posix_spawn_file_actions_t file_actions;
1882 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1883 if (error.Fail() || log)
1884 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1885 if (error.Fail())
1886 return error;
1887
1888 // Make a quick class that will cleanup the posix spawn attributes in case
1889 // we return in the middle of this function.
1890 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1891
1892 for (size_t i=0; i<num_file_actions; ++i)
1893 {
1894 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1895 if (launch_file_action)
1896 {
1897 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1898 launch_file_action,
1899 log,
1900 error))
1901 return error;
1902 }
1903 }
1904
1905 error.SetError (::posix_spawnp (&pid,
1906 exe_path,
1907 &file_actions,
1908 &attr,
1909 argv,
1910 envp),
1911 eErrorTypePOSIX);
1912
1913 if (error.Fail() || log)
1914 {
1915 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 +00001916 pid, exe_path, static_cast<void*>(&file_actions),
1917 static_cast<void*>(&attr),
1918 reinterpret_cast<const void*>(argv),
1919 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001920 if (log)
1921 {
1922 for (int ii=0; argv[ii]; ++ii)
1923 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1924 }
1925 }
1926
1927 }
1928 else
1929 {
1930 error.SetError (::posix_spawnp (&pid,
1931 exe_path,
1932 NULL,
1933 &attr,
1934 argv,
1935 envp),
1936 eErrorTypePOSIX);
1937
1938 if (error.Fail() || log)
1939 {
1940 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 +00001941 pid, exe_path, static_cast<void*>(&attr),
1942 reinterpret_cast<const void*>(argv),
1943 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001944 if (log)
1945 {
1946 for (int ii=0; argv[ii]; ++ii)
1947 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1948 }
1949 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001950 }
1951
Todd Fiala76747122014-01-23 00:52:28 +00001952 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001953 {
Todd Fiala76747122014-01-23 00:52:28 +00001954#if defined (__APPLE__)
1955 // No more thread specific current working directory
1956 __pthread_fchdir (-1);
1957#else
1958 if (::chdir(current_dir) == -1 && error.Success())
1959 {
1960 error.SetError(errno, eErrorTypePOSIX);
1961 error.LogIfError(log, "unable to change current directory back to %s",
1962 current_dir);
1963 }
1964#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001965 }
1966
1967 return error;
1968}
1969
Todd Fiala76747122014-01-23 00:52:28 +00001970#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1971
1972
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001973#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
1974// The functions below implement process launching via posix_spawn() for Linux,
1975// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001976
1977Error
1978Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1979{
1980 Error error;
1981 char exe_path[PATH_MAX];
1982
1983 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1984
1985 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1986
1987 FileSpec exe_spec(launch_info.GetExecutableFile());
1988
1989 FileSpec::FileType file_type = exe_spec.GetFileType();
1990 if (file_type != FileSpec::eFileTypeRegular)
1991 {
1992 lldb::ModuleSP exe_module_sp;
1993 error = host_platform_sp->ResolveExecutable (exe_spec,
1994 arch_spec,
1995 exe_module_sp,
1996 NULL);
1997
1998 if (error.Fail())
1999 return error;
2000
2001 if (exe_module_sp)
2002 exe_spec = exe_module_sp->GetFileSpec();
2003 }
2004
2005 if (exe_spec.Exists())
2006 {
2007 exe_spec.GetPath (exe_path, sizeof(exe_path));
2008 }
2009 else
2010 {
2011 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2012 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2013 return error;
2014 }
2015
2016 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2017
2018 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2019
2020 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2021
2022 if (pid != LLDB_INVALID_PROCESS_ID)
2023 {
2024 // If all went well, then set the process ID into the launch info
2025 launch_info.SetProcessID(pid);
2026
Todd Fiala76747122014-01-23 00:52:28 +00002027 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2028
Daniel Malea4244cbd2013-08-27 20:58:59 +00002029 // Make sure we reap any processes we spawn or we will have zombies.
2030 if (!launch_info.MonitorProcess())
2031 {
2032 const bool monitor_signals = false;
2033 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2034 NULL,
2035 pid,
2036 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002037 if (log)
2038 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2039 }
2040 else
2041 {
2042 if (log)
2043 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002044 }
2045 }
2046 else
2047 {
2048 // Invalid process ID, something didn't go well
2049 if (error.Success())
2050 error.SetErrorString ("process launch failed for unknown reasons");
2051 }
2052 return error;
2053}
2054
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002055#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002056
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002057#ifndef _WIN32
2058
2059size_t
2060Host::GetPageSize()
2061{
2062 return ::getpagesize();
2063}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002064
Greg Claytone3e3fee2013-02-17 20:46:30 +00002065uint32_t
2066Host::GetNumberCPUS ()
2067{
2068 static uint32_t g_num_cores = UINT32_MAX;
2069 if (g_num_cores == UINT32_MAX)
2070 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002071#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002072
2073 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002074
Greg Claytone3e3fee2013-02-17 20:46:30 +00002075#else
2076
2077 // Assume POSIX support if a host specific case has not been supplied above
2078 g_num_cores = 0;
2079 int num_cores = 0;
2080 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002081#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002082 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002083#else
2084 int mib[] = { CTL_HW, HW_NCPU };
2085#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002086
2087 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002088 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 +00002089 {
2090 g_num_cores = num_cores;
2091 }
2092 else
2093 {
2094 mib[1] = HW_NCPU;
2095 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002096 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 +00002097 {
2098 if (num_cores > 0)
2099 g_num_cores = num_cores;
2100 }
2101 }
2102#endif
2103 }
2104 return g_num_cores;
2105}
2106
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002107void
2108Host::Kill(lldb::pid_t pid, int signo)
2109{
2110 ::kill(pid, signo);
2111}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002112
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002113#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002114
Johnny Chen8f3d8382011-08-02 20:52:42 +00002115#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002116bool
Greg Clayton3b147632010-12-18 01:54:34 +00002117Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002118{
2119 return false;
2120}
Greg Claytondd36def2010-10-17 22:03:32 +00002121
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002122void
2123Host::SetCrashDescriptionWithFormat (const char *format, ...)
2124{
2125}
2126
2127void
2128Host::SetCrashDescription (const char *description)
2129{
2130}
Greg Claytondd36def2010-10-17 22:03:32 +00002131
2132lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002133Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002134{
2135 return LLDB_INVALID_PROCESS_ID;
2136}
2137
Greg Claytonfbb76342013-11-20 21:07:01 +00002138#endif
2139
2140
2141#ifdef LLDB_DISABLE_POSIX
2142
2143Error
2144Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002145{
Greg Claytonfbb76342013-11-20 21:07:01 +00002146 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002147 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002148 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002149}
Greg Claytonfbb76342013-11-20 21:07:01 +00002150
2151Error
2152Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2153{
2154 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002155 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002156 return error;
2157}
2158
2159Error
2160Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2161{
2162 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002163 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002164 return error;
2165}
2166
2167Error
2168Host::Symlink (const char *src, const char *dst)
2169{
2170 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002171 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002172 return error;
2173}
2174
2175Error
2176Host::Readlink (const char *path, char *buf, size_t buf_len)
2177{
2178 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002179 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002180 return error;
2181}
2182
2183Error
2184Host::Unlink (const char *path)
2185{
2186 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002187 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002188 return error;
2189}
2190
Greg Clayton23f8c952014-03-24 23:10:19 +00002191Error
2192Host::RemoveDirectory (const char* path, bool recurse)
2193{
2194 Error error;
2195 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2196 return error;
2197}
2198
Greg Claytonfbb76342013-11-20 21:07:01 +00002199#else
2200
2201Error
2202Host::MakeDirectory (const char* path, uint32_t file_permissions)
2203{
2204 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002205 if (path && path[0])
2206 {
Greg Claytonfb909312013-11-23 01:58:15 +00002207 if (::mkdir(path, file_permissions) != 0)
2208 {
2209 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002210 switch (error.GetError())
2211 {
2212 case ENOENT:
2213 {
2214 // Parent directory doesn't exist, so lets make it if we can
2215 FileSpec spec(path, false);
2216 if (spec.GetDirectory() && spec.GetFilename())
2217 {
2218 // Make the parent directory and try again
2219 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2220 if (error2.Success())
2221 {
2222 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002223 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002224 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002225 else
Greg Claytonfb909312013-11-23 01:58:15 +00002226 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002227 }
2228 }
2229 }
2230 break;
2231 case EEXIST:
2232 {
2233 FileSpec path_spec(path, false);
2234 if (path_spec.IsDirectory())
2235 error.Clear(); // It is a directory and it already exists
2236 }
2237 break;
2238 }
2239 }
Greg Claytonfb909312013-11-23 01:58:15 +00002240 }
2241 else
2242 {
2243 error.SetErrorString("empty path");
2244 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002245 return error;
2246}
Greg Clayton23f8c952014-03-24 23:10:19 +00002247
2248Error
2249Host::RemoveDirectory (const char* path, bool recurse)
2250{
2251 Error error;
2252 if (path && path[0])
2253 {
2254 if (recurse)
2255 {
2256 StreamString command;
2257 command.Printf("rm -rf \"%s\"", path);
2258 int status = ::system(command.GetString().c_str());
2259 if (status != 0)
2260 error.SetError(status, eErrorTypeGeneric);
2261 }
2262 else
2263 {
2264 if (::rmdir(path) != 0)
2265 error.SetErrorToErrno();
2266 }
2267 }
2268 else
2269 {
2270 error.SetErrorString("empty path");
2271 }
2272 return error;
2273}
Greg Claytonfbb76342013-11-20 21:07:01 +00002274
2275Error
2276Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2277{
2278 Error error;
2279 struct stat file_stats;
2280 if (::stat (path, &file_stats) == 0)
2281 {
2282 // The bits in "st_mode" currently match the definitions
2283 // for the file mode bits in unix.
2284 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2285 }
2286 else
2287 {
2288 error.SetErrorToErrno();
2289 }
2290 return error;
2291}
2292
2293Error
2294Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2295{
2296 Error error;
2297 if (::chmod(path, file_permissions) != 0)
2298 error.SetErrorToErrno();
2299 return error;
2300}
2301
2302Error
2303Host::Symlink (const char *src, const char *dst)
2304{
2305 Error error;
2306 if (::symlink(dst, src) == -1)
2307 error.SetErrorToErrno();
2308 return error;
2309}
2310
2311Error
2312Host::Unlink (const char *path)
2313{
2314 Error error;
2315 if (::unlink(path) == -1)
2316 error.SetErrorToErrno();
2317 return error;
2318}
2319
2320Error
2321Host::Readlink (const char *path, char *buf, size_t buf_len)
2322{
2323 Error error;
2324 ssize_t count = ::readlink(path, buf, buf_len);
2325 if (count < 0)
2326 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002327 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002328 buf[count] = '\0'; // Success
2329 else
2330 error.SetErrorString("'buf' buffer is too small to contain link contents");
2331 return error;
2332}
2333
2334
Greg Clayton2bddd342010-09-07 20:11:56 +00002335#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002336
2337typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2338FDToFileMap& GetFDToFileMap()
2339{
2340 static FDToFileMap g_fd2filemap;
2341 return g_fd2filemap;
2342}
2343
2344lldb::user_id_t
2345Host::OpenFile (const FileSpec& file_spec,
2346 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002347 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002348 Error &error)
2349{
2350 std::string path (file_spec.GetPath());
2351 if (path.empty())
2352 {
2353 error.SetErrorString("empty path");
2354 return UINT64_MAX;
2355 }
2356 FileSP file_sp(new File());
2357 error = file_sp->Open(path.c_str(),flags,mode);
2358 if (file_sp->IsValid() == false)
2359 return UINT64_MAX;
2360 lldb::user_id_t fd = file_sp->GetDescriptor();
2361 GetFDToFileMap()[fd] = file_sp;
2362 return fd;
2363}
2364
2365bool
2366Host::CloseFile (lldb::user_id_t fd, Error &error)
2367{
2368 if (fd == UINT64_MAX)
2369 {
2370 error.SetErrorString ("invalid file descriptor");
2371 return false;
2372 }
2373 FDToFileMap& file_map = GetFDToFileMap();
2374 FDToFileMap::iterator pos = file_map.find(fd);
2375 if (pos == file_map.end())
2376 {
2377 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2378 return false;
2379 }
2380 FileSP file_sp = pos->second;
2381 if (!file_sp)
2382 {
2383 error.SetErrorString ("invalid host backing file");
2384 return false;
2385 }
2386 error = file_sp->Close();
2387 file_map.erase(pos);
2388 return error.Success();
2389}
2390
2391uint64_t
2392Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2393{
2394 if (fd == UINT64_MAX)
2395 {
2396 error.SetErrorString ("invalid file descriptor");
2397 return UINT64_MAX;
2398 }
2399 FDToFileMap& file_map = GetFDToFileMap();
2400 FDToFileMap::iterator pos = file_map.find(fd);
2401 if (pos == file_map.end())
2402 {
2403 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2404 return false;
2405 }
2406 FileSP file_sp = pos->second;
2407 if (!file_sp)
2408 {
2409 error.SetErrorString ("invalid host backing file");
2410 return UINT64_MAX;
2411 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002412 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2413 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002414 return UINT64_MAX;
2415 size_t bytes_written = src_len;
2416 error = file_sp->Write(src, bytes_written);
2417 if (error.Fail())
2418 return UINT64_MAX;
2419 return bytes_written;
2420}
2421
2422uint64_t
2423Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2424{
2425 if (fd == UINT64_MAX)
2426 {
2427 error.SetErrorString ("invalid file descriptor");
2428 return UINT64_MAX;
2429 }
2430 FDToFileMap& file_map = GetFDToFileMap();
2431 FDToFileMap::iterator pos = file_map.find(fd);
2432 if (pos == file_map.end())
2433 {
2434 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2435 return false;
2436 }
2437 FileSP file_sp = pos->second;
2438 if (!file_sp)
2439 {
2440 error.SetErrorString ("invalid host backing file");
2441 return UINT64_MAX;
2442 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002443 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2444 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002445 return UINT64_MAX;
2446 size_t bytes_read = dst_len;
2447 error = file_sp->Read(dst ,bytes_read);
2448 if (error.Fail())
2449 return UINT64_MAX;
2450 return bytes_read;
2451}
2452
2453lldb::user_id_t
2454Host::GetFileSize (const FileSpec& file_spec)
2455{
2456 return file_spec.GetByteSize();
2457}
2458
2459bool
2460Host::GetFileExists (const FileSpec& file_spec)
2461{
2462 return file_spec.Exists();
2463}
2464
2465bool
2466Host::CalculateMD5 (const FileSpec& file_spec,
2467 uint64_t &low,
2468 uint64_t &high)
2469{
2470#if defined (__APPLE__)
2471 StreamString md5_cmd_line;
2472 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2473 std::string hash_string;
2474 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2475 if (err.Fail())
2476 return false;
2477 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2478 // if the output is any other length it is probably wrong
2479 if (hash_string.size() != 32)
2480 return false;
2481 std::string part1(hash_string,0,16);
2482 std::string part2(hash_string,16);
2483 const char* part1_cstr = part1.c_str();
2484 const char* part2_cstr = part2.c_str();
2485 high = ::strtoull(part1_cstr, NULL, 16);
2486 low = ::strtoull(part2_cstr, NULL, 16);
2487 return true;
2488#else
2489 // your own MD5 implementation here
2490 return false;
2491#endif
2492}