blob: 7ac338016124adbd1f4601d091d1601e3ac44fb3 [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
21#include <dlfcn.h>
22#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000023#include <netdb.h>
24#include <pwd.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000025#endif
26
27#if !defined (__GNU__) && !defined (_WIN32)
28// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000029#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000030#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000031
32#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000033#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000034#include <mach/mach_init.h>
35#include <mach-o/dyld.h>
Ed Maste8b006c62013-06-25 18:58:11 +000036#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000037
Ed Maste8b006c62013-06-25 18:58:11 +000038#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000039#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000040#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000041#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000042#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000043
Ed Maste8b006c62013-06-25 18:58:11 +000044#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000045#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000046#endif
47
Greg Clayton2bddd342010-09-07 20:11:56 +000048#include "lldb/Host/Host.h"
49#include "lldb/Core/ArchSpec.h"
50#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000051#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000052#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000053#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000054#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000055#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000056#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000057#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000058#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000059#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000060#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000061#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000062#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000063#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000064
Daniel Maleafa7425d2013-08-06 21:40:08 +000065#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000066#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000067#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000068
Greg Clayton32e0a752011-03-30 18:16:51 +000069
Greg Clayton2bddd342010-09-07 20:11:56 +000070using namespace lldb;
71using namespace lldb_private;
72
Greg Claytone4e45922011-11-16 05:37:56 +000073
Virgile Bellob2f1fb22013-08-23 12:44:05 +000074#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000075struct MonitorInfo
76{
77 lldb::pid_t pid; // The process ID to monitor
78 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
79 void *callback_baton; // The callback baton for the callback function
80 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
81};
82
Virgile Bellob2f1fb22013-08-23 12:44:05 +000083static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000084MonitorChildProcessThreadFunction (void *arg);
85
86lldb::thread_t
87Host::StartMonitoringChildProcess
88(
89 Host::MonitorChildProcessCallback callback,
90 void *callback_baton,
91 lldb::pid_t pid,
92 bool monitor_signals
93)
94{
95 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +000096 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +000097
Greg Claytone4e45922011-11-16 05:37:56 +000098 info_ptr->pid = pid;
99 info_ptr->callback = callback;
100 info_ptr->callback_baton = callback_baton;
101 info_ptr->monitor_signals = monitor_signals;
102
103 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000104 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000105 thread = ThreadCreate (thread_name,
106 MonitorChildProcessThreadFunction,
107 info_ptr,
108 NULL);
109
Greg Clayton2bddd342010-09-07 20:11:56 +0000110 return thread;
111}
112
113//------------------------------------------------------------------
114// Scoped class that will disable thread canceling when it is
115// constructed, and exception safely restore the previous value it
116// when it goes out of scope.
117//------------------------------------------------------------------
118class ScopedPThreadCancelDisabler
119{
120public:
121 ScopedPThreadCancelDisabler()
122 {
123 // Disable the ability for this thread to be cancelled
124 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
125 if (err != 0)
126 m_old_state = -1;
127
128 }
129
130 ~ScopedPThreadCancelDisabler()
131 {
132 // Restore the ability for this thread to be cancelled to what it
133 // previously was.
134 if (m_old_state != -1)
135 ::pthread_setcancelstate (m_old_state, 0);
136 }
137private:
138 int m_old_state; // Save the old cancelability state.
139};
140
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000141static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000142MonitorChildProcessThreadFunction (void *arg)
143{
Greg Clayton5160ce52013-03-27 23:08:40 +0000144 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000145 const char *function = __FUNCTION__;
146 if (log)
147 log->Printf ("%s (arg = %p) thread starting...", function, arg);
148
149 MonitorInfo *info = (MonitorInfo *)arg;
150
151 const Host::MonitorChildProcessCallback callback = info->callback;
152 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000153 const bool monitor_signals = info->monitor_signals;
154
Daniel Malea4244cbd2013-08-27 20:58:59 +0000155 assert (info->pid <= UINT32_MAX);
156 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
157
Greg Clayton2bddd342010-09-07 20:11:56 +0000158 delete info;
159
160 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000161#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000162 #define __WALL 0
163#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000164 const int options = __WALL;
165
Greg Clayton2bddd342010-09-07 20:11:56 +0000166 while (1)
167 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000168 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000169 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000170 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000171
172 // Wait for all child processes
173 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000174 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000175 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000176 ::pthread_testcancel ();
177
178 if (wait_pid == -1)
179 {
180 if (errno == EINTR)
181 continue;
182 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000183 {
184 if (log)
185 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000186 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000187 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000188 }
Matt Kopec650648f2013-01-08 16:30:18 +0000189 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000190 {
191 bool exited = false;
192 int signal = 0;
193 int exit_status = 0;
194 const char *status_cstr = NULL;
195 if (WIFSTOPPED(status))
196 {
197 signal = WSTOPSIG(status);
198 status_cstr = "STOPPED";
199 }
200 else if (WIFEXITED(status))
201 {
202 exit_status = WEXITSTATUS(status);
203 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000204 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000205 }
206 else if (WIFSIGNALED(status))
207 {
208 signal = WTERMSIG(status);
209 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000210 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000211 exited = true;
212 exit_status = -1;
213 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000214 }
215 else
216 {
Johnny Chen44805302011-07-19 19:48:13 +0000217 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000218 }
219
220 // Scope for pthread_cancel_disabler
221 {
222 ScopedPThreadCancelDisabler pthread_cancel_disabler;
223
Caroline Tice20ad3c42010-10-29 21:48:37 +0000224 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000225 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000226 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 +0000227 function,
228 wait_pid,
229 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000230 pid,
231 status,
232 status_cstr,
233 signal,
234 exit_status);
235
236 if (exited || (signal != 0 && monitor_signals))
237 {
Greg Claytone4e45922011-11-16 05:37:56 +0000238 bool callback_return = false;
239 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000240 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000241
242 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000243 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000244 {
245 if (log)
246 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000247 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000248 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000249 // If the callback returns true, it means this process should
250 // exit
251 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000252 {
253 if (log)
254 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000255 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000256 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000257 }
258 }
259 }
260 }
261
Caroline Tice20ad3c42010-10-29 21:48:37 +0000262 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000263 if (log)
264 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
265
266 return NULL;
267}
268
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000269#endif // #if !defined (__APPLE__) && !defined (_WIN32)
270
271#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000272
273void
274Host::SystemLog (SystemLogType type, const char *format, va_list args)
275{
276 vfprintf (stderr, format, args);
277}
278
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000279#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000280
Greg Claytone38a5ed2012-01-05 03:57:59 +0000281void
282Host::SystemLog (SystemLogType type, const char *format, ...)
283{
284 va_list args;
285 va_start (args, format);
286 SystemLog (type, format, args);
287 va_end (args);
288}
289
Greg Clayton2bddd342010-09-07 20:11:56 +0000290const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000291Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000292{
Greg Clayton514487e2011-02-15 21:59:32 +0000293 static bool g_supports_32 = false;
294 static bool g_supports_64 = false;
295 static ArchSpec g_host_arch_32;
296 static ArchSpec g_host_arch_64;
297
Greg Clayton2bddd342010-09-07 20:11:56 +0000298#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000299
300 // Apple is different in that it can support both 32 and 64 bit executables
301 // in the same operating system running concurrently. Here we detect the
302 // correct host architectures for both 32 and 64 bit including if 64 bit
303 // executables are supported on the system.
304
305 if (g_supports_32 == false && g_supports_64 == false)
306 {
307 // All apple systems support 32 bit execution.
308 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000309 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000310 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000311 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000312 ArchSpec host_arch;
313 // These will tell us about the kernel architecture, which even on a 64
314 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000315 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
316 {
Greg Clayton514487e2011-02-15 21:59:32 +0000317 len = sizeof (cpusubtype);
318 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
319 cpusubtype = CPU_TYPE_ANY;
320
Greg Clayton2bddd342010-09-07 20:11:56 +0000321 len = sizeof (is_64_bit_capable);
322 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
323 {
324 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000325 g_supports_64 = true;
326 }
327
328 if (is_64_bit_capable)
329 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000330#if defined (__i386__) || defined (__x86_64__)
331 if (cpusubtype == CPU_SUBTYPE_486)
332 cpusubtype = CPU_SUBTYPE_I386_ALL;
333#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000334 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000335 {
Greg Clayton514487e2011-02-15 21:59:32 +0000336 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000337 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
338 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000339 }
340 else
341 {
342 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000343 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000344 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000345 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000346 }
347 }
Greg Clayton514487e2011-02-15 21:59:32 +0000348 else
349 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000350 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000351 g_host_arch_64.Clear();
352 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000353 }
Greg Clayton514487e2011-02-15 21:59:32 +0000354 }
355
356#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000357
Greg Clayton514487e2011-02-15 21:59:32 +0000358 if (g_supports_32 == false && g_supports_64 == false)
359 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000360 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000361
Stephen Wilsonbd588712011-02-24 19:15:09 +0000362 g_host_arch_32.Clear();
363 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000364
Greg Claytonb29e6c62012-10-11 17:38:58 +0000365 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
366 // for the default triple. It's probably an artifact of config.guess.
367 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
368 triple.setVendorName("");
369
Stephen Wilsonbd588712011-02-24 19:15:09 +0000370 switch (triple.getArch())
371 {
372 default:
373 g_host_arch_32.SetTriple(triple);
374 g_supports_32 = true;
375 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000376
Stephen Wilsonbd588712011-02-24 19:15:09 +0000377 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000378 g_host_arch_64.SetTriple(triple);
379 g_supports_64 = true;
380 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
381 g_supports_32 = true;
382 break;
383
Stephen Wilsonbd588712011-02-24 19:15:09 +0000384 case llvm::Triple::sparcv9:
385 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000386 g_host_arch_64.SetTriple(triple);
387 g_supports_64 = true;
388 break;
389 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000390
391 g_supports_32 = g_host_arch_32.IsValid();
392 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000393 }
Greg Clayton514487e2011-02-15 21:59:32 +0000394
395#endif // #else for #if defined (__APPLE__)
396
397 if (arch_kind == eSystemDefaultArchitecture32)
398 return g_host_arch_32;
399 else if (arch_kind == eSystemDefaultArchitecture64)
400 return g_host_arch_64;
401
402 if (g_supports_64)
403 return g_host_arch_64;
404
405 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000406}
407
408const ConstString &
409Host::GetVendorString()
410{
411 static ConstString g_vendor;
412 if (!g_vendor)
413 {
Greg Clayton950971f2012-05-12 00:01:21 +0000414 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
415 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
416 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000417 }
418 return g_vendor;
419}
420
421const ConstString &
422Host::GetOSString()
423{
424 static ConstString g_os_string;
425 if (!g_os_string)
426 {
Greg Clayton950971f2012-05-12 00:01:21 +0000427 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
428 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
429 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000430 }
431 return g_os_string;
432}
433
434const ConstString &
435Host::GetTargetTriple()
436{
437 static ConstString g_host_triple;
438 if (!(g_host_triple))
439 {
Greg Clayton950971f2012-05-12 00:01:21 +0000440 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
441 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000442 }
443 return g_host_triple;
444}
445
446lldb::pid_t
447Host::GetCurrentProcessID()
448{
449 return ::getpid();
450}
451
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000452#ifndef _WIN32
453
Greg Clayton2bddd342010-09-07 20:11:56 +0000454lldb::tid_t
455Host::GetCurrentThreadID()
456{
457#if defined (__APPLE__)
Greg Clayton813ddfc2012-09-18 18:19:49 +0000458 // Calling "mach_port_deallocate()" bumps the reference count on the thread
459 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
460 // count.
461 thread_port_t thread_self = mach_thread_self();
462 mach_port_deallocate(mach_task_self(), thread_self);
463 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000464#elif defined(__FreeBSD__)
465 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000466#elif defined(__linux__)
467 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000468#else
469 return lldb::tid_t(pthread_self());
470#endif
471}
472
Jim Ingham372787f2012-04-07 00:00:41 +0000473lldb::thread_t
474Host::GetCurrentThread ()
475{
476 return lldb::thread_t(pthread_self());
477}
478
Greg Clayton2bddd342010-09-07 20:11:56 +0000479const char *
480Host::GetSignalAsCString (int signo)
481{
482 switch (signo)
483 {
484 case SIGHUP: return "SIGHUP"; // 1 hangup
485 case SIGINT: return "SIGINT"; // 2 interrupt
486 case SIGQUIT: return "SIGQUIT"; // 3 quit
487 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
488 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
489 case SIGABRT: return "SIGABRT"; // 6 abort()
Greg Clayton0ddf6be2011-11-04 03:42:38 +0000490#if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE))
Greg Clayton2bddd342010-09-07 20:11:56 +0000491 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000492#endif
493#if !defined(_POSIX_C_SOURCE)
Greg Clayton2bddd342010-09-07 20:11:56 +0000494 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000495#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000496 case SIGFPE: return "SIGFPE"; // 8 floating point exception
497 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
498 case SIGBUS: return "SIGBUS"; // 10 bus error
499 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
500 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
501 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
502 case SIGALRM: return "SIGALRM"; // 14 alarm clock
503 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
504 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
505 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
506 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
507 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
508 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
509 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
510 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
511#if !defined(_POSIX_C_SOURCE)
512 case SIGIO: return "SIGIO"; // 23 input/output possible signal
513#endif
514 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
515 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
516 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
517 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
518#if !defined(_POSIX_C_SOURCE)
519 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
520 case SIGINFO: return "SIGINFO"; // 29 information request
521#endif
522 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
523 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
524 default:
525 break;
526 }
527 return NULL;
528}
529
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000530#endif
531
Greg Clayton2bddd342010-09-07 20:11:56 +0000532void
533Host::WillTerminate ()
534{
535}
536
Sylvestre Ledru59405832013-07-01 08:21:36 +0000537#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000538
Greg Clayton2bddd342010-09-07 20:11:56 +0000539void
540Host::ThreadCreated (const char *thread_name)
541{
542}
Greg Claytone5219662010-12-03 06:02:24 +0000543
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000544void
Greg Claytone5219662010-12-03 06:02:24 +0000545Host::Backtrace (Stream &strm, uint32_t max_frames)
546{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000547 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000548}
549
Greg Clayton85851dd2010-12-04 00:10:17 +0000550size_t
551Host::GetEnvironment (StringList &env)
552{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000553 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000554 return 0;
555}
556
Sylvestre Ledru59405832013-07-01 08:21:36 +0000557#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000558
559struct HostThreadCreateInfo
560{
561 std::string thread_name;
562 thread_func_t thread_fptr;
563 thread_arg_t thread_arg;
564
565 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
566 thread_name (name ? name : ""),
567 thread_fptr (fptr),
568 thread_arg (arg)
569 {
570 }
571};
572
573static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000574#ifdef _WIN32
575__stdcall
576#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000577ThreadCreateTrampoline (thread_arg_t arg)
578{
579 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
580 Host::ThreadCreated (info->thread_name.c_str());
581 thread_func_t thread_fptr = info->thread_fptr;
582 thread_arg_t thread_arg = info->thread_arg;
583
Greg Clayton5160ce52013-03-27 23:08:40 +0000584 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000585 if (log)
586 log->Printf("thread created");
587
588 delete info;
589 return thread_fptr (thread_arg);
590}
591
592lldb::thread_t
593Host::ThreadCreate
594(
595 const char *thread_name,
596 thread_func_t thread_fptr,
597 thread_arg_t thread_arg,
598 Error *error
599)
600{
601 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
602
603 // Host::ThreadCreateTrampoline will delete this pointer for us.
604 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
605
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000606#ifdef _WIN32
607 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
608 int err = thread <= 0 ? GetLastError() : 0;
609#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000610 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000611#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000612 if (err == 0)
613 {
614 if (error)
615 error->Clear();
616 return thread;
617 }
618
619 if (error)
620 error->SetError (err, eErrorTypePOSIX);
621
622 return LLDB_INVALID_HOST_THREAD;
623}
624
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000625#ifndef _WIN32
626
Greg Clayton2bddd342010-09-07 20:11:56 +0000627bool
628Host::ThreadCancel (lldb::thread_t thread, Error *error)
629{
630 int err = ::pthread_cancel (thread);
631 if (error)
632 error->SetError(err, eErrorTypePOSIX);
633 return err == 0;
634}
635
636bool
637Host::ThreadDetach (lldb::thread_t thread, Error *error)
638{
639 int err = ::pthread_detach (thread);
640 if (error)
641 error->SetError(err, eErrorTypePOSIX);
642 return err == 0;
643}
644
645bool
646Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
647{
648 int err = ::pthread_join (thread, thread_result_ptr);
649 if (error)
650 error->SetError(err, eErrorTypePOSIX);
651 return err == 0;
652}
653
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000654lldb::thread_key_t
655Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
656{
657 pthread_key_t key;
658 ::pthread_key_create (&key, callback);
659 return key;
660}
661
662void*
663Host::ThreadLocalStorageGet(lldb::thread_key_t key)
664{
665 return ::pthread_getspecific (key);
666}
667
668void
669Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
670{
671 ::pthread_setspecific (key, value);
672}
673
Matt Kopec62502c62013-05-13 19:33:58 +0000674bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000675Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
676{
Greg Clayton85719632013-02-27 22:51:58 +0000677#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000678 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
679 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
680 if (pid == LLDB_INVALID_PROCESS_ID)
681 pid = curr_pid;
682
683 if (tid == LLDB_INVALID_THREAD_ID)
684 tid = curr_tid;
685
Greg Clayton2bddd342010-09-07 20:11:56 +0000686 // Set the pthread name if possible
687 if (pid == curr_pid && tid == curr_tid)
688 {
Matt Kopec62502c62013-05-13 19:33:58 +0000689 if (::pthread_setname_np (name) == 0)
690 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000691 }
Matt Kopec62502c62013-05-13 19:33:58 +0000692 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000693#elif defined (__FreeBSD__)
694 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
695 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
696 if (pid == LLDB_INVALID_PROCESS_ID)
697 pid = curr_pid;
698
699 if (tid == LLDB_INVALID_THREAD_ID)
700 tid = curr_tid;
701
702 // Set the pthread name if possible
703 if (pid == curr_pid && tid == curr_tid)
704 {
Michael Sartainc2052432013-08-01 18:51:08 +0000705 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000706 return true;
707 }
708 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000709#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000710 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
711 if (fn)
712 {
Matt Kopec62502c62013-05-13 19:33:58 +0000713 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
714 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000715 if (pid == LLDB_INVALID_PROCESS_ID)
716 pid = curr_pid;
717
718 if (tid == LLDB_INVALID_THREAD_ID)
719 tid = curr_tid;
720
Michael Sartainc2052432013-08-01 18:51:08 +0000721 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000722 {
Michael Sartainc2052432013-08-01 18:51:08 +0000723 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
724 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
725
726 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000727 return true;
728 }
729 }
730 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000731#else
732 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000733#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000734}
735
Ed Maste02983be2013-07-25 19:10:32 +0000736bool
737Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
738 const char *thread_name, size_t len)
739{
740 char *namebuf = (char *)::malloc (len + 1);
741
742 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
743 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
744 // off leads to a lot of similar named threads. Go through the thread name
745 // and search for the last dot and use that.
746 const char *lastdot = ::strrchr (thread_name, '.');
747
748 if (lastdot && lastdot != thread_name)
749 thread_name = lastdot + 1;
750 ::strncpy (namebuf, thread_name, len);
751 namebuf[len] = 0;
752
753 int namebuflen = strlen(namebuf);
754 if (namebuflen > 0)
755 {
756 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
757 {
758 // Trim off trailing '(' and '>' characters for a bit more cleanup.
759 namebuflen--;
760 namebuf[namebuflen] = 0;
761 }
762 return Host::SetThreadName (pid, tid, namebuf);
763 }
764 return false;
765}
766
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000767#endif
768
Greg Clayton2bddd342010-09-07 20:11:56 +0000769FileSpec
770Host::GetProgramFileSpec ()
771{
772 static FileSpec g_program_filespec;
773 if (!g_program_filespec)
774 {
775#if defined (__APPLE__)
776 char program_fullpath[PATH_MAX];
777 // If DST is NULL, then return the number of bytes needed.
778 uint32_t len = sizeof(program_fullpath);
779 int err = _NSGetExecutablePath (program_fullpath, &len);
780 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000781 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000782 else if (err == -1)
783 {
784 char *large_program_fullpath = (char *)::malloc (len + 1);
785
786 err = _NSGetExecutablePath (large_program_fullpath, &len);
787 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000788 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000789
790 ::free (large_program_fullpath);
791 }
792#elif defined (__linux__)
793 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000794 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
795 if (len > 0) {
796 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000797 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000798 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000799#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000800 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
801 size_t exe_path_size;
802 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
803 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000804 char *exe_path = new char[exe_path_size];
805 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
806 g_program_filespec.SetFile(exe_path, false);
807 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000808 }
809#endif
810 }
811 return g_program_filespec;
812}
813
Greg Clayton2bddd342010-09-07 20:11:56 +0000814#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000815
816bool
817Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
818{
819 bundle.Clear();
820 return false;
821}
822
Greg Clayton2bddd342010-09-07 20:11:56 +0000823bool
Greg Claytondd36def2010-10-17 22:03:32 +0000824Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000825{
Greg Claytondd36def2010-10-17 22:03:32 +0000826 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000827}
828#endif
829
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000830#ifndef _WIN32
831
Greg Clayton45319462011-02-08 00:35:34 +0000832// Opaque info that tracks a dynamic library that was loaded
833struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000834{
Greg Clayton45319462011-02-08 00:35:34 +0000835 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
836 file_spec (fs),
837 open_options (o),
838 handle (h)
839 {
840 }
841
842 const FileSpec file_spec;
843 uint32_t open_options;
844 void * handle;
845};
846
847void *
848Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
849{
Greg Clayton4272cc72011-02-02 02:24:04 +0000850 char path[PATH_MAX];
851 if (file_spec.GetPath(path, sizeof(path)))
852 {
Greg Clayton45319462011-02-08 00:35:34 +0000853 int mode = 0;
854
855 if (options & eDynamicLibraryOpenOptionLazy)
856 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000857 else
858 mode |= RTLD_NOW;
859
Greg Clayton45319462011-02-08 00:35:34 +0000860
861 if (options & eDynamicLibraryOpenOptionLocal)
862 mode |= RTLD_LOCAL;
863 else
864 mode |= RTLD_GLOBAL;
865
866#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
867 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
868 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000869#endif
Greg Clayton45319462011-02-08 00:35:34 +0000870
871 void * opaque = ::dlopen (path, mode);
872
873 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000874 {
875 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000876 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000877 }
878 else
879 {
880 error.SetErrorString(::dlerror());
881 }
882 }
883 else
884 {
885 error.SetErrorString("failed to extract path");
886 }
Greg Clayton45319462011-02-08 00:35:34 +0000887 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000888}
889
890Error
Greg Clayton45319462011-02-08 00:35:34 +0000891Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000892{
893 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000894 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000895 {
896 error.SetErrorString ("invalid dynamic library handle");
897 }
Greg Clayton45319462011-02-08 00:35:34 +0000898 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000899 {
Greg Clayton45319462011-02-08 00:35:34 +0000900 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
901 if (::dlclose (dylib_info->handle) != 0)
902 {
903 error.SetErrorString(::dlerror());
904 }
905
906 dylib_info->open_options = 0;
907 dylib_info->handle = 0;
908 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000909 }
910 return error;
911}
912
913void *
Greg Clayton45319462011-02-08 00:35:34 +0000914Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000915{
Greg Clayton45319462011-02-08 00:35:34 +0000916 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000917 {
918 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000919 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000920 else
Greg Clayton45319462011-02-08 00:35:34 +0000921 {
922 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
923
924 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
925 if (symbol_addr)
926 {
927#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
928 // This host doesn't support limiting searches to this shared library
929 // so we need to verify that the match came from this shared library
930 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000931 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000932 {
933 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
934 if (match_dylib_spec != dylib_info->file_spec)
935 {
936 char dylib_path[PATH_MAX];
937 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
938 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
939 else
940 error.SetErrorString ("symbol not found");
941 return NULL;
942 }
943 }
944#endif
945 error.Clear();
946 return symbol_addr;
947 }
948 else
949 {
950 error.SetErrorString(::dlerror());
951 }
952 }
953 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000954}
Greg Claytondd36def2010-10-17 22:03:32 +0000955
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000956FileSpec
957Host::GetModuleFileSpecForHostAddress (const void *host_addr)
958{
959 FileSpec module_filespec;
960 Dl_info info;
961 if (::dladdr (host_addr, &info))
962 {
963 if (info.dli_fname)
964 module_filespec.SetFile(info.dli_fname, true);
965 }
966 return module_filespec;
967}
968
969#endif
970
Greg Claytondd36def2010-10-17 22:03:32 +0000971bool
972Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
973{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000974 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000975 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
976 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000977 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000978 // need to be modified to "do the right thing".
979
980 switch (path_type)
981 {
982 case ePathTypeLLDBShlibDir:
983 {
984 static ConstString g_lldb_so_dir;
985 if (!g_lldb_so_dir)
986 {
987 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
988 g_lldb_so_dir = lldb_file_spec.GetDirectory();
989 }
990 file_spec.GetDirectory() = g_lldb_so_dir;
991 return file_spec.GetDirectory();
992 }
993 break;
994
995 case ePathTypeSupportExecutableDir:
996 {
997 static ConstString g_lldb_support_exe_dir;
998 if (!g_lldb_support_exe_dir)
999 {
1000 FileSpec lldb_file_spec;
1001 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1002 {
1003 char raw_path[PATH_MAX];
1004 char resolved_path[PATH_MAX];
1005 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1006
1007#if defined (__APPLE__)
1008 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1009 if (framework_pos)
1010 {
1011 framework_pos += strlen("LLDB.framework");
Greg Claytondce502e2011-11-04 03:34:56 +00001012#if !defined (__arm__)
Greg Claytondd36def2010-10-17 22:03:32 +00001013 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001014#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001015 }
1016#endif
1017 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1018 g_lldb_support_exe_dir.SetCString(resolved_path);
1019 }
1020 }
1021 file_spec.GetDirectory() = g_lldb_support_exe_dir;
1022 return file_spec.GetDirectory();
1023 }
1024 break;
1025
1026 case ePathTypeHeaderDir:
1027 {
1028 static ConstString g_lldb_headers_dir;
1029 if (!g_lldb_headers_dir)
1030 {
1031#if defined (__APPLE__)
1032 FileSpec lldb_file_spec;
1033 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1034 {
1035 char raw_path[PATH_MAX];
1036 char resolved_path[PATH_MAX];
1037 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1038
1039 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1040 if (framework_pos)
1041 {
1042 framework_pos += strlen("LLDB.framework");
1043 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1044 }
1045 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1046 g_lldb_headers_dir.SetCString(resolved_path);
1047 }
1048#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001049 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001050 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1051#endif
1052 }
1053 file_spec.GetDirectory() = g_lldb_headers_dir;
1054 return file_spec.GetDirectory();
1055 }
1056 break;
1057
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001058#ifdef LLDB_DISABLE_PYTHON
1059 case ePathTypePythonDir:
1060 return false;
1061#else
1062 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001063 {
Greg Claytondd36def2010-10-17 22:03:32 +00001064 static ConstString g_lldb_python_dir;
1065 if (!g_lldb_python_dir)
1066 {
1067 FileSpec lldb_file_spec;
1068 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1069 {
1070 char raw_path[PATH_MAX];
1071 char resolved_path[PATH_MAX];
1072 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1073
1074#if defined (__APPLE__)
1075 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1076 if (framework_pos)
1077 {
1078 framework_pos += strlen("LLDB.framework");
1079 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1080 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001081#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001082 llvm::SmallString<256> python_version_dir;
1083 llvm::raw_svector_ostream os(python_version_dir);
1084 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1085 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001086
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001087 // We may get our string truncated. Should we protect
1088 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001089
Daniel Maleafa7425d2013-08-06 21:40:08 +00001090 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001091 sizeof(raw_path) - strlen(raw_path) - 1);
1092
Greg Claytondd36def2010-10-17 22:03:32 +00001093#endif
1094 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1095 g_lldb_python_dir.SetCString(resolved_path);
1096 }
1097 }
1098 file_spec.GetDirectory() = g_lldb_python_dir;
1099 return file_spec.GetDirectory();
1100 }
1101 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001102#endif
1103
Greg Clayton4272cc72011-02-02 02:24:04 +00001104 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1105 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001106#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001107 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001108 static bool g_lldb_system_plugin_dir_located = false;
1109 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001110 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001111 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001112#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001113 FileSpec lldb_file_spec;
1114 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1115 {
1116 char raw_path[PATH_MAX];
1117 char resolved_path[PATH_MAX];
1118 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1119
1120 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1121 if (framework_pos)
1122 {
1123 framework_pos += strlen("LLDB.framework");
1124 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001125 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1126 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001127 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001128 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001129 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001130#elif defined (__linux__)
1131 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1132 if (lldb_file_spec.Exists())
1133 {
1134 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1135 }
1136#endif // __APPLE__ || __linux__
Greg Clayton4272cc72011-02-02 02:24:04 +00001137 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001138
1139 if (g_lldb_system_plugin_dir)
1140 {
1141 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1142 return true;
1143 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001144#else
1145 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001146 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001147#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001148 }
1149 break;
1150
1151 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1152 {
1153#if defined (__APPLE__)
1154 static ConstString g_lldb_user_plugin_dir;
1155 if (!g_lldb_user_plugin_dir)
1156 {
1157 char user_plugin_path[PATH_MAX];
1158 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1159 user_plugin_path,
1160 sizeof(user_plugin_path)))
1161 {
1162 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1163 }
1164 }
1165 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1166 return file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001167#elif defined (__linux__)
1168 static ConstString g_lldb_user_plugin_dir;
1169 if (!g_lldb_user_plugin_dir)
1170 {
1171 // XDG Base Directory Specification
1172 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1173 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1174 FileSpec lldb_file_spec;
1175 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1176 if (xdg_data_home && xdg_data_home[0])
1177 {
1178 std::string user_plugin_dir (xdg_data_home);
1179 user_plugin_dir += "/lldb";
1180 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1181 }
1182 else
1183 {
1184 const char *home_dir = getenv("HOME");
1185 if (home_dir && home_dir[0])
1186 {
1187 std::string user_plugin_dir (home_dir);
1188 user_plugin_dir += "/.local/share/lldb";
1189 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1190 }
1191 }
1192
1193 if (lldb_file_spec.Exists())
1194 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1195 }
1196 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1197 return file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001198#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001199 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001200 return false;
1201 }
Greg Claytondd36def2010-10-17 22:03:32 +00001202 }
1203
1204 return false;
1205}
1206
Greg Clayton1cb64962011-03-24 04:28:38 +00001207
1208bool
1209Host::GetHostname (std::string &s)
1210{
1211 char hostname[PATH_MAX];
1212 hostname[sizeof(hostname) - 1] = '\0';
1213 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1214 {
1215 struct hostent* h = ::gethostbyname (hostname);
1216 if (h)
1217 s.assign (h->h_name);
1218 else
1219 s.assign (hostname);
1220 return true;
1221 }
1222 return false;
1223}
1224
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001225#ifndef _WIN32
1226
Greg Clayton32e0a752011-03-30 18:16:51 +00001227const char *
1228Host::GetUserName (uint32_t uid, std::string &user_name)
1229{
1230 struct passwd user_info;
1231 struct passwd *user_info_ptr = &user_info;
1232 char user_buffer[PATH_MAX];
1233 size_t user_buffer_size = sizeof(user_buffer);
1234 if (::getpwuid_r (uid,
1235 &user_info,
1236 user_buffer,
1237 user_buffer_size,
1238 &user_info_ptr) == 0)
1239 {
1240 if (user_info_ptr)
1241 {
1242 user_name.assign (user_info_ptr->pw_name);
1243 return user_name.c_str();
1244 }
1245 }
1246 user_name.clear();
1247 return NULL;
1248}
1249
1250const char *
1251Host::GetGroupName (uint32_t gid, std::string &group_name)
1252{
1253 char group_buffer[PATH_MAX];
1254 size_t group_buffer_size = sizeof(group_buffer);
1255 struct group group_info;
1256 struct group *group_info_ptr = &group_info;
1257 // Try the threadsafe version first
1258 if (::getgrgid_r (gid,
1259 &group_info,
1260 group_buffer,
1261 group_buffer_size,
1262 &group_info_ptr) == 0)
1263 {
1264 if (group_info_ptr)
1265 {
1266 group_name.assign (group_info_ptr->gr_name);
1267 return group_name.c_str();
1268 }
1269 }
1270 else
1271 {
1272 // The threadsafe version isn't currently working
1273 // for me on darwin, but the non-threadsafe version
1274 // is, so I am calling it below.
1275 group_info_ptr = ::getgrgid (gid);
1276 if (group_info_ptr)
1277 {
1278 group_name.assign (group_info_ptr->gr_name);
1279 return group_name.c_str();
1280 }
1281 }
1282 group_name.clear();
1283 return NULL;
1284}
1285
Han Ming Ong84647042012-02-25 01:07:38 +00001286uint32_t
1287Host::GetUserID ()
1288{
1289 return getuid();
1290}
1291
1292uint32_t
1293Host::GetGroupID ()
1294{
1295 return getgid();
1296}
1297
1298uint32_t
1299Host::GetEffectiveUserID ()
1300{
1301 return geteuid();
1302}
1303
1304uint32_t
1305Host::GetEffectiveGroupID ()
1306{
1307 return getegid();
1308}
1309
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001310#endif
1311
1312#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1313bool
1314Host::GetOSBuildString (std::string &s)
1315{
1316 s.clear();
1317 return false;
1318}
1319
1320bool
1321Host::GetOSKernelDescription (std::string &s)
1322{
1323 s.clear();
1324 return false;
1325}
1326#endif
1327
Ed Maste47e575e2013-08-29 18:44:27 +00001328#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001329uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001330Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001331{
1332 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001333 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001334}
1335
Greg Claytone996fd32011-03-08 22:40:15 +00001336bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001337Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001338{
Greg Claytone996fd32011-03-08 22:40:15 +00001339 process_info.Clear();
1340 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001341}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001342#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001343
Matt Kopec085d6ce2013-05-31 22:00:07 +00001344#if !defined(__linux__)
1345bool
1346Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1347{
1348 return false;
1349}
1350#endif
1351
Sean Callananc0a6e062011-10-27 21:22:25 +00001352lldb::TargetSP
1353Host::GetDummyTarget (lldb_private::Debugger &debugger)
1354{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001355 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001356
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001357 // FIXME: Maybe the dummy target should be per-Debugger
1358 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1359 {
1360 ArchSpec arch(Target::GetDefaultArchitecture());
1361 if (!arch.IsValid())
1362 arch = Host::GetArchitecture ();
1363 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001364 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001365 arch.GetTriple().getTriple().c_str(),
1366 false,
1367 NULL,
1368 g_dummy_target_sp);
1369 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001370
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001371 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001372}
1373
Greg Claytond1cf11a2012-04-14 01:42:46 +00001374struct ShellInfo
1375{
1376 ShellInfo () :
1377 process_reaped (false),
1378 can_delete (false),
1379 pid (LLDB_INVALID_PROCESS_ID),
1380 signo(-1),
1381 status(-1)
1382 {
1383 }
1384
1385 lldb_private::Predicate<bool> process_reaped;
1386 lldb_private::Predicate<bool> can_delete;
1387 lldb::pid_t pid;
1388 int signo;
1389 int status;
1390};
1391
1392static bool
1393MonitorShellCommand (void *callback_baton,
1394 lldb::pid_t pid,
1395 bool exited, // True if the process did exit
1396 int signo, // Zero for no signal
1397 int status) // Exit value of process if signal is zero
1398{
1399 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1400 shell_info->pid = pid;
1401 shell_info->signo = signo;
1402 shell_info->status = status;
1403 // Let the thread running Host::RunShellCommand() know that the process
1404 // exited and that ShellInfo has been filled in by broadcasting to it
1405 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1406 // Now wait for a handshake back from that thread running Host::RunShellCommand
1407 // so we know that we can delete shell_info_ptr
1408 shell_info->can_delete.WaitForValueEqualTo(true);
1409 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1410 usleep(1000);
1411 // Now delete the shell info that was passed into this function
1412 delete shell_info;
1413 return true;
1414}
1415
1416Error
1417Host::RunShellCommand (const char *command,
1418 const char *working_dir,
1419 int *status_ptr,
1420 int *signo_ptr,
1421 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001422 uint32_t timeout_sec,
1423 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001424{
1425 Error error;
1426 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001427 if (shell && shell[0])
1428 {
1429 // Run the command in a shell
1430 launch_info.SetShell(shell);
1431 launch_info.GetArguments().AppendArgument(command);
1432 const bool localhost = true;
1433 const bool will_debug = false;
1434 const bool first_arg_is_full_shell_command = true;
1435 launch_info.ConvertArgumentsForLaunchingInShell (error,
1436 localhost,
1437 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001438 first_arg_is_full_shell_command,
1439 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001440 }
1441 else
1442 {
1443 // No shell, just run it
1444 Args args (command);
1445 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001446 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001447 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001448
1449 if (working_dir)
1450 launch_info.SetWorkingDirectory(working_dir);
1451 char output_file_path_buffer[L_tmpnam];
1452 const char *output_file_path = NULL;
1453 if (command_output_ptr)
1454 {
1455 // Create a temporary file to get the stdout/stderr and redirect the
1456 // output of the command into this file. We will later read this file
1457 // if all goes well and fill the data into "command_output_ptr"
1458 output_file_path = ::tmpnam(output_file_path_buffer);
1459 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1460 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001461 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001462 }
1463 else
1464 {
1465 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1466 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1467 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1468 }
1469
1470 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001471 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001472
1473 const bool monitor_signals = false;
1474 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1475
1476 error = LaunchProcess (launch_info);
1477 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001478
1479 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1480 error.SetErrorString("failed to get process ID");
1481
1482 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001483 {
1484 // The process successfully launched, so we can defer ownership of
1485 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001486 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001487 // doesn't need to delete the ShellInfo anymore.
1488 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001489 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001490 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001491 if (timeout_sec > 0) {
1492 timeout_time.OffsetWithSeconds(timeout_sec);
1493 timeout_ptr = &timeout_time;
1494 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001495 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001496 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001497 if (timed_out)
1498 {
1499 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001500
Greg Claytond1cf11a2012-04-14 01:42:46 +00001501 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001502 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001503 // Wait for the monitor callback to get the message
1504 timeout_time = TimeValue::Now();
1505 timeout_time.OffsetWithSeconds(1);
1506 timed_out = false;
1507 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1508 }
1509 else
1510 {
1511 if (status_ptr)
1512 *status_ptr = shell_info->status;
1513
1514 if (signo_ptr)
1515 *signo_ptr = shell_info->signo;
1516
1517 if (command_output_ptr)
1518 {
1519 command_output_ptr->clear();
1520 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1521 uint64_t file_size = file_spec.GetByteSize();
1522 if (file_size > 0)
1523 {
1524 if (file_size > command_output_ptr->max_size())
1525 {
1526 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1527 }
1528 else
1529 {
1530 command_output_ptr->resize(file_size);
1531 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1532 }
1533 }
1534 }
1535 }
1536 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1537 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001538
1539 if (output_file_path)
1540 ::unlink (output_file_path);
1541 // Handshake with the monitor thread, or just let it know in advance that
1542 // it can delete "shell_info" in case we timed out and were not able to kill
1543 // the process...
1544 return error;
1545}
1546
Daniel Malea4244cbd2013-08-27 20:58:59 +00001547#if defined(__linux__) or defined(__FreeBSD__)
1548// The functions below implement process launching via posix_spawn() for Linux
1549// and FreeBSD.
1550
1551// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1552static Error
1553LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1554{
1555 Error error;
1556 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1557
1558 assert(exe_path);
1559 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1560
1561 posix_spawnattr_t attr;
1562
1563 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1564 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1565 if (error.Fail())
1566 return error;
1567
1568 // Make a quick class that will cleanup the posix spawn attributes in case
1569 // we return in the middle of this function.
1570 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1571
1572 sigset_t no_signals;
1573 sigset_t all_signals;
1574 sigemptyset (&no_signals);
1575 sigfillset (&all_signals);
1576 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1577 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1578
1579 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1580
1581 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1582 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1583 if (error.Fail())
1584 return error;
1585
1586 const size_t num_file_actions = launch_info.GetNumFileActions ();
1587 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1588 // Make a quick class that will cleanup the posix spawn attributes in case
1589 // we return in the middle of this function.
1590 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1591 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1592
1593 if (num_file_actions > 0)
1594 {
1595 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1596 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1597 if (error.Fail())
1598 return error;
1599
1600 file_action_ptr = &file_actions;
1601 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1602
1603 for (size_t i = 0; i < num_file_actions; ++i)
1604 {
1605 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1606 if (launch_file_action &&
1607 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1608 launch_file_action,
1609 log,
1610 error))
1611 return error;
1612 }
1613 }
1614
1615 // Change working directory if neccessary.
1616 char current_dir[PATH_MAX];
1617 current_dir[0] = '\0';
1618
1619 const char *working_dir = launch_info.GetWorkingDirectory();
1620 if (working_dir != NULL)
1621 {
1622 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1623 {
1624 error.SetError(errno, eErrorTypePOSIX);
1625 error.LogIfError(log, "unable to save the current directory");
1626 return error;
1627 }
1628
1629 if (::chdir(working_dir) == -1)
1630 {
1631 error.SetError(errno, eErrorTypePOSIX);
1632 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1633 return error;
1634 }
1635 }
1636
1637 const char *tmp_argv[2];
1638 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1639 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1640
1641 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1642 // We must pass argv into posix_spawnp and it must contain at least two items -
1643 // pointer to an executable and NULL.
1644 if (argv == NULL)
1645 {
1646 tmp_argv[0] = exe_path;
1647 tmp_argv[1] = NULL;
1648 argv = (char * const*)tmp_argv;
1649 }
1650
1651 error.SetError (::posix_spawnp (&pid,
1652 exe_path,
1653 (num_file_actions > 0) ? &file_actions : NULL,
1654 &attr,
1655 argv,
1656 envp),
1657 eErrorTypePOSIX);
1658
1659 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1660 pid, exe_path, file_action_ptr, &attr, argv, envp);
1661
1662 // Change back the current directory.
1663 // NOTE: do not override previously established error from posix_spawnp.
1664 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1665 {
1666 error.SetError(errno, eErrorTypePOSIX);
1667 error.LogIfError(log, "unable to change current directory back to %s",
1668 current_dir);
1669 }
1670
1671 return error;
1672}
1673
1674
1675Error
1676Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1677{
1678 Error error;
1679 char exe_path[PATH_MAX];
1680
1681 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1682
1683 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1684
1685 FileSpec exe_spec(launch_info.GetExecutableFile());
1686
1687 FileSpec::FileType file_type = exe_spec.GetFileType();
1688 if (file_type != FileSpec::eFileTypeRegular)
1689 {
1690 lldb::ModuleSP exe_module_sp;
1691 error = host_platform_sp->ResolveExecutable (exe_spec,
1692 arch_spec,
1693 exe_module_sp,
1694 NULL);
1695
1696 if (error.Fail())
1697 return error;
1698
1699 if (exe_module_sp)
1700 exe_spec = exe_module_sp->GetFileSpec();
1701 }
1702
1703 if (exe_spec.Exists())
1704 {
1705 exe_spec.GetPath (exe_path, sizeof(exe_path));
1706 }
1707 else
1708 {
1709 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1710 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1711 return error;
1712 }
1713
1714 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1715
1716 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1717
1718 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1719
1720 if (pid != LLDB_INVALID_PROCESS_ID)
1721 {
1722 // If all went well, then set the process ID into the launch info
1723 launch_info.SetProcessID(pid);
1724
1725 // Make sure we reap any processes we spawn or we will have zombies.
1726 if (!launch_info.MonitorProcess())
1727 {
1728 const bool monitor_signals = false;
1729 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1730 NULL,
1731 pid,
1732 monitor_signals);
1733 }
1734 }
1735 else
1736 {
1737 // Invalid process ID, something didn't go well
1738 if (error.Success())
1739 error.SetErrorString ("process launch failed for unknown reasons");
1740 }
1741 return error;
1742}
1743
1744#endif // defined(__linux__) or defined(__FreeBSD__)
1745
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001746#ifndef _WIN32
1747
1748size_t
1749Host::GetPageSize()
1750{
1751 return ::getpagesize();
1752}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001753
Greg Claytone3e3fee2013-02-17 20:46:30 +00001754uint32_t
1755Host::GetNumberCPUS ()
1756{
1757 static uint32_t g_num_cores = UINT32_MAX;
1758 if (g_num_cores == UINT32_MAX)
1759 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001760#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001761
1762 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001763
Greg Claytone3e3fee2013-02-17 20:46:30 +00001764#else
1765
1766 // Assume POSIX support if a host specific case has not been supplied above
1767 g_num_cores = 0;
1768 int num_cores = 0;
1769 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001770#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001771 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001772#else
1773 int mib[] = { CTL_HW, HW_NCPU };
1774#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001775
1776 /* get the number of CPUs from the system */
1777 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1778 {
1779 g_num_cores = num_cores;
1780 }
1781 else
1782 {
1783 mib[1] = HW_NCPU;
1784 num_cores_len = sizeof(num_cores);
1785 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1786 {
1787 if (num_cores > 0)
1788 g_num_cores = num_cores;
1789 }
1790 }
1791#endif
1792 }
1793 return g_num_cores;
1794}
1795
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001796void
1797Host::Kill(lldb::pid_t pid, int signo)
1798{
1799 ::kill(pid, signo);
1800}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001801
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001802#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001803
Johnny Chen8f3d8382011-08-02 20:52:42 +00001804#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001805bool
Greg Clayton3b147632010-12-18 01:54:34 +00001806Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001807{
1808 return false;
1809}
Greg Claytondd36def2010-10-17 22:03:32 +00001810
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001811void
1812Host::SetCrashDescriptionWithFormat (const char *format, ...)
1813{
1814}
1815
1816void
1817Host::SetCrashDescription (const char *description)
1818{
1819}
Greg Claytondd36def2010-10-17 22:03:32 +00001820
1821lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001822Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001823{
1824 return LLDB_INVALID_PROCESS_ID;
1825}
1826
Daniel Maleae0f8f572013-08-26 23:57:52 +00001827uint32_t
1828Host::MakeDirectory (const char* path, mode_t mode)
1829{
1830 return UINT32_MAX;
1831}
Greg Clayton2bddd342010-09-07 20:11:56 +00001832#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00001833
1834typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
1835FDToFileMap& GetFDToFileMap()
1836{
1837 static FDToFileMap g_fd2filemap;
1838 return g_fd2filemap;
1839}
1840
1841lldb::user_id_t
1842Host::OpenFile (const FileSpec& file_spec,
1843 uint32_t flags,
1844 mode_t mode,
1845 Error &error)
1846{
1847 std::string path (file_spec.GetPath());
1848 if (path.empty())
1849 {
1850 error.SetErrorString("empty path");
1851 return UINT64_MAX;
1852 }
1853 FileSP file_sp(new File());
1854 error = file_sp->Open(path.c_str(),flags,mode);
1855 if (file_sp->IsValid() == false)
1856 return UINT64_MAX;
1857 lldb::user_id_t fd = file_sp->GetDescriptor();
1858 GetFDToFileMap()[fd] = file_sp;
1859 return fd;
1860}
1861
1862bool
1863Host::CloseFile (lldb::user_id_t fd, Error &error)
1864{
1865 if (fd == UINT64_MAX)
1866 {
1867 error.SetErrorString ("invalid file descriptor");
1868 return false;
1869 }
1870 FDToFileMap& file_map = GetFDToFileMap();
1871 FDToFileMap::iterator pos = file_map.find(fd);
1872 if (pos == file_map.end())
1873 {
1874 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1875 return false;
1876 }
1877 FileSP file_sp = pos->second;
1878 if (!file_sp)
1879 {
1880 error.SetErrorString ("invalid host backing file");
1881 return false;
1882 }
1883 error = file_sp->Close();
1884 file_map.erase(pos);
1885 return error.Success();
1886}
1887
1888uint64_t
1889Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
1890{
1891 if (fd == UINT64_MAX)
1892 {
1893 error.SetErrorString ("invalid file descriptor");
1894 return UINT64_MAX;
1895 }
1896 FDToFileMap& file_map = GetFDToFileMap();
1897 FDToFileMap::iterator pos = file_map.find(fd);
1898 if (pos == file_map.end())
1899 {
1900 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
1901 return false;
1902 }
1903 FileSP file_sp = pos->second;
1904 if (!file_sp)
1905 {
1906 error.SetErrorString ("invalid host backing file");
1907 return UINT64_MAX;
1908 }
1909 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
1910 return UINT64_MAX;
1911 size_t bytes_written = src_len;
1912 error = file_sp->Write(src, bytes_written);
1913 if (error.Fail())
1914 return UINT64_MAX;
1915 return bytes_written;
1916}
1917
1918uint64_t
1919Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
1920{
1921 if (fd == UINT64_MAX)
1922 {
1923 error.SetErrorString ("invalid file descriptor");
1924 return UINT64_MAX;
1925 }
1926 FDToFileMap& file_map = GetFDToFileMap();
1927 FDToFileMap::iterator pos = file_map.find(fd);
1928 if (pos == file_map.end())
1929 {
1930 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1931 return false;
1932 }
1933 FileSP file_sp = pos->second;
1934 if (!file_sp)
1935 {
1936 error.SetErrorString ("invalid host backing file");
1937 return UINT64_MAX;
1938 }
1939 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
1940 return UINT64_MAX;
1941 size_t bytes_read = dst_len;
1942 error = file_sp->Read(dst ,bytes_read);
1943 if (error.Fail())
1944 return UINT64_MAX;
1945 return bytes_read;
1946}
1947
1948lldb::user_id_t
1949Host::GetFileSize (const FileSpec& file_spec)
1950{
1951 return file_spec.GetByteSize();
1952}
1953
1954bool
1955Host::GetFileExists (const FileSpec& file_spec)
1956{
1957 return file_spec.Exists();
1958}
1959
1960bool
1961Host::CalculateMD5 (const FileSpec& file_spec,
1962 uint64_t &low,
1963 uint64_t &high)
1964{
1965#if defined (__APPLE__)
1966 StreamString md5_cmd_line;
1967 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
1968 std::string hash_string;
1969 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
1970 if (err.Fail())
1971 return false;
1972 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
1973 // if the output is any other length it is probably wrong
1974 if (hash_string.size() != 32)
1975 return false;
1976 std::string part1(hash_string,0,16);
1977 std::string part2(hash_string,16);
1978 const char* part1_cstr = part1.c_str();
1979 const char* part2_cstr = part2.c_str();
1980 high = ::strtoull(part1_cstr, NULL, 16);
1981 low = ::strtoull(part2_cstr, NULL, 16);
1982 return true;
1983#else
1984 // your own MD5 implementation here
1985 return false;
1986#endif
1987}