blob: c469ead2be6dbfb97689554abc7440daf49de931 [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];
1183 char resolved_path[PATH_MAX];
1184 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1185
1186 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1187 if (framework_pos)
1188 {
1189 framework_pos += strlen("LLDB.framework");
1190 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1191 }
1192 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1193 g_lldb_headers_dir.SetCString(resolved_path);
1194 }
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];
1278 char resolved_path[PATH_MAX];
1279 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1280
1281 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1282 if (framework_pos)
1283 {
1284 framework_pos += strlen("LLDB.framework");
1285 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001286 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1287 g_lldb_system_plugin_dir.SetCString(resolved_path);
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 {
1322 char user_plugin_path[PATH_MAX];
1323 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1324 user_plugin_path,
1325 sizeof(user_plugin_path)))
1326 {
1327 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1328 }
1329 }
1330 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001331 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001332#elif defined (__linux__)
1333 static ConstString g_lldb_user_plugin_dir;
1334 if (!g_lldb_user_plugin_dir)
1335 {
1336 // XDG Base Directory Specification
1337 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1338 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1339 FileSpec lldb_file_spec;
1340 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1341 if (xdg_data_home && xdg_data_home[0])
1342 {
1343 std::string user_plugin_dir (xdg_data_home);
1344 user_plugin_dir += "/lldb";
1345 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1346 }
1347 else
1348 {
1349 const char *home_dir = getenv("HOME");
1350 if (home_dir && home_dir[0])
1351 {
1352 std::string user_plugin_dir (home_dir);
1353 user_plugin_dir += "/.local/share/lldb";
1354 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1355 }
1356 }
1357
1358 if (lldb_file_spec.Exists())
1359 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001360 if (log)
1361 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001362 }
1363 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001364 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001365#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001366 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001367 return false;
1368 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001369
1370 case ePathTypeLLDBTempSystemDir:
1371 {
1372 static ConstString g_lldb_tmp_dir;
1373 if (!g_lldb_tmp_dir)
1374 {
1375 const char *tmpdir_cstr = getenv("TMPDIR");
1376 if (tmpdir_cstr == NULL)
1377 {
1378 tmpdir_cstr = getenv("TMP");
1379 if (tmpdir_cstr == NULL)
1380 tmpdir_cstr = getenv("TEMP");
1381 }
1382 if (tmpdir_cstr)
1383 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001384 StreamString pid_tmpdir;
1385 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1386 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1387 {
1388 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1389 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1390 {
1391 // Make an atexit handler to clean up the process specify LLDB temp dir
1392 // and all of its contents.
1393 ::atexit (CleanupProcessSpecificLLDBTempDir);
1394 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1395 if (log)
1396 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1397
1398 }
1399 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001400 }
1401 }
1402 file_spec.GetDirectory() = g_lldb_tmp_dir;
1403 return (bool)file_spec.GetDirectory();
1404 }
Greg Claytondd36def2010-10-17 22:03:32 +00001405 }
1406
1407 return false;
1408}
1409
Greg Clayton1cb64962011-03-24 04:28:38 +00001410
1411bool
1412Host::GetHostname (std::string &s)
1413{
1414 char hostname[PATH_MAX];
1415 hostname[sizeof(hostname) - 1] = '\0';
1416 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1417 {
1418 struct hostent* h = ::gethostbyname (hostname);
1419 if (h)
1420 s.assign (h->h_name);
1421 else
1422 s.assign (hostname);
1423 return true;
1424 }
1425 return false;
1426}
1427
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001428#ifndef _WIN32
1429
Greg Clayton32e0a752011-03-30 18:16:51 +00001430const char *
1431Host::GetUserName (uint32_t uid, std::string &user_name)
1432{
1433 struct passwd user_info;
1434 struct passwd *user_info_ptr = &user_info;
1435 char user_buffer[PATH_MAX];
1436 size_t user_buffer_size = sizeof(user_buffer);
1437 if (::getpwuid_r (uid,
1438 &user_info,
1439 user_buffer,
1440 user_buffer_size,
1441 &user_info_ptr) == 0)
1442 {
1443 if (user_info_ptr)
1444 {
1445 user_name.assign (user_info_ptr->pw_name);
1446 return user_name.c_str();
1447 }
1448 }
1449 user_name.clear();
1450 return NULL;
1451}
1452
1453const char *
1454Host::GetGroupName (uint32_t gid, std::string &group_name)
1455{
1456 char group_buffer[PATH_MAX];
1457 size_t group_buffer_size = sizeof(group_buffer);
1458 struct group group_info;
1459 struct group *group_info_ptr = &group_info;
1460 // Try the threadsafe version first
1461 if (::getgrgid_r (gid,
1462 &group_info,
1463 group_buffer,
1464 group_buffer_size,
1465 &group_info_ptr) == 0)
1466 {
1467 if (group_info_ptr)
1468 {
1469 group_name.assign (group_info_ptr->gr_name);
1470 return group_name.c_str();
1471 }
1472 }
1473 else
1474 {
1475 // The threadsafe version isn't currently working
1476 // for me on darwin, but the non-threadsafe version
1477 // is, so I am calling it below.
1478 group_info_ptr = ::getgrgid (gid);
1479 if (group_info_ptr)
1480 {
1481 group_name.assign (group_info_ptr->gr_name);
1482 return group_name.c_str();
1483 }
1484 }
1485 group_name.clear();
1486 return NULL;
1487}
1488
Han Ming Ong84647042012-02-25 01:07:38 +00001489uint32_t
1490Host::GetUserID ()
1491{
1492 return getuid();
1493}
1494
1495uint32_t
1496Host::GetGroupID ()
1497{
1498 return getgid();
1499}
1500
1501uint32_t
1502Host::GetEffectiveUserID ()
1503{
1504 return geteuid();
1505}
1506
1507uint32_t
1508Host::GetEffectiveGroupID ()
1509{
1510 return getegid();
1511}
1512
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001513#endif
1514
1515#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1516bool
1517Host::GetOSBuildString (std::string &s)
1518{
1519 s.clear();
1520 return false;
1521}
1522
1523bool
1524Host::GetOSKernelDescription (std::string &s)
1525{
1526 s.clear();
1527 return false;
1528}
1529#endif
1530
Zachary Turner310035a2014-07-08 04:52:15 +00001531#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1532 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001533uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001534Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001535{
1536 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001537 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001538}
1539
Greg Claytone996fd32011-03-08 22:40:15 +00001540bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001541Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001542{
Greg Claytone996fd32011-03-08 22:40:15 +00001543 process_info.Clear();
1544 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001545}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001546#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001547
Matt Kopec085d6ce2013-05-31 22:00:07 +00001548#if !defined(__linux__)
1549bool
1550Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1551{
1552 return false;
1553}
1554#endif
1555
Sean Callananc0a6e062011-10-27 21:22:25 +00001556lldb::TargetSP
1557Host::GetDummyTarget (lldb_private::Debugger &debugger)
1558{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001559 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001560
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001561 // FIXME: Maybe the dummy target should be per-Debugger
1562 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1563 {
1564 ArchSpec arch(Target::GetDefaultArchitecture());
1565 if (!arch.IsValid())
1566 arch = Host::GetArchitecture ();
1567 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001568 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001569 arch.GetTriple().getTriple().c_str(),
1570 false,
1571 NULL,
1572 g_dummy_target_sp);
1573 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001574
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001575 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001576}
1577
Greg Claytond1cf11a2012-04-14 01:42:46 +00001578struct ShellInfo
1579{
1580 ShellInfo () :
1581 process_reaped (false),
1582 can_delete (false),
1583 pid (LLDB_INVALID_PROCESS_ID),
1584 signo(-1),
1585 status(-1)
1586 {
1587 }
1588
1589 lldb_private::Predicate<bool> process_reaped;
1590 lldb_private::Predicate<bool> can_delete;
1591 lldb::pid_t pid;
1592 int signo;
1593 int status;
1594};
1595
1596static bool
1597MonitorShellCommand (void *callback_baton,
1598 lldb::pid_t pid,
1599 bool exited, // True if the process did exit
1600 int signo, // Zero for no signal
1601 int status) // Exit value of process if signal is zero
1602{
1603 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1604 shell_info->pid = pid;
1605 shell_info->signo = signo;
1606 shell_info->status = status;
1607 // Let the thread running Host::RunShellCommand() know that the process
1608 // exited and that ShellInfo has been filled in by broadcasting to it
1609 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1610 // Now wait for a handshake back from that thread running Host::RunShellCommand
1611 // so we know that we can delete shell_info_ptr
1612 shell_info->can_delete.WaitForValueEqualTo(true);
1613 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1614 usleep(1000);
1615 // Now delete the shell info that was passed into this function
1616 delete shell_info;
1617 return true;
1618}
1619
1620Error
1621Host::RunShellCommand (const char *command,
1622 const char *working_dir,
1623 int *status_ptr,
1624 int *signo_ptr,
1625 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001626 uint32_t timeout_sec,
1627 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001628{
1629 Error error;
1630 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001631 if (shell && shell[0])
1632 {
1633 // Run the command in a shell
1634 launch_info.SetShell(shell);
1635 launch_info.GetArguments().AppendArgument(command);
1636 const bool localhost = true;
1637 const bool will_debug = false;
1638 const bool first_arg_is_full_shell_command = true;
1639 launch_info.ConvertArgumentsForLaunchingInShell (error,
1640 localhost,
1641 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001642 first_arg_is_full_shell_command,
1643 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001644 }
1645 else
1646 {
1647 // No shell, just run it
1648 Args args (command);
1649 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001650 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001651 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001652
1653 if (working_dir)
1654 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001655 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001656 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001657
Greg Claytond1cf11a2012-04-14 01:42:46 +00001658 if (command_output_ptr)
1659 {
1660 // Create a temporary file to get the stdout/stderr and redirect the
1661 // output of the command into this file. We will later read this file
1662 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001663 FileSpec tmpdir_file_spec;
1664 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1665 {
1666 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1667 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1668 }
1669 else
1670 {
1671 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1672 }
1673
1674 output_file_path = ::mktemp(output_file_path_buffer);
1675 }
1676
1677 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1678 if (output_file_path)
1679 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001680 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001681 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001682 }
1683 else
1684 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001685 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1686 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1687 }
1688
1689 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001690 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001691
1692 const bool monitor_signals = false;
1693 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1694
1695 error = LaunchProcess (launch_info);
1696 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001697
1698 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1699 error.SetErrorString("failed to get process ID");
1700
1701 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001702 {
1703 // The process successfully launched, so we can defer ownership of
1704 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001705 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001706 // doesn't need to delete the ShellInfo anymore.
1707 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001708 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001709 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001710 if (timeout_sec > 0) {
1711 timeout_time.OffsetWithSeconds(timeout_sec);
1712 timeout_ptr = &timeout_time;
1713 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001714 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001715 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001716 if (timed_out)
1717 {
1718 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001719
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001720 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001721 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001722 // Wait for the monitor callback to get the message
1723 timeout_time = TimeValue::Now();
1724 timeout_time.OffsetWithSeconds(1);
1725 timed_out = false;
1726 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1727 }
1728 else
1729 {
1730 if (status_ptr)
1731 *status_ptr = shell_info->status;
1732
1733 if (signo_ptr)
1734 *signo_ptr = shell_info->signo;
1735
1736 if (command_output_ptr)
1737 {
1738 command_output_ptr->clear();
1739 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1740 uint64_t file_size = file_spec.GetByteSize();
1741 if (file_size > 0)
1742 {
1743 if (file_size > command_output_ptr->max_size())
1744 {
1745 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1746 }
1747 else
1748 {
1749 command_output_ptr->resize(file_size);
1750 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1751 }
1752 }
1753 }
1754 }
1755 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1756 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001757
1758 if (output_file_path)
1759 ::unlink (output_file_path);
1760 // Handshake with the monitor thread, or just let it know in advance that
1761 // it can delete "shell_info" in case we timed out and were not able to kill
1762 // the process...
1763 return error;
1764}
1765
Daniel Malea4244cbd2013-08-27 20:58:59 +00001766
Todd Fiala76747122014-01-23 00:52:28 +00001767// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1768// systems
1769
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001770#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001771
1772// this method needs to be visible to macosx/Host.cpp and
1773// common/Host.cpp.
1774
1775short
1776Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1777{
1778 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1779
1780#if defined (__APPLE__)
1781 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1782 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1783
1784 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1785 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1786
1787 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1788 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1789
1790 if (launch_info.GetLaunchInSeparateProcessGroup())
1791 flags |= POSIX_SPAWN_SETPGROUP;
1792
1793#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1794#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1795 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1796 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1797 {
1798 g_use_close_on_exec_flag = eLazyBoolNo;
1799
1800 uint32_t major, minor, update;
1801 if (Host::GetOSVersion(major, minor, update))
1802 {
1803 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1804 if (major > 10 || (major == 10 && minor > 7))
1805 {
1806 // Only enable for 10.8 and later OS versions
1807 g_use_close_on_exec_flag = eLazyBoolYes;
1808 }
1809 }
1810 }
1811#else
1812 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1813#endif
1814 // Close all files exception those with file actions if this is supported.
1815 if (g_use_close_on_exec_flag == eLazyBoolYes)
1816 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1817#endif
1818#endif // #if defined (__APPLE__)
1819 return flags;
1820}
1821
1822Error
1823Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001824{
1825 Error error;
1826 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1827
Daniel Malea4244cbd2013-08-27 20:58:59 +00001828 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001829 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001830
1831 if (error.Fail() || log)
1832 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001833 if (error.Fail())
1834 return error;
1835
1836 // Make a quick class that will cleanup the posix spawn attributes in case
1837 // we return in the middle of this function.
1838 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1839
1840 sigset_t no_signals;
1841 sigset_t all_signals;
1842 sigemptyset (&no_signals);
1843 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001844 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001845#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001846 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001847#else
1848 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1849#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001850
Todd Fiala76747122014-01-23 00:52:28 +00001851 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001852
1853 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001854 if (error.Fail() || log)
1855 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001856 if (error.Fail())
1857 return error;
1858
Todd Fiala76747122014-01-23 00:52:28 +00001859 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1860 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1861#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001862
1863 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1864 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1865 // to do that job on OSX.
1866
1867 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001868 {
Jim Ingham90331d52014-02-21 01:25:21 +00001869 // We don't need to do this for ARM, and we really shouldn't now that we
1870 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1871 // to set which CPU subtype to launch...
1872 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1873 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1874 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1875 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001876 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1877 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001878 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1879 {
1880 size_t ocount = 0;
1881 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1882 if (error.Fail() || log)
1883 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 +00001884
Jim Ingham90331d52014-02-21 01:25:21 +00001885 if (error.Fail() || ocount != 1)
1886 return error;
1887 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001888 }
1889
Todd Fiala76747122014-01-23 00:52:28 +00001890#endif
1891
1892 const char *tmp_argv[2];
1893 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1894 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1895 if (argv == NULL)
1896 {
1897 // posix_spawn gets very unhappy if it doesn't have at least the program
1898 // name in argv[0]. One of the side affects I have noticed is the environment
1899 // variables don't make it into the child process if "argv == NULL"!!!
1900 tmp_argv[0] = exe_path;
1901 tmp_argv[1] = NULL;
1902 argv = (char * const*)tmp_argv;
1903 }
1904
1905#if !defined (__APPLE__)
1906 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001907 char current_dir[PATH_MAX];
1908 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001909#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001910
1911 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001912 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001913 {
Todd Fiala76747122014-01-23 00:52:28 +00001914#if defined (__APPLE__)
1915 // Set the working directory on this thread only
1916 if (__pthread_chdir (working_dir) < 0) {
1917 if (errno == ENOENT) {
1918 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1919 } else if (errno == ENOTDIR) {
1920 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1921 } else {
1922 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1923 }
1924 return error;
1925 }
1926#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001927 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1928 {
1929 error.SetError(errno, eErrorTypePOSIX);
1930 error.LogIfError(log, "unable to save the current directory");
1931 return error;
1932 }
1933
1934 if (::chdir(working_dir) == -1)
1935 {
1936 error.SetError(errno, eErrorTypePOSIX);
1937 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1938 return error;
1939 }
Todd Fiala76747122014-01-23 00:52:28 +00001940#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001941 }
1942
Todd Fiala76747122014-01-23 00:52:28 +00001943 const size_t num_file_actions = launch_info.GetNumFileActions ();
1944 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001945 {
Todd Fiala76747122014-01-23 00:52:28 +00001946 posix_spawn_file_actions_t file_actions;
1947 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1948 if (error.Fail() || log)
1949 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1950 if (error.Fail())
1951 return error;
1952
1953 // Make a quick class that will cleanup the posix spawn attributes in case
1954 // we return in the middle of this function.
1955 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1956
1957 for (size_t i=0; i<num_file_actions; ++i)
1958 {
1959 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1960 if (launch_file_action)
1961 {
1962 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1963 launch_file_action,
1964 log,
1965 error))
1966 return error;
1967 }
1968 }
1969
1970 error.SetError (::posix_spawnp (&pid,
1971 exe_path,
1972 &file_actions,
1973 &attr,
1974 argv,
1975 envp),
1976 eErrorTypePOSIX);
1977
1978 if (error.Fail() || log)
1979 {
1980 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 +00001981 pid, exe_path, static_cast<void*>(&file_actions),
1982 static_cast<void*>(&attr),
1983 reinterpret_cast<const void*>(argv),
1984 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001985 if (log)
1986 {
1987 for (int ii=0; argv[ii]; ++ii)
1988 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1989 }
1990 }
1991
1992 }
1993 else
1994 {
1995 error.SetError (::posix_spawnp (&pid,
1996 exe_path,
1997 NULL,
1998 &attr,
1999 argv,
2000 envp),
2001 eErrorTypePOSIX);
2002
2003 if (error.Fail() || log)
2004 {
2005 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 +00002006 pid, exe_path, static_cast<void*>(&attr),
2007 reinterpret_cast<const void*>(argv),
2008 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00002009 if (log)
2010 {
2011 for (int ii=0; argv[ii]; ++ii)
2012 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
2013 }
2014 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00002015 }
2016
Todd Fiala76747122014-01-23 00:52:28 +00002017 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002018 {
Todd Fiala76747122014-01-23 00:52:28 +00002019#if defined (__APPLE__)
2020 // No more thread specific current working directory
2021 __pthread_fchdir (-1);
2022#else
2023 if (::chdir(current_dir) == -1 && error.Success())
2024 {
2025 error.SetError(errno, eErrorTypePOSIX);
2026 error.LogIfError(log, "unable to change current directory back to %s",
2027 current_dir);
2028 }
2029#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00002030 }
2031
2032 return error;
2033}
2034
Todd Fiala76747122014-01-23 00:52:28 +00002035#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2036
2037
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002038#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2039// The functions below implement process launching via posix_spawn() for Linux,
2040// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00002041
2042Error
2043Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2044{
2045 Error error;
2046 char exe_path[PATH_MAX];
2047
2048 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2049
2050 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2051
2052 FileSpec exe_spec(launch_info.GetExecutableFile());
2053
2054 FileSpec::FileType file_type = exe_spec.GetFileType();
2055 if (file_type != FileSpec::eFileTypeRegular)
2056 {
2057 lldb::ModuleSP exe_module_sp;
2058 error = host_platform_sp->ResolveExecutable (exe_spec,
2059 arch_spec,
2060 exe_module_sp,
2061 NULL);
2062
2063 if (error.Fail())
2064 return error;
2065
2066 if (exe_module_sp)
2067 exe_spec = exe_module_sp->GetFileSpec();
2068 }
2069
2070 if (exe_spec.Exists())
2071 {
2072 exe_spec.GetPath (exe_path, sizeof(exe_path));
2073 }
2074 else
2075 {
2076 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2077 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2078 return error;
2079 }
2080
2081 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2082
2083 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2084
2085 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2086
2087 if (pid != LLDB_INVALID_PROCESS_ID)
2088 {
2089 // If all went well, then set the process ID into the launch info
2090 launch_info.SetProcessID(pid);
2091
Todd Fiala76747122014-01-23 00:52:28 +00002092 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2093
Daniel Malea4244cbd2013-08-27 20:58:59 +00002094 // Make sure we reap any processes we spawn or we will have zombies.
2095 if (!launch_info.MonitorProcess())
2096 {
2097 const bool monitor_signals = false;
2098 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2099 NULL,
2100 pid,
2101 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002102 if (log)
2103 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2104 }
2105 else
2106 {
2107 if (log)
2108 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002109 }
2110 }
2111 else
2112 {
2113 // Invalid process ID, something didn't go well
2114 if (error.Success())
2115 error.SetErrorString ("process launch failed for unknown reasons");
2116 }
2117 return error;
2118}
2119
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002120#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002121
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002122#ifndef _WIN32
2123
2124size_t
2125Host::GetPageSize()
2126{
2127 return ::getpagesize();
2128}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002129
Greg Claytone3e3fee2013-02-17 20:46:30 +00002130uint32_t
2131Host::GetNumberCPUS ()
2132{
2133 static uint32_t g_num_cores = UINT32_MAX;
2134 if (g_num_cores == UINT32_MAX)
2135 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002136#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002137
2138 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002139
Greg Claytone3e3fee2013-02-17 20:46:30 +00002140#else
2141
2142 // Assume POSIX support if a host specific case has not been supplied above
2143 g_num_cores = 0;
2144 int num_cores = 0;
2145 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002146#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002147 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002148#else
2149 int mib[] = { CTL_HW, HW_NCPU };
2150#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002151
2152 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002153 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 +00002154 {
2155 g_num_cores = num_cores;
2156 }
2157 else
2158 {
2159 mib[1] = HW_NCPU;
2160 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002161 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 +00002162 {
2163 if (num_cores > 0)
2164 g_num_cores = num_cores;
2165 }
2166 }
2167#endif
2168 }
2169 return g_num_cores;
2170}
2171
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002172void
2173Host::Kill(lldb::pid_t pid, int signo)
2174{
2175 ::kill(pid, signo);
2176}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002177
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002178#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002179
Johnny Chen8f3d8382011-08-02 20:52:42 +00002180#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002181bool
Greg Clayton3b147632010-12-18 01:54:34 +00002182Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002183{
2184 return false;
2185}
Greg Claytondd36def2010-10-17 22:03:32 +00002186
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002187void
2188Host::SetCrashDescriptionWithFormat (const char *format, ...)
2189{
2190}
2191
2192void
2193Host::SetCrashDescription (const char *description)
2194{
2195}
Greg Claytondd36def2010-10-17 22:03:32 +00002196
2197lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002198Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002199{
2200 return LLDB_INVALID_PROCESS_ID;
2201}
2202
Greg Claytonfbb76342013-11-20 21:07:01 +00002203#endif
2204
2205
2206#ifdef LLDB_DISABLE_POSIX
2207
2208Error
2209Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002210{
Greg Claytonfbb76342013-11-20 21:07:01 +00002211 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002212 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002213 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002214}
Greg Claytonfbb76342013-11-20 21:07:01 +00002215
2216Error
2217Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2218{
2219 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002220 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002221 return error;
2222}
2223
2224Error
2225Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2226{
2227 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002228 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002229 return error;
2230}
2231
2232Error
2233Host::Symlink (const char *src, const char *dst)
2234{
2235 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002236 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002237 return error;
2238}
2239
2240Error
2241Host::Readlink (const char *path, char *buf, size_t buf_len)
2242{
2243 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002244 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002245 return error;
2246}
2247
2248Error
2249Host::Unlink (const char *path)
2250{
2251 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002252 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002253 return error;
2254}
2255
Greg Clayton23f8c952014-03-24 23:10:19 +00002256Error
2257Host::RemoveDirectory (const char* path, bool recurse)
2258{
2259 Error error;
2260 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2261 return error;
2262}
2263
Greg Claytonfbb76342013-11-20 21:07:01 +00002264#else
2265
2266Error
2267Host::MakeDirectory (const char* path, uint32_t file_permissions)
2268{
2269 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002270 if (path && path[0])
2271 {
Greg Claytonfb909312013-11-23 01:58:15 +00002272 if (::mkdir(path, file_permissions) != 0)
2273 {
2274 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002275 switch (error.GetError())
2276 {
2277 case ENOENT:
2278 {
2279 // Parent directory doesn't exist, so lets make it if we can
2280 FileSpec spec(path, false);
2281 if (spec.GetDirectory() && spec.GetFilename())
2282 {
2283 // Make the parent directory and try again
2284 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2285 if (error2.Success())
2286 {
2287 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002288 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002289 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002290 else
Greg Claytonfb909312013-11-23 01:58:15 +00002291 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002292 }
2293 }
2294 }
2295 break;
2296 case EEXIST:
2297 {
2298 FileSpec path_spec(path, false);
2299 if (path_spec.IsDirectory())
2300 error.Clear(); // It is a directory and it already exists
2301 }
2302 break;
2303 }
2304 }
Greg Claytonfb909312013-11-23 01:58:15 +00002305 }
2306 else
2307 {
2308 error.SetErrorString("empty path");
2309 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002310 return error;
2311}
Greg Clayton23f8c952014-03-24 23:10:19 +00002312
2313Error
2314Host::RemoveDirectory (const char* path, bool recurse)
2315{
2316 Error error;
2317 if (path && path[0])
2318 {
2319 if (recurse)
2320 {
2321 StreamString command;
2322 command.Printf("rm -rf \"%s\"", path);
2323 int status = ::system(command.GetString().c_str());
2324 if (status != 0)
2325 error.SetError(status, eErrorTypeGeneric);
2326 }
2327 else
2328 {
2329 if (::rmdir(path) != 0)
2330 error.SetErrorToErrno();
2331 }
2332 }
2333 else
2334 {
2335 error.SetErrorString("empty path");
2336 }
2337 return error;
2338}
Greg Claytonfbb76342013-11-20 21:07:01 +00002339
2340Error
2341Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2342{
2343 Error error;
2344 struct stat file_stats;
2345 if (::stat (path, &file_stats) == 0)
2346 {
2347 // The bits in "st_mode" currently match the definitions
2348 // for the file mode bits in unix.
2349 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2350 }
2351 else
2352 {
2353 error.SetErrorToErrno();
2354 }
2355 return error;
2356}
2357
2358Error
2359Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2360{
2361 Error error;
2362 if (::chmod(path, file_permissions) != 0)
2363 error.SetErrorToErrno();
2364 return error;
2365}
2366
2367Error
2368Host::Symlink (const char *src, const char *dst)
2369{
2370 Error error;
2371 if (::symlink(dst, src) == -1)
2372 error.SetErrorToErrno();
2373 return error;
2374}
2375
2376Error
2377Host::Unlink (const char *path)
2378{
2379 Error error;
2380 if (::unlink(path) == -1)
2381 error.SetErrorToErrno();
2382 return error;
2383}
2384
2385Error
2386Host::Readlink (const char *path, char *buf, size_t buf_len)
2387{
2388 Error error;
2389 ssize_t count = ::readlink(path, buf, buf_len);
2390 if (count < 0)
2391 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002392 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002393 buf[count] = '\0'; // Success
2394 else
2395 error.SetErrorString("'buf' buffer is too small to contain link contents");
2396 return error;
2397}
2398
2399
Greg Clayton2bddd342010-09-07 20:11:56 +00002400#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002401
2402typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2403FDToFileMap& GetFDToFileMap()
2404{
2405 static FDToFileMap g_fd2filemap;
2406 return g_fd2filemap;
2407}
2408
2409lldb::user_id_t
2410Host::OpenFile (const FileSpec& file_spec,
2411 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002412 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002413 Error &error)
2414{
2415 std::string path (file_spec.GetPath());
2416 if (path.empty())
2417 {
2418 error.SetErrorString("empty path");
2419 return UINT64_MAX;
2420 }
2421 FileSP file_sp(new File());
2422 error = file_sp->Open(path.c_str(),flags,mode);
2423 if (file_sp->IsValid() == false)
2424 return UINT64_MAX;
2425 lldb::user_id_t fd = file_sp->GetDescriptor();
2426 GetFDToFileMap()[fd] = file_sp;
2427 return fd;
2428}
2429
2430bool
2431Host::CloseFile (lldb::user_id_t fd, Error &error)
2432{
2433 if (fd == UINT64_MAX)
2434 {
2435 error.SetErrorString ("invalid file descriptor");
2436 return false;
2437 }
2438 FDToFileMap& file_map = GetFDToFileMap();
2439 FDToFileMap::iterator pos = file_map.find(fd);
2440 if (pos == file_map.end())
2441 {
2442 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2443 return false;
2444 }
2445 FileSP file_sp = pos->second;
2446 if (!file_sp)
2447 {
2448 error.SetErrorString ("invalid host backing file");
2449 return false;
2450 }
2451 error = file_sp->Close();
2452 file_map.erase(pos);
2453 return error.Success();
2454}
2455
2456uint64_t
2457Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2458{
2459 if (fd == UINT64_MAX)
2460 {
2461 error.SetErrorString ("invalid file descriptor");
2462 return UINT64_MAX;
2463 }
2464 FDToFileMap& file_map = GetFDToFileMap();
2465 FDToFileMap::iterator pos = file_map.find(fd);
2466 if (pos == file_map.end())
2467 {
2468 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2469 return false;
2470 }
2471 FileSP file_sp = pos->second;
2472 if (!file_sp)
2473 {
2474 error.SetErrorString ("invalid host backing file");
2475 return UINT64_MAX;
2476 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002477 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2478 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002479 return UINT64_MAX;
2480 size_t bytes_written = src_len;
2481 error = file_sp->Write(src, bytes_written);
2482 if (error.Fail())
2483 return UINT64_MAX;
2484 return bytes_written;
2485}
2486
2487uint64_t
2488Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2489{
2490 if (fd == UINT64_MAX)
2491 {
2492 error.SetErrorString ("invalid file descriptor");
2493 return UINT64_MAX;
2494 }
2495 FDToFileMap& file_map = GetFDToFileMap();
2496 FDToFileMap::iterator pos = file_map.find(fd);
2497 if (pos == file_map.end())
2498 {
2499 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2500 return false;
2501 }
2502 FileSP file_sp = pos->second;
2503 if (!file_sp)
2504 {
2505 error.SetErrorString ("invalid host backing file");
2506 return UINT64_MAX;
2507 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002508 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2509 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002510 return UINT64_MAX;
2511 size_t bytes_read = dst_len;
2512 error = file_sp->Read(dst ,bytes_read);
2513 if (error.Fail())
2514 return UINT64_MAX;
2515 return bytes_read;
2516}
2517
2518lldb::user_id_t
2519Host::GetFileSize (const FileSpec& file_spec)
2520{
2521 return file_spec.GetByteSize();
2522}
2523
2524bool
2525Host::GetFileExists (const FileSpec& file_spec)
2526{
2527 return file_spec.Exists();
2528}
2529
2530bool
2531Host::CalculateMD5 (const FileSpec& file_spec,
2532 uint64_t &low,
2533 uint64_t &high)
2534{
2535#if defined (__APPLE__)
2536 StreamString md5_cmd_line;
2537 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2538 std::string hash_string;
2539 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2540 if (err.Fail())
2541 return false;
2542 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2543 // if the output is any other length it is probably wrong
2544 if (hash_string.size() != 32)
2545 return false;
2546 std::string part1(hash_string,0,16);
2547 std::string part2(hash_string,16);
2548 const char* part1_cstr = part1.c_str();
2549 const char* part2_cstr = part2.c_str();
2550 high = ::strtoull(part1_cstr, NULL, 16);
2551 low = ::strtoull(part2_cstr, NULL, 16);
2552 return true;
2553#else
2554 // your own MD5 implementation here
2555 return false;
2556#endif
2557}