blob: 9e5e4cbdb04aa3d94793e6e4faf04692a83471d9 [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>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#include <sys/types.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifdef _WIN32
17#include "lldb/Host/windows/windows.h"
18#include <winsock2.h>
19#include <WS2tcpip.h>
20#else
Deepak Panickalb36da432014-01-13 14:55:15 +000021#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000022#include <dlfcn.h>
23#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000024#include <netdb.h>
25#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000026#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000027#endif
28
29#if !defined (__GNU__) && !defined (_WIN32)
30// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000031#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000032#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000033
34#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000035#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000036#include <mach/mach_init.h>
37#include <mach-o/dyld.h>
Jim Ingham1a7ee702013-11-22 00:51:36 +000038#include <AvailabilityMacros.h>
Ed Maste8b006c62013-06-25 18:58:11 +000039#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000040
Todd Fiala76747122014-01-23 00:52:28 +000041#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000042#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000043#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000044#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000045#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000046
Ed Maste8b006c62013-06-25 18:58:11 +000047#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000048#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#endif
50
Greg Clayton2bddd342010-09-07 20:11:56 +000051#include "lldb/Host/Host.h"
52#include "lldb/Core/ArchSpec.h"
53#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000054#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000055#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000057#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000059#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000060#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000061#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000062#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000064#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000065#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000066#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000067
Daniel Maleafa7425d2013-08-06 21:40:08 +000068#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000069#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000070#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000071
Todd Fiala76747122014-01-23 00:52:28 +000072#if defined (__APPLE__)
73#ifndef _POSIX_SPAWN_DISABLE_ASLR
74#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
75#endif
76
77extern "C"
78{
79 int __pthread_chdir(const char *path);
80 int __pthread_fchdir (int fildes);
81}
82
83#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000084
Greg Clayton2bddd342010-09-07 20:11:56 +000085using namespace lldb;
86using namespace lldb_private;
87
Greg Claytone4e45922011-11-16 05:37:56 +000088
Virgile Bellob2f1fb22013-08-23 12:44:05 +000089#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000090struct MonitorInfo
91{
92 lldb::pid_t pid; // The process ID to monitor
93 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
94 void *callback_baton; // The callback baton for the callback function
95 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
96};
97
Virgile Bellob2f1fb22013-08-23 12:44:05 +000098static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000099MonitorChildProcessThreadFunction (void *arg);
100
101lldb::thread_t
102Host::StartMonitoringChildProcess
103(
104 Host::MonitorChildProcessCallback callback,
105 void *callback_baton,
106 lldb::pid_t pid,
107 bool monitor_signals
108)
109{
110 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000111 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000112
Greg Claytone4e45922011-11-16 05:37:56 +0000113 info_ptr->pid = pid;
114 info_ptr->callback = callback;
115 info_ptr->callback_baton = callback_baton;
116 info_ptr->monitor_signals = monitor_signals;
117
118 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000119 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000120 thread = ThreadCreate (thread_name,
121 MonitorChildProcessThreadFunction,
122 info_ptr,
123 NULL);
124
Greg Clayton2bddd342010-09-07 20:11:56 +0000125 return thread;
126}
127
128//------------------------------------------------------------------
129// Scoped class that will disable thread canceling when it is
130// constructed, and exception safely restore the previous value it
131// when it goes out of scope.
132//------------------------------------------------------------------
133class ScopedPThreadCancelDisabler
134{
135public:
136 ScopedPThreadCancelDisabler()
137 {
138 // Disable the ability for this thread to be cancelled
139 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
140 if (err != 0)
141 m_old_state = -1;
142
143 }
144
145 ~ScopedPThreadCancelDisabler()
146 {
147 // Restore the ability for this thread to be cancelled to what it
148 // previously was.
149 if (m_old_state != -1)
150 ::pthread_setcancelstate (m_old_state, 0);
151 }
152private:
153 int m_old_state; // Save the old cancelability state.
154};
155
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000156static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000157MonitorChildProcessThreadFunction (void *arg)
158{
Greg Clayton5160ce52013-03-27 23:08:40 +0000159 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000160 const char *function = __FUNCTION__;
161 if (log)
162 log->Printf ("%s (arg = %p) thread starting...", function, arg);
163
164 MonitorInfo *info = (MonitorInfo *)arg;
165
166 const Host::MonitorChildProcessCallback callback = info->callback;
167 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000168 const bool monitor_signals = info->monitor_signals;
169
Daniel Malea4244cbd2013-08-27 20:58:59 +0000170 assert (info->pid <= UINT32_MAX);
171 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
172
Greg Clayton2bddd342010-09-07 20:11:56 +0000173 delete info;
174
175 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000176#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000177 #define __WALL 0
178#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000179 const int options = __WALL;
180
Greg Clayton2bddd342010-09-07 20:11:56 +0000181 while (1)
182 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000183 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000184 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000185 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000186
187 // Wait for all child processes
188 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000189 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000190 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000191 ::pthread_testcancel ();
192
193 if (wait_pid == -1)
194 {
195 if (errno == EINTR)
196 continue;
197 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000198 {
199 if (log)
200 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000201 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000202 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000203 }
Matt Kopec650648f2013-01-08 16:30:18 +0000204 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000205 {
206 bool exited = false;
207 int signal = 0;
208 int exit_status = 0;
209 const char *status_cstr = NULL;
210 if (WIFSTOPPED(status))
211 {
212 signal = WSTOPSIG(status);
213 status_cstr = "STOPPED";
214 }
215 else if (WIFEXITED(status))
216 {
217 exit_status = WEXITSTATUS(status);
218 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000219 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000220 }
221 else if (WIFSIGNALED(status))
222 {
223 signal = WTERMSIG(status);
224 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000225 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000226 exited = true;
227 exit_status = -1;
228 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000229 }
230 else
231 {
Johnny Chen44805302011-07-19 19:48:13 +0000232 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000233 }
234
235 // Scope for pthread_cancel_disabler
236 {
237 ScopedPThreadCancelDisabler pthread_cancel_disabler;
238
Caroline Tice20ad3c42010-10-29 21:48:37 +0000239 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000240 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000241 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 +0000242 function,
243 wait_pid,
244 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000245 pid,
246 status,
247 status_cstr,
248 signal,
249 exit_status);
250
251 if (exited || (signal != 0 && monitor_signals))
252 {
Greg Claytone4e45922011-11-16 05:37:56 +0000253 bool callback_return = false;
254 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000255 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000256
257 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000258 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000259 {
260 if (log)
261 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000262 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000263 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000264 // If the callback returns true, it means this process should
265 // exit
266 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000267 {
268 if (log)
269 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000270 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000271 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000272 }
273 }
274 }
275 }
276
Caroline Tice20ad3c42010-10-29 21:48:37 +0000277 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000278 if (log)
279 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
280
281 return NULL;
282}
283
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000284#endif // #if !defined (__APPLE__) && !defined (_WIN32)
285
286#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000287
288void
289Host::SystemLog (SystemLogType type, const char *format, va_list args)
290{
291 vfprintf (stderr, format, args);
292}
293
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000294#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000295
Greg Claytone38a5ed2012-01-05 03:57:59 +0000296void
297Host::SystemLog (SystemLogType type, const char *format, ...)
298{
299 va_list args;
300 va_start (args, format);
301 SystemLog (type, format, args);
302 va_end (args);
303}
304
Greg Clayton2bddd342010-09-07 20:11:56 +0000305const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000306Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000307{
Greg Clayton514487e2011-02-15 21:59:32 +0000308 static bool g_supports_32 = false;
309 static bool g_supports_64 = false;
310 static ArchSpec g_host_arch_32;
311 static ArchSpec g_host_arch_64;
312
Greg Clayton2bddd342010-09-07 20:11:56 +0000313#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000314
315 // Apple is different in that it can support both 32 and 64 bit executables
316 // in the same operating system running concurrently. Here we detect the
317 // correct host architectures for both 32 and 64 bit including if 64 bit
318 // executables are supported on the system.
319
320 if (g_supports_32 == false && g_supports_64 == false)
321 {
322 // All apple systems support 32 bit execution.
323 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000324 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000325 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000326 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000327 ArchSpec host_arch;
328 // These will tell us about the kernel architecture, which even on a 64
329 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000330 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
331 {
Greg Clayton514487e2011-02-15 21:59:32 +0000332 len = sizeof (cpusubtype);
333 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
334 cpusubtype = CPU_TYPE_ANY;
335
Greg Clayton2bddd342010-09-07 20:11:56 +0000336 len = sizeof (is_64_bit_capable);
337 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
338 {
339 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000340 g_supports_64 = true;
341 }
342
343 if (is_64_bit_capable)
344 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000345#if defined (__i386__) || defined (__x86_64__)
346 if (cpusubtype == CPU_SUBTYPE_486)
347 cpusubtype = CPU_SUBTYPE_I386_ALL;
348#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000349 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000350 {
Greg Clayton514487e2011-02-15 21:59:32 +0000351 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000352 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
353 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000354 }
355 else
356 {
357 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000358 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000359 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000360 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000361 }
362 }
Greg Clayton514487e2011-02-15 21:59:32 +0000363 else
364 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000365 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000366 g_host_arch_64.Clear();
367 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000368 }
Greg Clayton514487e2011-02-15 21:59:32 +0000369 }
370
371#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000372
Greg Clayton514487e2011-02-15 21:59:32 +0000373 if (g_supports_32 == false && g_supports_64 == false)
374 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000375 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000376
Stephen Wilsonbd588712011-02-24 19:15:09 +0000377 g_host_arch_32.Clear();
378 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000379
Greg Claytonb29e6c62012-10-11 17:38:58 +0000380 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
381 // for the default triple. It's probably an artifact of config.guess.
382 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000383 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000384
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000385 const char* distribution_id = GetDistributionId ().AsCString();
386
Stephen Wilsonbd588712011-02-24 19:15:09 +0000387 switch (triple.getArch())
388 {
389 default:
390 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000391 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000392 g_supports_32 = true;
393 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000394
Stephen Wilsonbd588712011-02-24 19:15:09 +0000395 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000396 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000397 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000398 g_supports_64 = true;
399 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000400 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000401 g_supports_32 = true;
402 break;
403
Stephen Wilsonbd588712011-02-24 19:15:09 +0000404 case llvm::Triple::sparcv9:
405 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000406 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000407 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000408 g_supports_64 = true;
409 break;
410 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000411
412 g_supports_32 = g_host_arch_32.IsValid();
413 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000414 }
Greg Clayton514487e2011-02-15 21:59:32 +0000415
416#endif // #else for #if defined (__APPLE__)
417
418 if (arch_kind == eSystemDefaultArchitecture32)
419 return g_host_arch_32;
420 else if (arch_kind == eSystemDefaultArchitecture64)
421 return g_host_arch_64;
422
423 if (g_supports_64)
424 return g_host_arch_64;
425
426 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000427}
428
429const ConstString &
430Host::GetVendorString()
431{
432 static ConstString g_vendor;
433 if (!g_vendor)
434 {
Greg Clayton950971f2012-05-12 00:01:21 +0000435 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
436 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
437 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000438 }
439 return g_vendor;
440}
441
442const ConstString &
443Host::GetOSString()
444{
445 static ConstString g_os_string;
446 if (!g_os_string)
447 {
Greg Clayton950971f2012-05-12 00:01:21 +0000448 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
449 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
450 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000451 }
452 return g_os_string;
453}
454
455const ConstString &
456Host::GetTargetTriple()
457{
458 static ConstString g_host_triple;
459 if (!(g_host_triple))
460 {
Greg Clayton950971f2012-05-12 00:01:21 +0000461 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
462 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000463 }
464 return g_host_triple;
465}
466
Todd Fialaf3d61de2014-01-17 20:18:59 +0000467// See linux/Host.cpp for Linux-based implementations of this.
468// Add your platform-specific implementation to the appropriate host file.
469#if !defined(__linux__)
470
471const ConstString &
472 Host::GetDistributionId ()
473{
474 static ConstString s_distribution_id;
475 return s_distribution_id;
476}
477
478#endif // #if !defined(__linux__)
479
Greg Clayton2bddd342010-09-07 20:11:56 +0000480lldb::pid_t
481Host::GetCurrentProcessID()
482{
483 return ::getpid();
484}
485
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000486#ifndef _WIN32
487
Greg Clayton2bddd342010-09-07 20:11:56 +0000488lldb::tid_t
489Host::GetCurrentThreadID()
490{
491#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000492 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000493 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
494 // count.
495 thread_port_t thread_self = mach_thread_self();
496 mach_port_deallocate(mach_task_self(), thread_self);
497 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000498#elif defined(__FreeBSD__)
499 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000500#elif defined(__linux__)
501 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000502#else
503 return lldb::tid_t(pthread_self());
504#endif
505}
506
Jim Ingham372787f2012-04-07 00:00:41 +0000507lldb::thread_t
508Host::GetCurrentThread ()
509{
510 return lldb::thread_t(pthread_self());
511}
512
Greg Clayton2bddd342010-09-07 20:11:56 +0000513const char *
514Host::GetSignalAsCString (int signo)
515{
516 switch (signo)
517 {
518 case SIGHUP: return "SIGHUP"; // 1 hangup
519 case SIGINT: return "SIGINT"; // 2 interrupt
520 case SIGQUIT: return "SIGQUIT"; // 3 quit
521 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
522 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
523 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000524#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000525#if !defined(SIGIO) || (SIGPOLL != SIGIO)
526// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
527// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000528 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000529#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000530#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000531#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000532 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000533#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000534 case SIGFPE: return "SIGFPE"; // 8 floating point exception
535 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
536 case SIGBUS: return "SIGBUS"; // 10 bus error
537 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
538 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
539 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
540 case SIGALRM: return "SIGALRM"; // 14 alarm clock
541 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
542 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
543 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
544 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
545 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
546 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
547 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
548 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000549#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000550 case SIGIO: return "SIGIO"; // 23 input/output possible signal
551#endif
552 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
553 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
554 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
555 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000556#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000557 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000558#endif
559#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000560 case SIGINFO: return "SIGINFO"; // 29 information request
561#endif
562 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
563 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
564 default:
565 break;
566 }
567 return NULL;
568}
569
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000570#endif
571
Greg Clayton2bddd342010-09-07 20:11:56 +0000572void
573Host::WillTerminate ()
574{
575}
576
Sylvestre Ledru59405832013-07-01 08:21:36 +0000577#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000578
Greg Clayton2bddd342010-09-07 20:11:56 +0000579void
580Host::ThreadCreated (const char *thread_name)
581{
582}
Greg Claytone5219662010-12-03 06:02:24 +0000583
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000584void
Greg Claytone5219662010-12-03 06:02:24 +0000585Host::Backtrace (Stream &strm, uint32_t max_frames)
586{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000587 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000588}
589
Greg Clayton85851dd2010-12-04 00:10:17 +0000590size_t
591Host::GetEnvironment (StringList &env)
592{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000593 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000594 return 0;
595}
596
Sylvestre Ledru59405832013-07-01 08:21:36 +0000597#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000598
599struct HostThreadCreateInfo
600{
601 std::string thread_name;
602 thread_func_t thread_fptr;
603 thread_arg_t thread_arg;
604
605 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
606 thread_name (name ? name : ""),
607 thread_fptr (fptr),
608 thread_arg (arg)
609 {
610 }
611};
612
613static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000614#ifdef _WIN32
615__stdcall
616#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000617ThreadCreateTrampoline (thread_arg_t arg)
618{
619 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
620 Host::ThreadCreated (info->thread_name.c_str());
621 thread_func_t thread_fptr = info->thread_fptr;
622 thread_arg_t thread_arg = info->thread_arg;
623
Greg Clayton5160ce52013-03-27 23:08:40 +0000624 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000625 if (log)
626 log->Printf("thread created");
627
628 delete info;
629 return thread_fptr (thread_arg);
630}
631
632lldb::thread_t
633Host::ThreadCreate
634(
635 const char *thread_name,
636 thread_func_t thread_fptr,
637 thread_arg_t thread_arg,
638 Error *error
639)
640{
641 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
642
643 // Host::ThreadCreateTrampoline will delete this pointer for us.
644 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
645
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000646#ifdef _WIN32
647 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
648 int err = thread <= 0 ? GetLastError() : 0;
649#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000650 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000651#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000652 if (err == 0)
653 {
654 if (error)
655 error->Clear();
656 return thread;
657 }
658
659 if (error)
660 error->SetError (err, eErrorTypePOSIX);
661
662 return LLDB_INVALID_HOST_THREAD;
663}
664
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000665#ifndef _WIN32
666
Greg Clayton2bddd342010-09-07 20:11:56 +0000667bool
668Host::ThreadCancel (lldb::thread_t thread, Error *error)
669{
670 int err = ::pthread_cancel (thread);
671 if (error)
672 error->SetError(err, eErrorTypePOSIX);
673 return err == 0;
674}
675
676bool
677Host::ThreadDetach (lldb::thread_t thread, Error *error)
678{
679 int err = ::pthread_detach (thread);
680 if (error)
681 error->SetError(err, eErrorTypePOSIX);
682 return err == 0;
683}
684
685bool
686Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
687{
688 int err = ::pthread_join (thread, thread_result_ptr);
689 if (error)
690 error->SetError(err, eErrorTypePOSIX);
691 return err == 0;
692}
693
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000694lldb::thread_key_t
695Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
696{
697 pthread_key_t key;
698 ::pthread_key_create (&key, callback);
699 return key;
700}
701
702void*
703Host::ThreadLocalStorageGet(lldb::thread_key_t key)
704{
705 return ::pthread_getspecific (key);
706}
707
708void
709Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
710{
711 ::pthread_setspecific (key, value);
712}
713
Matt Kopec62502c62013-05-13 19:33:58 +0000714bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000715Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
716{
Greg Clayton85719632013-02-27 22:51:58 +0000717#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000718 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
719 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
720 if (pid == LLDB_INVALID_PROCESS_ID)
721 pid = curr_pid;
722
723 if (tid == LLDB_INVALID_THREAD_ID)
724 tid = curr_tid;
725
Greg Clayton2bddd342010-09-07 20:11:56 +0000726 // Set the pthread name if possible
727 if (pid == curr_pid && tid == curr_tid)
728 {
Matt Kopec62502c62013-05-13 19:33:58 +0000729 if (::pthread_setname_np (name) == 0)
730 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000731 }
Matt Kopec62502c62013-05-13 19:33:58 +0000732 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000733#elif defined (__FreeBSD__)
734 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
735 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
736 if (pid == LLDB_INVALID_PROCESS_ID)
737 pid = curr_pid;
738
739 if (tid == LLDB_INVALID_THREAD_ID)
740 tid = curr_tid;
741
742 // Set the pthread name if possible
743 if (pid == curr_pid && tid == curr_tid)
744 {
Michael Sartainc2052432013-08-01 18:51:08 +0000745 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000746 return true;
747 }
748 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000749#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000750 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
751 if (fn)
752 {
Matt Kopec62502c62013-05-13 19:33:58 +0000753 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
754 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000755 if (pid == LLDB_INVALID_PROCESS_ID)
756 pid = curr_pid;
757
758 if (tid == LLDB_INVALID_THREAD_ID)
759 tid = curr_tid;
760
Michael Sartainc2052432013-08-01 18:51:08 +0000761 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000762 {
Michael Sartainc2052432013-08-01 18:51:08 +0000763 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
764 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
765
766 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000767 return true;
768 }
769 }
770 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000771#else
772 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000773#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000774}
775
Ed Maste02983be2013-07-25 19:10:32 +0000776bool
777Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
778 const char *thread_name, size_t len)
779{
Enrico Granata67530b62014-02-12 03:37:33 +0000780 std::unique_ptr<char[]> namebuf(new char[len+1]);
781
Ed Maste02983be2013-07-25 19:10:32 +0000782 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
783 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
784 // off leads to a lot of similar named threads. Go through the thread name
785 // and search for the last dot and use that.
786 const char *lastdot = ::strrchr (thread_name, '.');
787
788 if (lastdot && lastdot != thread_name)
789 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000790 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000791 namebuf[len] = 0;
792
Enrico Granata67530b62014-02-12 03:37:33 +0000793 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000794 if (namebuflen > 0)
795 {
796 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
797 {
798 // Trim off trailing '(' and '>' characters for a bit more cleanup.
799 namebuflen--;
800 namebuf[namebuflen] = 0;
801 }
Enrico Granata67530b62014-02-12 03:37:33 +0000802 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000803 }
804 return false;
805}
806
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000807#endif
808
Greg Clayton2bddd342010-09-07 20:11:56 +0000809FileSpec
810Host::GetProgramFileSpec ()
811{
812 static FileSpec g_program_filespec;
813 if (!g_program_filespec)
814 {
815#if defined (__APPLE__)
816 char program_fullpath[PATH_MAX];
817 // If DST is NULL, then return the number of bytes needed.
818 uint32_t len = sizeof(program_fullpath);
819 int err = _NSGetExecutablePath (program_fullpath, &len);
820 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000821 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000822 else if (err == -1)
823 {
824 char *large_program_fullpath = (char *)::malloc (len + 1);
825
826 err = _NSGetExecutablePath (large_program_fullpath, &len);
827 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000828 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000829
830 ::free (large_program_fullpath);
831 }
832#elif defined (__linux__)
833 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000834 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
835 if (len > 0) {
836 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000837 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000838 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000839#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000840 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
841 size_t exe_path_size;
842 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
843 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000844 char *exe_path = new char[exe_path_size];
845 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
846 g_program_filespec.SetFile(exe_path, false);
847 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000848 }
849#endif
850 }
851 return g_program_filespec;
852}
853
Greg Clayton2bddd342010-09-07 20:11:56 +0000854#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000855
856bool
857Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
858{
859 bundle.Clear();
860 return false;
861}
862
Greg Clayton2bddd342010-09-07 20:11:56 +0000863bool
Greg Claytondd36def2010-10-17 22:03:32 +0000864Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000865{
Greg Claytondd36def2010-10-17 22:03:32 +0000866 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000867}
868#endif
869
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000870#ifndef _WIN32
871
Greg Clayton45319462011-02-08 00:35:34 +0000872// Opaque info that tracks a dynamic library that was loaded
873struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000874{
Greg Clayton45319462011-02-08 00:35:34 +0000875 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
876 file_spec (fs),
877 open_options (o),
878 handle (h)
879 {
880 }
881
882 const FileSpec file_spec;
883 uint32_t open_options;
884 void * handle;
885};
886
887void *
888Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
889{
Greg Clayton4272cc72011-02-02 02:24:04 +0000890 char path[PATH_MAX];
891 if (file_spec.GetPath(path, sizeof(path)))
892 {
Greg Clayton45319462011-02-08 00:35:34 +0000893 int mode = 0;
894
895 if (options & eDynamicLibraryOpenOptionLazy)
896 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000897 else
898 mode |= RTLD_NOW;
899
Greg Clayton45319462011-02-08 00:35:34 +0000900
901 if (options & eDynamicLibraryOpenOptionLocal)
902 mode |= RTLD_LOCAL;
903 else
904 mode |= RTLD_GLOBAL;
905
906#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
907 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
908 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000909#endif
Greg Clayton45319462011-02-08 00:35:34 +0000910
911 void * opaque = ::dlopen (path, mode);
912
913 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000914 {
915 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000916 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000917 }
918 else
919 {
920 error.SetErrorString(::dlerror());
921 }
922 }
923 else
924 {
925 error.SetErrorString("failed to extract path");
926 }
Greg Clayton45319462011-02-08 00:35:34 +0000927 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000928}
929
930Error
Greg Clayton45319462011-02-08 00:35:34 +0000931Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000932{
933 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000934 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000935 {
936 error.SetErrorString ("invalid dynamic library handle");
937 }
Greg Clayton45319462011-02-08 00:35:34 +0000938 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000939 {
Greg Clayton45319462011-02-08 00:35:34 +0000940 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
941 if (::dlclose (dylib_info->handle) != 0)
942 {
943 error.SetErrorString(::dlerror());
944 }
945
946 dylib_info->open_options = 0;
947 dylib_info->handle = 0;
948 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000949 }
950 return error;
951}
952
953void *
Greg Clayton45319462011-02-08 00:35:34 +0000954Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000955{
Greg Clayton45319462011-02-08 00:35:34 +0000956 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000957 {
958 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000959 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000960 else
Greg Clayton45319462011-02-08 00:35:34 +0000961 {
962 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
963
964 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
965 if (symbol_addr)
966 {
967#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
968 // This host doesn't support limiting searches to this shared library
969 // so we need to verify that the match came from this shared library
970 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000971 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000972 {
973 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
974 if (match_dylib_spec != dylib_info->file_spec)
975 {
976 char dylib_path[PATH_MAX];
977 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
978 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
979 else
980 error.SetErrorString ("symbol not found");
981 return NULL;
982 }
983 }
984#endif
985 error.Clear();
986 return symbol_addr;
987 }
988 else
989 {
990 error.SetErrorString(::dlerror());
991 }
992 }
993 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000994}
Greg Claytondd36def2010-10-17 22:03:32 +0000995
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000996FileSpec
997Host::GetModuleFileSpecForHostAddress (const void *host_addr)
998{
999 FileSpec module_filespec;
1000 Dl_info info;
1001 if (::dladdr (host_addr, &info))
1002 {
1003 if (info.dli_fname)
1004 module_filespec.SetFile(info.dli_fname, true);
1005 }
1006 return module_filespec;
1007}
1008
1009#endif
1010
Greg Claytondd36def2010-10-17 22:03:32 +00001011bool
1012Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1013{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001014 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001015 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1016 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001017 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001018 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001019 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001020
1021 switch (path_type)
1022 {
1023 case ePathTypeLLDBShlibDir:
1024 {
1025 static ConstString g_lldb_so_dir;
1026 if (!g_lldb_so_dir)
1027 {
1028 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
1029 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001030 if (log)
1031 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001032 }
1033 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001034 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001035 }
1036 break;
1037
1038 case ePathTypeSupportExecutableDir:
1039 {
1040 static ConstString g_lldb_support_exe_dir;
1041 if (!g_lldb_support_exe_dir)
1042 {
1043 FileSpec lldb_file_spec;
1044 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1045 {
1046 char raw_path[PATH_MAX];
1047 char resolved_path[PATH_MAX];
1048 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1049
1050#if defined (__APPLE__)
1051 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1052 if (framework_pos)
1053 {
1054 framework_pos += strlen("LLDB.framework");
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001055#if defined (__arm__)
1056 // Shallow bundle
1057 *framework_pos = '\0';
1058#else
1059 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001060 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001061#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001062 }
1063#endif
1064 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1065 g_lldb_support_exe_dir.SetCString(resolved_path);
1066 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001067 if (log)
1068 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001069 }
1070 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001071 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001072 }
1073 break;
1074
1075 case ePathTypeHeaderDir:
1076 {
1077 static ConstString g_lldb_headers_dir;
1078 if (!g_lldb_headers_dir)
1079 {
1080#if defined (__APPLE__)
1081 FileSpec lldb_file_spec;
1082 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1083 {
1084 char raw_path[PATH_MAX];
1085 char resolved_path[PATH_MAX];
1086 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1087
1088 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1089 if (framework_pos)
1090 {
1091 framework_pos += strlen("LLDB.framework");
1092 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1093 }
1094 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1095 g_lldb_headers_dir.SetCString(resolved_path);
1096 }
1097#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001098 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001099 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1100#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001101 if (log)
1102 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001103 }
1104 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001105 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001106 }
1107 break;
1108
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001109#ifdef LLDB_DISABLE_PYTHON
1110 case ePathTypePythonDir:
1111 return false;
1112#else
1113 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001114 {
Greg Claytondd36def2010-10-17 22:03:32 +00001115 static ConstString g_lldb_python_dir;
1116 if (!g_lldb_python_dir)
1117 {
1118 FileSpec lldb_file_spec;
1119 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1120 {
1121 char raw_path[PATH_MAX];
1122 char resolved_path[PATH_MAX];
1123 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1124
1125#if defined (__APPLE__)
1126 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1127 if (framework_pos)
1128 {
1129 framework_pos += strlen("LLDB.framework");
1130 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001131 }
1132 else
1133 {
1134#endif
1135 llvm::SmallString<256> python_version_dir;
1136 llvm::raw_svector_ostream os(python_version_dir);
1137 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1138 os.flush();
1139
1140 // We may get our string truncated. Should we protect
1141 // this with an assert?
1142
1143 ::strncat(raw_path, python_version_dir.c_str(),
1144 sizeof(raw_path) - strlen(raw_path) - 1);
1145
1146#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001147 }
1148#endif
1149 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1150 g_lldb_python_dir.SetCString(resolved_path);
1151 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001152
1153 if (log)
1154 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1155
Greg Claytondd36def2010-10-17 22:03:32 +00001156 }
1157 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001158 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001159 }
1160 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001161#endif
1162
Greg Clayton4272cc72011-02-02 02:24:04 +00001163 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1164 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001165#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001166 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001167 static bool g_lldb_system_plugin_dir_located = false;
1168 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001169 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001170 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001171#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001172 FileSpec lldb_file_spec;
1173 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1174 {
1175 char raw_path[PATH_MAX];
1176 char resolved_path[PATH_MAX];
1177 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1178
1179 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1180 if (framework_pos)
1181 {
1182 framework_pos += strlen("LLDB.framework");
1183 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001184 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1185 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001186 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001187 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001188 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001189#elif defined (__linux__)
1190 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1191 if (lldb_file_spec.Exists())
1192 {
1193 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1194 }
1195#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001196
1197 if (log)
1198 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1199
Greg Clayton4272cc72011-02-02 02:24:04 +00001200 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001201
1202 if (g_lldb_system_plugin_dir)
1203 {
1204 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1205 return true;
1206 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001207#else
1208 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001209 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001210#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001211 }
1212 break;
1213
1214 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1215 {
1216#if defined (__APPLE__)
1217 static ConstString g_lldb_user_plugin_dir;
1218 if (!g_lldb_user_plugin_dir)
1219 {
1220 char user_plugin_path[PATH_MAX];
1221 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1222 user_plugin_path,
1223 sizeof(user_plugin_path)))
1224 {
1225 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1226 }
1227 }
1228 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001229 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001230#elif defined (__linux__)
1231 static ConstString g_lldb_user_plugin_dir;
1232 if (!g_lldb_user_plugin_dir)
1233 {
1234 // XDG Base Directory Specification
1235 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1236 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1237 FileSpec lldb_file_spec;
1238 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1239 if (xdg_data_home && xdg_data_home[0])
1240 {
1241 std::string user_plugin_dir (xdg_data_home);
1242 user_plugin_dir += "/lldb";
1243 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1244 }
1245 else
1246 {
1247 const char *home_dir = getenv("HOME");
1248 if (home_dir && home_dir[0])
1249 {
1250 std::string user_plugin_dir (home_dir);
1251 user_plugin_dir += "/.local/share/lldb";
1252 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1253 }
1254 }
1255
1256 if (lldb_file_spec.Exists())
1257 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001258 if (log)
1259 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001260 }
1261 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001262 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001263#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001264 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001265 return false;
1266 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001267
1268 case ePathTypeLLDBTempSystemDir:
1269 {
1270 static ConstString g_lldb_tmp_dir;
1271 if (!g_lldb_tmp_dir)
1272 {
1273 const char *tmpdir_cstr = getenv("TMPDIR");
1274 if (tmpdir_cstr == NULL)
1275 {
1276 tmpdir_cstr = getenv("TMP");
1277 if (tmpdir_cstr == NULL)
1278 tmpdir_cstr = getenv("TEMP");
1279 }
1280 if (tmpdir_cstr)
1281 {
1282 g_lldb_tmp_dir.SetCString(tmpdir_cstr);
1283 if (log)
1284 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1285 }
1286 }
1287 file_spec.GetDirectory() = g_lldb_tmp_dir;
1288 return (bool)file_spec.GetDirectory();
1289 }
Greg Claytondd36def2010-10-17 22:03:32 +00001290 }
1291
1292 return false;
1293}
1294
Greg Clayton1cb64962011-03-24 04:28:38 +00001295
1296bool
1297Host::GetHostname (std::string &s)
1298{
1299 char hostname[PATH_MAX];
1300 hostname[sizeof(hostname) - 1] = '\0';
1301 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1302 {
1303 struct hostent* h = ::gethostbyname (hostname);
1304 if (h)
1305 s.assign (h->h_name);
1306 else
1307 s.assign (hostname);
1308 return true;
1309 }
1310 return false;
1311}
1312
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001313#ifndef _WIN32
1314
Greg Clayton32e0a752011-03-30 18:16:51 +00001315const char *
1316Host::GetUserName (uint32_t uid, std::string &user_name)
1317{
1318 struct passwd user_info;
1319 struct passwd *user_info_ptr = &user_info;
1320 char user_buffer[PATH_MAX];
1321 size_t user_buffer_size = sizeof(user_buffer);
1322 if (::getpwuid_r (uid,
1323 &user_info,
1324 user_buffer,
1325 user_buffer_size,
1326 &user_info_ptr) == 0)
1327 {
1328 if (user_info_ptr)
1329 {
1330 user_name.assign (user_info_ptr->pw_name);
1331 return user_name.c_str();
1332 }
1333 }
1334 user_name.clear();
1335 return NULL;
1336}
1337
1338const char *
1339Host::GetGroupName (uint32_t gid, std::string &group_name)
1340{
1341 char group_buffer[PATH_MAX];
1342 size_t group_buffer_size = sizeof(group_buffer);
1343 struct group group_info;
1344 struct group *group_info_ptr = &group_info;
1345 // Try the threadsafe version first
1346 if (::getgrgid_r (gid,
1347 &group_info,
1348 group_buffer,
1349 group_buffer_size,
1350 &group_info_ptr) == 0)
1351 {
1352 if (group_info_ptr)
1353 {
1354 group_name.assign (group_info_ptr->gr_name);
1355 return group_name.c_str();
1356 }
1357 }
1358 else
1359 {
1360 // The threadsafe version isn't currently working
1361 // for me on darwin, but the non-threadsafe version
1362 // is, so I am calling it below.
1363 group_info_ptr = ::getgrgid (gid);
1364 if (group_info_ptr)
1365 {
1366 group_name.assign (group_info_ptr->gr_name);
1367 return group_name.c_str();
1368 }
1369 }
1370 group_name.clear();
1371 return NULL;
1372}
1373
Han Ming Ong84647042012-02-25 01:07:38 +00001374uint32_t
1375Host::GetUserID ()
1376{
1377 return getuid();
1378}
1379
1380uint32_t
1381Host::GetGroupID ()
1382{
1383 return getgid();
1384}
1385
1386uint32_t
1387Host::GetEffectiveUserID ()
1388{
1389 return geteuid();
1390}
1391
1392uint32_t
1393Host::GetEffectiveGroupID ()
1394{
1395 return getegid();
1396}
1397
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001398#endif
1399
1400#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1401bool
1402Host::GetOSBuildString (std::string &s)
1403{
1404 s.clear();
1405 return false;
1406}
1407
1408bool
1409Host::GetOSKernelDescription (std::string &s)
1410{
1411 s.clear();
1412 return false;
1413}
1414#endif
1415
Ed Maste47e575e2013-08-29 18:44:27 +00001416#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001417uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001418Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001419{
1420 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001421 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001422}
1423
Greg Claytone996fd32011-03-08 22:40:15 +00001424bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001425Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001426{
Greg Claytone996fd32011-03-08 22:40:15 +00001427 process_info.Clear();
1428 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001429}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001430#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001431
Matt Kopec085d6ce2013-05-31 22:00:07 +00001432#if !defined(__linux__)
1433bool
1434Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1435{
1436 return false;
1437}
1438#endif
1439
Sean Callananc0a6e062011-10-27 21:22:25 +00001440lldb::TargetSP
1441Host::GetDummyTarget (lldb_private::Debugger &debugger)
1442{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001443 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001444
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001445 // FIXME: Maybe the dummy target should be per-Debugger
1446 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1447 {
1448 ArchSpec arch(Target::GetDefaultArchitecture());
1449 if (!arch.IsValid())
1450 arch = Host::GetArchitecture ();
1451 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001452 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001453 arch.GetTriple().getTriple().c_str(),
1454 false,
1455 NULL,
1456 g_dummy_target_sp);
1457 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001458
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001459 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001460}
1461
Greg Claytond1cf11a2012-04-14 01:42:46 +00001462struct ShellInfo
1463{
1464 ShellInfo () :
1465 process_reaped (false),
1466 can_delete (false),
1467 pid (LLDB_INVALID_PROCESS_ID),
1468 signo(-1),
1469 status(-1)
1470 {
1471 }
1472
1473 lldb_private::Predicate<bool> process_reaped;
1474 lldb_private::Predicate<bool> can_delete;
1475 lldb::pid_t pid;
1476 int signo;
1477 int status;
1478};
1479
1480static bool
1481MonitorShellCommand (void *callback_baton,
1482 lldb::pid_t pid,
1483 bool exited, // True if the process did exit
1484 int signo, // Zero for no signal
1485 int status) // Exit value of process if signal is zero
1486{
1487 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1488 shell_info->pid = pid;
1489 shell_info->signo = signo;
1490 shell_info->status = status;
1491 // Let the thread running Host::RunShellCommand() know that the process
1492 // exited and that ShellInfo has been filled in by broadcasting to it
1493 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1494 // Now wait for a handshake back from that thread running Host::RunShellCommand
1495 // so we know that we can delete shell_info_ptr
1496 shell_info->can_delete.WaitForValueEqualTo(true);
1497 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1498 usleep(1000);
1499 // Now delete the shell info that was passed into this function
1500 delete shell_info;
1501 return true;
1502}
1503
1504Error
1505Host::RunShellCommand (const char *command,
1506 const char *working_dir,
1507 int *status_ptr,
1508 int *signo_ptr,
1509 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001510 uint32_t timeout_sec,
1511 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001512{
1513 Error error;
1514 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001515 if (shell && shell[0])
1516 {
1517 // Run the command in a shell
1518 launch_info.SetShell(shell);
1519 launch_info.GetArguments().AppendArgument(command);
1520 const bool localhost = true;
1521 const bool will_debug = false;
1522 const bool first_arg_is_full_shell_command = true;
1523 launch_info.ConvertArgumentsForLaunchingInShell (error,
1524 localhost,
1525 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001526 first_arg_is_full_shell_command,
1527 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001528 }
1529 else
1530 {
1531 // No shell, just run it
1532 Args args (command);
1533 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001534 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001535 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001536
1537 if (working_dir)
1538 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001539 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001540 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001541
Greg Claytond1cf11a2012-04-14 01:42:46 +00001542 if (command_output_ptr)
1543 {
1544 // Create a temporary file to get the stdout/stderr and redirect the
1545 // output of the command into this file. We will later read this file
1546 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001547 FileSpec tmpdir_file_spec;
1548 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1549 {
1550 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1551 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1552 }
1553 else
1554 {
1555 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1556 }
1557
1558 output_file_path = ::mktemp(output_file_path_buffer);
1559 }
1560
1561 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1562 if (output_file_path)
1563 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001564 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001565 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001566 }
1567 else
1568 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001569 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1570 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1571 }
1572
1573 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001574 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001575
1576 const bool monitor_signals = false;
1577 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1578
1579 error = LaunchProcess (launch_info);
1580 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001581
1582 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1583 error.SetErrorString("failed to get process ID");
1584
1585 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001586 {
1587 // The process successfully launched, so we can defer ownership of
1588 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001589 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001590 // doesn't need to delete the ShellInfo anymore.
1591 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001592 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001593 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001594 if (timeout_sec > 0) {
1595 timeout_time.OffsetWithSeconds(timeout_sec);
1596 timeout_ptr = &timeout_time;
1597 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001598 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001599 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001600 if (timed_out)
1601 {
1602 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001603
Greg Claytond1cf11a2012-04-14 01:42:46 +00001604 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001605 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001606 // Wait for the monitor callback to get the message
1607 timeout_time = TimeValue::Now();
1608 timeout_time.OffsetWithSeconds(1);
1609 timed_out = false;
1610 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1611 }
1612 else
1613 {
1614 if (status_ptr)
1615 *status_ptr = shell_info->status;
1616
1617 if (signo_ptr)
1618 *signo_ptr = shell_info->signo;
1619
1620 if (command_output_ptr)
1621 {
1622 command_output_ptr->clear();
1623 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1624 uint64_t file_size = file_spec.GetByteSize();
1625 if (file_size > 0)
1626 {
1627 if (file_size > command_output_ptr->max_size())
1628 {
1629 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1630 }
1631 else
1632 {
1633 command_output_ptr->resize(file_size);
1634 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1635 }
1636 }
1637 }
1638 }
1639 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1640 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001641
1642 if (output_file_path)
1643 ::unlink (output_file_path);
1644 // Handshake with the monitor thread, or just let it know in advance that
1645 // it can delete "shell_info" in case we timed out and were not able to kill
1646 // the process...
1647 return error;
1648}
1649
Daniel Malea4244cbd2013-08-27 20:58:59 +00001650
Todd Fiala76747122014-01-23 00:52:28 +00001651// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1652// systems
1653
1654#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__)
1655
1656// this method needs to be visible to macosx/Host.cpp and
1657// common/Host.cpp.
1658
1659short
1660Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1661{
1662 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1663
1664#if defined (__APPLE__)
1665 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1666 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1667
1668 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1669 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1670
1671 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1672 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1673
1674 if (launch_info.GetLaunchInSeparateProcessGroup())
1675 flags |= POSIX_SPAWN_SETPGROUP;
1676
1677#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1678#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1679 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1680 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1681 {
1682 g_use_close_on_exec_flag = eLazyBoolNo;
1683
1684 uint32_t major, minor, update;
1685 if (Host::GetOSVersion(major, minor, update))
1686 {
1687 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1688 if (major > 10 || (major == 10 && minor > 7))
1689 {
1690 // Only enable for 10.8 and later OS versions
1691 g_use_close_on_exec_flag = eLazyBoolYes;
1692 }
1693 }
1694 }
1695#else
1696 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1697#endif
1698 // Close all files exception those with file actions if this is supported.
1699 if (g_use_close_on_exec_flag == eLazyBoolYes)
1700 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1701#endif
1702#endif // #if defined (__APPLE__)
1703 return flags;
1704}
1705
1706Error
1707Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001708{
1709 Error error;
1710 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1711
Daniel Malea4244cbd2013-08-27 20:58:59 +00001712 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001713 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001714
1715 if (error.Fail() || log)
1716 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001717 if (error.Fail())
1718 return error;
1719
1720 // Make a quick class that will cleanup the posix spawn attributes in case
1721 // we return in the middle of this function.
1722 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1723
1724 sigset_t no_signals;
1725 sigset_t all_signals;
1726 sigemptyset (&no_signals);
1727 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001728 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001729#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001730 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001731#else
1732 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1733#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001734
Todd Fiala76747122014-01-23 00:52:28 +00001735 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001736
1737 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001738 if (error.Fail() || log)
1739 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001740 if (error.Fail())
1741 return error;
1742
Todd Fiala76747122014-01-23 00:52:28 +00001743 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1744 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1745#if defined (__APPLE__) && !defined (__arm__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001746
Todd Fiala76747122014-01-23 00:52:28 +00001747 // We don't need to do this for ARM, and we really shouldn't now that we
1748 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1749 // to set which CPU subtype to launch...
1750 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1751 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1752 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1753 if (cpu != 0 &&
1754 cpu != UINT32_MAX &&
1755 cpu != LLDB_INVALID_CPUTYPE &&
1756 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
Daniel Malea4244cbd2013-08-27 20:58:59 +00001757 {
Todd Fiala76747122014-01-23 00:52:28 +00001758 size_t ocount = 0;
1759 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1760 if (error.Fail() || log)
1761 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu, (uint64_t)ocount);
1762
1763 if (error.Fail() || ocount != 1)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001764 return error;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001765 }
1766
Todd Fiala76747122014-01-23 00:52:28 +00001767#endif
1768
1769 const char *tmp_argv[2];
1770 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1771 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1772 if (argv == NULL)
1773 {
1774 // posix_spawn gets very unhappy if it doesn't have at least the program
1775 // name in argv[0]. One of the side affects I have noticed is the environment
1776 // variables don't make it into the child process if "argv == NULL"!!!
1777 tmp_argv[0] = exe_path;
1778 tmp_argv[1] = NULL;
1779 argv = (char * const*)tmp_argv;
1780 }
1781
1782#if !defined (__APPLE__)
1783 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001784 char current_dir[PATH_MAX];
1785 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001786#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001787
1788 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001789 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001790 {
Todd Fiala76747122014-01-23 00:52:28 +00001791#if defined (__APPLE__)
1792 // Set the working directory on this thread only
1793 if (__pthread_chdir (working_dir) < 0) {
1794 if (errno == ENOENT) {
1795 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1796 } else if (errno == ENOTDIR) {
1797 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1798 } else {
1799 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1800 }
1801 return error;
1802 }
1803#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001804 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1805 {
1806 error.SetError(errno, eErrorTypePOSIX);
1807 error.LogIfError(log, "unable to save the current directory");
1808 return error;
1809 }
1810
1811 if (::chdir(working_dir) == -1)
1812 {
1813 error.SetError(errno, eErrorTypePOSIX);
1814 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1815 return error;
1816 }
Todd Fiala76747122014-01-23 00:52:28 +00001817#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001818 }
1819
Todd Fiala76747122014-01-23 00:52:28 +00001820 const size_t num_file_actions = launch_info.GetNumFileActions ();
1821 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001822 {
Todd Fiala76747122014-01-23 00:52:28 +00001823 posix_spawn_file_actions_t file_actions;
1824 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1825 if (error.Fail() || log)
1826 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1827 if (error.Fail())
1828 return error;
1829
1830 // Make a quick class that will cleanup the posix spawn attributes in case
1831 // we return in the middle of this function.
1832 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1833
1834 for (size_t i=0; i<num_file_actions; ++i)
1835 {
1836 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1837 if (launch_file_action)
1838 {
1839 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1840 launch_file_action,
1841 log,
1842 error))
1843 return error;
1844 }
1845 }
1846
1847 error.SetError (::posix_spawnp (&pid,
1848 exe_path,
1849 &file_actions,
1850 &attr,
1851 argv,
1852 envp),
1853 eErrorTypePOSIX);
1854
1855 if (error.Fail() || log)
1856 {
1857 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1858 pid,
1859 exe_path,
1860 &file_actions,
1861 &attr,
1862 argv,
1863 envp);
1864 if (log)
1865 {
1866 for (int ii=0; argv[ii]; ++ii)
1867 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1868 }
1869 }
1870
1871 }
1872 else
1873 {
1874 error.SetError (::posix_spawnp (&pid,
1875 exe_path,
1876 NULL,
1877 &attr,
1878 argv,
1879 envp),
1880 eErrorTypePOSIX);
1881
1882 if (error.Fail() || log)
1883 {
1884 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
1885 pid,
1886 exe_path,
1887 &attr,
1888 argv,
1889 envp);
1890 if (log)
1891 {
1892 for (int ii=0; argv[ii]; ++ii)
1893 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1894 }
1895 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001896 }
1897
Todd Fiala76747122014-01-23 00:52:28 +00001898 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001899 {
Todd Fiala76747122014-01-23 00:52:28 +00001900#if defined (__APPLE__)
1901 // No more thread specific current working directory
1902 __pthread_fchdir (-1);
1903#else
1904 if (::chdir(current_dir) == -1 && error.Success())
1905 {
1906 error.SetError(errno, eErrorTypePOSIX);
1907 error.LogIfError(log, "unable to change current directory back to %s",
1908 current_dir);
1909 }
1910#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001911 }
1912
1913 return error;
1914}
1915
Todd Fiala76747122014-01-23 00:52:28 +00001916#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1917
1918
1919#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__)
1920// The functions below implement process launching via posix_spawn() for Linux
1921// and FreeBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001922
1923Error
1924Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1925{
1926 Error error;
1927 char exe_path[PATH_MAX];
1928
1929 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1930
1931 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1932
1933 FileSpec exe_spec(launch_info.GetExecutableFile());
1934
1935 FileSpec::FileType file_type = exe_spec.GetFileType();
1936 if (file_type != FileSpec::eFileTypeRegular)
1937 {
1938 lldb::ModuleSP exe_module_sp;
1939 error = host_platform_sp->ResolveExecutable (exe_spec,
1940 arch_spec,
1941 exe_module_sp,
1942 NULL);
1943
1944 if (error.Fail())
1945 return error;
1946
1947 if (exe_module_sp)
1948 exe_spec = exe_module_sp->GetFileSpec();
1949 }
1950
1951 if (exe_spec.Exists())
1952 {
1953 exe_spec.GetPath (exe_path, sizeof(exe_path));
1954 }
1955 else
1956 {
1957 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1958 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1959 return error;
1960 }
1961
1962 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1963
1964 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1965
1966 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1967
1968 if (pid != LLDB_INVALID_PROCESS_ID)
1969 {
1970 // If all went well, then set the process ID into the launch info
1971 launch_info.SetProcessID(pid);
1972
Todd Fiala76747122014-01-23 00:52:28 +00001973 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1974
Daniel Malea4244cbd2013-08-27 20:58:59 +00001975 // Make sure we reap any processes we spawn or we will have zombies.
1976 if (!launch_info.MonitorProcess())
1977 {
1978 const bool monitor_signals = false;
1979 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1980 NULL,
1981 pid,
1982 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001983 if (log)
1984 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
1985 }
1986 else
1987 {
1988 if (log)
1989 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001990 }
1991 }
1992 else
1993 {
1994 // Invalid process ID, something didn't go well
1995 if (error.Success())
1996 error.SetErrorString ("process launch failed for unknown reasons");
1997 }
1998 return error;
1999}
2000
2001#endif // defined(__linux__) or defined(__FreeBSD__)
2002
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002003#ifndef _WIN32
2004
2005size_t
2006Host::GetPageSize()
2007{
2008 return ::getpagesize();
2009}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002010
Greg Claytone3e3fee2013-02-17 20:46:30 +00002011uint32_t
2012Host::GetNumberCPUS ()
2013{
2014 static uint32_t g_num_cores = UINT32_MAX;
2015 if (g_num_cores == UINT32_MAX)
2016 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002017#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002018
2019 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002020
Greg Claytone3e3fee2013-02-17 20:46:30 +00002021#else
2022
2023 // Assume POSIX support if a host specific case has not been supplied above
2024 g_num_cores = 0;
2025 int num_cores = 0;
2026 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002027#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002028 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002029#else
2030 int mib[] = { CTL_HW, HW_NCPU };
2031#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002032
2033 /* get the number of CPUs from the system */
2034 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
2035 {
2036 g_num_cores = num_cores;
2037 }
2038 else
2039 {
2040 mib[1] = HW_NCPU;
2041 num_cores_len = sizeof(num_cores);
2042 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
2043 {
2044 if (num_cores > 0)
2045 g_num_cores = num_cores;
2046 }
2047 }
2048#endif
2049 }
2050 return g_num_cores;
2051}
2052
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002053void
2054Host::Kill(lldb::pid_t pid, int signo)
2055{
2056 ::kill(pid, signo);
2057}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002058
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002059#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002060
Johnny Chen8f3d8382011-08-02 20:52:42 +00002061#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002062bool
Greg Clayton3b147632010-12-18 01:54:34 +00002063Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002064{
2065 return false;
2066}
Greg Claytondd36def2010-10-17 22:03:32 +00002067
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002068void
2069Host::SetCrashDescriptionWithFormat (const char *format, ...)
2070{
2071}
2072
2073void
2074Host::SetCrashDescription (const char *description)
2075{
2076}
Greg Claytondd36def2010-10-17 22:03:32 +00002077
2078lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002079Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002080{
2081 return LLDB_INVALID_PROCESS_ID;
2082}
2083
Greg Claytonfbb76342013-11-20 21:07:01 +00002084#endif
2085
2086
2087#ifdef LLDB_DISABLE_POSIX
2088
2089Error
2090Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002091{
Greg Claytonfbb76342013-11-20 21:07:01 +00002092 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002093 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002094 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002095}
Greg Claytonfbb76342013-11-20 21:07:01 +00002096
2097Error
2098Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2099{
2100 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002101 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002102 return error;
2103}
2104
2105Error
2106Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2107{
2108 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002109 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002110 return error;
2111}
2112
2113Error
2114Host::Symlink (const char *src, const char *dst)
2115{
2116 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002117 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002118 return error;
2119}
2120
2121Error
2122Host::Readlink (const char *path, char *buf, size_t buf_len)
2123{
2124 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002125 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002126 return error;
2127}
2128
2129Error
2130Host::Unlink (const char *path)
2131{
2132 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002133 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002134 return error;
2135}
2136
2137#else
2138
2139Error
2140Host::MakeDirectory (const char* path, uint32_t file_permissions)
2141{
2142 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002143 if (path && path[0])
2144 {
Greg Claytonfb909312013-11-23 01:58:15 +00002145 if (::mkdir(path, file_permissions) != 0)
2146 {
2147 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002148 switch (error.GetError())
2149 {
2150 case ENOENT:
2151 {
2152 // Parent directory doesn't exist, so lets make it if we can
2153 FileSpec spec(path, false);
2154 if (spec.GetDirectory() && spec.GetFilename())
2155 {
2156 // Make the parent directory and try again
2157 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2158 if (error2.Success())
2159 {
2160 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002161 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002162 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002163 else
Greg Claytonfb909312013-11-23 01:58:15 +00002164 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002165 }
2166 }
2167 }
2168 break;
2169 case EEXIST:
2170 {
2171 FileSpec path_spec(path, false);
2172 if (path_spec.IsDirectory())
2173 error.Clear(); // It is a directory and it already exists
2174 }
2175 break;
2176 }
2177 }
Greg Claytonfb909312013-11-23 01:58:15 +00002178 }
2179 else
2180 {
2181 error.SetErrorString("empty path");
2182 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002183 return error;
2184}
2185
2186Error
2187Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2188{
2189 Error error;
2190 struct stat file_stats;
2191 if (::stat (path, &file_stats) == 0)
2192 {
2193 // The bits in "st_mode" currently match the definitions
2194 // for the file mode bits in unix.
2195 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2196 }
2197 else
2198 {
2199 error.SetErrorToErrno();
2200 }
2201 return error;
2202}
2203
2204Error
2205Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2206{
2207 Error error;
2208 if (::chmod(path, file_permissions) != 0)
2209 error.SetErrorToErrno();
2210 return error;
2211}
2212
2213Error
2214Host::Symlink (const char *src, const char *dst)
2215{
2216 Error error;
2217 if (::symlink(dst, src) == -1)
2218 error.SetErrorToErrno();
2219 return error;
2220}
2221
2222Error
2223Host::Unlink (const char *path)
2224{
2225 Error error;
2226 if (::unlink(path) == -1)
2227 error.SetErrorToErrno();
2228 return error;
2229}
2230
2231Error
2232Host::Readlink (const char *path, char *buf, size_t buf_len)
2233{
2234 Error error;
2235 ssize_t count = ::readlink(path, buf, buf_len);
2236 if (count < 0)
2237 error.SetErrorToErrno();
2238 else if (count < (buf_len-1))
2239 buf[count] = '\0'; // Success
2240 else
2241 error.SetErrorString("'buf' buffer is too small to contain link contents");
2242 return error;
2243}
2244
2245
Greg Clayton2bddd342010-09-07 20:11:56 +00002246#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002247
2248typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2249FDToFileMap& GetFDToFileMap()
2250{
2251 static FDToFileMap g_fd2filemap;
2252 return g_fd2filemap;
2253}
2254
2255lldb::user_id_t
2256Host::OpenFile (const FileSpec& file_spec,
2257 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002258 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002259 Error &error)
2260{
2261 std::string path (file_spec.GetPath());
2262 if (path.empty())
2263 {
2264 error.SetErrorString("empty path");
2265 return UINT64_MAX;
2266 }
2267 FileSP file_sp(new File());
2268 error = file_sp->Open(path.c_str(),flags,mode);
2269 if (file_sp->IsValid() == false)
2270 return UINT64_MAX;
2271 lldb::user_id_t fd = file_sp->GetDescriptor();
2272 GetFDToFileMap()[fd] = file_sp;
2273 return fd;
2274}
2275
2276bool
2277Host::CloseFile (lldb::user_id_t fd, Error &error)
2278{
2279 if (fd == UINT64_MAX)
2280 {
2281 error.SetErrorString ("invalid file descriptor");
2282 return false;
2283 }
2284 FDToFileMap& file_map = GetFDToFileMap();
2285 FDToFileMap::iterator pos = file_map.find(fd);
2286 if (pos == file_map.end())
2287 {
2288 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2289 return false;
2290 }
2291 FileSP file_sp = pos->second;
2292 if (!file_sp)
2293 {
2294 error.SetErrorString ("invalid host backing file");
2295 return false;
2296 }
2297 error = file_sp->Close();
2298 file_map.erase(pos);
2299 return error.Success();
2300}
2301
2302uint64_t
2303Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2304{
2305 if (fd == UINT64_MAX)
2306 {
2307 error.SetErrorString ("invalid file descriptor");
2308 return UINT64_MAX;
2309 }
2310 FDToFileMap& file_map = GetFDToFileMap();
2311 FDToFileMap::iterator pos = file_map.find(fd);
2312 if (pos == file_map.end())
2313 {
2314 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2315 return false;
2316 }
2317 FileSP file_sp = pos->second;
2318 if (!file_sp)
2319 {
2320 error.SetErrorString ("invalid host backing file");
2321 return UINT64_MAX;
2322 }
2323 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2324 return UINT64_MAX;
2325 size_t bytes_written = src_len;
2326 error = file_sp->Write(src, bytes_written);
2327 if (error.Fail())
2328 return UINT64_MAX;
2329 return bytes_written;
2330}
2331
2332uint64_t
2333Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2334{
2335 if (fd == UINT64_MAX)
2336 {
2337 error.SetErrorString ("invalid file descriptor");
2338 return UINT64_MAX;
2339 }
2340 FDToFileMap& file_map = GetFDToFileMap();
2341 FDToFileMap::iterator pos = file_map.find(fd);
2342 if (pos == file_map.end())
2343 {
2344 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2345 return false;
2346 }
2347 FileSP file_sp = pos->second;
2348 if (!file_sp)
2349 {
2350 error.SetErrorString ("invalid host backing file");
2351 return UINT64_MAX;
2352 }
2353 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2354 return UINT64_MAX;
2355 size_t bytes_read = dst_len;
2356 error = file_sp->Read(dst ,bytes_read);
2357 if (error.Fail())
2358 return UINT64_MAX;
2359 return bytes_read;
2360}
2361
2362lldb::user_id_t
2363Host::GetFileSize (const FileSpec& file_spec)
2364{
2365 return file_spec.GetByteSize();
2366}
2367
2368bool
2369Host::GetFileExists (const FileSpec& file_spec)
2370{
2371 return file_spec.Exists();
2372}
2373
2374bool
2375Host::CalculateMD5 (const FileSpec& file_spec,
2376 uint64_t &low,
2377 uint64_t &high)
2378{
2379#if defined (__APPLE__)
2380 StreamString md5_cmd_line;
2381 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2382 std::string hash_string;
2383 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2384 if (err.Fail())
2385 return false;
2386 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2387 // if the output is any other length it is probably wrong
2388 if (hash_string.size() != 32)
2389 return false;
2390 std::string part1(hash_string,0,16);
2391 std::string part2(hash_string,16);
2392 const char* part1_cstr = part1.c_str();
2393 const char* part2_cstr = part2.c_str();
2394 high = ::strtoull(part1_cstr, NULL, 16);
2395 low = ::strtoull(part2_cstr, NULL, 16);
2396 return true;
2397#else
2398 // your own MD5 implementation here
2399 return false;
2400#endif
2401}