blob: 4da5a5ee2d619a40ff273065d46be558330efd07 [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 Claytonc76fa8a2014-07-29 21:27:21 +0000382
383 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
384 {
385 g_host_arch_32.GetTriple().setOS(llvm::Triple::IOS);
386 g_host_arch_64.GetTriple().setOS(llvm::Triple::IOS);
387 }
388 else
389 {
390 g_host_arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
391 g_host_arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
392 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000393 }
Greg Clayton514487e2011-02-15 21:59:32 +0000394 else
395 {
Greg Clayton52edb362014-07-14 22:53:02 +0000396 // We have a 32 bit kernel on a 32 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000397 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000398 g_host_arch_64.Clear();
399 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000400 }
Greg Clayton514487e2011-02-15 21:59:32 +0000401 }
402
403#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000404
Greg Clayton514487e2011-02-15 21:59:32 +0000405 if (g_supports_32 == false && g_supports_64 == false)
406 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000407 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000408
Stephen Wilsonbd588712011-02-24 19:15:09 +0000409 g_host_arch_32.Clear();
410 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000411
Greg Claytonb29e6c62012-10-11 17:38:58 +0000412 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
413 // for the default triple. It's probably an artifact of config.guess.
414 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000415 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000416
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000417 const char* distribution_id = GetDistributionId ().AsCString();
418
Stephen Wilsonbd588712011-02-24 19:15:09 +0000419 switch (triple.getArch())
420 {
421 default:
422 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000423 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000424 g_supports_32 = true;
425 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000426
Stephen Wilsonbd588712011-02-24 19:15:09 +0000427 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000428 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000429 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000430 g_supports_64 = true;
431 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000432 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000433 g_supports_32 = true;
434 break;
435
Ed Mastea8375762014-04-01 18:06:45 +0000436 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000437 case llvm::Triple::sparcv9:
438 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000439 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000440 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000441 g_supports_64 = true;
442 break;
443 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000444
445 g_supports_32 = g_host_arch_32.IsValid();
446 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000447 }
Greg Clayton514487e2011-02-15 21:59:32 +0000448
449#endif // #else for #if defined (__APPLE__)
450
451 if (arch_kind == eSystemDefaultArchitecture32)
452 return g_host_arch_32;
453 else if (arch_kind == eSystemDefaultArchitecture64)
454 return g_host_arch_64;
455
456 if (g_supports_64)
457 return g_host_arch_64;
458
459 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000460}
461
462const ConstString &
463Host::GetVendorString()
464{
465 static ConstString g_vendor;
466 if (!g_vendor)
467 {
Greg Clayton950971f2012-05-12 00:01:21 +0000468 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
469 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
470 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000471 }
472 return g_vendor;
473}
474
475const ConstString &
476Host::GetOSString()
477{
478 static ConstString g_os_string;
479 if (!g_os_string)
480 {
Greg Clayton950971f2012-05-12 00:01:21 +0000481 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
482 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
483 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000484 }
485 return g_os_string;
486}
487
488const ConstString &
489Host::GetTargetTriple()
490{
491 static ConstString g_host_triple;
492 if (!(g_host_triple))
493 {
Greg Clayton950971f2012-05-12 00:01:21 +0000494 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
495 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000496 }
497 return g_host_triple;
498}
499
Todd Fialaf3d61de2014-01-17 20:18:59 +0000500// See linux/Host.cpp for Linux-based implementations of this.
501// Add your platform-specific implementation to the appropriate host file.
502#if !defined(__linux__)
503
504const ConstString &
505 Host::GetDistributionId ()
506{
507 static ConstString s_distribution_id;
508 return s_distribution_id;
509}
510
511#endif // #if !defined(__linux__)
512
Greg Clayton2bddd342010-09-07 20:11:56 +0000513lldb::pid_t
514Host::GetCurrentProcessID()
515{
516 return ::getpid();
517}
518
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000519#ifndef _WIN32
520
Greg Clayton2bddd342010-09-07 20:11:56 +0000521lldb::tid_t
522Host::GetCurrentThreadID()
523{
524#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000525 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000526 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
527 // count.
528 thread_port_t thread_self = mach_thread_self();
529 mach_port_deallocate(mach_task_self(), thread_self);
530 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000531#elif defined(__FreeBSD__)
532 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000533#elif defined(__linux__)
534 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000535#else
536 return lldb::tid_t(pthread_self());
537#endif
538}
539
Jim Ingham372787f2012-04-07 00:00:41 +0000540lldb::thread_t
541Host::GetCurrentThread ()
542{
543 return lldb::thread_t(pthread_self());
544}
545
Greg Clayton2bddd342010-09-07 20:11:56 +0000546const char *
547Host::GetSignalAsCString (int signo)
548{
549 switch (signo)
550 {
551 case SIGHUP: return "SIGHUP"; // 1 hangup
552 case SIGINT: return "SIGINT"; // 2 interrupt
553 case SIGQUIT: return "SIGQUIT"; // 3 quit
554 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
555 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
556 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000557#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000558#if !defined(SIGIO) || (SIGPOLL != SIGIO)
559// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
560// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000561 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000562#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000563#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000564#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000565 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000566#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000567 case SIGFPE: return "SIGFPE"; // 8 floating point exception
568 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
569 case SIGBUS: return "SIGBUS"; // 10 bus error
570 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
571 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
572 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
573 case SIGALRM: return "SIGALRM"; // 14 alarm clock
574 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
575 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
576 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
577 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
578 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
579 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
580 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
581 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000582#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000583 case SIGIO: return "SIGIO"; // 23 input/output possible signal
584#endif
585 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
586 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
587 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
588 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000589#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000590 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000591#endif
592#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000593 case SIGINFO: return "SIGINFO"; // 29 information request
594#endif
595 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
596 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
597 default:
598 break;
599 }
600 return NULL;
601}
602
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000603#endif
604
Greg Clayton2bddd342010-09-07 20:11:56 +0000605void
606Host::WillTerminate ()
607{
608}
609
Sylvestre Ledru59405832013-07-01 08:21:36 +0000610#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000611
Greg Clayton2bddd342010-09-07 20:11:56 +0000612void
613Host::ThreadCreated (const char *thread_name)
614{
615}
Greg Claytone5219662010-12-03 06:02:24 +0000616
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000617void
Greg Claytone5219662010-12-03 06:02:24 +0000618Host::Backtrace (Stream &strm, uint32_t max_frames)
619{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000620 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000621}
622
Greg Clayton85851dd2010-12-04 00:10:17 +0000623size_t
624Host::GetEnvironment (StringList &env)
625{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000626 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000627 return 0;
628}
629
Sylvestre Ledru59405832013-07-01 08:21:36 +0000630#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000631
632struct HostThreadCreateInfo
633{
634 std::string thread_name;
635 thread_func_t thread_fptr;
636 thread_arg_t thread_arg;
637
638 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
639 thread_name (name ? name : ""),
640 thread_fptr (fptr),
641 thread_arg (arg)
642 {
643 }
644};
645
646static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000647#ifdef _WIN32
648__stdcall
649#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000650ThreadCreateTrampoline (thread_arg_t arg)
651{
652 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
653 Host::ThreadCreated (info->thread_name.c_str());
654 thread_func_t thread_fptr = info->thread_fptr;
655 thread_arg_t thread_arg = info->thread_arg;
656
Greg Clayton5160ce52013-03-27 23:08:40 +0000657 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000658 if (log)
659 log->Printf("thread created");
660
661 delete info;
662 return thread_fptr (thread_arg);
663}
664
665lldb::thread_t
666Host::ThreadCreate
667(
668 const char *thread_name,
669 thread_func_t thread_fptr,
670 thread_arg_t thread_arg,
671 Error *error
672)
673{
674 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
675
676 // Host::ThreadCreateTrampoline will delete this pointer for us.
677 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
678
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000679#ifdef _WIN32
680 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
681 int err = thread <= 0 ? GetLastError() : 0;
682#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000683 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000684#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000685 if (err == 0)
686 {
687 if (error)
688 error->Clear();
689 return thread;
690 }
691
692 if (error)
693 error->SetError (err, eErrorTypePOSIX);
694
695 return LLDB_INVALID_HOST_THREAD;
696}
697
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000698#ifndef _WIN32
699
Greg Clayton2bddd342010-09-07 20:11:56 +0000700bool
701Host::ThreadCancel (lldb::thread_t thread, Error *error)
702{
703 int err = ::pthread_cancel (thread);
704 if (error)
705 error->SetError(err, eErrorTypePOSIX);
706 return err == 0;
707}
708
709bool
710Host::ThreadDetach (lldb::thread_t thread, Error *error)
711{
712 int err = ::pthread_detach (thread);
713 if (error)
714 error->SetError(err, eErrorTypePOSIX);
715 return err == 0;
716}
717
718bool
719Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
720{
721 int err = ::pthread_join (thread, thread_result_ptr);
722 if (error)
723 error->SetError(err, eErrorTypePOSIX);
724 return err == 0;
725}
726
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000727lldb::thread_key_t
728Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
729{
730 pthread_key_t key;
731 ::pthread_key_create (&key, callback);
732 return key;
733}
734
735void*
736Host::ThreadLocalStorageGet(lldb::thread_key_t key)
737{
738 return ::pthread_getspecific (key);
739}
740
741void
742Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
743{
744 ::pthread_setspecific (key, value);
745}
746
Matt Kopec62502c62013-05-13 19:33:58 +0000747bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000748Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
749{
Greg Clayton85719632013-02-27 22:51:58 +0000750#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000751 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
752 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
753 if (pid == LLDB_INVALID_PROCESS_ID)
754 pid = curr_pid;
755
756 if (tid == LLDB_INVALID_THREAD_ID)
757 tid = curr_tid;
758
Greg Clayton2bddd342010-09-07 20:11:56 +0000759 // Set the pthread name if possible
760 if (pid == curr_pid && tid == curr_tid)
761 {
Matt Kopec62502c62013-05-13 19:33:58 +0000762 if (::pthread_setname_np (name) == 0)
763 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000764 }
Matt Kopec62502c62013-05-13 19:33:58 +0000765 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000766#elif defined (__FreeBSD__)
767 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
768 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
769 if (pid == LLDB_INVALID_PROCESS_ID)
770 pid = curr_pid;
771
772 if (tid == LLDB_INVALID_THREAD_ID)
773 tid = curr_tid;
774
775 // Set the pthread name if possible
776 if (pid == curr_pid && tid == curr_tid)
777 {
Michael Sartainc2052432013-08-01 18:51:08 +0000778 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000779 return true;
780 }
781 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000782#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000783 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
784 if (fn)
785 {
Matt Kopec62502c62013-05-13 19:33:58 +0000786 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
787 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000788 if (pid == LLDB_INVALID_PROCESS_ID)
789 pid = curr_pid;
790
791 if (tid == LLDB_INVALID_THREAD_ID)
792 tid = curr_tid;
793
Michael Sartainc2052432013-08-01 18:51:08 +0000794 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000795 {
Michael Sartainc2052432013-08-01 18:51:08 +0000796 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
797 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
798
799 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000800 return true;
801 }
802 }
803 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000804#else
805 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000806#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000807}
808
Ed Maste02983be2013-07-25 19:10:32 +0000809bool
810Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
811 const char *thread_name, size_t len)
812{
Enrico Granata67530b62014-02-12 03:37:33 +0000813 std::unique_ptr<char[]> namebuf(new char[len+1]);
814
Ed Maste02983be2013-07-25 19:10:32 +0000815 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
816 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
817 // off leads to a lot of similar named threads. Go through the thread name
818 // and search for the last dot and use that.
819 const char *lastdot = ::strrchr (thread_name, '.');
820
821 if (lastdot && lastdot != thread_name)
822 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000823 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000824 namebuf[len] = 0;
825
Enrico Granata67530b62014-02-12 03:37:33 +0000826 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000827 if (namebuflen > 0)
828 {
829 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
830 {
831 // Trim off trailing '(' and '>' characters for a bit more cleanup.
832 namebuflen--;
833 namebuf[namebuflen] = 0;
834 }
Enrico Granata67530b62014-02-12 03:37:33 +0000835 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000836 }
837 return false;
838}
839
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000840#endif
841
Zachary Turnerdf62f202014-08-07 17:33:07 +0000842FileSpec::PathSyntax
843Host::GetHostPathSyntax()
844{
845#if defined(_WIN32)
846 return FileSpec::ePathSyntaxWindows;
847#else
848 return FileSpec::ePathSyntaxPosix;
849#endif
850}
851
Greg Clayton2bddd342010-09-07 20:11:56 +0000852FileSpec
Zachary Turner9e757b72014-07-28 16:45:05 +0000853Host::GetUserProfileFileSpec ()
854{
855 static FileSpec g_profile_filespec;
856 if (!g_profile_filespec)
857 {
858 llvm::SmallString<64> path;
859 llvm::sys::path::home_directory(path);
860 return FileSpec(path.c_str(), false);
861 }
862 return g_profile_filespec;
863}
864
865FileSpec
Greg Clayton2bddd342010-09-07 20:11:56 +0000866Host::GetProgramFileSpec ()
867{
868 static FileSpec g_program_filespec;
869 if (!g_program_filespec)
870 {
871#if defined (__APPLE__)
872 char program_fullpath[PATH_MAX];
873 // If DST is NULL, then return the number of bytes needed.
874 uint32_t len = sizeof(program_fullpath);
875 int err = _NSGetExecutablePath (program_fullpath, &len);
876 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000877 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000878 else if (err == -1)
879 {
880 char *large_program_fullpath = (char *)::malloc (len + 1);
881
882 err = _NSGetExecutablePath (large_program_fullpath, &len);
883 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000884 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000885
886 ::free (large_program_fullpath);
887 }
888#elif defined (__linux__)
889 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000890 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
891 if (len > 0) {
892 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000893 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000894 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000895#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000896 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
897 size_t exe_path_size;
898 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
899 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000900 char *exe_path = new char[exe_path_size];
901 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
902 g_program_filespec.SetFile(exe_path, false);
903 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000904 }
Zachary Turner9e757b72014-07-28 16:45:05 +0000905#elif defined(_WIN32)
906 std::vector<char> buffer(PATH_MAX);
907 ::GetModuleFileName(NULL, &buffer[0], buffer.size());
Zachary Turnerd8a52732014-07-29 05:39:21 +0000908 g_program_filespec.SetFile(&buffer[0], false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000909#endif
910 }
911 return g_program_filespec;
912}
913
Greg Clayton2bddd342010-09-07 20:11:56 +0000914#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000915
916bool
917Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
918{
919 bundle.Clear();
920 return false;
921}
922
Greg Clayton2bddd342010-09-07 20:11:56 +0000923bool
Greg Claytondd36def2010-10-17 22:03:32 +0000924Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000925{
Greg Claytondd36def2010-10-17 22:03:32 +0000926 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000927}
928#endif
929
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000930#ifndef _WIN32
931
Greg Clayton45319462011-02-08 00:35:34 +0000932// Opaque info that tracks a dynamic library that was loaded
933struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000934{
Greg Clayton45319462011-02-08 00:35:34 +0000935 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
936 file_spec (fs),
937 open_options (o),
938 handle (h)
939 {
940 }
941
942 const FileSpec file_spec;
943 uint32_t open_options;
944 void * handle;
945};
946
947void *
948Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
949{
Greg Clayton4272cc72011-02-02 02:24:04 +0000950 char path[PATH_MAX];
951 if (file_spec.GetPath(path, sizeof(path)))
952 {
Greg Clayton45319462011-02-08 00:35:34 +0000953 int mode = 0;
954
955 if (options & eDynamicLibraryOpenOptionLazy)
956 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000957 else
958 mode |= RTLD_NOW;
959
Greg Clayton45319462011-02-08 00:35:34 +0000960
961 if (options & eDynamicLibraryOpenOptionLocal)
962 mode |= RTLD_LOCAL;
963 else
964 mode |= RTLD_GLOBAL;
965
966#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
967 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
968 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000969#endif
Greg Clayton45319462011-02-08 00:35:34 +0000970
971 void * opaque = ::dlopen (path, mode);
972
973 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000974 {
975 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000976 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000977 }
978 else
979 {
980 error.SetErrorString(::dlerror());
981 }
982 }
983 else
984 {
985 error.SetErrorString("failed to extract path");
986 }
Greg Clayton45319462011-02-08 00:35:34 +0000987 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000988}
989
990Error
Greg Clayton45319462011-02-08 00:35:34 +0000991Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000992{
993 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000994 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000995 {
996 error.SetErrorString ("invalid dynamic library handle");
997 }
Greg Clayton45319462011-02-08 00:35:34 +0000998 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000999 {
Greg Clayton45319462011-02-08 00:35:34 +00001000 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1001 if (::dlclose (dylib_info->handle) != 0)
1002 {
1003 error.SetErrorString(::dlerror());
1004 }
1005
1006 dylib_info->open_options = 0;
1007 dylib_info->handle = 0;
1008 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +00001009 }
1010 return error;
1011}
1012
1013void *
Greg Clayton45319462011-02-08 00:35:34 +00001014Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +00001015{
Greg Clayton45319462011-02-08 00:35:34 +00001016 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +00001017 {
1018 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +00001019 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001020 else
Greg Clayton45319462011-02-08 00:35:34 +00001021 {
1022 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1023
1024 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
1025 if (symbol_addr)
1026 {
1027#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
1028 // This host doesn't support limiting searches to this shared library
1029 // so we need to verify that the match came from this shared library
1030 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +00001031 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +00001032 {
1033 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
1034 if (match_dylib_spec != dylib_info->file_spec)
1035 {
1036 char dylib_path[PATH_MAX];
1037 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
1038 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
1039 else
1040 error.SetErrorString ("symbol not found");
1041 return NULL;
1042 }
1043 }
1044#endif
1045 error.Clear();
1046 return symbol_addr;
1047 }
1048 else
1049 {
1050 error.SetErrorString(::dlerror());
1051 }
1052 }
1053 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +00001054}
Greg Claytondd36def2010-10-17 22:03:32 +00001055
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001056FileSpec
1057Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1058{
1059 FileSpec module_filespec;
1060 Dl_info info;
1061 if (::dladdr (host_addr, &info))
1062 {
1063 if (info.dli_fname)
1064 module_filespec.SetFile(info.dli_fname, true);
1065 }
1066 return module_filespec;
1067}
1068
1069#endif
1070
Greg Clayton23f8c952014-03-24 23:10:19 +00001071
1072static void CleanupProcessSpecificLLDBTempDir ()
1073{
1074 // Get the process specific LLDB temporary directory and delete it.
1075 FileSpec tmpdir_file_spec;
1076 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1077 {
1078 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1079 // true to all files that were created for the LLDB process can be cleaned up.
1080 const bool recurse = true;
1081 Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1082 }
1083}
1084
Greg Claytondd36def2010-10-17 22:03:32 +00001085bool
1086Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1087{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001088 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001089 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1090 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001091 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001092 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001093 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001094
1095 switch (path_type)
1096 {
1097 case ePathTypeLLDBShlibDir:
1098 {
1099 static ConstString g_lldb_so_dir;
1100 if (!g_lldb_so_dir)
1101 {
David Majnemer8490da12014-07-22 22:00:42 +00001102 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1103 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +00001104 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001105 if (log)
1106 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001107 }
1108 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001109 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001110 }
1111 break;
1112
1113 case ePathTypeSupportExecutableDir:
1114 {
1115 static ConstString g_lldb_support_exe_dir;
1116 if (!g_lldb_support_exe_dir)
1117 {
1118 FileSpec lldb_file_spec;
1119 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1120 {
1121 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001122 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1123
1124#if defined (__APPLE__)
1125 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1126 if (framework_pos)
1127 {
1128 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +00001129#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001130 // Shallow bundle
1131 *framework_pos = '\0';
1132#else
1133 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001134 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001135#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001136 }
Todd Fiala015d8182014-07-22 23:41:36 +00001137#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1138 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1139 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
1140 // different trees.
1141 if (log)
1142 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1143 char *lib_pos = ::strstr (raw_path, "/lib");
1144 if (lib_pos != nullptr)
1145 {
1146 // First terminate the raw path at the start of lib.
1147 *lib_pos = '\0';
1148
1149 // Now write in bin in place of lib.
1150 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1151
1152 if (log)
1153 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1154 }
1155 else
1156 {
1157 if (log)
1158 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1159 }
Jason Molendaa3329782014-03-29 18:54:20 +00001160#endif // #if defined (__APPLE__)
Zachary Turner3f559742014-08-07 17:33:36 +00001161 llvm::SmallString<64> resolved_path(raw_path);
1162 FileSpec::Resolve (resolved_path);
1163 g_lldb_support_exe_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001164 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001165 if (log)
1166 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001167 }
1168 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001169 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001170 }
1171 break;
1172
1173 case ePathTypeHeaderDir:
1174 {
1175 static ConstString g_lldb_headers_dir;
1176 if (!g_lldb_headers_dir)
1177 {
1178#if defined (__APPLE__)
1179 FileSpec lldb_file_spec;
1180 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1181 {
1182 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001183 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1184
1185 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1186 if (framework_pos)
1187 {
1188 framework_pos += strlen("LLDB.framework");
1189 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1190 }
Jim Inghame1d263e2014-08-07 22:37:43 +00001191 llvm::SmallString<64> resolved_path(raw_path);
1192 FileSpec::Resolve (resolved_path);
1193 g_lldb_headers_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001194 }
1195#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001196 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001197 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1198#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001199 if (log)
1200 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001201 }
1202 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001203 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001204 }
1205 break;
1206
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001207#ifdef LLDB_DISABLE_PYTHON
1208 case ePathTypePythonDir:
1209 return false;
1210#else
1211 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001212 {
Greg Claytondd36def2010-10-17 22:03:32 +00001213 static ConstString g_lldb_python_dir;
1214 if (!g_lldb_python_dir)
1215 {
1216 FileSpec lldb_file_spec;
1217 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1218 {
1219 char raw_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001220#if defined(_WIN32)
1221 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1222 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1223#else
Greg Claytondd36def2010-10-17 22:03:32 +00001224 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1225
1226#if defined (__APPLE__)
1227 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1228 if (framework_pos)
1229 {
1230 framework_pos += strlen("LLDB.framework");
1231 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001232 }
1233 else
1234 {
1235#endif
1236 llvm::SmallString<256> python_version_dir;
1237 llvm::raw_svector_ostream os(python_version_dir);
1238 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1239 os.flush();
1240
1241 // We may get our string truncated. Should we protect
1242 // this with an assert?
1243
1244 ::strncat(raw_path, python_version_dir.c_str(),
1245 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001246#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001247#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001248 }
1249#endif
Zachary Turner3f559742014-08-07 17:33:36 +00001250 llvm::SmallString<64> resolved_path(raw_path);
1251 FileSpec::Resolve (resolved_path);
1252 g_lldb_python_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001253 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001254
1255 if (log)
1256 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1257
Greg Claytondd36def2010-10-17 22:03:32 +00001258 }
1259 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001260 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001261 }
1262 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001263#endif
1264
Greg Clayton4272cc72011-02-02 02:24:04 +00001265 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1266 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001267#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001268 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001269 static bool g_lldb_system_plugin_dir_located = false;
1270 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001271 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001272 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001273#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001274 FileSpec lldb_file_spec;
1275 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1276 {
1277 char raw_path[PATH_MAX];
Greg Clayton4272cc72011-02-02 02:24:04 +00001278 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1279
1280 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1281 if (framework_pos)
1282 {
1283 framework_pos += strlen("LLDB.framework");
1284 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Jim Inghame1d263e2014-08-07 22:37:43 +00001285 llvm::SmallString<64> resolved_path(raw_path);
1286 FileSpec::Resolve (resolved_path);
1287 g_lldb_system_plugin_dir.SetCString(resolved_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001288 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001289 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001290 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001291#elif defined (__linux__)
1292 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1293 if (lldb_file_spec.Exists())
1294 {
1295 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1296 }
1297#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001298
1299 if (log)
1300 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1301
Greg Clayton4272cc72011-02-02 02:24:04 +00001302 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001303
1304 if (g_lldb_system_plugin_dir)
1305 {
1306 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1307 return true;
1308 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001309#else
1310 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001311 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001312#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001313 }
1314 break;
1315
1316 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1317 {
1318#if defined (__APPLE__)
1319 static ConstString g_lldb_user_plugin_dir;
1320 if (!g_lldb_user_plugin_dir)
1321 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001322 llvm::SmallString<64> user_plugin_path("~/Library/Application Support/LLDB/PlugIns");
1323 FileSpec::Resolve (user_plugin_path);
1324 if (user_plugin_path.size())
Greg Clayton4272cc72011-02-02 02:24:04 +00001325 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001326 g_lldb_user_plugin_dir.SetCString(user_plugin_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001327 }
1328 }
1329 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001330 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001331#elif defined (__linux__)
1332 static ConstString g_lldb_user_plugin_dir;
1333 if (!g_lldb_user_plugin_dir)
1334 {
1335 // XDG Base Directory Specification
1336 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1337 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1338 FileSpec lldb_file_spec;
1339 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1340 if (xdg_data_home && xdg_data_home[0])
1341 {
1342 std::string user_plugin_dir (xdg_data_home);
1343 user_plugin_dir += "/lldb";
1344 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1345 }
1346 else
1347 {
1348 const char *home_dir = getenv("HOME");
1349 if (home_dir && home_dir[0])
1350 {
1351 std::string user_plugin_dir (home_dir);
1352 user_plugin_dir += "/.local/share/lldb";
1353 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1354 }
1355 }
1356
1357 if (lldb_file_spec.Exists())
1358 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001359 if (log)
1360 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001361 }
1362 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001363 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001364#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001365 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001366 return false;
1367 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001368
1369 case ePathTypeLLDBTempSystemDir:
1370 {
1371 static ConstString g_lldb_tmp_dir;
1372 if (!g_lldb_tmp_dir)
1373 {
1374 const char *tmpdir_cstr = getenv("TMPDIR");
1375 if (tmpdir_cstr == NULL)
1376 {
1377 tmpdir_cstr = getenv("TMP");
1378 if (tmpdir_cstr == NULL)
1379 tmpdir_cstr = getenv("TEMP");
1380 }
1381 if (tmpdir_cstr)
1382 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001383 StreamString pid_tmpdir;
1384 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1385 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1386 {
1387 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1388 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1389 {
1390 // Make an atexit handler to clean up the process specify LLDB temp dir
1391 // and all of its contents.
1392 ::atexit (CleanupProcessSpecificLLDBTempDir);
1393 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1394 if (log)
1395 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1396
1397 }
1398 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001399 }
1400 }
1401 file_spec.GetDirectory() = g_lldb_tmp_dir;
1402 return (bool)file_spec.GetDirectory();
1403 }
Greg Claytondd36def2010-10-17 22:03:32 +00001404 }
1405
1406 return false;
1407}
1408
Greg Clayton1cb64962011-03-24 04:28:38 +00001409
1410bool
1411Host::GetHostname (std::string &s)
1412{
1413 char hostname[PATH_MAX];
1414 hostname[sizeof(hostname) - 1] = '\0';
1415 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1416 {
1417 struct hostent* h = ::gethostbyname (hostname);
1418 if (h)
1419 s.assign (h->h_name);
1420 else
1421 s.assign (hostname);
1422 return true;
1423 }
1424 return false;
1425}
1426
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001427#ifndef _WIN32
1428
Greg Clayton32e0a752011-03-30 18:16:51 +00001429const char *
1430Host::GetUserName (uint32_t uid, std::string &user_name)
1431{
1432 struct passwd user_info;
1433 struct passwd *user_info_ptr = &user_info;
1434 char user_buffer[PATH_MAX];
1435 size_t user_buffer_size = sizeof(user_buffer);
1436 if (::getpwuid_r (uid,
1437 &user_info,
1438 user_buffer,
1439 user_buffer_size,
1440 &user_info_ptr) == 0)
1441 {
1442 if (user_info_ptr)
1443 {
1444 user_name.assign (user_info_ptr->pw_name);
1445 return user_name.c_str();
1446 }
1447 }
1448 user_name.clear();
1449 return NULL;
1450}
1451
1452const char *
1453Host::GetGroupName (uint32_t gid, std::string &group_name)
1454{
1455 char group_buffer[PATH_MAX];
1456 size_t group_buffer_size = sizeof(group_buffer);
1457 struct group group_info;
1458 struct group *group_info_ptr = &group_info;
1459 // Try the threadsafe version first
1460 if (::getgrgid_r (gid,
1461 &group_info,
1462 group_buffer,
1463 group_buffer_size,
1464 &group_info_ptr) == 0)
1465 {
1466 if (group_info_ptr)
1467 {
1468 group_name.assign (group_info_ptr->gr_name);
1469 return group_name.c_str();
1470 }
1471 }
1472 else
1473 {
1474 // The threadsafe version isn't currently working
1475 // for me on darwin, but the non-threadsafe version
1476 // is, so I am calling it below.
1477 group_info_ptr = ::getgrgid (gid);
1478 if (group_info_ptr)
1479 {
1480 group_name.assign (group_info_ptr->gr_name);
1481 return group_name.c_str();
1482 }
1483 }
1484 group_name.clear();
1485 return NULL;
1486}
1487
Han Ming Ong84647042012-02-25 01:07:38 +00001488uint32_t
1489Host::GetUserID ()
1490{
1491 return getuid();
1492}
1493
1494uint32_t
1495Host::GetGroupID ()
1496{
1497 return getgid();
1498}
1499
1500uint32_t
1501Host::GetEffectiveUserID ()
1502{
1503 return geteuid();
1504}
1505
1506uint32_t
1507Host::GetEffectiveGroupID ()
1508{
1509 return getegid();
1510}
1511
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001512#endif
1513
1514#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1515bool
1516Host::GetOSBuildString (std::string &s)
1517{
1518 s.clear();
1519 return false;
1520}
1521
1522bool
1523Host::GetOSKernelDescription (std::string &s)
1524{
1525 s.clear();
1526 return false;
1527}
1528#endif
1529
Zachary Turner310035a2014-07-08 04:52:15 +00001530#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1531 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001532uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001533Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001534{
1535 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001536 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001537}
1538
Greg Claytone996fd32011-03-08 22:40:15 +00001539bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001540Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001541{
Greg Claytone996fd32011-03-08 22:40:15 +00001542 process_info.Clear();
1543 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001544}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001545#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001546
Matt Kopec085d6ce2013-05-31 22:00:07 +00001547#if !defined(__linux__)
1548bool
1549Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1550{
1551 return false;
1552}
1553#endif
1554
Sean Callananc0a6e062011-10-27 21:22:25 +00001555lldb::TargetSP
1556Host::GetDummyTarget (lldb_private::Debugger &debugger)
1557{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001558 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001559
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001560 // FIXME: Maybe the dummy target should be per-Debugger
1561 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1562 {
1563 ArchSpec arch(Target::GetDefaultArchitecture());
1564 if (!arch.IsValid())
1565 arch = Host::GetArchitecture ();
1566 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001567 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001568 arch.GetTriple().getTriple().c_str(),
1569 false,
1570 NULL,
1571 g_dummy_target_sp);
1572 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001573
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001574 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001575}
1576
Greg Claytond1cf11a2012-04-14 01:42:46 +00001577struct ShellInfo
1578{
1579 ShellInfo () :
1580 process_reaped (false),
1581 can_delete (false),
1582 pid (LLDB_INVALID_PROCESS_ID),
1583 signo(-1),
1584 status(-1)
1585 {
1586 }
1587
1588 lldb_private::Predicate<bool> process_reaped;
1589 lldb_private::Predicate<bool> can_delete;
1590 lldb::pid_t pid;
1591 int signo;
1592 int status;
1593};
1594
1595static bool
1596MonitorShellCommand (void *callback_baton,
1597 lldb::pid_t pid,
1598 bool exited, // True if the process did exit
1599 int signo, // Zero for no signal
1600 int status) // Exit value of process if signal is zero
1601{
1602 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1603 shell_info->pid = pid;
1604 shell_info->signo = signo;
1605 shell_info->status = status;
1606 // Let the thread running Host::RunShellCommand() know that the process
1607 // exited and that ShellInfo has been filled in by broadcasting to it
1608 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1609 // Now wait for a handshake back from that thread running Host::RunShellCommand
1610 // so we know that we can delete shell_info_ptr
1611 shell_info->can_delete.WaitForValueEqualTo(true);
1612 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1613 usleep(1000);
1614 // Now delete the shell info that was passed into this function
1615 delete shell_info;
1616 return true;
1617}
1618
1619Error
1620Host::RunShellCommand (const char *command,
1621 const char *working_dir,
1622 int *status_ptr,
1623 int *signo_ptr,
1624 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001625 uint32_t timeout_sec,
1626 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001627{
1628 Error error;
1629 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001630 if (shell && shell[0])
1631 {
1632 // Run the command in a shell
1633 launch_info.SetShell(shell);
1634 launch_info.GetArguments().AppendArgument(command);
1635 const bool localhost = true;
1636 const bool will_debug = false;
1637 const bool first_arg_is_full_shell_command = true;
1638 launch_info.ConvertArgumentsForLaunchingInShell (error,
1639 localhost,
1640 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001641 first_arg_is_full_shell_command,
1642 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001643 }
1644 else
1645 {
1646 // No shell, just run it
1647 Args args (command);
1648 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001649 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001650 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001651
1652 if (working_dir)
1653 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001654 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001655 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001656
Greg Claytond1cf11a2012-04-14 01:42:46 +00001657 if (command_output_ptr)
1658 {
1659 // Create a temporary file to get the stdout/stderr and redirect the
1660 // output of the command into this file. We will later read this file
1661 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001662 FileSpec tmpdir_file_spec;
1663 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1664 {
1665 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1666 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1667 }
1668 else
1669 {
1670 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1671 }
1672
1673 output_file_path = ::mktemp(output_file_path_buffer);
1674 }
1675
1676 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1677 if (output_file_path)
1678 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001679 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001680 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001681 }
1682 else
1683 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001684 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1685 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1686 }
1687
1688 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001689 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001690
1691 const bool monitor_signals = false;
1692 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1693
1694 error = LaunchProcess (launch_info);
1695 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001696
1697 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1698 error.SetErrorString("failed to get process ID");
1699
1700 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001701 {
1702 // The process successfully launched, so we can defer ownership of
1703 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001704 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001705 // doesn't need to delete the ShellInfo anymore.
1706 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001707 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001708 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001709 if (timeout_sec > 0) {
1710 timeout_time.OffsetWithSeconds(timeout_sec);
1711 timeout_ptr = &timeout_time;
1712 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001713 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001714 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001715 if (timed_out)
1716 {
1717 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001718
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001719 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001720 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001721 // Wait for the monitor callback to get the message
1722 timeout_time = TimeValue::Now();
1723 timeout_time.OffsetWithSeconds(1);
1724 timed_out = false;
1725 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1726 }
1727 else
1728 {
1729 if (status_ptr)
1730 *status_ptr = shell_info->status;
1731
1732 if (signo_ptr)
1733 *signo_ptr = shell_info->signo;
1734
1735 if (command_output_ptr)
1736 {
1737 command_output_ptr->clear();
1738 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1739 uint64_t file_size = file_spec.GetByteSize();
1740 if (file_size > 0)
1741 {
1742 if (file_size > command_output_ptr->max_size())
1743 {
1744 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1745 }
1746 else
1747 {
1748 command_output_ptr->resize(file_size);
1749 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1750 }
1751 }
1752 }
1753 }
1754 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1755 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001756
1757 if (output_file_path)
1758 ::unlink (output_file_path);
1759 // Handshake with the monitor thread, or just let it know in advance that
1760 // it can delete "shell_info" in case we timed out and were not able to kill
1761 // the process...
1762 return error;
1763}
1764
Daniel Malea4244cbd2013-08-27 20:58:59 +00001765
Todd Fiala76747122014-01-23 00:52:28 +00001766// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1767// systems
1768
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001769#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001770
1771// this method needs to be visible to macosx/Host.cpp and
1772// common/Host.cpp.
1773
1774short
1775Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1776{
1777 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1778
1779#if defined (__APPLE__)
1780 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1781 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1782
1783 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1784 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1785
1786 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1787 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1788
1789 if (launch_info.GetLaunchInSeparateProcessGroup())
1790 flags |= POSIX_SPAWN_SETPGROUP;
1791
1792#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1793#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1794 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1795 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1796 {
1797 g_use_close_on_exec_flag = eLazyBoolNo;
1798
1799 uint32_t major, minor, update;
1800 if (Host::GetOSVersion(major, minor, update))
1801 {
1802 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1803 if (major > 10 || (major == 10 && minor > 7))
1804 {
1805 // Only enable for 10.8 and later OS versions
1806 g_use_close_on_exec_flag = eLazyBoolYes;
1807 }
1808 }
1809 }
1810#else
1811 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1812#endif
1813 // Close all files exception those with file actions if this is supported.
1814 if (g_use_close_on_exec_flag == eLazyBoolYes)
1815 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1816#endif
1817#endif // #if defined (__APPLE__)
1818 return flags;
1819}
1820
1821Error
1822Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001823{
1824 Error error;
1825 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1826
Daniel Malea4244cbd2013-08-27 20:58:59 +00001827 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001828 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001829
1830 if (error.Fail() || log)
1831 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001832 if (error.Fail())
1833 return error;
1834
1835 // Make a quick class that will cleanup the posix spawn attributes in case
1836 // we return in the middle of this function.
1837 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1838
1839 sigset_t no_signals;
1840 sigset_t all_signals;
1841 sigemptyset (&no_signals);
1842 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001843 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001844#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001845 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001846#else
1847 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1848#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001849
Todd Fiala76747122014-01-23 00:52:28 +00001850 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001851
1852 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001853 if (error.Fail() || log)
1854 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001855 if (error.Fail())
1856 return error;
1857
Todd Fiala76747122014-01-23 00:52:28 +00001858 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1859 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1860#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001861
1862 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1863 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1864 // to do that job on OSX.
1865
1866 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001867 {
Jim Ingham90331d52014-02-21 01:25:21 +00001868 // We don't need to do this for ARM, and we really shouldn't now that we
1869 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1870 // to set which CPU subtype to launch...
1871 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1872 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1873 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1874 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001875 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1876 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001877 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1878 {
1879 size_t ocount = 0;
1880 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1881 if (error.Fail() || log)
1882 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 +00001883
Jim Ingham90331d52014-02-21 01:25:21 +00001884 if (error.Fail() || ocount != 1)
1885 return error;
1886 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001887 }
1888
Todd Fiala76747122014-01-23 00:52:28 +00001889#endif
1890
1891 const char *tmp_argv[2];
1892 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1893 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1894 if (argv == NULL)
1895 {
1896 // posix_spawn gets very unhappy if it doesn't have at least the program
1897 // name in argv[0]. One of the side affects I have noticed is the environment
1898 // variables don't make it into the child process if "argv == NULL"!!!
1899 tmp_argv[0] = exe_path;
1900 tmp_argv[1] = NULL;
1901 argv = (char * const*)tmp_argv;
1902 }
1903
1904#if !defined (__APPLE__)
1905 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001906 char current_dir[PATH_MAX];
1907 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001908#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001909
1910 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001911 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001912 {
Todd Fiala76747122014-01-23 00:52:28 +00001913#if defined (__APPLE__)
1914 // Set the working directory on this thread only
1915 if (__pthread_chdir (working_dir) < 0) {
1916 if (errno == ENOENT) {
1917 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1918 } else if (errno == ENOTDIR) {
1919 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1920 } else {
1921 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1922 }
1923 return error;
1924 }
1925#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001926 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1927 {
1928 error.SetError(errno, eErrorTypePOSIX);
1929 error.LogIfError(log, "unable to save the current directory");
1930 return error;
1931 }
1932
1933 if (::chdir(working_dir) == -1)
1934 {
1935 error.SetError(errno, eErrorTypePOSIX);
1936 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1937 return error;
1938 }
Todd Fiala76747122014-01-23 00:52:28 +00001939#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001940 }
1941
Todd Fiala76747122014-01-23 00:52:28 +00001942 const size_t num_file_actions = launch_info.GetNumFileActions ();
1943 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001944 {
Todd Fiala76747122014-01-23 00:52:28 +00001945 posix_spawn_file_actions_t file_actions;
1946 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1947 if (error.Fail() || log)
1948 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1949 if (error.Fail())
1950 return error;
1951
1952 // Make a quick class that will cleanup the posix spawn attributes in case
1953 // we return in the middle of this function.
1954 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1955
1956 for (size_t i=0; i<num_file_actions; ++i)
1957 {
1958 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1959 if (launch_file_action)
1960 {
1961 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1962 launch_file_action,
1963 log,
1964 error))
1965 return error;
1966 }
1967 }
1968
1969 error.SetError (::posix_spawnp (&pid,
1970 exe_path,
1971 &file_actions,
1972 &attr,
1973 argv,
1974 envp),
1975 eErrorTypePOSIX);
1976
1977 if (error.Fail() || log)
1978 {
1979 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 +00001980 pid, exe_path, static_cast<void*>(&file_actions),
1981 static_cast<void*>(&attr),
1982 reinterpret_cast<const void*>(argv),
1983 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001984 if (log)
1985 {
1986 for (int ii=0; argv[ii]; ++ii)
1987 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1988 }
1989 }
1990
1991 }
1992 else
1993 {
1994 error.SetError (::posix_spawnp (&pid,
1995 exe_path,
1996 NULL,
1997 &attr,
1998 argv,
1999 envp),
2000 eErrorTypePOSIX);
2001
2002 if (error.Fail() || log)
2003 {
2004 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 +00002005 pid, exe_path, static_cast<void*>(&attr),
2006 reinterpret_cast<const void*>(argv),
2007 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00002008 if (log)
2009 {
2010 for (int ii=0; argv[ii]; ++ii)
2011 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
2012 }
2013 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00002014 }
2015
Todd Fiala76747122014-01-23 00:52:28 +00002016 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002017 {
Todd Fiala76747122014-01-23 00:52:28 +00002018#if defined (__APPLE__)
2019 // No more thread specific current working directory
2020 __pthread_fchdir (-1);
2021#else
2022 if (::chdir(current_dir) == -1 && error.Success())
2023 {
2024 error.SetError(errno, eErrorTypePOSIX);
2025 error.LogIfError(log, "unable to change current directory back to %s",
2026 current_dir);
2027 }
2028#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00002029 }
2030
2031 return error;
2032}
2033
Todd Fiala76747122014-01-23 00:52:28 +00002034#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2035
2036
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002037#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2038// The functions below implement process launching via posix_spawn() for Linux,
2039// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00002040
2041Error
2042Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2043{
2044 Error error;
2045 char exe_path[PATH_MAX];
2046
2047 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2048
2049 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2050
2051 FileSpec exe_spec(launch_info.GetExecutableFile());
2052
2053 FileSpec::FileType file_type = exe_spec.GetFileType();
2054 if (file_type != FileSpec::eFileTypeRegular)
2055 {
2056 lldb::ModuleSP exe_module_sp;
2057 error = host_platform_sp->ResolveExecutable (exe_spec,
2058 arch_spec,
2059 exe_module_sp,
2060 NULL);
2061
2062 if (error.Fail())
2063 return error;
2064
2065 if (exe_module_sp)
2066 exe_spec = exe_module_sp->GetFileSpec();
2067 }
2068
2069 if (exe_spec.Exists())
2070 {
2071 exe_spec.GetPath (exe_path, sizeof(exe_path));
2072 }
2073 else
2074 {
2075 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2076 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2077 return error;
2078 }
2079
2080 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2081
2082 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2083
2084 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2085
2086 if (pid != LLDB_INVALID_PROCESS_ID)
2087 {
2088 // If all went well, then set the process ID into the launch info
2089 launch_info.SetProcessID(pid);
2090
Todd Fiala76747122014-01-23 00:52:28 +00002091 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2092
Daniel Malea4244cbd2013-08-27 20:58:59 +00002093 // Make sure we reap any processes we spawn or we will have zombies.
2094 if (!launch_info.MonitorProcess())
2095 {
2096 const bool monitor_signals = false;
2097 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2098 NULL,
2099 pid,
2100 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002101 if (log)
2102 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2103 }
2104 else
2105 {
2106 if (log)
2107 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002108 }
2109 }
2110 else
2111 {
2112 // Invalid process ID, something didn't go well
2113 if (error.Success())
2114 error.SetErrorString ("process launch failed for unknown reasons");
2115 }
2116 return error;
2117}
2118
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002119#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002120
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002121#ifndef _WIN32
2122
2123size_t
2124Host::GetPageSize()
2125{
2126 return ::getpagesize();
2127}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002128
Greg Claytone3e3fee2013-02-17 20:46:30 +00002129uint32_t
2130Host::GetNumberCPUS ()
2131{
2132 static uint32_t g_num_cores = UINT32_MAX;
2133 if (g_num_cores == UINT32_MAX)
2134 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002135#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002136
2137 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002138
Greg Claytone3e3fee2013-02-17 20:46:30 +00002139#else
2140
2141 // Assume POSIX support if a host specific case has not been supplied above
2142 g_num_cores = 0;
2143 int num_cores = 0;
2144 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002145#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002146 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002147#else
2148 int mib[] = { CTL_HW, HW_NCPU };
2149#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002150
2151 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002152 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 +00002153 {
2154 g_num_cores = num_cores;
2155 }
2156 else
2157 {
2158 mib[1] = HW_NCPU;
2159 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002160 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 +00002161 {
2162 if (num_cores > 0)
2163 g_num_cores = num_cores;
2164 }
2165 }
2166#endif
2167 }
2168 return g_num_cores;
2169}
2170
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002171void
2172Host::Kill(lldb::pid_t pid, int signo)
2173{
2174 ::kill(pid, signo);
2175}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002176
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002177#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002178
Johnny Chen8f3d8382011-08-02 20:52:42 +00002179#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002180bool
Greg Clayton3b147632010-12-18 01:54:34 +00002181Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002182{
2183 return false;
2184}
Greg Claytondd36def2010-10-17 22:03:32 +00002185
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002186void
2187Host::SetCrashDescriptionWithFormat (const char *format, ...)
2188{
2189}
2190
2191void
2192Host::SetCrashDescription (const char *description)
2193{
2194}
Greg Claytondd36def2010-10-17 22:03:32 +00002195
2196lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002197Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002198{
2199 return LLDB_INVALID_PROCESS_ID;
2200}
2201
Greg Claytonfbb76342013-11-20 21:07:01 +00002202#endif
2203
2204
2205#ifdef LLDB_DISABLE_POSIX
2206
2207Error
2208Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002209{
Greg Claytonfbb76342013-11-20 21:07:01 +00002210 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002211 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002212 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002213}
Greg Claytonfbb76342013-11-20 21:07:01 +00002214
2215Error
2216Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2217{
2218 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002219 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002220 return error;
2221}
2222
2223Error
2224Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2225{
2226 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002227 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002228 return error;
2229}
2230
2231Error
2232Host::Symlink (const char *src, const char *dst)
2233{
2234 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002235 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002236 return error;
2237}
2238
2239Error
2240Host::Readlink (const char *path, char *buf, size_t buf_len)
2241{
2242 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002243 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002244 return error;
2245}
2246
2247Error
2248Host::Unlink (const char *path)
2249{
2250 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002251 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002252 return error;
2253}
2254
Greg Clayton23f8c952014-03-24 23:10:19 +00002255Error
2256Host::RemoveDirectory (const char* path, bool recurse)
2257{
2258 Error error;
2259 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2260 return error;
2261}
2262
Greg Claytonfbb76342013-11-20 21:07:01 +00002263#else
2264
2265Error
2266Host::MakeDirectory (const char* path, uint32_t file_permissions)
2267{
2268 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002269 if (path && path[0])
2270 {
Greg Claytonfb909312013-11-23 01:58:15 +00002271 if (::mkdir(path, file_permissions) != 0)
2272 {
2273 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002274 switch (error.GetError())
2275 {
2276 case ENOENT:
2277 {
2278 // Parent directory doesn't exist, so lets make it if we can
2279 FileSpec spec(path, false);
2280 if (spec.GetDirectory() && spec.GetFilename())
2281 {
2282 // Make the parent directory and try again
2283 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2284 if (error2.Success())
2285 {
2286 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002287 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002288 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002289 else
Greg Claytonfb909312013-11-23 01:58:15 +00002290 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002291 }
2292 }
2293 }
2294 break;
2295 case EEXIST:
2296 {
2297 FileSpec path_spec(path, false);
2298 if (path_spec.IsDirectory())
2299 error.Clear(); // It is a directory and it already exists
2300 }
2301 break;
2302 }
2303 }
Greg Claytonfb909312013-11-23 01:58:15 +00002304 }
2305 else
2306 {
2307 error.SetErrorString("empty path");
2308 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002309 return error;
2310}
Greg Clayton23f8c952014-03-24 23:10:19 +00002311
2312Error
2313Host::RemoveDirectory (const char* path, bool recurse)
2314{
2315 Error error;
2316 if (path && path[0])
2317 {
2318 if (recurse)
2319 {
2320 StreamString command;
2321 command.Printf("rm -rf \"%s\"", path);
2322 int status = ::system(command.GetString().c_str());
2323 if (status != 0)
2324 error.SetError(status, eErrorTypeGeneric);
2325 }
2326 else
2327 {
2328 if (::rmdir(path) != 0)
2329 error.SetErrorToErrno();
2330 }
2331 }
2332 else
2333 {
2334 error.SetErrorString("empty path");
2335 }
2336 return error;
2337}
Greg Claytonfbb76342013-11-20 21:07:01 +00002338
2339Error
2340Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2341{
2342 Error error;
2343 struct stat file_stats;
2344 if (::stat (path, &file_stats) == 0)
2345 {
2346 // The bits in "st_mode" currently match the definitions
2347 // for the file mode bits in unix.
2348 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2349 }
2350 else
2351 {
2352 error.SetErrorToErrno();
2353 }
2354 return error;
2355}
2356
2357Error
2358Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2359{
2360 Error error;
2361 if (::chmod(path, file_permissions) != 0)
2362 error.SetErrorToErrno();
2363 return error;
2364}
2365
2366Error
2367Host::Symlink (const char *src, const char *dst)
2368{
2369 Error error;
2370 if (::symlink(dst, src) == -1)
2371 error.SetErrorToErrno();
2372 return error;
2373}
2374
2375Error
2376Host::Unlink (const char *path)
2377{
2378 Error error;
2379 if (::unlink(path) == -1)
2380 error.SetErrorToErrno();
2381 return error;
2382}
2383
2384Error
2385Host::Readlink (const char *path, char *buf, size_t buf_len)
2386{
2387 Error error;
2388 ssize_t count = ::readlink(path, buf, buf_len);
2389 if (count < 0)
2390 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002391 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002392 buf[count] = '\0'; // Success
2393 else
2394 error.SetErrorString("'buf' buffer is too small to contain link contents");
2395 return error;
2396}
2397
2398
Greg Clayton2bddd342010-09-07 20:11:56 +00002399#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002400
2401typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2402FDToFileMap& GetFDToFileMap()
2403{
2404 static FDToFileMap g_fd2filemap;
2405 return g_fd2filemap;
2406}
2407
2408lldb::user_id_t
2409Host::OpenFile (const FileSpec& file_spec,
2410 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002411 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002412 Error &error)
2413{
2414 std::string path (file_spec.GetPath());
2415 if (path.empty())
2416 {
2417 error.SetErrorString("empty path");
2418 return UINT64_MAX;
2419 }
2420 FileSP file_sp(new File());
2421 error = file_sp->Open(path.c_str(),flags,mode);
2422 if (file_sp->IsValid() == false)
2423 return UINT64_MAX;
2424 lldb::user_id_t fd = file_sp->GetDescriptor();
2425 GetFDToFileMap()[fd] = file_sp;
2426 return fd;
2427}
2428
2429bool
2430Host::CloseFile (lldb::user_id_t fd, Error &error)
2431{
2432 if (fd == UINT64_MAX)
2433 {
2434 error.SetErrorString ("invalid file descriptor");
2435 return false;
2436 }
2437 FDToFileMap& file_map = GetFDToFileMap();
2438 FDToFileMap::iterator pos = file_map.find(fd);
2439 if (pos == file_map.end())
2440 {
2441 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2442 return false;
2443 }
2444 FileSP file_sp = pos->second;
2445 if (!file_sp)
2446 {
2447 error.SetErrorString ("invalid host backing file");
2448 return false;
2449 }
2450 error = file_sp->Close();
2451 file_map.erase(pos);
2452 return error.Success();
2453}
2454
2455uint64_t
2456Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2457{
2458 if (fd == UINT64_MAX)
2459 {
2460 error.SetErrorString ("invalid file descriptor");
2461 return UINT64_MAX;
2462 }
2463 FDToFileMap& file_map = GetFDToFileMap();
2464 FDToFileMap::iterator pos = file_map.find(fd);
2465 if (pos == file_map.end())
2466 {
2467 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2468 return false;
2469 }
2470 FileSP file_sp = pos->second;
2471 if (!file_sp)
2472 {
2473 error.SetErrorString ("invalid host backing file");
2474 return UINT64_MAX;
2475 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002476 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2477 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002478 return UINT64_MAX;
2479 size_t bytes_written = src_len;
2480 error = file_sp->Write(src, bytes_written);
2481 if (error.Fail())
2482 return UINT64_MAX;
2483 return bytes_written;
2484}
2485
2486uint64_t
2487Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2488{
2489 if (fd == UINT64_MAX)
2490 {
2491 error.SetErrorString ("invalid file descriptor");
2492 return UINT64_MAX;
2493 }
2494 FDToFileMap& file_map = GetFDToFileMap();
2495 FDToFileMap::iterator pos = file_map.find(fd);
2496 if (pos == file_map.end())
2497 {
2498 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2499 return false;
2500 }
2501 FileSP file_sp = pos->second;
2502 if (!file_sp)
2503 {
2504 error.SetErrorString ("invalid host backing file");
2505 return UINT64_MAX;
2506 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002507 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2508 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002509 return UINT64_MAX;
2510 size_t bytes_read = dst_len;
2511 error = file_sp->Read(dst ,bytes_read);
2512 if (error.Fail())
2513 return UINT64_MAX;
2514 return bytes_read;
2515}
2516
2517lldb::user_id_t
2518Host::GetFileSize (const FileSpec& file_spec)
2519{
2520 return file_spec.GetByteSize();
2521}
2522
2523bool
2524Host::GetFileExists (const FileSpec& file_spec)
2525{
2526 return file_spec.Exists();
2527}
2528
2529bool
2530Host::CalculateMD5 (const FileSpec& file_spec,
2531 uint64_t &low,
2532 uint64_t &high)
2533{
2534#if defined (__APPLE__)
2535 StreamString md5_cmd_line;
2536 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2537 std::string hash_string;
2538 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2539 if (err.Fail())
2540 return false;
2541 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2542 // if the output is any other length it is probably wrong
2543 if (hash_string.size() != 32)
2544 return false;
2545 std::string part1(hash_string,0,16);
2546 std::string part2(hash_string,16);
2547 const char* part1_cstr = part1.c_str();
2548 const char* part2_cstr = part2.c_str();
2549 high = ::strtoull(part1_cstr, NULL, 16);
2550 low = ::strtoull(part2_cstr, NULL, 16);
2551 return true;
2552#else
2553 // your own MD5 implementation here
2554 return false;
2555#endif
2556}