blob: 275b446744782e5f504c0d23c2374a3e7c69e56e [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 }
Todd Fiala015d8182014-07-22 23:41:36 +00001096#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1097 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1098 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
1099 // different trees.
1100 if (log)
1101 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1102 char *lib_pos = ::strstr (raw_path, "/lib");
1103 if (lib_pos != nullptr)
1104 {
1105 // First terminate the raw path at the start of lib.
1106 *lib_pos = '\0';
1107
1108 // Now write in bin in place of lib.
1109 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1110
1111 if (log)
1112 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1113 }
1114 else
1115 {
1116 if (log)
1117 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1118 }
Jason Molendaa3329782014-03-29 18:54:20 +00001119#endif // #if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001120 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1121 g_lldb_support_exe_dir.SetCString(resolved_path);
1122 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001123 if (log)
1124 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001125 }
1126 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001127 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001128 }
1129 break;
1130
1131 case ePathTypeHeaderDir:
1132 {
1133 static ConstString g_lldb_headers_dir;
1134 if (!g_lldb_headers_dir)
1135 {
1136#if defined (__APPLE__)
1137 FileSpec lldb_file_spec;
1138 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1139 {
1140 char raw_path[PATH_MAX];
1141 char resolved_path[PATH_MAX];
1142 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1143
1144 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1145 if (framework_pos)
1146 {
1147 framework_pos += strlen("LLDB.framework");
1148 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1149 }
1150 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1151 g_lldb_headers_dir.SetCString(resolved_path);
1152 }
1153#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001154 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001155 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1156#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001157 if (log)
1158 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001159 }
1160 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001161 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001162 }
1163 break;
1164
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001165#ifdef LLDB_DISABLE_PYTHON
1166 case ePathTypePythonDir:
1167 return false;
1168#else
1169 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001170 {
Greg Claytondd36def2010-10-17 22:03:32 +00001171 static ConstString g_lldb_python_dir;
1172 if (!g_lldb_python_dir)
1173 {
1174 FileSpec lldb_file_spec;
1175 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1176 {
1177 char raw_path[PATH_MAX];
1178 char resolved_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001179#if defined(_WIN32)
1180 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1181 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1182#else
Greg Claytondd36def2010-10-17 22:03:32 +00001183 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1184
1185#if defined (__APPLE__)
1186 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1187 if (framework_pos)
1188 {
1189 framework_pos += strlen("LLDB.framework");
1190 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001191 }
1192 else
1193 {
1194#endif
1195 llvm::SmallString<256> python_version_dir;
1196 llvm::raw_svector_ostream os(python_version_dir);
1197 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1198 os.flush();
1199
1200 // We may get our string truncated. Should we protect
1201 // this with an assert?
1202
1203 ::strncat(raw_path, python_version_dir.c_str(),
1204 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001205#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001206#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001207 }
1208#endif
1209 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1210 g_lldb_python_dir.SetCString(resolved_path);
1211 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001212
1213 if (log)
1214 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1215
Greg Claytondd36def2010-10-17 22:03:32 +00001216 }
1217 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001218 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001219 }
1220 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001221#endif
1222
Greg Clayton4272cc72011-02-02 02:24:04 +00001223 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1224 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001225#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001226 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001227 static bool g_lldb_system_plugin_dir_located = false;
1228 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001229 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001230 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001231#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001232 FileSpec lldb_file_spec;
1233 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1234 {
1235 char raw_path[PATH_MAX];
1236 char resolved_path[PATH_MAX];
1237 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1238
1239 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1240 if (framework_pos)
1241 {
1242 framework_pos += strlen("LLDB.framework");
1243 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001244 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1245 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001246 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001247 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001248 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001249#elif defined (__linux__)
1250 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1251 if (lldb_file_spec.Exists())
1252 {
1253 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1254 }
1255#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001256
1257 if (log)
1258 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1259
Greg Clayton4272cc72011-02-02 02:24:04 +00001260 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001261
1262 if (g_lldb_system_plugin_dir)
1263 {
1264 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1265 return true;
1266 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001267#else
1268 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001269 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001270#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001271 }
1272 break;
1273
1274 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1275 {
1276#if defined (__APPLE__)
1277 static ConstString g_lldb_user_plugin_dir;
1278 if (!g_lldb_user_plugin_dir)
1279 {
1280 char user_plugin_path[PATH_MAX];
1281 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1282 user_plugin_path,
1283 sizeof(user_plugin_path)))
1284 {
1285 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1286 }
1287 }
1288 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001289 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001290#elif defined (__linux__)
1291 static ConstString g_lldb_user_plugin_dir;
1292 if (!g_lldb_user_plugin_dir)
1293 {
1294 // XDG Base Directory Specification
1295 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1296 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1297 FileSpec lldb_file_spec;
1298 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1299 if (xdg_data_home && xdg_data_home[0])
1300 {
1301 std::string user_plugin_dir (xdg_data_home);
1302 user_plugin_dir += "/lldb";
1303 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1304 }
1305 else
1306 {
1307 const char *home_dir = getenv("HOME");
1308 if (home_dir && home_dir[0])
1309 {
1310 std::string user_plugin_dir (home_dir);
1311 user_plugin_dir += "/.local/share/lldb";
1312 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1313 }
1314 }
1315
1316 if (lldb_file_spec.Exists())
1317 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001318 if (log)
1319 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001320 }
1321 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001322 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001323#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001324 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001325 return false;
1326 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001327
1328 case ePathTypeLLDBTempSystemDir:
1329 {
1330 static ConstString g_lldb_tmp_dir;
1331 if (!g_lldb_tmp_dir)
1332 {
1333 const char *tmpdir_cstr = getenv("TMPDIR");
1334 if (tmpdir_cstr == NULL)
1335 {
1336 tmpdir_cstr = getenv("TMP");
1337 if (tmpdir_cstr == NULL)
1338 tmpdir_cstr = getenv("TEMP");
1339 }
1340 if (tmpdir_cstr)
1341 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001342 StreamString pid_tmpdir;
1343 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1344 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1345 {
1346 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1347 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1348 {
1349 // Make an atexit handler to clean up the process specify LLDB temp dir
1350 // and all of its contents.
1351 ::atexit (CleanupProcessSpecificLLDBTempDir);
1352 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1353 if (log)
1354 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1355
1356 }
1357 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001358 }
1359 }
1360 file_spec.GetDirectory() = g_lldb_tmp_dir;
1361 return (bool)file_spec.GetDirectory();
1362 }
Greg Claytondd36def2010-10-17 22:03:32 +00001363 }
1364
1365 return false;
1366}
1367
Greg Clayton1cb64962011-03-24 04:28:38 +00001368
1369bool
1370Host::GetHostname (std::string &s)
1371{
1372 char hostname[PATH_MAX];
1373 hostname[sizeof(hostname) - 1] = '\0';
1374 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1375 {
1376 struct hostent* h = ::gethostbyname (hostname);
1377 if (h)
1378 s.assign (h->h_name);
1379 else
1380 s.assign (hostname);
1381 return true;
1382 }
1383 return false;
1384}
1385
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001386#ifndef _WIN32
1387
Greg Clayton32e0a752011-03-30 18:16:51 +00001388const char *
1389Host::GetUserName (uint32_t uid, std::string &user_name)
1390{
1391 struct passwd user_info;
1392 struct passwd *user_info_ptr = &user_info;
1393 char user_buffer[PATH_MAX];
1394 size_t user_buffer_size = sizeof(user_buffer);
1395 if (::getpwuid_r (uid,
1396 &user_info,
1397 user_buffer,
1398 user_buffer_size,
1399 &user_info_ptr) == 0)
1400 {
1401 if (user_info_ptr)
1402 {
1403 user_name.assign (user_info_ptr->pw_name);
1404 return user_name.c_str();
1405 }
1406 }
1407 user_name.clear();
1408 return NULL;
1409}
1410
1411const char *
1412Host::GetGroupName (uint32_t gid, std::string &group_name)
1413{
1414 char group_buffer[PATH_MAX];
1415 size_t group_buffer_size = sizeof(group_buffer);
1416 struct group group_info;
1417 struct group *group_info_ptr = &group_info;
1418 // Try the threadsafe version first
1419 if (::getgrgid_r (gid,
1420 &group_info,
1421 group_buffer,
1422 group_buffer_size,
1423 &group_info_ptr) == 0)
1424 {
1425 if (group_info_ptr)
1426 {
1427 group_name.assign (group_info_ptr->gr_name);
1428 return group_name.c_str();
1429 }
1430 }
1431 else
1432 {
1433 // The threadsafe version isn't currently working
1434 // for me on darwin, but the non-threadsafe version
1435 // is, so I am calling it below.
1436 group_info_ptr = ::getgrgid (gid);
1437 if (group_info_ptr)
1438 {
1439 group_name.assign (group_info_ptr->gr_name);
1440 return group_name.c_str();
1441 }
1442 }
1443 group_name.clear();
1444 return NULL;
1445}
1446
Han Ming Ong84647042012-02-25 01:07:38 +00001447uint32_t
1448Host::GetUserID ()
1449{
1450 return getuid();
1451}
1452
1453uint32_t
1454Host::GetGroupID ()
1455{
1456 return getgid();
1457}
1458
1459uint32_t
1460Host::GetEffectiveUserID ()
1461{
1462 return geteuid();
1463}
1464
1465uint32_t
1466Host::GetEffectiveGroupID ()
1467{
1468 return getegid();
1469}
1470
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001471#endif
1472
1473#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1474bool
1475Host::GetOSBuildString (std::string &s)
1476{
1477 s.clear();
1478 return false;
1479}
1480
1481bool
1482Host::GetOSKernelDescription (std::string &s)
1483{
1484 s.clear();
1485 return false;
1486}
1487#endif
1488
Zachary Turner310035a2014-07-08 04:52:15 +00001489#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1490 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001491uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001492Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001493{
1494 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001495 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001496}
1497
Greg Claytone996fd32011-03-08 22:40:15 +00001498bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001499Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001500{
Greg Claytone996fd32011-03-08 22:40:15 +00001501 process_info.Clear();
1502 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001503}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001504#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001505
Matt Kopec085d6ce2013-05-31 22:00:07 +00001506#if !defined(__linux__)
1507bool
1508Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1509{
1510 return false;
1511}
1512#endif
1513
Sean Callananc0a6e062011-10-27 21:22:25 +00001514lldb::TargetSP
1515Host::GetDummyTarget (lldb_private::Debugger &debugger)
1516{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001517 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001518
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001519 // FIXME: Maybe the dummy target should be per-Debugger
1520 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1521 {
1522 ArchSpec arch(Target::GetDefaultArchitecture());
1523 if (!arch.IsValid())
1524 arch = Host::GetArchitecture ();
1525 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001526 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001527 arch.GetTriple().getTriple().c_str(),
1528 false,
1529 NULL,
1530 g_dummy_target_sp);
1531 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001532
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001533 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001534}
1535
Greg Claytond1cf11a2012-04-14 01:42:46 +00001536struct ShellInfo
1537{
1538 ShellInfo () :
1539 process_reaped (false),
1540 can_delete (false),
1541 pid (LLDB_INVALID_PROCESS_ID),
1542 signo(-1),
1543 status(-1)
1544 {
1545 }
1546
1547 lldb_private::Predicate<bool> process_reaped;
1548 lldb_private::Predicate<bool> can_delete;
1549 lldb::pid_t pid;
1550 int signo;
1551 int status;
1552};
1553
1554static bool
1555MonitorShellCommand (void *callback_baton,
1556 lldb::pid_t pid,
1557 bool exited, // True if the process did exit
1558 int signo, // Zero for no signal
1559 int status) // Exit value of process if signal is zero
1560{
1561 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1562 shell_info->pid = pid;
1563 shell_info->signo = signo;
1564 shell_info->status = status;
1565 // Let the thread running Host::RunShellCommand() know that the process
1566 // exited and that ShellInfo has been filled in by broadcasting to it
1567 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1568 // Now wait for a handshake back from that thread running Host::RunShellCommand
1569 // so we know that we can delete shell_info_ptr
1570 shell_info->can_delete.WaitForValueEqualTo(true);
1571 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1572 usleep(1000);
1573 // Now delete the shell info that was passed into this function
1574 delete shell_info;
1575 return true;
1576}
1577
1578Error
1579Host::RunShellCommand (const char *command,
1580 const char *working_dir,
1581 int *status_ptr,
1582 int *signo_ptr,
1583 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001584 uint32_t timeout_sec,
1585 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001586{
1587 Error error;
1588 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001589 if (shell && shell[0])
1590 {
1591 // Run the command in a shell
1592 launch_info.SetShell(shell);
1593 launch_info.GetArguments().AppendArgument(command);
1594 const bool localhost = true;
1595 const bool will_debug = false;
1596 const bool first_arg_is_full_shell_command = true;
1597 launch_info.ConvertArgumentsForLaunchingInShell (error,
1598 localhost,
1599 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001600 first_arg_is_full_shell_command,
1601 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001602 }
1603 else
1604 {
1605 // No shell, just run it
1606 Args args (command);
1607 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001608 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001609 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001610
1611 if (working_dir)
1612 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001613 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001614 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001615
Greg Claytond1cf11a2012-04-14 01:42:46 +00001616 if (command_output_ptr)
1617 {
1618 // Create a temporary file to get the stdout/stderr and redirect the
1619 // output of the command into this file. We will later read this file
1620 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001621 FileSpec tmpdir_file_spec;
1622 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1623 {
1624 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1625 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1626 }
1627 else
1628 {
1629 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1630 }
1631
1632 output_file_path = ::mktemp(output_file_path_buffer);
1633 }
1634
1635 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1636 if (output_file_path)
1637 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001638 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001639 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001640 }
1641 else
1642 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001643 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1644 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1645 }
1646
1647 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001648 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001649
1650 const bool monitor_signals = false;
1651 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1652
1653 error = LaunchProcess (launch_info);
1654 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001655
1656 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1657 error.SetErrorString("failed to get process ID");
1658
1659 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001660 {
1661 // The process successfully launched, so we can defer ownership of
1662 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001663 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001664 // doesn't need to delete the ShellInfo anymore.
1665 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001666 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001667 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001668 if (timeout_sec > 0) {
1669 timeout_time.OffsetWithSeconds(timeout_sec);
1670 timeout_ptr = &timeout_time;
1671 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001672 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001673 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001674 if (timed_out)
1675 {
1676 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001677
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001678 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001679 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001680 // Wait for the monitor callback to get the message
1681 timeout_time = TimeValue::Now();
1682 timeout_time.OffsetWithSeconds(1);
1683 timed_out = false;
1684 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1685 }
1686 else
1687 {
1688 if (status_ptr)
1689 *status_ptr = shell_info->status;
1690
1691 if (signo_ptr)
1692 *signo_ptr = shell_info->signo;
1693
1694 if (command_output_ptr)
1695 {
1696 command_output_ptr->clear();
1697 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1698 uint64_t file_size = file_spec.GetByteSize();
1699 if (file_size > 0)
1700 {
1701 if (file_size > command_output_ptr->max_size())
1702 {
1703 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1704 }
1705 else
1706 {
1707 command_output_ptr->resize(file_size);
1708 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1709 }
1710 }
1711 }
1712 }
1713 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1714 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001715
1716 if (output_file_path)
1717 ::unlink (output_file_path);
1718 // Handshake with the monitor thread, or just let it know in advance that
1719 // it can delete "shell_info" in case we timed out and were not able to kill
1720 // the process...
1721 return error;
1722}
1723
Daniel Malea4244cbd2013-08-27 20:58:59 +00001724
Todd Fiala76747122014-01-23 00:52:28 +00001725// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1726// systems
1727
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001728#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001729
1730// this method needs to be visible to macosx/Host.cpp and
1731// common/Host.cpp.
1732
1733short
1734Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1735{
1736 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1737
1738#if defined (__APPLE__)
1739 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1740 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1741
1742 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1743 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1744
1745 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1746 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1747
1748 if (launch_info.GetLaunchInSeparateProcessGroup())
1749 flags |= POSIX_SPAWN_SETPGROUP;
1750
1751#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1752#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1753 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1754 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1755 {
1756 g_use_close_on_exec_flag = eLazyBoolNo;
1757
1758 uint32_t major, minor, update;
1759 if (Host::GetOSVersion(major, minor, update))
1760 {
1761 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1762 if (major > 10 || (major == 10 && minor > 7))
1763 {
1764 // Only enable for 10.8 and later OS versions
1765 g_use_close_on_exec_flag = eLazyBoolYes;
1766 }
1767 }
1768 }
1769#else
1770 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1771#endif
1772 // Close all files exception those with file actions if this is supported.
1773 if (g_use_close_on_exec_flag == eLazyBoolYes)
1774 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1775#endif
1776#endif // #if defined (__APPLE__)
1777 return flags;
1778}
1779
1780Error
1781Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001782{
1783 Error error;
1784 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1785
Daniel Malea4244cbd2013-08-27 20:58:59 +00001786 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001787 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001788
1789 if (error.Fail() || log)
1790 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001791 if (error.Fail())
1792 return error;
1793
1794 // Make a quick class that will cleanup the posix spawn attributes in case
1795 // we return in the middle of this function.
1796 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1797
1798 sigset_t no_signals;
1799 sigset_t all_signals;
1800 sigemptyset (&no_signals);
1801 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001802 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001803#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001804 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001805#else
1806 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1807#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001808
Todd Fiala76747122014-01-23 00:52:28 +00001809 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001810
1811 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001812 if (error.Fail() || log)
1813 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001814 if (error.Fail())
1815 return error;
1816
Todd Fiala76747122014-01-23 00:52:28 +00001817 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1818 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1819#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001820
1821 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1822 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1823 // to do that job on OSX.
1824
1825 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001826 {
Jim Ingham90331d52014-02-21 01:25:21 +00001827 // We don't need to do this for ARM, and we really shouldn't now that we
1828 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1829 // to set which CPU subtype to launch...
1830 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1831 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1832 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1833 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001834 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1835 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001836 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1837 {
1838 size_t ocount = 0;
1839 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1840 if (error.Fail() || log)
1841 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 +00001842
Jim Ingham90331d52014-02-21 01:25:21 +00001843 if (error.Fail() || ocount != 1)
1844 return error;
1845 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001846 }
1847
Todd Fiala76747122014-01-23 00:52:28 +00001848#endif
1849
1850 const char *tmp_argv[2];
1851 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1852 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1853 if (argv == NULL)
1854 {
1855 // posix_spawn gets very unhappy if it doesn't have at least the program
1856 // name in argv[0]. One of the side affects I have noticed is the environment
1857 // variables don't make it into the child process if "argv == NULL"!!!
1858 tmp_argv[0] = exe_path;
1859 tmp_argv[1] = NULL;
1860 argv = (char * const*)tmp_argv;
1861 }
1862
1863#if !defined (__APPLE__)
1864 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001865 char current_dir[PATH_MAX];
1866 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001867#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001868
1869 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001870 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001871 {
Todd Fiala76747122014-01-23 00:52:28 +00001872#if defined (__APPLE__)
1873 // Set the working directory on this thread only
1874 if (__pthread_chdir (working_dir) < 0) {
1875 if (errno == ENOENT) {
1876 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1877 } else if (errno == ENOTDIR) {
1878 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1879 } else {
1880 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1881 }
1882 return error;
1883 }
1884#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001885 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1886 {
1887 error.SetError(errno, eErrorTypePOSIX);
1888 error.LogIfError(log, "unable to save the current directory");
1889 return error;
1890 }
1891
1892 if (::chdir(working_dir) == -1)
1893 {
1894 error.SetError(errno, eErrorTypePOSIX);
1895 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1896 return error;
1897 }
Todd Fiala76747122014-01-23 00:52:28 +00001898#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001899 }
1900
Todd Fiala76747122014-01-23 00:52:28 +00001901 const size_t num_file_actions = launch_info.GetNumFileActions ();
1902 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001903 {
Todd Fiala76747122014-01-23 00:52:28 +00001904 posix_spawn_file_actions_t file_actions;
1905 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1906 if (error.Fail() || log)
1907 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1908 if (error.Fail())
1909 return error;
1910
1911 // Make a quick class that will cleanup the posix spawn attributes in case
1912 // we return in the middle of this function.
1913 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1914
1915 for (size_t i=0; i<num_file_actions; ++i)
1916 {
1917 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1918 if (launch_file_action)
1919 {
1920 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1921 launch_file_action,
1922 log,
1923 error))
1924 return error;
1925 }
1926 }
1927
1928 error.SetError (::posix_spawnp (&pid,
1929 exe_path,
1930 &file_actions,
1931 &attr,
1932 argv,
1933 envp),
1934 eErrorTypePOSIX);
1935
1936 if (error.Fail() || log)
1937 {
1938 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 +00001939 pid, exe_path, static_cast<void*>(&file_actions),
1940 static_cast<void*>(&attr),
1941 reinterpret_cast<const void*>(argv),
1942 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001943 if (log)
1944 {
1945 for (int ii=0; argv[ii]; ++ii)
1946 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1947 }
1948 }
1949
1950 }
1951 else
1952 {
1953 error.SetError (::posix_spawnp (&pid,
1954 exe_path,
1955 NULL,
1956 &attr,
1957 argv,
1958 envp),
1959 eErrorTypePOSIX);
1960
1961 if (error.Fail() || log)
1962 {
1963 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 +00001964 pid, exe_path, static_cast<void*>(&attr),
1965 reinterpret_cast<const void*>(argv),
1966 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001967 if (log)
1968 {
1969 for (int ii=0; argv[ii]; ++ii)
1970 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1971 }
1972 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001973 }
1974
Todd Fiala76747122014-01-23 00:52:28 +00001975 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001976 {
Todd Fiala76747122014-01-23 00:52:28 +00001977#if defined (__APPLE__)
1978 // No more thread specific current working directory
1979 __pthread_fchdir (-1);
1980#else
1981 if (::chdir(current_dir) == -1 && error.Success())
1982 {
1983 error.SetError(errno, eErrorTypePOSIX);
1984 error.LogIfError(log, "unable to change current directory back to %s",
1985 current_dir);
1986 }
1987#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001988 }
1989
1990 return error;
1991}
1992
Todd Fiala76747122014-01-23 00:52:28 +00001993#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1994
1995
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001996#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
1997// The functions below implement process launching via posix_spawn() for Linux,
1998// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001999
2000Error
2001Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2002{
2003 Error error;
2004 char exe_path[PATH_MAX];
2005
2006 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2007
2008 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2009
2010 FileSpec exe_spec(launch_info.GetExecutableFile());
2011
2012 FileSpec::FileType file_type = exe_spec.GetFileType();
2013 if (file_type != FileSpec::eFileTypeRegular)
2014 {
2015 lldb::ModuleSP exe_module_sp;
2016 error = host_platform_sp->ResolveExecutable (exe_spec,
2017 arch_spec,
2018 exe_module_sp,
2019 NULL);
2020
2021 if (error.Fail())
2022 return error;
2023
2024 if (exe_module_sp)
2025 exe_spec = exe_module_sp->GetFileSpec();
2026 }
2027
2028 if (exe_spec.Exists())
2029 {
2030 exe_spec.GetPath (exe_path, sizeof(exe_path));
2031 }
2032 else
2033 {
2034 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2035 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2036 return error;
2037 }
2038
2039 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2040
2041 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2042
2043 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2044
2045 if (pid != LLDB_INVALID_PROCESS_ID)
2046 {
2047 // If all went well, then set the process ID into the launch info
2048 launch_info.SetProcessID(pid);
2049
Todd Fiala76747122014-01-23 00:52:28 +00002050 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2051
Daniel Malea4244cbd2013-08-27 20:58:59 +00002052 // Make sure we reap any processes we spawn or we will have zombies.
2053 if (!launch_info.MonitorProcess())
2054 {
2055 const bool monitor_signals = false;
2056 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2057 NULL,
2058 pid,
2059 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002060 if (log)
2061 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2062 }
2063 else
2064 {
2065 if (log)
2066 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002067 }
2068 }
2069 else
2070 {
2071 // Invalid process ID, something didn't go well
2072 if (error.Success())
2073 error.SetErrorString ("process launch failed for unknown reasons");
2074 }
2075 return error;
2076}
2077
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002078#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002079
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002080#ifndef _WIN32
2081
2082size_t
2083Host::GetPageSize()
2084{
2085 return ::getpagesize();
2086}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002087
Greg Claytone3e3fee2013-02-17 20:46:30 +00002088uint32_t
2089Host::GetNumberCPUS ()
2090{
2091 static uint32_t g_num_cores = UINT32_MAX;
2092 if (g_num_cores == UINT32_MAX)
2093 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002094#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002095
2096 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002097
Greg Claytone3e3fee2013-02-17 20:46:30 +00002098#else
2099
2100 // Assume POSIX support if a host specific case has not been supplied above
2101 g_num_cores = 0;
2102 int num_cores = 0;
2103 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002104#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002105 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002106#else
2107 int mib[] = { CTL_HW, HW_NCPU };
2108#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002109
2110 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002111 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 +00002112 {
2113 g_num_cores = num_cores;
2114 }
2115 else
2116 {
2117 mib[1] = HW_NCPU;
2118 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002119 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 +00002120 {
2121 if (num_cores > 0)
2122 g_num_cores = num_cores;
2123 }
2124 }
2125#endif
2126 }
2127 return g_num_cores;
2128}
2129
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002130void
2131Host::Kill(lldb::pid_t pid, int signo)
2132{
2133 ::kill(pid, signo);
2134}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002135
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002136#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002137
Johnny Chen8f3d8382011-08-02 20:52:42 +00002138#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002139bool
Greg Clayton3b147632010-12-18 01:54:34 +00002140Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002141{
2142 return false;
2143}
Greg Claytondd36def2010-10-17 22:03:32 +00002144
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002145void
2146Host::SetCrashDescriptionWithFormat (const char *format, ...)
2147{
2148}
2149
2150void
2151Host::SetCrashDescription (const char *description)
2152{
2153}
Greg Claytondd36def2010-10-17 22:03:32 +00002154
2155lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002156Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002157{
2158 return LLDB_INVALID_PROCESS_ID;
2159}
2160
Greg Claytonfbb76342013-11-20 21:07:01 +00002161#endif
2162
2163
2164#ifdef LLDB_DISABLE_POSIX
2165
2166Error
2167Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002168{
Greg Claytonfbb76342013-11-20 21:07:01 +00002169 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002170 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002171 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002172}
Greg Claytonfbb76342013-11-20 21:07:01 +00002173
2174Error
2175Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2176{
2177 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002178 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002179 return error;
2180}
2181
2182Error
2183Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2184{
2185 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002186 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002187 return error;
2188}
2189
2190Error
2191Host::Symlink (const char *src, const char *dst)
2192{
2193 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002194 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002195 return error;
2196}
2197
2198Error
2199Host::Readlink (const char *path, char *buf, size_t buf_len)
2200{
2201 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002202 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002203 return error;
2204}
2205
2206Error
2207Host::Unlink (const char *path)
2208{
2209 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002210 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002211 return error;
2212}
2213
Greg Clayton23f8c952014-03-24 23:10:19 +00002214Error
2215Host::RemoveDirectory (const char* path, bool recurse)
2216{
2217 Error error;
2218 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2219 return error;
2220}
2221
Greg Claytonfbb76342013-11-20 21:07:01 +00002222#else
2223
2224Error
2225Host::MakeDirectory (const char* path, uint32_t file_permissions)
2226{
2227 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002228 if (path && path[0])
2229 {
Greg Claytonfb909312013-11-23 01:58:15 +00002230 if (::mkdir(path, file_permissions) != 0)
2231 {
2232 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002233 switch (error.GetError())
2234 {
2235 case ENOENT:
2236 {
2237 // Parent directory doesn't exist, so lets make it if we can
2238 FileSpec spec(path, false);
2239 if (spec.GetDirectory() && spec.GetFilename())
2240 {
2241 // Make the parent directory and try again
2242 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2243 if (error2.Success())
2244 {
2245 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002246 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002247 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002248 else
Greg Claytonfb909312013-11-23 01:58:15 +00002249 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002250 }
2251 }
2252 }
2253 break;
2254 case EEXIST:
2255 {
2256 FileSpec path_spec(path, false);
2257 if (path_spec.IsDirectory())
2258 error.Clear(); // It is a directory and it already exists
2259 }
2260 break;
2261 }
2262 }
Greg Claytonfb909312013-11-23 01:58:15 +00002263 }
2264 else
2265 {
2266 error.SetErrorString("empty path");
2267 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002268 return error;
2269}
Greg Clayton23f8c952014-03-24 23:10:19 +00002270
2271Error
2272Host::RemoveDirectory (const char* path, bool recurse)
2273{
2274 Error error;
2275 if (path && path[0])
2276 {
2277 if (recurse)
2278 {
2279 StreamString command;
2280 command.Printf("rm -rf \"%s\"", path);
2281 int status = ::system(command.GetString().c_str());
2282 if (status != 0)
2283 error.SetError(status, eErrorTypeGeneric);
2284 }
2285 else
2286 {
2287 if (::rmdir(path) != 0)
2288 error.SetErrorToErrno();
2289 }
2290 }
2291 else
2292 {
2293 error.SetErrorString("empty path");
2294 }
2295 return error;
2296}
Greg Claytonfbb76342013-11-20 21:07:01 +00002297
2298Error
2299Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2300{
2301 Error error;
2302 struct stat file_stats;
2303 if (::stat (path, &file_stats) == 0)
2304 {
2305 // The bits in "st_mode" currently match the definitions
2306 // for the file mode bits in unix.
2307 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2308 }
2309 else
2310 {
2311 error.SetErrorToErrno();
2312 }
2313 return error;
2314}
2315
2316Error
2317Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2318{
2319 Error error;
2320 if (::chmod(path, file_permissions) != 0)
2321 error.SetErrorToErrno();
2322 return error;
2323}
2324
2325Error
2326Host::Symlink (const char *src, const char *dst)
2327{
2328 Error error;
2329 if (::symlink(dst, src) == -1)
2330 error.SetErrorToErrno();
2331 return error;
2332}
2333
2334Error
2335Host::Unlink (const char *path)
2336{
2337 Error error;
2338 if (::unlink(path) == -1)
2339 error.SetErrorToErrno();
2340 return error;
2341}
2342
2343Error
2344Host::Readlink (const char *path, char *buf, size_t buf_len)
2345{
2346 Error error;
2347 ssize_t count = ::readlink(path, buf, buf_len);
2348 if (count < 0)
2349 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002350 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002351 buf[count] = '\0'; // Success
2352 else
2353 error.SetErrorString("'buf' buffer is too small to contain link contents");
2354 return error;
2355}
2356
2357
Greg Clayton2bddd342010-09-07 20:11:56 +00002358#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002359
2360typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2361FDToFileMap& GetFDToFileMap()
2362{
2363 static FDToFileMap g_fd2filemap;
2364 return g_fd2filemap;
2365}
2366
2367lldb::user_id_t
2368Host::OpenFile (const FileSpec& file_spec,
2369 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002370 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002371 Error &error)
2372{
2373 std::string path (file_spec.GetPath());
2374 if (path.empty())
2375 {
2376 error.SetErrorString("empty path");
2377 return UINT64_MAX;
2378 }
2379 FileSP file_sp(new File());
2380 error = file_sp->Open(path.c_str(),flags,mode);
2381 if (file_sp->IsValid() == false)
2382 return UINT64_MAX;
2383 lldb::user_id_t fd = file_sp->GetDescriptor();
2384 GetFDToFileMap()[fd] = file_sp;
2385 return fd;
2386}
2387
2388bool
2389Host::CloseFile (lldb::user_id_t fd, Error &error)
2390{
2391 if (fd == UINT64_MAX)
2392 {
2393 error.SetErrorString ("invalid file descriptor");
2394 return false;
2395 }
2396 FDToFileMap& file_map = GetFDToFileMap();
2397 FDToFileMap::iterator pos = file_map.find(fd);
2398 if (pos == file_map.end())
2399 {
2400 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2401 return false;
2402 }
2403 FileSP file_sp = pos->second;
2404 if (!file_sp)
2405 {
2406 error.SetErrorString ("invalid host backing file");
2407 return false;
2408 }
2409 error = file_sp->Close();
2410 file_map.erase(pos);
2411 return error.Success();
2412}
2413
2414uint64_t
2415Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2416{
2417 if (fd == UINT64_MAX)
2418 {
2419 error.SetErrorString ("invalid file descriptor");
2420 return UINT64_MAX;
2421 }
2422 FDToFileMap& file_map = GetFDToFileMap();
2423 FDToFileMap::iterator pos = file_map.find(fd);
2424 if (pos == file_map.end())
2425 {
2426 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2427 return false;
2428 }
2429 FileSP file_sp = pos->second;
2430 if (!file_sp)
2431 {
2432 error.SetErrorString ("invalid host backing file");
2433 return UINT64_MAX;
2434 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002435 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2436 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002437 return UINT64_MAX;
2438 size_t bytes_written = src_len;
2439 error = file_sp->Write(src, bytes_written);
2440 if (error.Fail())
2441 return UINT64_MAX;
2442 return bytes_written;
2443}
2444
2445uint64_t
2446Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2447{
2448 if (fd == UINT64_MAX)
2449 {
2450 error.SetErrorString ("invalid file descriptor");
2451 return UINT64_MAX;
2452 }
2453 FDToFileMap& file_map = GetFDToFileMap();
2454 FDToFileMap::iterator pos = file_map.find(fd);
2455 if (pos == file_map.end())
2456 {
2457 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2458 return false;
2459 }
2460 FileSP file_sp = pos->second;
2461 if (!file_sp)
2462 {
2463 error.SetErrorString ("invalid host backing file");
2464 return UINT64_MAX;
2465 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002466 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2467 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002468 return UINT64_MAX;
2469 size_t bytes_read = dst_len;
2470 error = file_sp->Read(dst ,bytes_read);
2471 if (error.Fail())
2472 return UINT64_MAX;
2473 return bytes_read;
2474}
2475
2476lldb::user_id_t
2477Host::GetFileSize (const FileSpec& file_spec)
2478{
2479 return file_spec.GetByteSize();
2480}
2481
2482bool
2483Host::GetFileExists (const FileSpec& file_spec)
2484{
2485 return file_spec.Exists();
2486}
2487
2488bool
2489Host::CalculateMD5 (const FileSpec& file_spec,
2490 uint64_t &low,
2491 uint64_t &high)
2492{
2493#if defined (__APPLE__)
2494 StreamString md5_cmd_line;
2495 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2496 std::string hash_string;
2497 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2498 if (err.Fail())
2499 return false;
2500 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2501 // if the output is any other length it is probably wrong
2502 if (hash_string.size() != 32)
2503 return false;
2504 std::string part1(hash_string,0,16);
2505 std::string part2(hash_string,16);
2506 const char* part1_cstr = part1.c_str();
2507 const char* part2_cstr = part2.c_str();
2508 high = ::strtoull(part1_cstr, NULL, 16);
2509 low = ::strtoull(part2_cstr, NULL, 16);
2510 return true;
2511#else
2512 // your own MD5 implementation here
2513 return false;
2514#endif
2515}