blob: 9bf61ad24c9bed7b5aad518ae927071b474a08a3 [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>
Ed Mastef2b01622013-06-28 12:35:08 +000025#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000026#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000027
28#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000029#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000030#include <mach/mach_init.h>
31#include <mach-o/dyld.h>
Ed Maste8b006c62013-06-25 18:58:11 +000032#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000033
Ed Maste8b006c62013-06-25 18:58:11 +000034#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000035#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000036#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000037#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000038#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000039
Ed Maste8b006c62013-06-25 18:58:11 +000040#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000041#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000042#endif
43
Greg Clayton2bddd342010-09-07 20:11:56 +000044#include "lldb/Host/Host.h"
45#include "lldb/Core/ArchSpec.h"
46#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000047#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000048#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000049#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000050#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000051#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000052#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000053#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000054#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000055#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000057#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000058#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000059#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000060
Daniel Maleafa7425d2013-08-06 21:40:08 +000061#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000062#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000063#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000064
Greg Clayton32e0a752011-03-30 18:16:51 +000065
Greg Clayton2bddd342010-09-07 20:11:56 +000066using namespace lldb;
67using namespace lldb_private;
68
Greg Claytone4e45922011-11-16 05:37:56 +000069
Virgile Bellob2f1fb22013-08-23 12:44:05 +000070#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000071struct MonitorInfo
72{
73 lldb::pid_t pid; // The process ID to monitor
74 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
75 void *callback_baton; // The callback baton for the callback function
76 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
77};
78
Virgile Bellob2f1fb22013-08-23 12:44:05 +000079static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000080MonitorChildProcessThreadFunction (void *arg);
81
82lldb::thread_t
83Host::StartMonitoringChildProcess
84(
85 Host::MonitorChildProcessCallback callback,
86 void *callback_baton,
87 lldb::pid_t pid,
88 bool monitor_signals
89)
90{
91 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +000092 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +000093
Greg Claytone4e45922011-11-16 05:37:56 +000094 info_ptr->pid = pid;
95 info_ptr->callback = callback;
96 info_ptr->callback_baton = callback_baton;
97 info_ptr->monitor_signals = monitor_signals;
98
99 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000100 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000101 thread = ThreadCreate (thread_name,
102 MonitorChildProcessThreadFunction,
103 info_ptr,
104 NULL);
105
Greg Clayton2bddd342010-09-07 20:11:56 +0000106 return thread;
107}
108
109//------------------------------------------------------------------
110// Scoped class that will disable thread canceling when it is
111// constructed, and exception safely restore the previous value it
112// when it goes out of scope.
113//------------------------------------------------------------------
114class ScopedPThreadCancelDisabler
115{
116public:
117 ScopedPThreadCancelDisabler()
118 {
119 // Disable the ability for this thread to be cancelled
120 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
121 if (err != 0)
122 m_old_state = -1;
123
124 }
125
126 ~ScopedPThreadCancelDisabler()
127 {
128 // Restore the ability for this thread to be cancelled to what it
129 // previously was.
130 if (m_old_state != -1)
131 ::pthread_setcancelstate (m_old_state, 0);
132 }
133private:
134 int m_old_state; // Save the old cancelability state.
135};
136
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000137static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000138MonitorChildProcessThreadFunction (void *arg)
139{
Greg Clayton5160ce52013-03-27 23:08:40 +0000140 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000141 const char *function = __FUNCTION__;
142 if (log)
143 log->Printf ("%s (arg = %p) thread starting...", function, arg);
144
145 MonitorInfo *info = (MonitorInfo *)arg;
146
147 const Host::MonitorChildProcessCallback callback = info->callback;
148 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000149 const bool monitor_signals = info->monitor_signals;
150
Daniel Malea4244cbd2013-08-27 20:58:59 +0000151 assert (info->pid <= UINT32_MAX);
152 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
153
Greg Clayton2bddd342010-09-07 20:11:56 +0000154 delete info;
155
156 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000157#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000158 #define __WALL 0
159#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000160 const int options = __WALL;
161
Greg Clayton2bddd342010-09-07 20:11:56 +0000162 while (1)
163 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000164 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000165 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000166 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000167
168 // Wait for all child processes
169 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000170 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000171 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000172 ::pthread_testcancel ();
173
174 if (wait_pid == -1)
175 {
176 if (errno == EINTR)
177 continue;
178 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000179 {
180 if (log)
181 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000182 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000183 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000184 }
Matt Kopec650648f2013-01-08 16:30:18 +0000185 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000186 {
187 bool exited = false;
188 int signal = 0;
189 int exit_status = 0;
190 const char *status_cstr = NULL;
191 if (WIFSTOPPED(status))
192 {
193 signal = WSTOPSIG(status);
194 status_cstr = "STOPPED";
195 }
196 else if (WIFEXITED(status))
197 {
198 exit_status = WEXITSTATUS(status);
199 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000200 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000201 }
202 else if (WIFSIGNALED(status))
203 {
204 signal = WTERMSIG(status);
205 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000206 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000207 exited = true;
208 exit_status = -1;
209 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000210 }
211 else
212 {
Johnny Chen44805302011-07-19 19:48:13 +0000213 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000214 }
215
216 // Scope for pthread_cancel_disabler
217 {
218 ScopedPThreadCancelDisabler pthread_cancel_disabler;
219
Caroline Tice20ad3c42010-10-29 21:48:37 +0000220 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000221 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000222 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 +0000223 function,
224 wait_pid,
225 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000226 pid,
227 status,
228 status_cstr,
229 signal,
230 exit_status);
231
232 if (exited || (signal != 0 && monitor_signals))
233 {
Greg Claytone4e45922011-11-16 05:37:56 +0000234 bool callback_return = false;
235 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000236 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000237
238 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000239 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000240 {
241 if (log)
242 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000243 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000244 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000245 // If the callback returns true, it means this process should
246 // exit
247 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000248 {
249 if (log)
250 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000251 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000252 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000253 }
254 }
255 }
256 }
257
Caroline Tice20ad3c42010-10-29 21:48:37 +0000258 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000259 if (log)
260 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
261
262 return NULL;
263}
264
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000265#endif // #if !defined (__APPLE__) && !defined (_WIN32)
266
267#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000268
269void
270Host::SystemLog (SystemLogType type, const char *format, va_list args)
271{
272 vfprintf (stderr, format, args);
273}
274
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000275#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000276
Greg Claytone38a5ed2012-01-05 03:57:59 +0000277void
278Host::SystemLog (SystemLogType type, const char *format, ...)
279{
280 va_list args;
281 va_start (args, format);
282 SystemLog (type, format, args);
283 va_end (args);
284}
285
Greg Clayton2bddd342010-09-07 20:11:56 +0000286const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000287Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000288{
Greg Clayton514487e2011-02-15 21:59:32 +0000289 static bool g_supports_32 = false;
290 static bool g_supports_64 = false;
291 static ArchSpec g_host_arch_32;
292 static ArchSpec g_host_arch_64;
293
Greg Clayton2bddd342010-09-07 20:11:56 +0000294#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000295
296 // Apple is different in that it can support both 32 and 64 bit executables
297 // in the same operating system running concurrently. Here we detect the
298 // correct host architectures for both 32 and 64 bit including if 64 bit
299 // executables are supported on the system.
300
301 if (g_supports_32 == false && g_supports_64 == false)
302 {
303 // All apple systems support 32 bit execution.
304 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000305 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000306 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000307 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000308 ArchSpec host_arch;
309 // These will tell us about the kernel architecture, which even on a 64
310 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000311 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
312 {
Greg Clayton514487e2011-02-15 21:59:32 +0000313 len = sizeof (cpusubtype);
314 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
315 cpusubtype = CPU_TYPE_ANY;
316
Greg Clayton2bddd342010-09-07 20:11:56 +0000317 len = sizeof (is_64_bit_capable);
318 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
319 {
320 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000321 g_supports_64 = true;
322 }
323
324 if (is_64_bit_capable)
325 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000326#if defined (__i386__) || defined (__x86_64__)
327 if (cpusubtype == CPU_SUBTYPE_486)
328 cpusubtype = CPU_SUBTYPE_I386_ALL;
329#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000330 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000331 {
Greg Clayton514487e2011-02-15 21:59:32 +0000332 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000333 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
334 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000335 }
336 else
337 {
338 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000339 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000340 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000341 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000342 }
343 }
Greg Clayton514487e2011-02-15 21:59:32 +0000344 else
345 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000346 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000347 g_host_arch_64.Clear();
348 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000349 }
Greg Clayton514487e2011-02-15 21:59:32 +0000350 }
351
352#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000353
Greg Clayton514487e2011-02-15 21:59:32 +0000354 if (g_supports_32 == false && g_supports_64 == false)
355 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000356 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000357
Stephen Wilsonbd588712011-02-24 19:15:09 +0000358 g_host_arch_32.Clear();
359 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000360
Greg Claytonb29e6c62012-10-11 17:38:58 +0000361 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
362 // for the default triple. It's probably an artifact of config.guess.
363 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
364 triple.setVendorName("");
365
Stephen Wilsonbd588712011-02-24 19:15:09 +0000366 switch (triple.getArch())
367 {
368 default:
369 g_host_arch_32.SetTriple(triple);
370 g_supports_32 = true;
371 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000372
Stephen Wilsonbd588712011-02-24 19:15:09 +0000373 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000374 g_host_arch_64.SetTriple(triple);
375 g_supports_64 = true;
376 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
377 g_supports_32 = true;
378 break;
379
Stephen Wilsonbd588712011-02-24 19:15:09 +0000380 case llvm::Triple::sparcv9:
381 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000382 g_host_arch_64.SetTriple(triple);
383 g_supports_64 = true;
384 break;
385 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000386
387 g_supports_32 = g_host_arch_32.IsValid();
388 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000389 }
Greg Clayton514487e2011-02-15 21:59:32 +0000390
391#endif // #else for #if defined (__APPLE__)
392
393 if (arch_kind == eSystemDefaultArchitecture32)
394 return g_host_arch_32;
395 else if (arch_kind == eSystemDefaultArchitecture64)
396 return g_host_arch_64;
397
398 if (g_supports_64)
399 return g_host_arch_64;
400
401 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000402}
403
404const ConstString &
405Host::GetVendorString()
406{
407 static ConstString g_vendor;
408 if (!g_vendor)
409 {
Greg Clayton950971f2012-05-12 00:01:21 +0000410 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
411 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
412 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000413 }
414 return g_vendor;
415}
416
417const ConstString &
418Host::GetOSString()
419{
420 static ConstString g_os_string;
421 if (!g_os_string)
422 {
Greg Clayton950971f2012-05-12 00:01:21 +0000423 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
424 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
425 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000426 }
427 return g_os_string;
428}
429
430const ConstString &
431Host::GetTargetTriple()
432{
433 static ConstString g_host_triple;
434 if (!(g_host_triple))
435 {
Greg Clayton950971f2012-05-12 00:01:21 +0000436 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
437 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000438 }
439 return g_host_triple;
440}
441
442lldb::pid_t
443Host::GetCurrentProcessID()
444{
445 return ::getpid();
446}
447
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000448#ifndef _WIN32
449
Greg Clayton2bddd342010-09-07 20:11:56 +0000450lldb::tid_t
451Host::GetCurrentThreadID()
452{
453#if defined (__APPLE__)
Greg Clayton813ddfc2012-09-18 18:19:49 +0000454 // Calling "mach_port_deallocate()" bumps the reference count on the thread
455 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
456 // count.
457 thread_port_t thread_self = mach_thread_self();
458 mach_port_deallocate(mach_task_self(), thread_self);
459 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000460#elif defined(__FreeBSD__)
461 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000462#elif defined(__linux__)
463 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000464#else
465 return lldb::tid_t(pthread_self());
466#endif
467}
468
Jim Ingham372787f2012-04-07 00:00:41 +0000469lldb::thread_t
470Host::GetCurrentThread ()
471{
472 return lldb::thread_t(pthread_self());
473}
474
Greg Clayton2bddd342010-09-07 20:11:56 +0000475const char *
476Host::GetSignalAsCString (int signo)
477{
478 switch (signo)
479 {
480 case SIGHUP: return "SIGHUP"; // 1 hangup
481 case SIGINT: return "SIGINT"; // 2 interrupt
482 case SIGQUIT: return "SIGQUIT"; // 3 quit
483 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
484 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
485 case SIGABRT: return "SIGABRT"; // 6 abort()
Greg Clayton0ddf6be2011-11-04 03:42:38 +0000486#if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE))
Greg Clayton2bddd342010-09-07 20:11:56 +0000487 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000488#endif
489#if !defined(_POSIX_C_SOURCE)
Greg Clayton2bddd342010-09-07 20:11:56 +0000490 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000491#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000492 case SIGFPE: return "SIGFPE"; // 8 floating point exception
493 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
494 case SIGBUS: return "SIGBUS"; // 10 bus error
495 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
496 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
497 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
498 case SIGALRM: return "SIGALRM"; // 14 alarm clock
499 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
500 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
501 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
502 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
503 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
504 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
505 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
506 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
507#if !defined(_POSIX_C_SOURCE)
508 case SIGIO: return "SIGIO"; // 23 input/output possible signal
509#endif
510 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
511 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
512 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
513 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
514#if !defined(_POSIX_C_SOURCE)
515 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
516 case SIGINFO: return "SIGINFO"; // 29 information request
517#endif
518 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
519 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
520 default:
521 break;
522 }
523 return NULL;
524}
525
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000526#endif
527
Greg Clayton2bddd342010-09-07 20:11:56 +0000528void
529Host::WillTerminate ()
530{
531}
532
Sylvestre Ledru59405832013-07-01 08:21:36 +0000533#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000534
Greg Clayton2bddd342010-09-07 20:11:56 +0000535void
536Host::ThreadCreated (const char *thread_name)
537{
538}
Greg Claytone5219662010-12-03 06:02:24 +0000539
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000540void
Greg Claytone5219662010-12-03 06:02:24 +0000541Host::Backtrace (Stream &strm, uint32_t max_frames)
542{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000543 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000544}
545
Greg Clayton85851dd2010-12-04 00:10:17 +0000546size_t
547Host::GetEnvironment (StringList &env)
548{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000549 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000550 return 0;
551}
552
Sylvestre Ledru59405832013-07-01 08:21:36 +0000553#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000554
555struct HostThreadCreateInfo
556{
557 std::string thread_name;
558 thread_func_t thread_fptr;
559 thread_arg_t thread_arg;
560
561 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
562 thread_name (name ? name : ""),
563 thread_fptr (fptr),
564 thread_arg (arg)
565 {
566 }
567};
568
569static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000570#ifdef _WIN32
571__stdcall
572#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000573ThreadCreateTrampoline (thread_arg_t arg)
574{
575 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
576 Host::ThreadCreated (info->thread_name.c_str());
577 thread_func_t thread_fptr = info->thread_fptr;
578 thread_arg_t thread_arg = info->thread_arg;
579
Greg Clayton5160ce52013-03-27 23:08:40 +0000580 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000581 if (log)
582 log->Printf("thread created");
583
584 delete info;
585 return thread_fptr (thread_arg);
586}
587
588lldb::thread_t
589Host::ThreadCreate
590(
591 const char *thread_name,
592 thread_func_t thread_fptr,
593 thread_arg_t thread_arg,
594 Error *error
595)
596{
597 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
598
599 // Host::ThreadCreateTrampoline will delete this pointer for us.
600 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
601
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000602#ifdef _WIN32
603 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
604 int err = thread <= 0 ? GetLastError() : 0;
605#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000606 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000607#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000608 if (err == 0)
609 {
610 if (error)
611 error->Clear();
612 return thread;
613 }
614
615 if (error)
616 error->SetError (err, eErrorTypePOSIX);
617
618 return LLDB_INVALID_HOST_THREAD;
619}
620
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000621#ifndef _WIN32
622
Greg Clayton2bddd342010-09-07 20:11:56 +0000623bool
624Host::ThreadCancel (lldb::thread_t thread, Error *error)
625{
626 int err = ::pthread_cancel (thread);
627 if (error)
628 error->SetError(err, eErrorTypePOSIX);
629 return err == 0;
630}
631
632bool
633Host::ThreadDetach (lldb::thread_t thread, Error *error)
634{
635 int err = ::pthread_detach (thread);
636 if (error)
637 error->SetError(err, eErrorTypePOSIX);
638 return err == 0;
639}
640
641bool
642Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
643{
644 int err = ::pthread_join (thread, thread_result_ptr);
645 if (error)
646 error->SetError(err, eErrorTypePOSIX);
647 return err == 0;
648}
649
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000650lldb::thread_key_t
651Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
652{
653 pthread_key_t key;
654 ::pthread_key_create (&key, callback);
655 return key;
656}
657
658void*
659Host::ThreadLocalStorageGet(lldb::thread_key_t key)
660{
661 return ::pthread_getspecific (key);
662}
663
664void
665Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
666{
667 ::pthread_setspecific (key, value);
668}
669
Matt Kopec62502c62013-05-13 19:33:58 +0000670bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000671Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
672{
Greg Clayton85719632013-02-27 22:51:58 +0000673#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000674 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
675 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
676 if (pid == LLDB_INVALID_PROCESS_ID)
677 pid = curr_pid;
678
679 if (tid == LLDB_INVALID_THREAD_ID)
680 tid = curr_tid;
681
Greg Clayton2bddd342010-09-07 20:11:56 +0000682 // Set the pthread name if possible
683 if (pid == curr_pid && tid == curr_tid)
684 {
Matt Kopec62502c62013-05-13 19:33:58 +0000685 if (::pthread_setname_np (name) == 0)
686 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000687 }
Matt Kopec62502c62013-05-13 19:33:58 +0000688 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000689#elif defined (__FreeBSD__)
690 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
691 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
692 if (pid == LLDB_INVALID_PROCESS_ID)
693 pid = curr_pid;
694
695 if (tid == LLDB_INVALID_THREAD_ID)
696 tid = curr_tid;
697
698 // Set the pthread name if possible
699 if (pid == curr_pid && tid == curr_tid)
700 {
Michael Sartainc2052432013-08-01 18:51:08 +0000701 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000702 return true;
703 }
704 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000705#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000706 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
707 if (fn)
708 {
Matt Kopec62502c62013-05-13 19:33:58 +0000709 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
710 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000711 if (pid == LLDB_INVALID_PROCESS_ID)
712 pid = curr_pid;
713
714 if (tid == LLDB_INVALID_THREAD_ID)
715 tid = curr_tid;
716
Michael Sartainc2052432013-08-01 18:51:08 +0000717 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000718 {
Michael Sartainc2052432013-08-01 18:51:08 +0000719 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
720 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
721
722 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000723 return true;
724 }
725 }
726 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000727#else
728 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000729#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000730}
731
Ed Maste02983be2013-07-25 19:10:32 +0000732bool
733Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
734 const char *thread_name, size_t len)
735{
736 char *namebuf = (char *)::malloc (len + 1);
737
738 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
739 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
740 // off leads to a lot of similar named threads. Go through the thread name
741 // and search for the last dot and use that.
742 const char *lastdot = ::strrchr (thread_name, '.');
743
744 if (lastdot && lastdot != thread_name)
745 thread_name = lastdot + 1;
746 ::strncpy (namebuf, thread_name, len);
747 namebuf[len] = 0;
748
749 int namebuflen = strlen(namebuf);
750 if (namebuflen > 0)
751 {
752 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
753 {
754 // Trim off trailing '(' and '>' characters for a bit more cleanup.
755 namebuflen--;
756 namebuf[namebuflen] = 0;
757 }
758 return Host::SetThreadName (pid, tid, namebuf);
759 }
760 return false;
761}
762
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000763#endif
764
Greg Clayton2bddd342010-09-07 20:11:56 +0000765FileSpec
766Host::GetProgramFileSpec ()
767{
768 static FileSpec g_program_filespec;
769 if (!g_program_filespec)
770 {
771#if defined (__APPLE__)
772 char program_fullpath[PATH_MAX];
773 // If DST is NULL, then return the number of bytes needed.
774 uint32_t len = sizeof(program_fullpath);
775 int err = _NSGetExecutablePath (program_fullpath, &len);
776 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000777 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000778 else if (err == -1)
779 {
780 char *large_program_fullpath = (char *)::malloc (len + 1);
781
782 err = _NSGetExecutablePath (large_program_fullpath, &len);
783 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000784 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000785
786 ::free (large_program_fullpath);
787 }
788#elif defined (__linux__)
789 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000790 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
791 if (len > 0) {
792 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000793 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000794 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000795#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000796 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
797 size_t exe_path_size;
798 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
799 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000800 char *exe_path = new char[exe_path_size];
801 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
802 g_program_filespec.SetFile(exe_path, false);
803 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000804 }
805#endif
806 }
807 return g_program_filespec;
808}
809
Greg Clayton2bddd342010-09-07 20:11:56 +0000810#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000811
812bool
813Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
814{
815 bundle.Clear();
816 return false;
817}
818
Greg Clayton2bddd342010-09-07 20:11:56 +0000819bool
Greg Claytondd36def2010-10-17 22:03:32 +0000820Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000821{
Greg Claytondd36def2010-10-17 22:03:32 +0000822 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000823}
824#endif
825
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000826#ifndef _WIN32
827
Greg Clayton45319462011-02-08 00:35:34 +0000828// Opaque info that tracks a dynamic library that was loaded
829struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000830{
Greg Clayton45319462011-02-08 00:35:34 +0000831 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
832 file_spec (fs),
833 open_options (o),
834 handle (h)
835 {
836 }
837
838 const FileSpec file_spec;
839 uint32_t open_options;
840 void * handle;
841};
842
843void *
844Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
845{
Greg Clayton4272cc72011-02-02 02:24:04 +0000846 char path[PATH_MAX];
847 if (file_spec.GetPath(path, sizeof(path)))
848 {
Greg Clayton45319462011-02-08 00:35:34 +0000849 int mode = 0;
850
851 if (options & eDynamicLibraryOpenOptionLazy)
852 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000853 else
854 mode |= RTLD_NOW;
855
Greg Clayton45319462011-02-08 00:35:34 +0000856
857 if (options & eDynamicLibraryOpenOptionLocal)
858 mode |= RTLD_LOCAL;
859 else
860 mode |= RTLD_GLOBAL;
861
862#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
863 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
864 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000865#endif
Greg Clayton45319462011-02-08 00:35:34 +0000866
867 void * opaque = ::dlopen (path, mode);
868
869 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000870 {
871 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000872 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000873 }
874 else
875 {
876 error.SetErrorString(::dlerror());
877 }
878 }
879 else
880 {
881 error.SetErrorString("failed to extract path");
882 }
Greg Clayton45319462011-02-08 00:35:34 +0000883 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000884}
885
886Error
Greg Clayton45319462011-02-08 00:35:34 +0000887Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000888{
889 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000890 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000891 {
892 error.SetErrorString ("invalid dynamic library handle");
893 }
Greg Clayton45319462011-02-08 00:35:34 +0000894 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000895 {
Greg Clayton45319462011-02-08 00:35:34 +0000896 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
897 if (::dlclose (dylib_info->handle) != 0)
898 {
899 error.SetErrorString(::dlerror());
900 }
901
902 dylib_info->open_options = 0;
903 dylib_info->handle = 0;
904 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000905 }
906 return error;
907}
908
909void *
Greg Clayton45319462011-02-08 00:35:34 +0000910Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000911{
Greg Clayton45319462011-02-08 00:35:34 +0000912 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000913 {
914 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000915 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000916 else
Greg Clayton45319462011-02-08 00:35:34 +0000917 {
918 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
919
920 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
921 if (symbol_addr)
922 {
923#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
924 // This host doesn't support limiting searches to this shared library
925 // so we need to verify that the match came from this shared library
926 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000927 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000928 {
929 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
930 if (match_dylib_spec != dylib_info->file_spec)
931 {
932 char dylib_path[PATH_MAX];
933 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
934 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
935 else
936 error.SetErrorString ("symbol not found");
937 return NULL;
938 }
939 }
940#endif
941 error.Clear();
942 return symbol_addr;
943 }
944 else
945 {
946 error.SetErrorString(::dlerror());
947 }
948 }
949 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000950}
Greg Claytondd36def2010-10-17 22:03:32 +0000951
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000952FileSpec
953Host::GetModuleFileSpecForHostAddress (const void *host_addr)
954{
955 FileSpec module_filespec;
956 Dl_info info;
957 if (::dladdr (host_addr, &info))
958 {
959 if (info.dli_fname)
960 module_filespec.SetFile(info.dli_fname, true);
961 }
962 return module_filespec;
963}
964
965#endif
966
Greg Claytondd36def2010-10-17 22:03:32 +0000967bool
968Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
969{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000970 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000971 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
972 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000973 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000974 // need to be modified to "do the right thing".
975
976 switch (path_type)
977 {
978 case ePathTypeLLDBShlibDir:
979 {
980 static ConstString g_lldb_so_dir;
981 if (!g_lldb_so_dir)
982 {
983 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
984 g_lldb_so_dir = lldb_file_spec.GetDirectory();
985 }
986 file_spec.GetDirectory() = g_lldb_so_dir;
987 return file_spec.GetDirectory();
988 }
989 break;
990
991 case ePathTypeSupportExecutableDir:
992 {
993 static ConstString g_lldb_support_exe_dir;
994 if (!g_lldb_support_exe_dir)
995 {
996 FileSpec lldb_file_spec;
997 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
998 {
999 char raw_path[PATH_MAX];
1000 char resolved_path[PATH_MAX];
1001 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1002
1003#if defined (__APPLE__)
1004 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1005 if (framework_pos)
1006 {
1007 framework_pos += strlen("LLDB.framework");
Greg Claytondce502e2011-11-04 03:34:56 +00001008#if !defined (__arm__)
Greg Claytondd36def2010-10-17 22:03:32 +00001009 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001010#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001011 }
1012#endif
1013 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1014 g_lldb_support_exe_dir.SetCString(resolved_path);
1015 }
1016 }
1017 file_spec.GetDirectory() = g_lldb_support_exe_dir;
1018 return file_spec.GetDirectory();
1019 }
1020 break;
1021
1022 case ePathTypeHeaderDir:
1023 {
1024 static ConstString g_lldb_headers_dir;
1025 if (!g_lldb_headers_dir)
1026 {
1027#if defined (__APPLE__)
1028 FileSpec lldb_file_spec;
1029 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1030 {
1031 char raw_path[PATH_MAX];
1032 char resolved_path[PATH_MAX];
1033 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1034
1035 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1036 if (framework_pos)
1037 {
1038 framework_pos += strlen("LLDB.framework");
1039 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1040 }
1041 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1042 g_lldb_headers_dir.SetCString(resolved_path);
1043 }
1044#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001045 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001046 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1047#endif
1048 }
1049 file_spec.GetDirectory() = g_lldb_headers_dir;
1050 return file_spec.GetDirectory();
1051 }
1052 break;
1053
Ed Mastea85d3642013-07-02 19:30:52 +00001054#ifndef LLDB_DISABLE_PYTHON
Greg Claytondd36def2010-10-17 22:03:32 +00001055 case ePathTypePythonDir:
1056 {
Greg Claytondd36def2010-10-17 22:03:32 +00001057 static ConstString g_lldb_python_dir;
1058 if (!g_lldb_python_dir)
1059 {
1060 FileSpec lldb_file_spec;
1061 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1062 {
1063 char raw_path[PATH_MAX];
1064 char resolved_path[PATH_MAX];
1065 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1066
1067#if defined (__APPLE__)
1068 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1069 if (framework_pos)
1070 {
1071 framework_pos += strlen("LLDB.framework");
1072 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1073 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001074#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001075 llvm::SmallString<256> python_version_dir;
1076 llvm::raw_svector_ostream os(python_version_dir);
1077 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1078 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001079
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001080 // We may get our string truncated. Should we protect
1081 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001082
Daniel Maleafa7425d2013-08-06 21:40:08 +00001083 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001084 sizeof(raw_path) - strlen(raw_path) - 1);
1085
Greg Claytondd36def2010-10-17 22:03:32 +00001086#endif
1087 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1088 g_lldb_python_dir.SetCString(resolved_path);
1089 }
1090 }
1091 file_spec.GetDirectory() = g_lldb_python_dir;
1092 return file_spec.GetDirectory();
1093 }
1094 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001095#endif
1096
Greg Clayton4272cc72011-02-02 02:24:04 +00001097 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1098 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001099#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001100 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001101 static bool g_lldb_system_plugin_dir_located = false;
1102 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001103 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001104 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001105#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001106 FileSpec lldb_file_spec;
1107 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1108 {
1109 char raw_path[PATH_MAX];
1110 char resolved_path[PATH_MAX];
1111 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1112
1113 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1114 if (framework_pos)
1115 {
1116 framework_pos += strlen("LLDB.framework");
1117 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001118 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1119 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001120 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001121 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001122 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001123#elif defined (__linux__)
1124 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1125 if (lldb_file_spec.Exists())
1126 {
1127 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1128 }
1129#endif // __APPLE__ || __linux__
Greg Clayton4272cc72011-02-02 02:24:04 +00001130 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001131
1132 if (g_lldb_system_plugin_dir)
1133 {
1134 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1135 return true;
1136 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001137#else
1138 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001139 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001140#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001141 }
1142 break;
1143
1144 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1145 {
1146#if defined (__APPLE__)
1147 static ConstString g_lldb_user_plugin_dir;
1148 if (!g_lldb_user_plugin_dir)
1149 {
1150 char user_plugin_path[PATH_MAX];
1151 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1152 user_plugin_path,
1153 sizeof(user_plugin_path)))
1154 {
1155 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1156 }
1157 }
1158 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1159 return file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001160#elif defined (__linux__)
1161 static ConstString g_lldb_user_plugin_dir;
1162 if (!g_lldb_user_plugin_dir)
1163 {
1164 // XDG Base Directory Specification
1165 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1166 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1167 FileSpec lldb_file_spec;
1168 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1169 if (xdg_data_home && xdg_data_home[0])
1170 {
1171 std::string user_plugin_dir (xdg_data_home);
1172 user_plugin_dir += "/lldb";
1173 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1174 }
1175 else
1176 {
1177 const char *home_dir = getenv("HOME");
1178 if (home_dir && home_dir[0])
1179 {
1180 std::string user_plugin_dir (home_dir);
1181 user_plugin_dir += "/.local/share/lldb";
1182 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1183 }
1184 }
1185
1186 if (lldb_file_spec.Exists())
1187 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1188 }
1189 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
1190 return file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001191#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001192 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001193 return false;
1194 }
Greg Claytondd36def2010-10-17 22:03:32 +00001195 }
1196
1197 return false;
1198}
1199
Greg Clayton1cb64962011-03-24 04:28:38 +00001200
1201bool
1202Host::GetHostname (std::string &s)
1203{
1204 char hostname[PATH_MAX];
1205 hostname[sizeof(hostname) - 1] = '\0';
1206 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1207 {
1208 struct hostent* h = ::gethostbyname (hostname);
1209 if (h)
1210 s.assign (h->h_name);
1211 else
1212 s.assign (hostname);
1213 return true;
1214 }
1215 return false;
1216}
1217
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001218#ifndef _WIN32
1219
Greg Clayton32e0a752011-03-30 18:16:51 +00001220const char *
1221Host::GetUserName (uint32_t uid, std::string &user_name)
1222{
1223 struct passwd user_info;
1224 struct passwd *user_info_ptr = &user_info;
1225 char user_buffer[PATH_MAX];
1226 size_t user_buffer_size = sizeof(user_buffer);
1227 if (::getpwuid_r (uid,
1228 &user_info,
1229 user_buffer,
1230 user_buffer_size,
1231 &user_info_ptr) == 0)
1232 {
1233 if (user_info_ptr)
1234 {
1235 user_name.assign (user_info_ptr->pw_name);
1236 return user_name.c_str();
1237 }
1238 }
1239 user_name.clear();
1240 return NULL;
1241}
1242
1243const char *
1244Host::GetGroupName (uint32_t gid, std::string &group_name)
1245{
1246 char group_buffer[PATH_MAX];
1247 size_t group_buffer_size = sizeof(group_buffer);
1248 struct group group_info;
1249 struct group *group_info_ptr = &group_info;
1250 // Try the threadsafe version first
1251 if (::getgrgid_r (gid,
1252 &group_info,
1253 group_buffer,
1254 group_buffer_size,
1255 &group_info_ptr) == 0)
1256 {
1257 if (group_info_ptr)
1258 {
1259 group_name.assign (group_info_ptr->gr_name);
1260 return group_name.c_str();
1261 }
1262 }
1263 else
1264 {
1265 // The threadsafe version isn't currently working
1266 // for me on darwin, but the non-threadsafe version
1267 // is, so I am calling it below.
1268 group_info_ptr = ::getgrgid (gid);
1269 if (group_info_ptr)
1270 {
1271 group_name.assign (group_info_ptr->gr_name);
1272 return group_name.c_str();
1273 }
1274 }
1275 group_name.clear();
1276 return NULL;
1277}
1278
Han Ming Ong84647042012-02-25 01:07:38 +00001279uint32_t
1280Host::GetUserID ()
1281{
1282 return getuid();
1283}
1284
1285uint32_t
1286Host::GetGroupID ()
1287{
1288 return getgid();
1289}
1290
1291uint32_t
1292Host::GetEffectiveUserID ()
1293{
1294 return geteuid();
1295}
1296
1297uint32_t
1298Host::GetEffectiveGroupID ()
1299{
1300 return getegid();
1301}
1302
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001303#endif
1304
1305#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1306bool
1307Host::GetOSBuildString (std::string &s)
1308{
1309 s.clear();
1310 return false;
1311}
1312
1313bool
1314Host::GetOSKernelDescription (std::string &s)
1315{
1316 s.clear();
1317 return false;
1318}
1319#endif
1320
Ed Maste47e575e2013-08-29 18:44:27 +00001321#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001322uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001323Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001324{
1325 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001326 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001327}
1328
Greg Claytone996fd32011-03-08 22:40:15 +00001329bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001330Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001331{
Greg Claytone996fd32011-03-08 22:40:15 +00001332 process_info.Clear();
1333 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001334}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001335#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001336
Matt Kopec085d6ce2013-05-31 22:00:07 +00001337#if !defined(__linux__)
1338bool
1339Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1340{
1341 return false;
1342}
1343#endif
1344
Sean Callananc0a6e062011-10-27 21:22:25 +00001345lldb::TargetSP
1346Host::GetDummyTarget (lldb_private::Debugger &debugger)
1347{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001348 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001349
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001350 // FIXME: Maybe the dummy target should be per-Debugger
1351 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1352 {
1353 ArchSpec arch(Target::GetDefaultArchitecture());
1354 if (!arch.IsValid())
1355 arch = Host::GetArchitecture ();
1356 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001357 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001358 arch.GetTriple().getTriple().c_str(),
1359 false,
1360 NULL,
1361 g_dummy_target_sp);
1362 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001363
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001364 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001365}
1366
Greg Claytond1cf11a2012-04-14 01:42:46 +00001367struct ShellInfo
1368{
1369 ShellInfo () :
1370 process_reaped (false),
1371 can_delete (false),
1372 pid (LLDB_INVALID_PROCESS_ID),
1373 signo(-1),
1374 status(-1)
1375 {
1376 }
1377
1378 lldb_private::Predicate<bool> process_reaped;
1379 lldb_private::Predicate<bool> can_delete;
1380 lldb::pid_t pid;
1381 int signo;
1382 int status;
1383};
1384
1385static bool
1386MonitorShellCommand (void *callback_baton,
1387 lldb::pid_t pid,
1388 bool exited, // True if the process did exit
1389 int signo, // Zero for no signal
1390 int status) // Exit value of process if signal is zero
1391{
1392 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1393 shell_info->pid = pid;
1394 shell_info->signo = signo;
1395 shell_info->status = status;
1396 // Let the thread running Host::RunShellCommand() know that the process
1397 // exited and that ShellInfo has been filled in by broadcasting to it
1398 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1399 // Now wait for a handshake back from that thread running Host::RunShellCommand
1400 // so we know that we can delete shell_info_ptr
1401 shell_info->can_delete.WaitForValueEqualTo(true);
1402 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1403 usleep(1000);
1404 // Now delete the shell info that was passed into this function
1405 delete shell_info;
1406 return true;
1407}
1408
1409Error
1410Host::RunShellCommand (const char *command,
1411 const char *working_dir,
1412 int *status_ptr,
1413 int *signo_ptr,
1414 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001415 uint32_t timeout_sec,
1416 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001417{
1418 Error error;
1419 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001420 if (shell && shell[0])
1421 {
1422 // Run the command in a shell
1423 launch_info.SetShell(shell);
1424 launch_info.GetArguments().AppendArgument(command);
1425 const bool localhost = true;
1426 const bool will_debug = false;
1427 const bool first_arg_is_full_shell_command = true;
1428 launch_info.ConvertArgumentsForLaunchingInShell (error,
1429 localhost,
1430 will_debug,
1431 first_arg_is_full_shell_command);
1432 }
1433 else
1434 {
1435 // No shell, just run it
1436 Args args (command);
1437 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001438 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001439 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001440
1441 if (working_dir)
1442 launch_info.SetWorkingDirectory(working_dir);
1443 char output_file_path_buffer[L_tmpnam];
1444 const char *output_file_path = NULL;
1445 if (command_output_ptr)
1446 {
1447 // Create a temporary file to get the stdout/stderr and redirect the
1448 // output of the command into this file. We will later read this file
1449 // if all goes well and fill the data into "command_output_ptr"
1450 output_file_path = ::tmpnam(output_file_path_buffer);
1451 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1452 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001453 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001454 }
1455 else
1456 {
1457 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1458 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1459 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1460 }
1461
1462 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001463 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001464
1465 const bool monitor_signals = false;
1466 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1467
1468 error = LaunchProcess (launch_info);
1469 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001470
1471 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1472 error.SetErrorString("failed to get process ID");
1473
1474 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001475 {
1476 // The process successfully launched, so we can defer ownership of
1477 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001478 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001479 // doesn't need to delete the ShellInfo anymore.
1480 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001481 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001482 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001483 if (timeout_sec > 0) {
1484 timeout_time.OffsetWithSeconds(timeout_sec);
1485 timeout_ptr = &timeout_time;
1486 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001487 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001488 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001489 if (timed_out)
1490 {
1491 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001492
Greg Claytond1cf11a2012-04-14 01:42:46 +00001493 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001494 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001495 // Wait for the monitor callback to get the message
1496 timeout_time = TimeValue::Now();
1497 timeout_time.OffsetWithSeconds(1);
1498 timed_out = false;
1499 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1500 }
1501 else
1502 {
1503 if (status_ptr)
1504 *status_ptr = shell_info->status;
1505
1506 if (signo_ptr)
1507 *signo_ptr = shell_info->signo;
1508
1509 if (command_output_ptr)
1510 {
1511 command_output_ptr->clear();
1512 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1513 uint64_t file_size = file_spec.GetByteSize();
1514 if (file_size > 0)
1515 {
1516 if (file_size > command_output_ptr->max_size())
1517 {
1518 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1519 }
1520 else
1521 {
1522 command_output_ptr->resize(file_size);
1523 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1524 }
1525 }
1526 }
1527 }
1528 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1529 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001530
1531 if (output_file_path)
1532 ::unlink (output_file_path);
1533 // Handshake with the monitor thread, or just let it know in advance that
1534 // it can delete "shell_info" in case we timed out and were not able to kill
1535 // the process...
1536 return error;
1537}
1538
Daniel Malea4244cbd2013-08-27 20:58:59 +00001539#if defined(__linux__) or defined(__FreeBSD__)
1540// The functions below implement process launching via posix_spawn() for Linux
1541// and FreeBSD.
1542
1543// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1544static Error
1545LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1546{
1547 Error error;
1548 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1549
1550 assert(exe_path);
1551 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1552
1553 posix_spawnattr_t attr;
1554
1555 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1556 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1557 if (error.Fail())
1558 return error;
1559
1560 // Make a quick class that will cleanup the posix spawn attributes in case
1561 // we return in the middle of this function.
1562 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1563
1564 sigset_t no_signals;
1565 sigset_t all_signals;
1566 sigemptyset (&no_signals);
1567 sigfillset (&all_signals);
1568 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1569 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1570
1571 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1572
1573 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1574 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1575 if (error.Fail())
1576 return error;
1577
1578 const size_t num_file_actions = launch_info.GetNumFileActions ();
1579 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1580 // Make a quick class that will cleanup the posix spawn attributes in case
1581 // we return in the middle of this function.
1582 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1583 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1584
1585 if (num_file_actions > 0)
1586 {
1587 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1588 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1589 if (error.Fail())
1590 return error;
1591
1592 file_action_ptr = &file_actions;
1593 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1594
1595 for (size_t i = 0; i < num_file_actions; ++i)
1596 {
1597 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1598 if (launch_file_action &&
1599 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1600 launch_file_action,
1601 log,
1602 error))
1603 return error;
1604 }
1605 }
1606
1607 // Change working directory if neccessary.
1608 char current_dir[PATH_MAX];
1609 current_dir[0] = '\0';
1610
1611 const char *working_dir = launch_info.GetWorkingDirectory();
1612 if (working_dir != NULL)
1613 {
1614 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1615 {
1616 error.SetError(errno, eErrorTypePOSIX);
1617 error.LogIfError(log, "unable to save the current directory");
1618 return error;
1619 }
1620
1621 if (::chdir(working_dir) == -1)
1622 {
1623 error.SetError(errno, eErrorTypePOSIX);
1624 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1625 return error;
1626 }
1627 }
1628
1629 const char *tmp_argv[2];
1630 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1631 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1632
1633 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1634 // We must pass argv into posix_spawnp and it must contain at least two items -
1635 // pointer to an executable and NULL.
1636 if (argv == NULL)
1637 {
1638 tmp_argv[0] = exe_path;
1639 tmp_argv[1] = NULL;
1640 argv = (char * const*)tmp_argv;
1641 }
1642
1643 error.SetError (::posix_spawnp (&pid,
1644 exe_path,
1645 (num_file_actions > 0) ? &file_actions : NULL,
1646 &attr,
1647 argv,
1648 envp),
1649 eErrorTypePOSIX);
1650
1651 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1652 pid, exe_path, file_action_ptr, &attr, argv, envp);
1653
1654 // Change back the current directory.
1655 // NOTE: do not override previously established error from posix_spawnp.
1656 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1657 {
1658 error.SetError(errno, eErrorTypePOSIX);
1659 error.LogIfError(log, "unable to change current directory back to %s",
1660 current_dir);
1661 }
1662
1663 return error;
1664}
1665
1666
1667Error
1668Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1669{
1670 Error error;
1671 char exe_path[PATH_MAX];
1672
1673 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1674
1675 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1676
1677 FileSpec exe_spec(launch_info.GetExecutableFile());
1678
1679 FileSpec::FileType file_type = exe_spec.GetFileType();
1680 if (file_type != FileSpec::eFileTypeRegular)
1681 {
1682 lldb::ModuleSP exe_module_sp;
1683 error = host_platform_sp->ResolveExecutable (exe_spec,
1684 arch_spec,
1685 exe_module_sp,
1686 NULL);
1687
1688 if (error.Fail())
1689 return error;
1690
1691 if (exe_module_sp)
1692 exe_spec = exe_module_sp->GetFileSpec();
1693 }
1694
1695 if (exe_spec.Exists())
1696 {
1697 exe_spec.GetPath (exe_path, sizeof(exe_path));
1698 }
1699 else
1700 {
1701 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1702 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1703 return error;
1704 }
1705
1706 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1707
1708 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1709
1710 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1711
1712 if (pid != LLDB_INVALID_PROCESS_ID)
1713 {
1714 // If all went well, then set the process ID into the launch info
1715 launch_info.SetProcessID(pid);
1716
1717 // Make sure we reap any processes we spawn or we will have zombies.
1718 if (!launch_info.MonitorProcess())
1719 {
1720 const bool monitor_signals = false;
1721 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1722 NULL,
1723 pid,
1724 monitor_signals);
1725 }
1726 }
1727 else
1728 {
1729 // Invalid process ID, something didn't go well
1730 if (error.Success())
1731 error.SetErrorString ("process launch failed for unknown reasons");
1732 }
1733 return error;
1734}
1735
1736#endif // defined(__linux__) or defined(__FreeBSD__)
1737
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001738#ifndef _WIN32
1739
1740size_t
1741Host::GetPageSize()
1742{
1743 return ::getpagesize();
1744}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001745
Greg Claytone3e3fee2013-02-17 20:46:30 +00001746uint32_t
1747Host::GetNumberCPUS ()
1748{
1749 static uint32_t g_num_cores = UINT32_MAX;
1750 if (g_num_cores == UINT32_MAX)
1751 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001752#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001753
1754 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001755
Greg Claytone3e3fee2013-02-17 20:46:30 +00001756#else
1757
1758 // Assume POSIX support if a host specific case has not been supplied above
1759 g_num_cores = 0;
1760 int num_cores = 0;
1761 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001762#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001763 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001764#else
1765 int mib[] = { CTL_HW, HW_NCPU };
1766#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001767
1768 /* get the number of CPUs from the system */
1769 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1770 {
1771 g_num_cores = num_cores;
1772 }
1773 else
1774 {
1775 mib[1] = HW_NCPU;
1776 num_cores_len = sizeof(num_cores);
1777 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1778 {
1779 if (num_cores > 0)
1780 g_num_cores = num_cores;
1781 }
1782 }
1783#endif
1784 }
1785 return g_num_cores;
1786}
1787
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001788void
1789Host::Kill(lldb::pid_t pid, int signo)
1790{
1791 ::kill(pid, signo);
1792}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001793
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001794#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001795
Johnny Chen8f3d8382011-08-02 20:52:42 +00001796#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001797bool
Greg Clayton3b147632010-12-18 01:54:34 +00001798Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001799{
1800 return false;
1801}
Greg Claytondd36def2010-10-17 22:03:32 +00001802
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001803void
1804Host::SetCrashDescriptionWithFormat (const char *format, ...)
1805{
1806}
1807
1808void
1809Host::SetCrashDescription (const char *description)
1810{
1811}
Greg Claytondd36def2010-10-17 22:03:32 +00001812
1813lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001814Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001815{
1816 return LLDB_INVALID_PROCESS_ID;
1817}
1818
Daniel Maleae0f8f572013-08-26 23:57:52 +00001819uint32_t
1820Host::MakeDirectory (const char* path, mode_t mode)
1821{
1822 return UINT32_MAX;
1823}
Greg Clayton2bddd342010-09-07 20:11:56 +00001824#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00001825
1826typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
1827FDToFileMap& GetFDToFileMap()
1828{
1829 static FDToFileMap g_fd2filemap;
1830 return g_fd2filemap;
1831}
1832
1833lldb::user_id_t
1834Host::OpenFile (const FileSpec& file_spec,
1835 uint32_t flags,
1836 mode_t mode,
1837 Error &error)
1838{
1839 std::string path (file_spec.GetPath());
1840 if (path.empty())
1841 {
1842 error.SetErrorString("empty path");
1843 return UINT64_MAX;
1844 }
1845 FileSP file_sp(new File());
1846 error = file_sp->Open(path.c_str(),flags,mode);
1847 if (file_sp->IsValid() == false)
1848 return UINT64_MAX;
1849 lldb::user_id_t fd = file_sp->GetDescriptor();
1850 GetFDToFileMap()[fd] = file_sp;
1851 return fd;
1852}
1853
1854bool
1855Host::CloseFile (lldb::user_id_t fd, Error &error)
1856{
1857 if (fd == UINT64_MAX)
1858 {
1859 error.SetErrorString ("invalid file descriptor");
1860 return false;
1861 }
1862 FDToFileMap& file_map = GetFDToFileMap();
1863 FDToFileMap::iterator pos = file_map.find(fd);
1864 if (pos == file_map.end())
1865 {
1866 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1867 return false;
1868 }
1869 FileSP file_sp = pos->second;
1870 if (!file_sp)
1871 {
1872 error.SetErrorString ("invalid host backing file");
1873 return false;
1874 }
1875 error = file_sp->Close();
1876 file_map.erase(pos);
1877 return error.Success();
1878}
1879
1880uint64_t
1881Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
1882{
1883 if (fd == UINT64_MAX)
1884 {
1885 error.SetErrorString ("invalid file descriptor");
1886 return UINT64_MAX;
1887 }
1888 FDToFileMap& file_map = GetFDToFileMap();
1889 FDToFileMap::iterator pos = file_map.find(fd);
1890 if (pos == file_map.end())
1891 {
1892 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
1893 return false;
1894 }
1895 FileSP file_sp = pos->second;
1896 if (!file_sp)
1897 {
1898 error.SetErrorString ("invalid host backing file");
1899 return UINT64_MAX;
1900 }
1901 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
1902 return UINT64_MAX;
1903 size_t bytes_written = src_len;
1904 error = file_sp->Write(src, bytes_written);
1905 if (error.Fail())
1906 return UINT64_MAX;
1907 return bytes_written;
1908}
1909
1910uint64_t
1911Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
1912{
1913 if (fd == UINT64_MAX)
1914 {
1915 error.SetErrorString ("invalid file descriptor");
1916 return UINT64_MAX;
1917 }
1918 FDToFileMap& file_map = GetFDToFileMap();
1919 FDToFileMap::iterator pos = file_map.find(fd);
1920 if (pos == file_map.end())
1921 {
1922 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
1923 return false;
1924 }
1925 FileSP file_sp = pos->second;
1926 if (!file_sp)
1927 {
1928 error.SetErrorString ("invalid host backing file");
1929 return UINT64_MAX;
1930 }
1931 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
1932 return UINT64_MAX;
1933 size_t bytes_read = dst_len;
1934 error = file_sp->Read(dst ,bytes_read);
1935 if (error.Fail())
1936 return UINT64_MAX;
1937 return bytes_read;
1938}
1939
1940lldb::user_id_t
1941Host::GetFileSize (const FileSpec& file_spec)
1942{
1943 return file_spec.GetByteSize();
1944}
1945
1946bool
1947Host::GetFileExists (const FileSpec& file_spec)
1948{
1949 return file_spec.Exists();
1950}
1951
1952bool
1953Host::CalculateMD5 (const FileSpec& file_spec,
1954 uint64_t &low,
1955 uint64_t &high)
1956{
1957#if defined (__APPLE__)
1958 StreamString md5_cmd_line;
1959 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
1960 std::string hash_string;
1961 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
1962 if (err.Fail())
1963 return false;
1964 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
1965 // if the output is any other length it is probably wrong
1966 if (hash_string.size() != 32)
1967 return false;
1968 std::string part1(hash_string,0,16);
1969 std::string part2(hash_string,16);
1970 const char* part1_cstr = part1.c_str();
1971 const char* part2_cstr = part2.c_str();
1972 high = ::strtoull(part1_cstr, NULL, 16);
1973 low = ::strtoull(part2_cstr, NULL, 16);
1974 return true;
1975#else
1976 // your own MD5 implementation here
1977 return false;
1978#endif
1979}