blob: 32a1a08afae2e3c3205e6017182bd1c7e2dae214 [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>
Todd Fialae88aea32014-07-24 23:22:58 +000040#ifndef CPU_SUBTYPE_X86_64_H
41#define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8)
42#endif
Ed Maste8b006c62013-06-25 18:58:11 +000043#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000044
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +000045#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000046#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000047#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000048#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000049#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000050
Ed Maste8b006c62013-06-25 18:58:11 +000051#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000052#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000053#endif
54
Todd Fiala17096d72014-07-16 19:03:16 +000055// C++ includes
56#include <limits>
57
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Host/Host.h"
59#include "lldb/Core/ArchSpec.h"
60#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000061#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000062#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000064#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000065#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000066#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000067#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000068#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000069#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000070#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000071#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000072#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000073#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000074
Saleem Abdulrasool28606952014-06-27 05:17:41 +000075#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000076#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000077#include "llvm/Support/Host.h"
Zachary Turner9e757b72014-07-28 16:45:05 +000078#include "llvm/Support/Path.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000079#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000080
Todd Fiala76747122014-01-23 00:52:28 +000081#if defined (__APPLE__)
82#ifndef _POSIX_SPAWN_DISABLE_ASLR
83#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
84#endif
85
86extern "C"
87{
88 int __pthread_chdir(const char *path);
89 int __pthread_fchdir (int fildes);
90}
91
92#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000093
Greg Clayton2bddd342010-09-07 20:11:56 +000094using namespace lldb;
95using namespace lldb_private;
96
Todd Fiala17096d72014-07-16 19:03:16 +000097// Define maximum thread name length
98#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
99uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
100#else
101uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
102#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000103
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000104#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000105struct MonitorInfo
106{
107 lldb::pid_t pid; // The process ID to monitor
108 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
109 void *callback_baton; // The callback baton for the callback function
110 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
111};
112
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000113static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000114MonitorChildProcessThreadFunction (void *arg);
115
116lldb::thread_t
117Host::StartMonitoringChildProcess
118(
119 Host::MonitorChildProcessCallback callback,
120 void *callback_baton,
121 lldb::pid_t pid,
122 bool monitor_signals
123)
124{
125 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000126 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000127
Greg Claytone4e45922011-11-16 05:37:56 +0000128 info_ptr->pid = pid;
129 info_ptr->callback = callback;
130 info_ptr->callback_baton = callback_baton;
131 info_ptr->monitor_signals = monitor_signals;
132
133 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000134 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000135 thread = ThreadCreate (thread_name,
136 MonitorChildProcessThreadFunction,
137 info_ptr,
138 NULL);
139
Greg Clayton2bddd342010-09-07 20:11:56 +0000140 return thread;
141}
142
143//------------------------------------------------------------------
144// Scoped class that will disable thread canceling when it is
145// constructed, and exception safely restore the previous value it
146// when it goes out of scope.
147//------------------------------------------------------------------
148class ScopedPThreadCancelDisabler
149{
150public:
151 ScopedPThreadCancelDisabler()
152 {
153 // Disable the ability for this thread to be cancelled
154 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
155 if (err != 0)
156 m_old_state = -1;
157
158 }
159
160 ~ScopedPThreadCancelDisabler()
161 {
162 // Restore the ability for this thread to be cancelled to what it
163 // previously was.
164 if (m_old_state != -1)
165 ::pthread_setcancelstate (m_old_state, 0);
166 }
167private:
168 int m_old_state; // Save the old cancelability state.
169};
170
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000171static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000172MonitorChildProcessThreadFunction (void *arg)
173{
Greg Clayton5160ce52013-03-27 23:08:40 +0000174 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000175 const char *function = __FUNCTION__;
176 if (log)
177 log->Printf ("%s (arg = %p) thread starting...", function, arg);
178
179 MonitorInfo *info = (MonitorInfo *)arg;
180
181 const Host::MonitorChildProcessCallback callback = info->callback;
182 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000183 const bool monitor_signals = info->monitor_signals;
184
Daniel Malea4244cbd2013-08-27 20:58:59 +0000185 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000186 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000187
Greg Clayton2bddd342010-09-07 20:11:56 +0000188 delete info;
189
190 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000191#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000192 #define __WALL 0
193#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000194 const int options = __WALL;
195
Greg Clayton2bddd342010-09-07 20:11:56 +0000196 while (1)
197 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000198 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000199 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000200 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000201
202 // Wait for all child processes
203 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000204 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000205 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000206 ::pthread_testcancel ();
207
208 if (wait_pid == -1)
209 {
210 if (errno == EINTR)
211 continue;
212 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000213 {
214 if (log)
215 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000216 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000217 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000218 }
Matt Kopec650648f2013-01-08 16:30:18 +0000219 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000220 {
221 bool exited = false;
222 int signal = 0;
223 int exit_status = 0;
224 const char *status_cstr = NULL;
225 if (WIFSTOPPED(status))
226 {
227 signal = WSTOPSIG(status);
228 status_cstr = "STOPPED";
229 }
230 else if (WIFEXITED(status))
231 {
232 exit_status = WEXITSTATUS(status);
233 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000234 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000235 }
236 else if (WIFSIGNALED(status))
237 {
238 signal = WTERMSIG(status);
239 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000240 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000241 exited = true;
242 exit_status = -1;
243 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000244 }
245 else
246 {
Johnny Chen44805302011-07-19 19:48:13 +0000247 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000248 }
249
250 // Scope for pthread_cancel_disabler
251 {
252 ScopedPThreadCancelDisabler pthread_cancel_disabler;
253
Caroline Tice20ad3c42010-10-29 21:48:37 +0000254 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000255 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000256 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 +0000257 function,
258 wait_pid,
259 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000260 pid,
261 status,
262 status_cstr,
263 signal,
264 exit_status);
265
266 if (exited || (signal != 0 && monitor_signals))
267 {
Greg Claytone4e45922011-11-16 05:37:56 +0000268 bool callback_return = false;
269 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000270 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000271
272 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000273 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000274 {
275 if (log)
276 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000277 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000278 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000279 // If the callback returns true, it means this process should
280 // exit
281 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000282 {
283 if (log)
284 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000285 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000286 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000287 }
288 }
289 }
290 }
291
Caroline Tice20ad3c42010-10-29 21:48:37 +0000292 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000293 if (log)
294 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
295
296 return NULL;
297}
298
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000299#endif // #if !defined (__APPLE__) && !defined (_WIN32)
300
301#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000302
303void
304Host::SystemLog (SystemLogType type, const char *format, va_list args)
305{
306 vfprintf (stderr, format, args);
307}
308
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000309#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000310
Greg Claytone38a5ed2012-01-05 03:57:59 +0000311void
312Host::SystemLog (SystemLogType type, const char *format, ...)
313{
314 va_list args;
315 va_start (args, format);
316 SystemLog (type, format, args);
317 va_end (args);
318}
319
Greg Clayton2bddd342010-09-07 20:11:56 +0000320const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000321Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000322{
Greg Clayton514487e2011-02-15 21:59:32 +0000323 static bool g_supports_32 = false;
324 static bool g_supports_64 = false;
325 static ArchSpec g_host_arch_32;
326 static ArchSpec g_host_arch_64;
327
Greg Clayton2bddd342010-09-07 20:11:56 +0000328#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000329
330 // Apple is different in that it can support both 32 and 64 bit executables
331 // in the same operating system running concurrently. Here we detect the
332 // correct host architectures for both 32 and 64 bit including if 64 bit
333 // executables are supported on the system.
334
335 if (g_supports_32 == false && g_supports_64 == false)
336 {
337 // All apple systems support 32 bit execution.
338 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000339 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000340 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000341 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000342 ArchSpec host_arch;
343 // These will tell us about the kernel architecture, which even on a 64
344 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000345 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
346 {
Greg Clayton514487e2011-02-15 21:59:32 +0000347 len = sizeof (cpusubtype);
348 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
349 cpusubtype = CPU_TYPE_ANY;
350
Greg Clayton2bddd342010-09-07 20:11:56 +0000351 len = sizeof (is_64_bit_capable);
352 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
353 {
354 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000355 g_supports_64 = true;
356 }
357
358 if (is_64_bit_capable)
359 {
360 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000361 {
Greg Clayton514487e2011-02-15 21:59:32 +0000362 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000363 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000364 }
365 else
366 {
Greg Clayton52edb362014-07-14 22:53:02 +0000367 // We have a 64 bit kernel that is returning a 32 bit cputype, the
368 // cpusubtype will be correct as if it were for a 64 bit architecture
369 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype | CPU_ARCH_ABI64, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000370 }
Greg Clayton52edb362014-07-14 22:53:02 +0000371
372 // Now we need modify the cpusubtype for the 32 bit slices.
373 uint32_t cpusubtype32 = cpusubtype;
374#if defined (__i386__) || defined (__x86_64__)
375 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
376 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
377#elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
378 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
379 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
380#endif
381 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype & ~(CPU_ARCH_MASK), cpusubtype32);
Greg Clayton2bddd342010-09-07 20:11:56 +0000382 }
Greg Clayton514487e2011-02-15 21:59:32 +0000383 else
384 {
Greg Clayton52edb362014-07-14 22:53:02 +0000385 // We have a 32 bit kernel on a 32 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000386 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000387 g_host_arch_64.Clear();
388 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000389 }
Greg Clayton514487e2011-02-15 21:59:32 +0000390 }
391
392#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000393
Greg Clayton514487e2011-02-15 21:59:32 +0000394 if (g_supports_32 == false && g_supports_64 == false)
395 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000396 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000397
Stephen Wilsonbd588712011-02-24 19:15:09 +0000398 g_host_arch_32.Clear();
399 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000400
Greg Claytonb29e6c62012-10-11 17:38:58 +0000401 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
402 // for the default triple. It's probably an artifact of config.guess.
403 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000404 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000405
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000406 const char* distribution_id = GetDistributionId ().AsCString();
407
Stephen Wilsonbd588712011-02-24 19:15:09 +0000408 switch (triple.getArch())
409 {
410 default:
411 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000412 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000413 g_supports_32 = true;
414 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000415
Stephen Wilsonbd588712011-02-24 19:15:09 +0000416 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000417 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000418 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000419 g_supports_64 = true;
420 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000421 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000422 g_supports_32 = true;
423 break;
424
Ed Mastea8375762014-04-01 18:06:45 +0000425 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000426 case llvm::Triple::sparcv9:
427 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000428 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000429 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000430 g_supports_64 = true;
431 break;
432 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000433
434 g_supports_32 = g_host_arch_32.IsValid();
435 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000436 }
Greg Clayton514487e2011-02-15 21:59:32 +0000437
438#endif // #else for #if defined (__APPLE__)
439
440 if (arch_kind == eSystemDefaultArchitecture32)
441 return g_host_arch_32;
442 else if (arch_kind == eSystemDefaultArchitecture64)
443 return g_host_arch_64;
444
445 if (g_supports_64)
446 return g_host_arch_64;
447
448 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000449}
450
451const ConstString &
452Host::GetVendorString()
453{
454 static ConstString g_vendor;
455 if (!g_vendor)
456 {
Greg Clayton950971f2012-05-12 00:01:21 +0000457 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
458 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
459 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000460 }
461 return g_vendor;
462}
463
464const ConstString &
465Host::GetOSString()
466{
467 static ConstString g_os_string;
468 if (!g_os_string)
469 {
Greg Clayton950971f2012-05-12 00:01:21 +0000470 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
471 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
472 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000473 }
474 return g_os_string;
475}
476
477const ConstString &
478Host::GetTargetTriple()
479{
480 static ConstString g_host_triple;
481 if (!(g_host_triple))
482 {
Greg Clayton950971f2012-05-12 00:01:21 +0000483 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
484 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000485 }
486 return g_host_triple;
487}
488
Todd Fialaf3d61de2014-01-17 20:18:59 +0000489// See linux/Host.cpp for Linux-based implementations of this.
490// Add your platform-specific implementation to the appropriate host file.
491#if !defined(__linux__)
492
493const ConstString &
494 Host::GetDistributionId ()
495{
496 static ConstString s_distribution_id;
497 return s_distribution_id;
498}
499
500#endif // #if !defined(__linux__)
501
Greg Clayton2bddd342010-09-07 20:11:56 +0000502lldb::pid_t
503Host::GetCurrentProcessID()
504{
505 return ::getpid();
506}
507
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000508#ifndef _WIN32
509
Greg Clayton2bddd342010-09-07 20:11:56 +0000510lldb::tid_t
511Host::GetCurrentThreadID()
512{
513#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000514 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000515 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
516 // count.
517 thread_port_t thread_self = mach_thread_self();
518 mach_port_deallocate(mach_task_self(), thread_self);
519 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000520#elif defined(__FreeBSD__)
521 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000522#elif defined(__linux__)
523 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000524#else
525 return lldb::tid_t(pthread_self());
526#endif
527}
528
Jim Ingham372787f2012-04-07 00:00:41 +0000529lldb::thread_t
530Host::GetCurrentThread ()
531{
532 return lldb::thread_t(pthread_self());
533}
534
Greg Clayton2bddd342010-09-07 20:11:56 +0000535const char *
536Host::GetSignalAsCString (int signo)
537{
538 switch (signo)
539 {
540 case SIGHUP: return "SIGHUP"; // 1 hangup
541 case SIGINT: return "SIGINT"; // 2 interrupt
542 case SIGQUIT: return "SIGQUIT"; // 3 quit
543 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
544 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
545 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000546#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000547#if !defined(SIGIO) || (SIGPOLL != SIGIO)
548// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
549// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000550 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000551#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000552#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000553#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000554 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000555#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000556 case SIGFPE: return "SIGFPE"; // 8 floating point exception
557 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
558 case SIGBUS: return "SIGBUS"; // 10 bus error
559 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
560 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
561 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
562 case SIGALRM: return "SIGALRM"; // 14 alarm clock
563 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
564 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
565 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
566 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
567 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
568 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
569 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
570 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000571#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000572 case SIGIO: return "SIGIO"; // 23 input/output possible signal
573#endif
574 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
575 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
576 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
577 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000578#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000579 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000580#endif
581#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000582 case SIGINFO: return "SIGINFO"; // 29 information request
583#endif
584 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
585 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
586 default:
587 break;
588 }
589 return NULL;
590}
591
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000592#endif
593
Greg Clayton2bddd342010-09-07 20:11:56 +0000594void
595Host::WillTerminate ()
596{
597}
598
Sylvestre Ledru59405832013-07-01 08:21:36 +0000599#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000600
Greg Clayton2bddd342010-09-07 20:11:56 +0000601void
602Host::ThreadCreated (const char *thread_name)
603{
604}
Greg Claytone5219662010-12-03 06:02:24 +0000605
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000606void
Greg Claytone5219662010-12-03 06:02:24 +0000607Host::Backtrace (Stream &strm, uint32_t max_frames)
608{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000609 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000610}
611
Greg Clayton85851dd2010-12-04 00:10:17 +0000612size_t
613Host::GetEnvironment (StringList &env)
614{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000615 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000616 return 0;
617}
618
Sylvestre Ledru59405832013-07-01 08:21:36 +0000619#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000620
621struct HostThreadCreateInfo
622{
623 std::string thread_name;
624 thread_func_t thread_fptr;
625 thread_arg_t thread_arg;
626
627 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
628 thread_name (name ? name : ""),
629 thread_fptr (fptr),
630 thread_arg (arg)
631 {
632 }
633};
634
635static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000636#ifdef _WIN32
637__stdcall
638#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000639ThreadCreateTrampoline (thread_arg_t arg)
640{
641 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
642 Host::ThreadCreated (info->thread_name.c_str());
643 thread_func_t thread_fptr = info->thread_fptr;
644 thread_arg_t thread_arg = info->thread_arg;
645
Greg Clayton5160ce52013-03-27 23:08:40 +0000646 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000647 if (log)
648 log->Printf("thread created");
649
650 delete info;
651 return thread_fptr (thread_arg);
652}
653
654lldb::thread_t
655Host::ThreadCreate
656(
657 const char *thread_name,
658 thread_func_t thread_fptr,
659 thread_arg_t thread_arg,
660 Error *error
661)
662{
663 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
664
665 // Host::ThreadCreateTrampoline will delete this pointer for us.
666 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
667
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000668#ifdef _WIN32
669 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
670 int err = thread <= 0 ? GetLastError() : 0;
671#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000672 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000673#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000674 if (err == 0)
675 {
676 if (error)
677 error->Clear();
678 return thread;
679 }
680
681 if (error)
682 error->SetError (err, eErrorTypePOSIX);
683
684 return LLDB_INVALID_HOST_THREAD;
685}
686
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000687#ifndef _WIN32
688
Greg Clayton2bddd342010-09-07 20:11:56 +0000689bool
690Host::ThreadCancel (lldb::thread_t thread, Error *error)
691{
692 int err = ::pthread_cancel (thread);
693 if (error)
694 error->SetError(err, eErrorTypePOSIX);
695 return err == 0;
696}
697
698bool
699Host::ThreadDetach (lldb::thread_t thread, Error *error)
700{
701 int err = ::pthread_detach (thread);
702 if (error)
703 error->SetError(err, eErrorTypePOSIX);
704 return err == 0;
705}
706
707bool
708Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
709{
710 int err = ::pthread_join (thread, thread_result_ptr);
711 if (error)
712 error->SetError(err, eErrorTypePOSIX);
713 return err == 0;
714}
715
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000716lldb::thread_key_t
717Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
718{
719 pthread_key_t key;
720 ::pthread_key_create (&key, callback);
721 return key;
722}
723
724void*
725Host::ThreadLocalStorageGet(lldb::thread_key_t key)
726{
727 return ::pthread_getspecific (key);
728}
729
730void
731Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
732{
733 ::pthread_setspecific (key, value);
734}
735
Matt Kopec62502c62013-05-13 19:33:58 +0000736bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000737Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
738{
Greg Clayton85719632013-02-27 22:51:58 +0000739#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000740 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
741 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
742 if (pid == LLDB_INVALID_PROCESS_ID)
743 pid = curr_pid;
744
745 if (tid == LLDB_INVALID_THREAD_ID)
746 tid = curr_tid;
747
Greg Clayton2bddd342010-09-07 20:11:56 +0000748 // Set the pthread name if possible
749 if (pid == curr_pid && tid == curr_tid)
750 {
Matt Kopec62502c62013-05-13 19:33:58 +0000751 if (::pthread_setname_np (name) == 0)
752 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000753 }
Matt Kopec62502c62013-05-13 19:33:58 +0000754 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000755#elif defined (__FreeBSD__)
756 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
757 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
758 if (pid == LLDB_INVALID_PROCESS_ID)
759 pid = curr_pid;
760
761 if (tid == LLDB_INVALID_THREAD_ID)
762 tid = curr_tid;
763
764 // Set the pthread name if possible
765 if (pid == curr_pid && tid == curr_tid)
766 {
Michael Sartainc2052432013-08-01 18:51:08 +0000767 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000768 return true;
769 }
770 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000771#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000772 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
773 if (fn)
774 {
Matt Kopec62502c62013-05-13 19:33:58 +0000775 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
776 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000777 if (pid == LLDB_INVALID_PROCESS_ID)
778 pid = curr_pid;
779
780 if (tid == LLDB_INVALID_THREAD_ID)
781 tid = curr_tid;
782
Michael Sartainc2052432013-08-01 18:51:08 +0000783 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000784 {
Michael Sartainc2052432013-08-01 18:51:08 +0000785 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
786 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
787
788 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000789 return true;
790 }
791 }
792 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000793#else
794 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000795#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000796}
797
Ed Maste02983be2013-07-25 19:10:32 +0000798bool
799Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
800 const char *thread_name, size_t len)
801{
Enrico Granata67530b62014-02-12 03:37:33 +0000802 std::unique_ptr<char[]> namebuf(new char[len+1]);
803
Ed Maste02983be2013-07-25 19:10:32 +0000804 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
805 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
806 // off leads to a lot of similar named threads. Go through the thread name
807 // and search for the last dot and use that.
808 const char *lastdot = ::strrchr (thread_name, '.');
809
810 if (lastdot && lastdot != thread_name)
811 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000812 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000813 namebuf[len] = 0;
814
Enrico Granata67530b62014-02-12 03:37:33 +0000815 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000816 if (namebuflen > 0)
817 {
818 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
819 {
820 // Trim off trailing '(' and '>' characters for a bit more cleanup.
821 namebuflen--;
822 namebuf[namebuflen] = 0;
823 }
Enrico Granata67530b62014-02-12 03:37:33 +0000824 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000825 }
826 return false;
827}
828
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000829#endif
830
Greg Clayton2bddd342010-09-07 20:11:56 +0000831FileSpec
Zachary Turner9e757b72014-07-28 16:45:05 +0000832Host::GetUserProfileFileSpec ()
833{
834 static FileSpec g_profile_filespec;
835 if (!g_profile_filespec)
836 {
837 llvm::SmallString<64> path;
838 llvm::sys::path::home_directory(path);
839 return FileSpec(path.c_str(), false);
840 }
841 return g_profile_filespec;
842}
843
844FileSpec
Greg Clayton2bddd342010-09-07 20:11:56 +0000845Host::GetProgramFileSpec ()
846{
847 static FileSpec g_program_filespec;
848 if (!g_program_filespec)
849 {
850#if defined (__APPLE__)
851 char program_fullpath[PATH_MAX];
852 // If DST is NULL, then return the number of bytes needed.
853 uint32_t len = sizeof(program_fullpath);
854 int err = _NSGetExecutablePath (program_fullpath, &len);
855 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000856 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000857 else if (err == -1)
858 {
859 char *large_program_fullpath = (char *)::malloc (len + 1);
860
861 err = _NSGetExecutablePath (large_program_fullpath, &len);
862 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000863 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000864
865 ::free (large_program_fullpath);
866 }
867#elif defined (__linux__)
868 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000869 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
870 if (len > 0) {
871 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000872 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000873 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000874#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000875 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
876 size_t exe_path_size;
877 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
878 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000879 char *exe_path = new char[exe_path_size];
880 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
881 g_program_filespec.SetFile(exe_path, false);
882 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000883 }
Zachary Turner9e757b72014-07-28 16:45:05 +0000884#elif defined(_WIN32)
885 std::vector<char> buffer(PATH_MAX);
886 ::GetModuleFileName(NULL, &buffer[0], buffer.size());
Zachary Turnerd8a52732014-07-29 05:39:21 +0000887 g_program_filespec.SetFile(&buffer[0], false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000888#endif
889 }
890 return g_program_filespec;
891}
892
Greg Clayton2bddd342010-09-07 20:11:56 +0000893#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000894
895bool
896Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
897{
898 bundle.Clear();
899 return false;
900}
901
Greg Clayton2bddd342010-09-07 20:11:56 +0000902bool
Greg Claytondd36def2010-10-17 22:03:32 +0000903Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000904{
Greg Claytondd36def2010-10-17 22:03:32 +0000905 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000906}
907#endif
908
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000909#ifndef _WIN32
910
Greg Clayton45319462011-02-08 00:35:34 +0000911// Opaque info that tracks a dynamic library that was loaded
912struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000913{
Greg Clayton45319462011-02-08 00:35:34 +0000914 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
915 file_spec (fs),
916 open_options (o),
917 handle (h)
918 {
919 }
920
921 const FileSpec file_spec;
922 uint32_t open_options;
923 void * handle;
924};
925
926void *
927Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
928{
Greg Clayton4272cc72011-02-02 02:24:04 +0000929 char path[PATH_MAX];
930 if (file_spec.GetPath(path, sizeof(path)))
931 {
Greg Clayton45319462011-02-08 00:35:34 +0000932 int mode = 0;
933
934 if (options & eDynamicLibraryOpenOptionLazy)
935 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000936 else
937 mode |= RTLD_NOW;
938
Greg Clayton45319462011-02-08 00:35:34 +0000939
940 if (options & eDynamicLibraryOpenOptionLocal)
941 mode |= RTLD_LOCAL;
942 else
943 mode |= RTLD_GLOBAL;
944
945#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
946 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
947 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000948#endif
Greg Clayton45319462011-02-08 00:35:34 +0000949
950 void * opaque = ::dlopen (path, mode);
951
952 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000953 {
954 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000955 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000956 }
957 else
958 {
959 error.SetErrorString(::dlerror());
960 }
961 }
962 else
963 {
964 error.SetErrorString("failed to extract path");
965 }
Greg Clayton45319462011-02-08 00:35:34 +0000966 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000967}
968
969Error
Greg Clayton45319462011-02-08 00:35:34 +0000970Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000971{
972 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000973 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000974 {
975 error.SetErrorString ("invalid dynamic library handle");
976 }
Greg Clayton45319462011-02-08 00:35:34 +0000977 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000978 {
Greg Clayton45319462011-02-08 00:35:34 +0000979 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
980 if (::dlclose (dylib_info->handle) != 0)
981 {
982 error.SetErrorString(::dlerror());
983 }
984
985 dylib_info->open_options = 0;
986 dylib_info->handle = 0;
987 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000988 }
989 return error;
990}
991
992void *
Greg Clayton45319462011-02-08 00:35:34 +0000993Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000994{
Greg Clayton45319462011-02-08 00:35:34 +0000995 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000996 {
997 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000998 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000999 else
Greg Clayton45319462011-02-08 00:35:34 +00001000 {
1001 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1002
1003 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
1004 if (symbol_addr)
1005 {
1006#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
1007 // This host doesn't support limiting searches to this shared library
1008 // so we need to verify that the match came from this shared library
1009 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +00001010 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +00001011 {
1012 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
1013 if (match_dylib_spec != dylib_info->file_spec)
1014 {
1015 char dylib_path[PATH_MAX];
1016 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
1017 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
1018 else
1019 error.SetErrorString ("symbol not found");
1020 return NULL;
1021 }
1022 }
1023#endif
1024 error.Clear();
1025 return symbol_addr;
1026 }
1027 else
1028 {
1029 error.SetErrorString(::dlerror());
1030 }
1031 }
1032 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +00001033}
Greg Claytondd36def2010-10-17 22:03:32 +00001034
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001035FileSpec
1036Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1037{
1038 FileSpec module_filespec;
1039 Dl_info info;
1040 if (::dladdr (host_addr, &info))
1041 {
1042 if (info.dli_fname)
1043 module_filespec.SetFile(info.dli_fname, true);
1044 }
1045 return module_filespec;
1046}
1047
1048#endif
1049
Greg Clayton23f8c952014-03-24 23:10:19 +00001050
1051static void CleanupProcessSpecificLLDBTempDir ()
1052{
1053 // Get the process specific LLDB temporary directory and delete it.
1054 FileSpec tmpdir_file_spec;
1055 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1056 {
1057 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1058 // true to all files that were created for the LLDB process can be cleaned up.
1059 const bool recurse = true;
1060 Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1061 }
1062}
1063
Greg Claytondd36def2010-10-17 22:03:32 +00001064bool
1065Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1066{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001067 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001068 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1069 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001070 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001071 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001072 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001073
1074 switch (path_type)
1075 {
1076 case ePathTypeLLDBShlibDir:
1077 {
1078 static ConstString g_lldb_so_dir;
1079 if (!g_lldb_so_dir)
1080 {
David Majnemer8490da12014-07-22 22:00:42 +00001081 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1082 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +00001083 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001084 if (log)
1085 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001086 }
1087 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001088 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001089 }
1090 break;
1091
1092 case ePathTypeSupportExecutableDir:
1093 {
1094 static ConstString g_lldb_support_exe_dir;
1095 if (!g_lldb_support_exe_dir)
1096 {
1097 FileSpec lldb_file_spec;
1098 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1099 {
1100 char raw_path[PATH_MAX];
1101 char resolved_path[PATH_MAX];
1102 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1103
1104#if defined (__APPLE__)
1105 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1106 if (framework_pos)
1107 {
1108 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +00001109#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001110 // Shallow bundle
1111 *framework_pos = '\0';
1112#else
1113 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001114 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001115#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001116 }
Todd Fiala015d8182014-07-22 23:41:36 +00001117#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1118 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1119 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
1120 // different trees.
1121 if (log)
1122 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1123 char *lib_pos = ::strstr (raw_path, "/lib");
1124 if (lib_pos != nullptr)
1125 {
1126 // First terminate the raw path at the start of lib.
1127 *lib_pos = '\0';
1128
1129 // Now write in bin in place of lib.
1130 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1131
1132 if (log)
1133 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1134 }
1135 else
1136 {
1137 if (log)
1138 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1139 }
Jason Molendaa3329782014-03-29 18:54:20 +00001140#endif // #if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001141 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1142 g_lldb_support_exe_dir.SetCString(resolved_path);
1143 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001144 if (log)
1145 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001146 }
1147 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001148 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001149 }
1150 break;
1151
1152 case ePathTypeHeaderDir:
1153 {
1154 static ConstString g_lldb_headers_dir;
1155 if (!g_lldb_headers_dir)
1156 {
1157#if defined (__APPLE__)
1158 FileSpec lldb_file_spec;
1159 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1160 {
1161 char raw_path[PATH_MAX];
1162 char resolved_path[PATH_MAX];
1163 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1164
1165 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1166 if (framework_pos)
1167 {
1168 framework_pos += strlen("LLDB.framework");
1169 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1170 }
1171 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1172 g_lldb_headers_dir.SetCString(resolved_path);
1173 }
1174#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001175 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001176 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1177#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001178 if (log)
1179 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001180 }
1181 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001182 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001183 }
1184 break;
1185
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001186#ifdef LLDB_DISABLE_PYTHON
1187 case ePathTypePythonDir:
1188 return false;
1189#else
1190 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001191 {
Greg Claytondd36def2010-10-17 22:03:32 +00001192 static ConstString g_lldb_python_dir;
1193 if (!g_lldb_python_dir)
1194 {
1195 FileSpec lldb_file_spec;
1196 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1197 {
1198 char raw_path[PATH_MAX];
1199 char resolved_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001200#if defined(_WIN32)
1201 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1202 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1203#else
Greg Claytondd36def2010-10-17 22:03:32 +00001204 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1205
1206#if defined (__APPLE__)
1207 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1208 if (framework_pos)
1209 {
1210 framework_pos += strlen("LLDB.framework");
1211 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001212 }
1213 else
1214 {
1215#endif
1216 llvm::SmallString<256> python_version_dir;
1217 llvm::raw_svector_ostream os(python_version_dir);
1218 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1219 os.flush();
1220
1221 // We may get our string truncated. Should we protect
1222 // this with an assert?
1223
1224 ::strncat(raw_path, python_version_dir.c_str(),
1225 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001226#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001227#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001228 }
1229#endif
1230 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1231 g_lldb_python_dir.SetCString(resolved_path);
1232 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001233
1234 if (log)
1235 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1236
Greg Claytondd36def2010-10-17 22:03:32 +00001237 }
1238 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001239 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001240 }
1241 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001242#endif
1243
Greg Clayton4272cc72011-02-02 02:24:04 +00001244 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1245 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001246#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001247 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001248 static bool g_lldb_system_plugin_dir_located = false;
1249 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001250 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001251 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001252#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001253 FileSpec lldb_file_spec;
1254 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1255 {
1256 char raw_path[PATH_MAX];
1257 char resolved_path[PATH_MAX];
1258 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1259
1260 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1261 if (framework_pos)
1262 {
1263 framework_pos += strlen("LLDB.framework");
1264 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001265 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1266 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001267 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001268 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001269 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001270#elif defined (__linux__)
1271 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1272 if (lldb_file_spec.Exists())
1273 {
1274 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1275 }
1276#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001277
1278 if (log)
1279 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1280
Greg Clayton4272cc72011-02-02 02:24:04 +00001281 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001282
1283 if (g_lldb_system_plugin_dir)
1284 {
1285 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1286 return true;
1287 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001288#else
1289 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001290 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001291#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001292 }
1293 break;
1294
1295 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1296 {
1297#if defined (__APPLE__)
1298 static ConstString g_lldb_user_plugin_dir;
1299 if (!g_lldb_user_plugin_dir)
1300 {
1301 char user_plugin_path[PATH_MAX];
1302 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1303 user_plugin_path,
1304 sizeof(user_plugin_path)))
1305 {
1306 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1307 }
1308 }
1309 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001310 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001311#elif defined (__linux__)
1312 static ConstString g_lldb_user_plugin_dir;
1313 if (!g_lldb_user_plugin_dir)
1314 {
1315 // XDG Base Directory Specification
1316 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1317 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1318 FileSpec lldb_file_spec;
1319 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1320 if (xdg_data_home && xdg_data_home[0])
1321 {
1322 std::string user_plugin_dir (xdg_data_home);
1323 user_plugin_dir += "/lldb";
1324 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1325 }
1326 else
1327 {
1328 const char *home_dir = getenv("HOME");
1329 if (home_dir && home_dir[0])
1330 {
1331 std::string user_plugin_dir (home_dir);
1332 user_plugin_dir += "/.local/share/lldb";
1333 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1334 }
1335 }
1336
1337 if (lldb_file_spec.Exists())
1338 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001339 if (log)
1340 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001341 }
1342 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001343 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001344#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001345 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001346 return false;
1347 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001348
1349 case ePathTypeLLDBTempSystemDir:
1350 {
1351 static ConstString g_lldb_tmp_dir;
1352 if (!g_lldb_tmp_dir)
1353 {
1354 const char *tmpdir_cstr = getenv("TMPDIR");
1355 if (tmpdir_cstr == NULL)
1356 {
1357 tmpdir_cstr = getenv("TMP");
1358 if (tmpdir_cstr == NULL)
1359 tmpdir_cstr = getenv("TEMP");
1360 }
1361 if (tmpdir_cstr)
1362 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001363 StreamString pid_tmpdir;
1364 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1365 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1366 {
1367 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1368 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1369 {
1370 // Make an atexit handler to clean up the process specify LLDB temp dir
1371 // and all of its contents.
1372 ::atexit (CleanupProcessSpecificLLDBTempDir);
1373 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1374 if (log)
1375 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1376
1377 }
1378 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001379 }
1380 }
1381 file_spec.GetDirectory() = g_lldb_tmp_dir;
1382 return (bool)file_spec.GetDirectory();
1383 }
Greg Claytondd36def2010-10-17 22:03:32 +00001384 }
1385
1386 return false;
1387}
1388
Greg Clayton1cb64962011-03-24 04:28:38 +00001389
1390bool
1391Host::GetHostname (std::string &s)
1392{
1393 char hostname[PATH_MAX];
1394 hostname[sizeof(hostname) - 1] = '\0';
1395 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1396 {
1397 struct hostent* h = ::gethostbyname (hostname);
1398 if (h)
1399 s.assign (h->h_name);
1400 else
1401 s.assign (hostname);
1402 return true;
1403 }
1404 return false;
1405}
1406
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001407#ifndef _WIN32
1408
Greg Clayton32e0a752011-03-30 18:16:51 +00001409const char *
1410Host::GetUserName (uint32_t uid, std::string &user_name)
1411{
1412 struct passwd user_info;
1413 struct passwd *user_info_ptr = &user_info;
1414 char user_buffer[PATH_MAX];
1415 size_t user_buffer_size = sizeof(user_buffer);
1416 if (::getpwuid_r (uid,
1417 &user_info,
1418 user_buffer,
1419 user_buffer_size,
1420 &user_info_ptr) == 0)
1421 {
1422 if (user_info_ptr)
1423 {
1424 user_name.assign (user_info_ptr->pw_name);
1425 return user_name.c_str();
1426 }
1427 }
1428 user_name.clear();
1429 return NULL;
1430}
1431
1432const char *
1433Host::GetGroupName (uint32_t gid, std::string &group_name)
1434{
1435 char group_buffer[PATH_MAX];
1436 size_t group_buffer_size = sizeof(group_buffer);
1437 struct group group_info;
1438 struct group *group_info_ptr = &group_info;
1439 // Try the threadsafe version first
1440 if (::getgrgid_r (gid,
1441 &group_info,
1442 group_buffer,
1443 group_buffer_size,
1444 &group_info_ptr) == 0)
1445 {
1446 if (group_info_ptr)
1447 {
1448 group_name.assign (group_info_ptr->gr_name);
1449 return group_name.c_str();
1450 }
1451 }
1452 else
1453 {
1454 // The threadsafe version isn't currently working
1455 // for me on darwin, but the non-threadsafe version
1456 // is, so I am calling it below.
1457 group_info_ptr = ::getgrgid (gid);
1458 if (group_info_ptr)
1459 {
1460 group_name.assign (group_info_ptr->gr_name);
1461 return group_name.c_str();
1462 }
1463 }
1464 group_name.clear();
1465 return NULL;
1466}
1467
Han Ming Ong84647042012-02-25 01:07:38 +00001468uint32_t
1469Host::GetUserID ()
1470{
1471 return getuid();
1472}
1473
1474uint32_t
1475Host::GetGroupID ()
1476{
1477 return getgid();
1478}
1479
1480uint32_t
1481Host::GetEffectiveUserID ()
1482{
1483 return geteuid();
1484}
1485
1486uint32_t
1487Host::GetEffectiveGroupID ()
1488{
1489 return getegid();
1490}
1491
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001492#endif
1493
1494#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1495bool
1496Host::GetOSBuildString (std::string &s)
1497{
1498 s.clear();
1499 return false;
1500}
1501
1502bool
1503Host::GetOSKernelDescription (std::string &s)
1504{
1505 s.clear();
1506 return false;
1507}
1508#endif
1509
Zachary Turner310035a2014-07-08 04:52:15 +00001510#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1511 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001512uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001513Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001514{
1515 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001516 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001517}
1518
Greg Claytone996fd32011-03-08 22:40:15 +00001519bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001520Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001521{
Greg Claytone996fd32011-03-08 22:40:15 +00001522 process_info.Clear();
1523 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001524}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001525#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001526
Matt Kopec085d6ce2013-05-31 22:00:07 +00001527#if !defined(__linux__)
1528bool
1529Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1530{
1531 return false;
1532}
1533#endif
1534
Sean Callananc0a6e062011-10-27 21:22:25 +00001535lldb::TargetSP
1536Host::GetDummyTarget (lldb_private::Debugger &debugger)
1537{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001538 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001539
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001540 // FIXME: Maybe the dummy target should be per-Debugger
1541 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1542 {
1543 ArchSpec arch(Target::GetDefaultArchitecture());
1544 if (!arch.IsValid())
1545 arch = Host::GetArchitecture ();
1546 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001547 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001548 arch.GetTriple().getTriple().c_str(),
1549 false,
1550 NULL,
1551 g_dummy_target_sp);
1552 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001553
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001554 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001555}
1556
Greg Claytond1cf11a2012-04-14 01:42:46 +00001557struct ShellInfo
1558{
1559 ShellInfo () :
1560 process_reaped (false),
1561 can_delete (false),
1562 pid (LLDB_INVALID_PROCESS_ID),
1563 signo(-1),
1564 status(-1)
1565 {
1566 }
1567
1568 lldb_private::Predicate<bool> process_reaped;
1569 lldb_private::Predicate<bool> can_delete;
1570 lldb::pid_t pid;
1571 int signo;
1572 int status;
1573};
1574
1575static bool
1576MonitorShellCommand (void *callback_baton,
1577 lldb::pid_t pid,
1578 bool exited, // True if the process did exit
1579 int signo, // Zero for no signal
1580 int status) // Exit value of process if signal is zero
1581{
1582 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1583 shell_info->pid = pid;
1584 shell_info->signo = signo;
1585 shell_info->status = status;
1586 // Let the thread running Host::RunShellCommand() know that the process
1587 // exited and that ShellInfo has been filled in by broadcasting to it
1588 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1589 // Now wait for a handshake back from that thread running Host::RunShellCommand
1590 // so we know that we can delete shell_info_ptr
1591 shell_info->can_delete.WaitForValueEqualTo(true);
1592 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1593 usleep(1000);
1594 // Now delete the shell info that was passed into this function
1595 delete shell_info;
1596 return true;
1597}
1598
1599Error
1600Host::RunShellCommand (const char *command,
1601 const char *working_dir,
1602 int *status_ptr,
1603 int *signo_ptr,
1604 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001605 uint32_t timeout_sec,
1606 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001607{
1608 Error error;
1609 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001610 if (shell && shell[0])
1611 {
1612 // Run the command in a shell
1613 launch_info.SetShell(shell);
1614 launch_info.GetArguments().AppendArgument(command);
1615 const bool localhost = true;
1616 const bool will_debug = false;
1617 const bool first_arg_is_full_shell_command = true;
1618 launch_info.ConvertArgumentsForLaunchingInShell (error,
1619 localhost,
1620 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001621 first_arg_is_full_shell_command,
1622 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001623 }
1624 else
1625 {
1626 // No shell, just run it
1627 Args args (command);
1628 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001629 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001630 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001631
1632 if (working_dir)
1633 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001634 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001635 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001636
Greg Claytond1cf11a2012-04-14 01:42:46 +00001637 if (command_output_ptr)
1638 {
1639 // Create a temporary file to get the stdout/stderr and redirect the
1640 // output of the command into this file. We will later read this file
1641 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001642 FileSpec tmpdir_file_spec;
1643 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1644 {
1645 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1646 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1647 }
1648 else
1649 {
1650 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1651 }
1652
1653 output_file_path = ::mktemp(output_file_path_buffer);
1654 }
1655
1656 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1657 if (output_file_path)
1658 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001659 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001660 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001661 }
1662 else
1663 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001664 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1665 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1666 }
1667
1668 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001669 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001670
1671 const bool monitor_signals = false;
1672 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1673
1674 error = LaunchProcess (launch_info);
1675 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001676
1677 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1678 error.SetErrorString("failed to get process ID");
1679
1680 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001681 {
1682 // The process successfully launched, so we can defer ownership of
1683 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001684 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001685 // doesn't need to delete the ShellInfo anymore.
1686 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001687 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001688 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001689 if (timeout_sec > 0) {
1690 timeout_time.OffsetWithSeconds(timeout_sec);
1691 timeout_ptr = &timeout_time;
1692 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001693 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001694 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001695 if (timed_out)
1696 {
1697 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001698
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001699 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001700 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001701 // Wait for the monitor callback to get the message
1702 timeout_time = TimeValue::Now();
1703 timeout_time.OffsetWithSeconds(1);
1704 timed_out = false;
1705 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1706 }
1707 else
1708 {
1709 if (status_ptr)
1710 *status_ptr = shell_info->status;
1711
1712 if (signo_ptr)
1713 *signo_ptr = shell_info->signo;
1714
1715 if (command_output_ptr)
1716 {
1717 command_output_ptr->clear();
1718 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1719 uint64_t file_size = file_spec.GetByteSize();
1720 if (file_size > 0)
1721 {
1722 if (file_size > command_output_ptr->max_size())
1723 {
1724 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1725 }
1726 else
1727 {
1728 command_output_ptr->resize(file_size);
1729 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1730 }
1731 }
1732 }
1733 }
1734 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1735 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001736
1737 if (output_file_path)
1738 ::unlink (output_file_path);
1739 // Handshake with the monitor thread, or just let it know in advance that
1740 // it can delete "shell_info" in case we timed out and were not able to kill
1741 // the process...
1742 return error;
1743}
1744
Daniel Malea4244cbd2013-08-27 20:58:59 +00001745
Todd Fiala76747122014-01-23 00:52:28 +00001746// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1747// systems
1748
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001749#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001750
1751// this method needs to be visible to macosx/Host.cpp and
1752// common/Host.cpp.
1753
1754short
1755Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1756{
1757 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1758
1759#if defined (__APPLE__)
1760 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1761 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1762
1763 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1764 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1765
1766 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1767 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1768
1769 if (launch_info.GetLaunchInSeparateProcessGroup())
1770 flags |= POSIX_SPAWN_SETPGROUP;
1771
1772#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1773#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1774 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1775 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1776 {
1777 g_use_close_on_exec_flag = eLazyBoolNo;
1778
1779 uint32_t major, minor, update;
1780 if (Host::GetOSVersion(major, minor, update))
1781 {
1782 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1783 if (major > 10 || (major == 10 && minor > 7))
1784 {
1785 // Only enable for 10.8 and later OS versions
1786 g_use_close_on_exec_flag = eLazyBoolYes;
1787 }
1788 }
1789 }
1790#else
1791 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1792#endif
1793 // Close all files exception those with file actions if this is supported.
1794 if (g_use_close_on_exec_flag == eLazyBoolYes)
1795 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1796#endif
1797#endif // #if defined (__APPLE__)
1798 return flags;
1799}
1800
1801Error
1802Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001803{
1804 Error error;
1805 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1806
Daniel Malea4244cbd2013-08-27 20:58:59 +00001807 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001808 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001809
1810 if (error.Fail() || log)
1811 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001812 if (error.Fail())
1813 return error;
1814
1815 // Make a quick class that will cleanup the posix spawn attributes in case
1816 // we return in the middle of this function.
1817 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1818
1819 sigset_t no_signals;
1820 sigset_t all_signals;
1821 sigemptyset (&no_signals);
1822 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001823 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001824#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001825 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001826#else
1827 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1828#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001829
Todd Fiala76747122014-01-23 00:52:28 +00001830 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001831
1832 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001833 if (error.Fail() || log)
1834 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001835 if (error.Fail())
1836 return error;
1837
Todd Fiala76747122014-01-23 00:52:28 +00001838 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1839 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1840#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001841
1842 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1843 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1844 // to do that job on OSX.
1845
1846 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001847 {
Jim Ingham90331d52014-02-21 01:25:21 +00001848 // We don't need to do this for ARM, and we really shouldn't now that we
1849 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1850 // to set which CPU subtype to launch...
1851 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1852 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1853 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1854 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001855 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1856 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001857 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1858 {
1859 size_t ocount = 0;
1860 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1861 if (error.Fail() || log)
1862 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 +00001863
Jim Ingham90331d52014-02-21 01:25:21 +00001864 if (error.Fail() || ocount != 1)
1865 return error;
1866 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001867 }
1868
Todd Fiala76747122014-01-23 00:52:28 +00001869#endif
1870
1871 const char *tmp_argv[2];
1872 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1873 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1874 if (argv == NULL)
1875 {
1876 // posix_spawn gets very unhappy if it doesn't have at least the program
1877 // name in argv[0]. One of the side affects I have noticed is the environment
1878 // variables don't make it into the child process if "argv == NULL"!!!
1879 tmp_argv[0] = exe_path;
1880 tmp_argv[1] = NULL;
1881 argv = (char * const*)tmp_argv;
1882 }
1883
1884#if !defined (__APPLE__)
1885 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001886 char current_dir[PATH_MAX];
1887 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001888#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001889
1890 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001891 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001892 {
Todd Fiala76747122014-01-23 00:52:28 +00001893#if defined (__APPLE__)
1894 // Set the working directory on this thread only
1895 if (__pthread_chdir (working_dir) < 0) {
1896 if (errno == ENOENT) {
1897 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1898 } else if (errno == ENOTDIR) {
1899 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1900 } else {
1901 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1902 }
1903 return error;
1904 }
1905#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001906 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1907 {
1908 error.SetError(errno, eErrorTypePOSIX);
1909 error.LogIfError(log, "unable to save the current directory");
1910 return error;
1911 }
1912
1913 if (::chdir(working_dir) == -1)
1914 {
1915 error.SetError(errno, eErrorTypePOSIX);
1916 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1917 return error;
1918 }
Todd Fiala76747122014-01-23 00:52:28 +00001919#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001920 }
1921
Todd Fiala76747122014-01-23 00:52:28 +00001922 const size_t num_file_actions = launch_info.GetNumFileActions ();
1923 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001924 {
Todd Fiala76747122014-01-23 00:52:28 +00001925 posix_spawn_file_actions_t file_actions;
1926 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1927 if (error.Fail() || log)
1928 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1929 if (error.Fail())
1930 return error;
1931
1932 // Make a quick class that will cleanup the posix spawn attributes in case
1933 // we return in the middle of this function.
1934 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1935
1936 for (size_t i=0; i<num_file_actions; ++i)
1937 {
1938 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1939 if (launch_file_action)
1940 {
1941 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1942 launch_file_action,
1943 log,
1944 error))
1945 return error;
1946 }
1947 }
1948
1949 error.SetError (::posix_spawnp (&pid,
1950 exe_path,
1951 &file_actions,
1952 &attr,
1953 argv,
1954 envp),
1955 eErrorTypePOSIX);
1956
1957 if (error.Fail() || log)
1958 {
1959 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 +00001960 pid, exe_path, static_cast<void*>(&file_actions),
1961 static_cast<void*>(&attr),
1962 reinterpret_cast<const void*>(argv),
1963 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001964 if (log)
1965 {
1966 for (int ii=0; argv[ii]; ++ii)
1967 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1968 }
1969 }
1970
1971 }
1972 else
1973 {
1974 error.SetError (::posix_spawnp (&pid,
1975 exe_path,
1976 NULL,
1977 &attr,
1978 argv,
1979 envp),
1980 eErrorTypePOSIX);
1981
1982 if (error.Fail() || log)
1983 {
1984 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 +00001985 pid, exe_path, static_cast<void*>(&attr),
1986 reinterpret_cast<const void*>(argv),
1987 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001988 if (log)
1989 {
1990 for (int ii=0; argv[ii]; ++ii)
1991 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1992 }
1993 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001994 }
1995
Todd Fiala76747122014-01-23 00:52:28 +00001996 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001997 {
Todd Fiala76747122014-01-23 00:52:28 +00001998#if defined (__APPLE__)
1999 // No more thread specific current working directory
2000 __pthread_fchdir (-1);
2001#else
2002 if (::chdir(current_dir) == -1 && error.Success())
2003 {
2004 error.SetError(errno, eErrorTypePOSIX);
2005 error.LogIfError(log, "unable to change current directory back to %s",
2006 current_dir);
2007 }
2008#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00002009 }
2010
2011 return error;
2012}
2013
Todd Fiala76747122014-01-23 00:52:28 +00002014#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2015
2016
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002017#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2018// The functions below implement process launching via posix_spawn() for Linux,
2019// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00002020
2021Error
2022Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2023{
2024 Error error;
2025 char exe_path[PATH_MAX];
2026
2027 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2028
2029 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2030
2031 FileSpec exe_spec(launch_info.GetExecutableFile());
2032
2033 FileSpec::FileType file_type = exe_spec.GetFileType();
2034 if (file_type != FileSpec::eFileTypeRegular)
2035 {
2036 lldb::ModuleSP exe_module_sp;
2037 error = host_platform_sp->ResolveExecutable (exe_spec,
2038 arch_spec,
2039 exe_module_sp,
2040 NULL);
2041
2042 if (error.Fail())
2043 return error;
2044
2045 if (exe_module_sp)
2046 exe_spec = exe_module_sp->GetFileSpec();
2047 }
2048
2049 if (exe_spec.Exists())
2050 {
2051 exe_spec.GetPath (exe_path, sizeof(exe_path));
2052 }
2053 else
2054 {
2055 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2056 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2057 return error;
2058 }
2059
2060 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2061
2062 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2063
2064 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2065
2066 if (pid != LLDB_INVALID_PROCESS_ID)
2067 {
2068 // If all went well, then set the process ID into the launch info
2069 launch_info.SetProcessID(pid);
2070
Todd Fiala76747122014-01-23 00:52:28 +00002071 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2072
Daniel Malea4244cbd2013-08-27 20:58:59 +00002073 // Make sure we reap any processes we spawn or we will have zombies.
2074 if (!launch_info.MonitorProcess())
2075 {
2076 const bool monitor_signals = false;
2077 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2078 NULL,
2079 pid,
2080 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002081 if (log)
2082 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2083 }
2084 else
2085 {
2086 if (log)
2087 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002088 }
2089 }
2090 else
2091 {
2092 // Invalid process ID, something didn't go well
2093 if (error.Success())
2094 error.SetErrorString ("process launch failed for unknown reasons");
2095 }
2096 return error;
2097}
2098
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002099#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002100
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002101#ifndef _WIN32
2102
2103size_t
2104Host::GetPageSize()
2105{
2106 return ::getpagesize();
2107}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002108
Greg Claytone3e3fee2013-02-17 20:46:30 +00002109uint32_t
2110Host::GetNumberCPUS ()
2111{
2112 static uint32_t g_num_cores = UINT32_MAX;
2113 if (g_num_cores == UINT32_MAX)
2114 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002115#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002116
2117 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002118
Greg Claytone3e3fee2013-02-17 20:46:30 +00002119#else
2120
2121 // Assume POSIX support if a host specific case has not been supplied above
2122 g_num_cores = 0;
2123 int num_cores = 0;
2124 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002125#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002126 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002127#else
2128 int mib[] = { CTL_HW, HW_NCPU };
2129#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002130
2131 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002132 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 +00002133 {
2134 g_num_cores = num_cores;
2135 }
2136 else
2137 {
2138 mib[1] = HW_NCPU;
2139 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002140 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 +00002141 {
2142 if (num_cores > 0)
2143 g_num_cores = num_cores;
2144 }
2145 }
2146#endif
2147 }
2148 return g_num_cores;
2149}
2150
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002151void
2152Host::Kill(lldb::pid_t pid, int signo)
2153{
2154 ::kill(pid, signo);
2155}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002156
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002157#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002158
Johnny Chen8f3d8382011-08-02 20:52:42 +00002159#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002160bool
Greg Clayton3b147632010-12-18 01:54:34 +00002161Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002162{
2163 return false;
2164}
Greg Claytondd36def2010-10-17 22:03:32 +00002165
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002166void
2167Host::SetCrashDescriptionWithFormat (const char *format, ...)
2168{
2169}
2170
2171void
2172Host::SetCrashDescription (const char *description)
2173{
2174}
Greg Claytondd36def2010-10-17 22:03:32 +00002175
2176lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002177Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002178{
2179 return LLDB_INVALID_PROCESS_ID;
2180}
2181
Greg Claytonfbb76342013-11-20 21:07:01 +00002182#endif
2183
2184
2185#ifdef LLDB_DISABLE_POSIX
2186
2187Error
2188Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002189{
Greg Claytonfbb76342013-11-20 21:07:01 +00002190 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002191 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002192 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002193}
Greg Claytonfbb76342013-11-20 21:07:01 +00002194
2195Error
2196Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2197{
2198 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002199 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002200 return error;
2201}
2202
2203Error
2204Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2205{
2206 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002207 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002208 return error;
2209}
2210
2211Error
2212Host::Symlink (const char *src, const char *dst)
2213{
2214 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002215 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002216 return error;
2217}
2218
2219Error
2220Host::Readlink (const char *path, char *buf, size_t buf_len)
2221{
2222 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002223 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002224 return error;
2225}
2226
2227Error
2228Host::Unlink (const char *path)
2229{
2230 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002231 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002232 return error;
2233}
2234
Greg Clayton23f8c952014-03-24 23:10:19 +00002235Error
2236Host::RemoveDirectory (const char* path, bool recurse)
2237{
2238 Error error;
2239 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2240 return error;
2241}
2242
Greg Claytonfbb76342013-11-20 21:07:01 +00002243#else
2244
2245Error
2246Host::MakeDirectory (const char* path, uint32_t file_permissions)
2247{
2248 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002249 if (path && path[0])
2250 {
Greg Claytonfb909312013-11-23 01:58:15 +00002251 if (::mkdir(path, file_permissions) != 0)
2252 {
2253 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002254 switch (error.GetError())
2255 {
2256 case ENOENT:
2257 {
2258 // Parent directory doesn't exist, so lets make it if we can
2259 FileSpec spec(path, false);
2260 if (spec.GetDirectory() && spec.GetFilename())
2261 {
2262 // Make the parent directory and try again
2263 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2264 if (error2.Success())
2265 {
2266 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002267 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002268 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002269 else
Greg Claytonfb909312013-11-23 01:58:15 +00002270 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002271 }
2272 }
2273 }
2274 break;
2275 case EEXIST:
2276 {
2277 FileSpec path_spec(path, false);
2278 if (path_spec.IsDirectory())
2279 error.Clear(); // It is a directory and it already exists
2280 }
2281 break;
2282 }
2283 }
Greg Claytonfb909312013-11-23 01:58:15 +00002284 }
2285 else
2286 {
2287 error.SetErrorString("empty path");
2288 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002289 return error;
2290}
Greg Clayton23f8c952014-03-24 23:10:19 +00002291
2292Error
2293Host::RemoveDirectory (const char* path, bool recurse)
2294{
2295 Error error;
2296 if (path && path[0])
2297 {
2298 if (recurse)
2299 {
2300 StreamString command;
2301 command.Printf("rm -rf \"%s\"", path);
2302 int status = ::system(command.GetString().c_str());
2303 if (status != 0)
2304 error.SetError(status, eErrorTypeGeneric);
2305 }
2306 else
2307 {
2308 if (::rmdir(path) != 0)
2309 error.SetErrorToErrno();
2310 }
2311 }
2312 else
2313 {
2314 error.SetErrorString("empty path");
2315 }
2316 return error;
2317}
Greg Claytonfbb76342013-11-20 21:07:01 +00002318
2319Error
2320Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2321{
2322 Error error;
2323 struct stat file_stats;
2324 if (::stat (path, &file_stats) == 0)
2325 {
2326 // The bits in "st_mode" currently match the definitions
2327 // for the file mode bits in unix.
2328 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2329 }
2330 else
2331 {
2332 error.SetErrorToErrno();
2333 }
2334 return error;
2335}
2336
2337Error
2338Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2339{
2340 Error error;
2341 if (::chmod(path, file_permissions) != 0)
2342 error.SetErrorToErrno();
2343 return error;
2344}
2345
2346Error
2347Host::Symlink (const char *src, const char *dst)
2348{
2349 Error error;
2350 if (::symlink(dst, src) == -1)
2351 error.SetErrorToErrno();
2352 return error;
2353}
2354
2355Error
2356Host::Unlink (const char *path)
2357{
2358 Error error;
2359 if (::unlink(path) == -1)
2360 error.SetErrorToErrno();
2361 return error;
2362}
2363
2364Error
2365Host::Readlink (const char *path, char *buf, size_t buf_len)
2366{
2367 Error error;
2368 ssize_t count = ::readlink(path, buf, buf_len);
2369 if (count < 0)
2370 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002371 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002372 buf[count] = '\0'; // Success
2373 else
2374 error.SetErrorString("'buf' buffer is too small to contain link contents");
2375 return error;
2376}
2377
2378
Greg Clayton2bddd342010-09-07 20:11:56 +00002379#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002380
2381typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2382FDToFileMap& GetFDToFileMap()
2383{
2384 static FDToFileMap g_fd2filemap;
2385 return g_fd2filemap;
2386}
2387
2388lldb::user_id_t
2389Host::OpenFile (const FileSpec& file_spec,
2390 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002391 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002392 Error &error)
2393{
2394 std::string path (file_spec.GetPath());
2395 if (path.empty())
2396 {
2397 error.SetErrorString("empty path");
2398 return UINT64_MAX;
2399 }
2400 FileSP file_sp(new File());
2401 error = file_sp->Open(path.c_str(),flags,mode);
2402 if (file_sp->IsValid() == false)
2403 return UINT64_MAX;
2404 lldb::user_id_t fd = file_sp->GetDescriptor();
2405 GetFDToFileMap()[fd] = file_sp;
2406 return fd;
2407}
2408
2409bool
2410Host::CloseFile (lldb::user_id_t fd, Error &error)
2411{
2412 if (fd == UINT64_MAX)
2413 {
2414 error.SetErrorString ("invalid file descriptor");
2415 return false;
2416 }
2417 FDToFileMap& file_map = GetFDToFileMap();
2418 FDToFileMap::iterator pos = file_map.find(fd);
2419 if (pos == file_map.end())
2420 {
2421 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2422 return false;
2423 }
2424 FileSP file_sp = pos->second;
2425 if (!file_sp)
2426 {
2427 error.SetErrorString ("invalid host backing file");
2428 return false;
2429 }
2430 error = file_sp->Close();
2431 file_map.erase(pos);
2432 return error.Success();
2433}
2434
2435uint64_t
2436Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2437{
2438 if (fd == UINT64_MAX)
2439 {
2440 error.SetErrorString ("invalid file descriptor");
2441 return UINT64_MAX;
2442 }
2443 FDToFileMap& file_map = GetFDToFileMap();
2444 FDToFileMap::iterator pos = file_map.find(fd);
2445 if (pos == file_map.end())
2446 {
2447 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2448 return false;
2449 }
2450 FileSP file_sp = pos->second;
2451 if (!file_sp)
2452 {
2453 error.SetErrorString ("invalid host backing file");
2454 return UINT64_MAX;
2455 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002456 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2457 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002458 return UINT64_MAX;
2459 size_t bytes_written = src_len;
2460 error = file_sp->Write(src, bytes_written);
2461 if (error.Fail())
2462 return UINT64_MAX;
2463 return bytes_written;
2464}
2465
2466uint64_t
2467Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2468{
2469 if (fd == UINT64_MAX)
2470 {
2471 error.SetErrorString ("invalid file descriptor");
2472 return UINT64_MAX;
2473 }
2474 FDToFileMap& file_map = GetFDToFileMap();
2475 FDToFileMap::iterator pos = file_map.find(fd);
2476 if (pos == file_map.end())
2477 {
2478 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2479 return false;
2480 }
2481 FileSP file_sp = pos->second;
2482 if (!file_sp)
2483 {
2484 error.SetErrorString ("invalid host backing file");
2485 return UINT64_MAX;
2486 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002487 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2488 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002489 return UINT64_MAX;
2490 size_t bytes_read = dst_len;
2491 error = file_sp->Read(dst ,bytes_read);
2492 if (error.Fail())
2493 return UINT64_MAX;
2494 return bytes_read;
2495}
2496
2497lldb::user_id_t
2498Host::GetFileSize (const FileSpec& file_spec)
2499{
2500 return file_spec.GetByteSize();
2501}
2502
2503bool
2504Host::GetFileExists (const FileSpec& file_spec)
2505{
2506 return file_spec.Exists();
2507}
2508
2509bool
2510Host::CalculateMD5 (const FileSpec& file_spec,
2511 uint64_t &low,
2512 uint64_t &high)
2513{
2514#if defined (__APPLE__)
2515 StreamString md5_cmd_line;
2516 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2517 std::string hash_string;
2518 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2519 if (err.Fail())
2520 return false;
2521 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2522 // if the output is any other length it is probably wrong
2523 if (hash_string.size() != 32)
2524 return false;
2525 std::string part1(hash_string,0,16);
2526 std::string part2(hash_string,16);
2527 const char* part1_cstr = part1.c_str();
2528 const char* part2_cstr = part2.c_str();
2529 high = ::strtoull(part1_cstr, NULL, 16);
2530 low = ::strtoull(part2_cstr, NULL, 16);
2531 return true;
2532#else
2533 // your own MD5 implementation here
2534 return false;
2535#endif
2536}