blob: 9f7bce764b32704200a1a438381302e01b713eb0 [file] [log] [blame]
Greg Clayton2bddd342010-09-07 20:11:56 +00001//===-- Host.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Greg Claytone3e3fee2013-02-17 20:46:30 +000012// C includes
Greg Claytone3e3fee2013-02-17 20:46:30 +000013#include <errno.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000014#include <limits.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#include <sys/types.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifdef _WIN32
17#include "lldb/Host/windows/windows.h"
18#include <winsock2.h>
19#include <WS2tcpip.h>
20#else
Deepak Panickalb36da432014-01-13 14:55:15 +000021#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000022#include <dlfcn.h>
23#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000024#include <netdb.h>
25#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000026#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000027#endif
28
29#if !defined (__GNU__) && !defined (_WIN32)
30// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000031#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000032#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000033
34#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000035#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000036#include <mach/mach_init.h>
37#include <mach-o/dyld.h>
Jim Ingham1a7ee702013-11-22 00:51:36 +000038#include <AvailabilityMacros.h>
Ed Maste8b006c62013-06-25 18:58:11 +000039#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000040
Ed Maste8b006c62013-06-25 18:58:11 +000041#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000042#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000043#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000044#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000045#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000046
Ed Maste8b006c62013-06-25 18:58:11 +000047#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000048#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#endif
50
Greg Clayton2bddd342010-09-07 20:11:56 +000051#include "lldb/Host/Host.h"
52#include "lldb/Core/ArchSpec.h"
53#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000054#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000055#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000057#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000059#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000060#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000061#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000062#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000064#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000065#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000066#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000067
Daniel Maleafa7425d2013-08-06 21:40:08 +000068#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000069#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000070#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000071
Greg Clayton32e0a752011-03-30 18:16:51 +000072
Greg Clayton2bddd342010-09-07 20:11:56 +000073using namespace lldb;
74using namespace lldb_private;
75
Greg Claytone4e45922011-11-16 05:37:56 +000076
Virgile Bellob2f1fb22013-08-23 12:44:05 +000077#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000078struct MonitorInfo
79{
80 lldb::pid_t pid; // The process ID to monitor
81 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
82 void *callback_baton; // The callback baton for the callback function
83 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
84};
85
Virgile Bellob2f1fb22013-08-23 12:44:05 +000086static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000087MonitorChildProcessThreadFunction (void *arg);
88
89lldb::thread_t
90Host::StartMonitoringChildProcess
91(
92 Host::MonitorChildProcessCallback callback,
93 void *callback_baton,
94 lldb::pid_t pid,
95 bool monitor_signals
96)
97{
98 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +000099 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000100
Greg Claytone4e45922011-11-16 05:37:56 +0000101 info_ptr->pid = pid;
102 info_ptr->callback = callback;
103 info_ptr->callback_baton = callback_baton;
104 info_ptr->monitor_signals = monitor_signals;
105
106 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000107 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000108 thread = ThreadCreate (thread_name,
109 MonitorChildProcessThreadFunction,
110 info_ptr,
111 NULL);
112
Greg Clayton2bddd342010-09-07 20:11:56 +0000113 return thread;
114}
115
116//------------------------------------------------------------------
117// Scoped class that will disable thread canceling when it is
118// constructed, and exception safely restore the previous value it
119// when it goes out of scope.
120//------------------------------------------------------------------
121class ScopedPThreadCancelDisabler
122{
123public:
124 ScopedPThreadCancelDisabler()
125 {
126 // Disable the ability for this thread to be cancelled
127 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
128 if (err != 0)
129 m_old_state = -1;
130
131 }
132
133 ~ScopedPThreadCancelDisabler()
134 {
135 // Restore the ability for this thread to be cancelled to what it
136 // previously was.
137 if (m_old_state != -1)
138 ::pthread_setcancelstate (m_old_state, 0);
139 }
140private:
141 int m_old_state; // Save the old cancelability state.
142};
143
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000144static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000145MonitorChildProcessThreadFunction (void *arg)
146{
Greg Clayton5160ce52013-03-27 23:08:40 +0000147 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000148 const char *function = __FUNCTION__;
149 if (log)
150 log->Printf ("%s (arg = %p) thread starting...", function, arg);
151
152 MonitorInfo *info = (MonitorInfo *)arg;
153
154 const Host::MonitorChildProcessCallback callback = info->callback;
155 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000156 const bool monitor_signals = info->monitor_signals;
157
Daniel Malea4244cbd2013-08-27 20:58:59 +0000158 assert (info->pid <= UINT32_MAX);
159 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
160
Greg Clayton2bddd342010-09-07 20:11:56 +0000161 delete info;
162
163 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000164#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000165 #define __WALL 0
166#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000167 const int options = __WALL;
168
Greg Clayton2bddd342010-09-07 20:11:56 +0000169 while (1)
170 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000171 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000172 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000173 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000174
175 // Wait for all child processes
176 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000177 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000178 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000179 ::pthread_testcancel ();
180
181 if (wait_pid == -1)
182 {
183 if (errno == EINTR)
184 continue;
185 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000186 {
187 if (log)
188 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000189 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000190 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000191 }
Matt Kopec650648f2013-01-08 16:30:18 +0000192 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000193 {
194 bool exited = false;
195 int signal = 0;
196 int exit_status = 0;
197 const char *status_cstr = NULL;
198 if (WIFSTOPPED(status))
199 {
200 signal = WSTOPSIG(status);
201 status_cstr = "STOPPED";
202 }
203 else if (WIFEXITED(status))
204 {
205 exit_status = WEXITSTATUS(status);
206 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000207 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000208 }
209 else if (WIFSIGNALED(status))
210 {
211 signal = WTERMSIG(status);
212 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000213 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000214 exited = true;
215 exit_status = -1;
216 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000217 }
218 else
219 {
Johnny Chen44805302011-07-19 19:48:13 +0000220 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000221 }
222
223 // Scope for pthread_cancel_disabler
224 {
225 ScopedPThreadCancelDisabler pthread_cancel_disabler;
226
Caroline Tice20ad3c42010-10-29 21:48:37 +0000227 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000228 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000229 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 +0000230 function,
231 wait_pid,
232 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000233 pid,
234 status,
235 status_cstr,
236 signal,
237 exit_status);
238
239 if (exited || (signal != 0 && monitor_signals))
240 {
Greg Claytone4e45922011-11-16 05:37:56 +0000241 bool callback_return = false;
242 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000243 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000244
245 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000246 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000247 {
248 if (log)
249 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000250 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000251 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000252 // If the callback returns true, it means this process should
253 // exit
254 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000255 {
256 if (log)
257 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000259 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000260 }
261 }
262 }
263 }
264
Caroline Tice20ad3c42010-10-29 21:48:37 +0000265 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000266 if (log)
267 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
268
269 return NULL;
270}
271
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000272#endif // #if !defined (__APPLE__) && !defined (_WIN32)
273
274#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000275
276void
277Host::SystemLog (SystemLogType type, const char *format, va_list args)
278{
279 vfprintf (stderr, format, args);
280}
281
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000282#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000283
Greg Claytone38a5ed2012-01-05 03:57:59 +0000284void
285Host::SystemLog (SystemLogType type, const char *format, ...)
286{
287 va_list args;
288 va_start (args, format);
289 SystemLog (type, format, args);
290 va_end (args);
291}
292
Greg Clayton2bddd342010-09-07 20:11:56 +0000293const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000294Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000295{
Greg Clayton514487e2011-02-15 21:59:32 +0000296 static bool g_supports_32 = false;
297 static bool g_supports_64 = false;
298 static ArchSpec g_host_arch_32;
299 static ArchSpec g_host_arch_64;
300
Greg Clayton2bddd342010-09-07 20:11:56 +0000301#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000302
303 // Apple is different in that it can support both 32 and 64 bit executables
304 // in the same operating system running concurrently. Here we detect the
305 // correct host architectures for both 32 and 64 bit including if 64 bit
306 // executables are supported on the system.
307
308 if (g_supports_32 == false && g_supports_64 == false)
309 {
310 // All apple systems support 32 bit execution.
311 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000312 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000313 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000314 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000315 ArchSpec host_arch;
316 // These will tell us about the kernel architecture, which even on a 64
317 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000318 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
319 {
Greg Clayton514487e2011-02-15 21:59:32 +0000320 len = sizeof (cpusubtype);
321 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
322 cpusubtype = CPU_TYPE_ANY;
323
Greg Clayton2bddd342010-09-07 20:11:56 +0000324 len = sizeof (is_64_bit_capable);
325 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
326 {
327 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000328 g_supports_64 = true;
329 }
330
331 if (is_64_bit_capable)
332 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000333#if defined (__i386__) || defined (__x86_64__)
334 if (cpusubtype == CPU_SUBTYPE_486)
335 cpusubtype = CPU_SUBTYPE_I386_ALL;
336#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000337 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000338 {
Greg Clayton514487e2011-02-15 21:59:32 +0000339 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000340 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
341 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000342 }
343 else
344 {
345 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000346 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000347 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000348 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000349 }
350 }
Greg Clayton514487e2011-02-15 21:59:32 +0000351 else
352 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000353 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000354 g_host_arch_64.Clear();
355 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000356 }
Greg Clayton514487e2011-02-15 21:59:32 +0000357 }
358
359#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000360
Greg Clayton514487e2011-02-15 21:59:32 +0000361 if (g_supports_32 == false && g_supports_64 == false)
362 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000363 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000364
Stephen Wilsonbd588712011-02-24 19:15:09 +0000365 g_host_arch_32.Clear();
366 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000367
Greg Claytonb29e6c62012-10-11 17:38:58 +0000368 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
369 // for the default triple. It's probably an artifact of config.guess.
370 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
371 triple.setVendorName("");
372
Stephen Wilsonbd588712011-02-24 19:15:09 +0000373 switch (triple.getArch())
374 {
375 default:
376 g_host_arch_32.SetTriple(triple);
377 g_supports_32 = true;
378 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000379
Stephen Wilsonbd588712011-02-24 19:15:09 +0000380 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000381 g_host_arch_64.SetTriple(triple);
382 g_supports_64 = true;
383 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
384 g_supports_32 = true;
385 break;
386
Stephen Wilsonbd588712011-02-24 19:15:09 +0000387 case llvm::Triple::sparcv9:
388 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000389 g_host_arch_64.SetTriple(triple);
390 g_supports_64 = true;
391 break;
392 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000393
394 g_supports_32 = g_host_arch_32.IsValid();
395 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000396 }
Greg Clayton514487e2011-02-15 21:59:32 +0000397
398#endif // #else for #if defined (__APPLE__)
399
400 if (arch_kind == eSystemDefaultArchitecture32)
401 return g_host_arch_32;
402 else if (arch_kind == eSystemDefaultArchitecture64)
403 return g_host_arch_64;
404
405 if (g_supports_64)
406 return g_host_arch_64;
407
408 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000409}
410
411const ConstString &
412Host::GetVendorString()
413{
414 static ConstString g_vendor;
415 if (!g_vendor)
416 {
Greg Clayton950971f2012-05-12 00:01:21 +0000417 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
418 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
419 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000420 }
421 return g_vendor;
422}
423
424const ConstString &
425Host::GetOSString()
426{
427 static ConstString g_os_string;
428 if (!g_os_string)
429 {
Greg Clayton950971f2012-05-12 00:01:21 +0000430 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
431 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
432 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000433 }
434 return g_os_string;
435}
436
437const ConstString &
438Host::GetTargetTriple()
439{
440 static ConstString g_host_triple;
441 if (!(g_host_triple))
442 {
Greg Clayton950971f2012-05-12 00:01:21 +0000443 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
444 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000445 }
446 return g_host_triple;
447}
448
449lldb::pid_t
450Host::GetCurrentProcessID()
451{
452 return ::getpid();
453}
454
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000455#ifndef _WIN32
456
Greg Clayton2bddd342010-09-07 20:11:56 +0000457lldb::tid_t
458Host::GetCurrentThreadID()
459{
460#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000461 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000462 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
463 // count.
464 thread_port_t thread_self = mach_thread_self();
465 mach_port_deallocate(mach_task_self(), thread_self);
466 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000467#elif defined(__FreeBSD__)
468 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000469#elif defined(__linux__)
470 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000471#else
472 return lldb::tid_t(pthread_self());
473#endif
474}
475
Jim Ingham372787f2012-04-07 00:00:41 +0000476lldb::thread_t
477Host::GetCurrentThread ()
478{
479 return lldb::thread_t(pthread_self());
480}
481
Greg Clayton2bddd342010-09-07 20:11:56 +0000482const char *
483Host::GetSignalAsCString (int signo)
484{
485 switch (signo)
486 {
487 case SIGHUP: return "SIGHUP"; // 1 hangup
488 case SIGINT: return "SIGINT"; // 2 interrupt
489 case SIGQUIT: return "SIGQUIT"; // 3 quit
490 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
491 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
492 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000493#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000494#if !defined(SIGIO) || (SIGPOLL != SIGIO)
495// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
496// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000497 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000498#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000499#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000500#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000501 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000502#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000503 case SIGFPE: return "SIGFPE"; // 8 floating point exception
504 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
505 case SIGBUS: return "SIGBUS"; // 10 bus error
506 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
507 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
508 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
509 case SIGALRM: return "SIGALRM"; // 14 alarm clock
510 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
511 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
512 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
513 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
514 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
515 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
516 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
517 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000518#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000519 case SIGIO: return "SIGIO"; // 23 input/output possible signal
520#endif
521 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
522 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
523 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
524 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000525#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000526 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000527#endif
528#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000529 case SIGINFO: return "SIGINFO"; // 29 information request
530#endif
531 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
532 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
533 default:
534 break;
535 }
536 return NULL;
537}
538
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000539#endif
540
Greg Clayton2bddd342010-09-07 20:11:56 +0000541void
542Host::WillTerminate ()
543{
544}
545
Sylvestre Ledru59405832013-07-01 08:21:36 +0000546#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000547
Greg Clayton2bddd342010-09-07 20:11:56 +0000548void
549Host::ThreadCreated (const char *thread_name)
550{
551}
Greg Claytone5219662010-12-03 06:02:24 +0000552
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000553void
Greg Claytone5219662010-12-03 06:02:24 +0000554Host::Backtrace (Stream &strm, uint32_t max_frames)
555{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000556 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000557}
558
Greg Clayton85851dd2010-12-04 00:10:17 +0000559size_t
560Host::GetEnvironment (StringList &env)
561{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000562 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000563 return 0;
564}
565
Sylvestre Ledru59405832013-07-01 08:21:36 +0000566#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000567
568struct HostThreadCreateInfo
569{
570 std::string thread_name;
571 thread_func_t thread_fptr;
572 thread_arg_t thread_arg;
573
574 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
575 thread_name (name ? name : ""),
576 thread_fptr (fptr),
577 thread_arg (arg)
578 {
579 }
580};
581
582static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000583#ifdef _WIN32
584__stdcall
585#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000586ThreadCreateTrampoline (thread_arg_t arg)
587{
588 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
589 Host::ThreadCreated (info->thread_name.c_str());
590 thread_func_t thread_fptr = info->thread_fptr;
591 thread_arg_t thread_arg = info->thread_arg;
592
Greg Clayton5160ce52013-03-27 23:08:40 +0000593 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000594 if (log)
595 log->Printf("thread created");
596
597 delete info;
598 return thread_fptr (thread_arg);
599}
600
601lldb::thread_t
602Host::ThreadCreate
603(
604 const char *thread_name,
605 thread_func_t thread_fptr,
606 thread_arg_t thread_arg,
607 Error *error
608)
609{
610 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
611
612 // Host::ThreadCreateTrampoline will delete this pointer for us.
613 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
614
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000615#ifdef _WIN32
616 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
617 int err = thread <= 0 ? GetLastError() : 0;
618#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000619 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000620#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000621 if (err == 0)
622 {
623 if (error)
624 error->Clear();
625 return thread;
626 }
627
628 if (error)
629 error->SetError (err, eErrorTypePOSIX);
630
631 return LLDB_INVALID_HOST_THREAD;
632}
633
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000634#ifndef _WIN32
635
Greg Clayton2bddd342010-09-07 20:11:56 +0000636bool
637Host::ThreadCancel (lldb::thread_t thread, Error *error)
638{
639 int err = ::pthread_cancel (thread);
640 if (error)
641 error->SetError(err, eErrorTypePOSIX);
642 return err == 0;
643}
644
645bool
646Host::ThreadDetach (lldb::thread_t thread, Error *error)
647{
648 int err = ::pthread_detach (thread);
649 if (error)
650 error->SetError(err, eErrorTypePOSIX);
651 return err == 0;
652}
653
654bool
655Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
656{
657 int err = ::pthread_join (thread, thread_result_ptr);
658 if (error)
659 error->SetError(err, eErrorTypePOSIX);
660 return err == 0;
661}
662
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000663lldb::thread_key_t
664Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
665{
666 pthread_key_t key;
667 ::pthread_key_create (&key, callback);
668 return key;
669}
670
671void*
672Host::ThreadLocalStorageGet(lldb::thread_key_t key)
673{
674 return ::pthread_getspecific (key);
675}
676
677void
678Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
679{
680 ::pthread_setspecific (key, value);
681}
682
Matt Kopec62502c62013-05-13 19:33:58 +0000683bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000684Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
685{
Greg Clayton85719632013-02-27 22:51:58 +0000686#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000687 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
688 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
689 if (pid == LLDB_INVALID_PROCESS_ID)
690 pid = curr_pid;
691
692 if (tid == LLDB_INVALID_THREAD_ID)
693 tid = curr_tid;
694
Greg Clayton2bddd342010-09-07 20:11:56 +0000695 // Set the pthread name if possible
696 if (pid == curr_pid && tid == curr_tid)
697 {
Matt Kopec62502c62013-05-13 19:33:58 +0000698 if (::pthread_setname_np (name) == 0)
699 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000700 }
Matt Kopec62502c62013-05-13 19:33:58 +0000701 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000702#elif defined (__FreeBSD__)
703 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
704 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
705 if (pid == LLDB_INVALID_PROCESS_ID)
706 pid = curr_pid;
707
708 if (tid == LLDB_INVALID_THREAD_ID)
709 tid = curr_tid;
710
711 // Set the pthread name if possible
712 if (pid == curr_pid && tid == curr_tid)
713 {
Michael Sartainc2052432013-08-01 18:51:08 +0000714 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000715 return true;
716 }
717 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000718#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000719 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
720 if (fn)
721 {
Matt Kopec62502c62013-05-13 19:33:58 +0000722 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
723 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000724 if (pid == LLDB_INVALID_PROCESS_ID)
725 pid = curr_pid;
726
727 if (tid == LLDB_INVALID_THREAD_ID)
728 tid = curr_tid;
729
Michael Sartainc2052432013-08-01 18:51:08 +0000730 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000731 {
Michael Sartainc2052432013-08-01 18:51:08 +0000732 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
733 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
734
735 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000736 return true;
737 }
738 }
739 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000740#else
741 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000742#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000743}
744
Ed Maste02983be2013-07-25 19:10:32 +0000745bool
746Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
747 const char *thread_name, size_t len)
748{
749 char *namebuf = (char *)::malloc (len + 1);
750
751 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
752 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
753 // off leads to a lot of similar named threads. Go through the thread name
754 // and search for the last dot and use that.
755 const char *lastdot = ::strrchr (thread_name, '.');
756
757 if (lastdot && lastdot != thread_name)
758 thread_name = lastdot + 1;
759 ::strncpy (namebuf, thread_name, len);
760 namebuf[len] = 0;
761
762 int namebuflen = strlen(namebuf);
763 if (namebuflen > 0)
764 {
765 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
766 {
767 // Trim off trailing '(' and '>' characters for a bit more cleanup.
768 namebuflen--;
769 namebuf[namebuflen] = 0;
770 }
771 return Host::SetThreadName (pid, tid, namebuf);
772 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000773
774 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000775 return false;
776}
777
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000778#endif
779
Greg Clayton2bddd342010-09-07 20:11:56 +0000780FileSpec
781Host::GetProgramFileSpec ()
782{
783 static FileSpec g_program_filespec;
784 if (!g_program_filespec)
785 {
786#if defined (__APPLE__)
787 char program_fullpath[PATH_MAX];
788 // If DST is NULL, then return the number of bytes needed.
789 uint32_t len = sizeof(program_fullpath);
790 int err = _NSGetExecutablePath (program_fullpath, &len);
791 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000792 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000793 else if (err == -1)
794 {
795 char *large_program_fullpath = (char *)::malloc (len + 1);
796
797 err = _NSGetExecutablePath (large_program_fullpath, &len);
798 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000799 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000800
801 ::free (large_program_fullpath);
802 }
803#elif defined (__linux__)
804 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000805 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
806 if (len > 0) {
807 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000808 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000809 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000810#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000811 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
812 size_t exe_path_size;
813 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
814 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000815 char *exe_path = new char[exe_path_size];
816 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
817 g_program_filespec.SetFile(exe_path, false);
818 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000819 }
820#endif
821 }
822 return g_program_filespec;
823}
824
Greg Clayton2bddd342010-09-07 20:11:56 +0000825#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000826
827bool
828Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
829{
830 bundle.Clear();
831 return false;
832}
833
Greg Clayton2bddd342010-09-07 20:11:56 +0000834bool
Greg Claytondd36def2010-10-17 22:03:32 +0000835Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000836{
Greg Claytondd36def2010-10-17 22:03:32 +0000837 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000838}
839#endif
840
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000841#ifndef _WIN32
842
Greg Clayton45319462011-02-08 00:35:34 +0000843// Opaque info that tracks a dynamic library that was loaded
844struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000845{
Greg Clayton45319462011-02-08 00:35:34 +0000846 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
847 file_spec (fs),
848 open_options (o),
849 handle (h)
850 {
851 }
852
853 const FileSpec file_spec;
854 uint32_t open_options;
855 void * handle;
856};
857
858void *
859Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
860{
Greg Clayton4272cc72011-02-02 02:24:04 +0000861 char path[PATH_MAX];
862 if (file_spec.GetPath(path, sizeof(path)))
863 {
Greg Clayton45319462011-02-08 00:35:34 +0000864 int mode = 0;
865
866 if (options & eDynamicLibraryOpenOptionLazy)
867 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000868 else
869 mode |= RTLD_NOW;
870
Greg Clayton45319462011-02-08 00:35:34 +0000871
872 if (options & eDynamicLibraryOpenOptionLocal)
873 mode |= RTLD_LOCAL;
874 else
875 mode |= RTLD_GLOBAL;
876
877#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
878 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
879 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000880#endif
Greg Clayton45319462011-02-08 00:35:34 +0000881
882 void * opaque = ::dlopen (path, mode);
883
884 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000885 {
886 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000887 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000888 }
889 else
890 {
891 error.SetErrorString(::dlerror());
892 }
893 }
894 else
895 {
896 error.SetErrorString("failed to extract path");
897 }
Greg Clayton45319462011-02-08 00:35:34 +0000898 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000899}
900
901Error
Greg Clayton45319462011-02-08 00:35:34 +0000902Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000903{
904 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000905 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000906 {
907 error.SetErrorString ("invalid dynamic library handle");
908 }
Greg Clayton45319462011-02-08 00:35:34 +0000909 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000910 {
Greg Clayton45319462011-02-08 00:35:34 +0000911 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
912 if (::dlclose (dylib_info->handle) != 0)
913 {
914 error.SetErrorString(::dlerror());
915 }
916
917 dylib_info->open_options = 0;
918 dylib_info->handle = 0;
919 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000920 }
921 return error;
922}
923
924void *
Greg Clayton45319462011-02-08 00:35:34 +0000925Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000926{
Greg Clayton45319462011-02-08 00:35:34 +0000927 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000928 {
929 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000930 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000931 else
Greg Clayton45319462011-02-08 00:35:34 +0000932 {
933 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
934
935 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
936 if (symbol_addr)
937 {
938#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
939 // This host doesn't support limiting searches to this shared library
940 // so we need to verify that the match came from this shared library
941 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000942 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000943 {
944 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
945 if (match_dylib_spec != dylib_info->file_spec)
946 {
947 char dylib_path[PATH_MAX];
948 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
949 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
950 else
951 error.SetErrorString ("symbol not found");
952 return NULL;
953 }
954 }
955#endif
956 error.Clear();
957 return symbol_addr;
958 }
959 else
960 {
961 error.SetErrorString(::dlerror());
962 }
963 }
964 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000965}
Greg Claytondd36def2010-10-17 22:03:32 +0000966
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000967FileSpec
968Host::GetModuleFileSpecForHostAddress (const void *host_addr)
969{
970 FileSpec module_filespec;
971 Dl_info info;
972 if (::dladdr (host_addr, &info))
973 {
974 if (info.dli_fname)
975 module_filespec.SetFile(info.dli_fname, true);
976 }
977 return module_filespec;
978}
979
980#endif
981
Greg Claytondd36def2010-10-17 22:03:32 +0000982bool
983Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
984{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000985 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000986 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
987 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000988 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000989 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000990 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +0000991
992 switch (path_type)
993 {
994 case ePathTypeLLDBShlibDir:
995 {
996 static ConstString g_lldb_so_dir;
997 if (!g_lldb_so_dir)
998 {
999 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
1000 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001001 if (log)
1002 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001003 }
1004 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001005 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001006 }
1007 break;
1008
1009 case ePathTypeSupportExecutableDir:
1010 {
1011 static ConstString g_lldb_support_exe_dir;
1012 if (!g_lldb_support_exe_dir)
1013 {
1014 FileSpec lldb_file_spec;
1015 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1016 {
1017 char raw_path[PATH_MAX];
1018 char resolved_path[PATH_MAX];
1019 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1020
1021#if defined (__APPLE__)
1022 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1023 if (framework_pos)
1024 {
1025 framework_pos += strlen("LLDB.framework");
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001026#if defined (__arm__)
1027 // Shallow bundle
1028 *framework_pos = '\0';
1029#else
1030 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001031 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001032#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001033 }
1034#endif
1035 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1036 g_lldb_support_exe_dir.SetCString(resolved_path);
1037 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001038 if (log)
1039 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001040 }
1041 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001042 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001043 }
1044 break;
1045
1046 case ePathTypeHeaderDir:
1047 {
1048 static ConstString g_lldb_headers_dir;
1049 if (!g_lldb_headers_dir)
1050 {
1051#if defined (__APPLE__)
1052 FileSpec lldb_file_spec;
1053 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1054 {
1055 char raw_path[PATH_MAX];
1056 char resolved_path[PATH_MAX];
1057 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1058
1059 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1060 if (framework_pos)
1061 {
1062 framework_pos += strlen("LLDB.framework");
1063 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1064 }
1065 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1066 g_lldb_headers_dir.SetCString(resolved_path);
1067 }
1068#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001069 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001070 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1071#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001072 if (log)
1073 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001074 }
1075 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001076 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001077 }
1078 break;
1079
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001080#ifdef LLDB_DISABLE_PYTHON
1081 case ePathTypePythonDir:
1082 return false;
1083#else
1084 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001085 {
Greg Claytondd36def2010-10-17 22:03:32 +00001086 static ConstString g_lldb_python_dir;
1087 if (!g_lldb_python_dir)
1088 {
1089 FileSpec lldb_file_spec;
1090 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1091 {
1092 char raw_path[PATH_MAX];
1093 char resolved_path[PATH_MAX];
1094 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1095
1096#if defined (__APPLE__)
1097 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1098 if (framework_pos)
1099 {
1100 framework_pos += strlen("LLDB.framework");
1101 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1102 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001103#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001104 llvm::SmallString<256> python_version_dir;
1105 llvm::raw_svector_ostream os(python_version_dir);
1106 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1107 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001108
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001109 // We may get our string truncated. Should we protect
1110 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001111
Daniel Maleafa7425d2013-08-06 21:40:08 +00001112 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001113 sizeof(raw_path) - strlen(raw_path) - 1);
1114
Greg Claytondd36def2010-10-17 22:03:32 +00001115#endif
1116 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1117 g_lldb_python_dir.SetCString(resolved_path);
1118 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001119
1120 if (log)
1121 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1122
Greg Claytondd36def2010-10-17 22:03:32 +00001123 }
1124 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001125 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001126 }
1127 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001128#endif
1129
Greg Clayton4272cc72011-02-02 02:24:04 +00001130 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1131 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001132#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001133 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001134 static bool g_lldb_system_plugin_dir_located = false;
1135 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001136 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001137 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001138#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001139 FileSpec lldb_file_spec;
1140 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1141 {
1142 char raw_path[PATH_MAX];
1143 char resolved_path[PATH_MAX];
1144 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1145
1146 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1147 if (framework_pos)
1148 {
1149 framework_pos += strlen("LLDB.framework");
1150 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001151 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1152 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001153 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001154 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001155 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001156#elif defined (__linux__)
1157 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1158 if (lldb_file_spec.Exists())
1159 {
1160 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1161 }
1162#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001163
1164 if (log)
1165 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1166
Greg Clayton4272cc72011-02-02 02:24:04 +00001167 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001168
1169 if (g_lldb_system_plugin_dir)
1170 {
1171 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1172 return true;
1173 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001174#else
1175 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001176 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001177#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001178 }
1179 break;
1180
1181 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1182 {
1183#if defined (__APPLE__)
1184 static ConstString g_lldb_user_plugin_dir;
1185 if (!g_lldb_user_plugin_dir)
1186 {
1187 char user_plugin_path[PATH_MAX];
1188 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1189 user_plugin_path,
1190 sizeof(user_plugin_path)))
1191 {
1192 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1193 }
1194 }
1195 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001196 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001197#elif defined (__linux__)
1198 static ConstString g_lldb_user_plugin_dir;
1199 if (!g_lldb_user_plugin_dir)
1200 {
1201 // XDG Base Directory Specification
1202 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1203 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1204 FileSpec lldb_file_spec;
1205 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1206 if (xdg_data_home && xdg_data_home[0])
1207 {
1208 std::string user_plugin_dir (xdg_data_home);
1209 user_plugin_dir += "/lldb";
1210 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1211 }
1212 else
1213 {
1214 const char *home_dir = getenv("HOME");
1215 if (home_dir && home_dir[0])
1216 {
1217 std::string user_plugin_dir (home_dir);
1218 user_plugin_dir += "/.local/share/lldb";
1219 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1220 }
1221 }
1222
1223 if (lldb_file_spec.Exists())
1224 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001225 if (log)
1226 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001227 }
1228 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001229 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001230#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001231 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001232 return false;
1233 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001234
1235 case ePathTypeLLDBTempSystemDir:
1236 {
1237 static ConstString g_lldb_tmp_dir;
1238 if (!g_lldb_tmp_dir)
1239 {
1240 const char *tmpdir_cstr = getenv("TMPDIR");
1241 if (tmpdir_cstr == NULL)
1242 {
1243 tmpdir_cstr = getenv("TMP");
1244 if (tmpdir_cstr == NULL)
1245 tmpdir_cstr = getenv("TEMP");
1246 }
1247 if (tmpdir_cstr)
1248 {
1249 g_lldb_tmp_dir.SetCString(tmpdir_cstr);
1250 if (log)
1251 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1252 }
1253 }
1254 file_spec.GetDirectory() = g_lldb_tmp_dir;
1255 return (bool)file_spec.GetDirectory();
1256 }
Greg Claytondd36def2010-10-17 22:03:32 +00001257 }
1258
1259 return false;
1260}
1261
Greg Clayton1cb64962011-03-24 04:28:38 +00001262
1263bool
1264Host::GetHostname (std::string &s)
1265{
1266 char hostname[PATH_MAX];
1267 hostname[sizeof(hostname) - 1] = '\0';
1268 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1269 {
1270 struct hostent* h = ::gethostbyname (hostname);
1271 if (h)
1272 s.assign (h->h_name);
1273 else
1274 s.assign (hostname);
1275 return true;
1276 }
1277 return false;
1278}
1279
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001280#ifndef _WIN32
1281
Greg Clayton32e0a752011-03-30 18:16:51 +00001282const char *
1283Host::GetUserName (uint32_t uid, std::string &user_name)
1284{
1285 struct passwd user_info;
1286 struct passwd *user_info_ptr = &user_info;
1287 char user_buffer[PATH_MAX];
1288 size_t user_buffer_size = sizeof(user_buffer);
1289 if (::getpwuid_r (uid,
1290 &user_info,
1291 user_buffer,
1292 user_buffer_size,
1293 &user_info_ptr) == 0)
1294 {
1295 if (user_info_ptr)
1296 {
1297 user_name.assign (user_info_ptr->pw_name);
1298 return user_name.c_str();
1299 }
1300 }
1301 user_name.clear();
1302 return NULL;
1303}
1304
1305const char *
1306Host::GetGroupName (uint32_t gid, std::string &group_name)
1307{
1308 char group_buffer[PATH_MAX];
1309 size_t group_buffer_size = sizeof(group_buffer);
1310 struct group group_info;
1311 struct group *group_info_ptr = &group_info;
1312 // Try the threadsafe version first
1313 if (::getgrgid_r (gid,
1314 &group_info,
1315 group_buffer,
1316 group_buffer_size,
1317 &group_info_ptr) == 0)
1318 {
1319 if (group_info_ptr)
1320 {
1321 group_name.assign (group_info_ptr->gr_name);
1322 return group_name.c_str();
1323 }
1324 }
1325 else
1326 {
1327 // The threadsafe version isn't currently working
1328 // for me on darwin, but the non-threadsafe version
1329 // is, so I am calling it below.
1330 group_info_ptr = ::getgrgid (gid);
1331 if (group_info_ptr)
1332 {
1333 group_name.assign (group_info_ptr->gr_name);
1334 return group_name.c_str();
1335 }
1336 }
1337 group_name.clear();
1338 return NULL;
1339}
1340
Han Ming Ong84647042012-02-25 01:07:38 +00001341uint32_t
1342Host::GetUserID ()
1343{
1344 return getuid();
1345}
1346
1347uint32_t
1348Host::GetGroupID ()
1349{
1350 return getgid();
1351}
1352
1353uint32_t
1354Host::GetEffectiveUserID ()
1355{
1356 return geteuid();
1357}
1358
1359uint32_t
1360Host::GetEffectiveGroupID ()
1361{
1362 return getegid();
1363}
1364
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001365#endif
1366
1367#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1368bool
1369Host::GetOSBuildString (std::string &s)
1370{
1371 s.clear();
1372 return false;
1373}
1374
1375bool
1376Host::GetOSKernelDescription (std::string &s)
1377{
1378 s.clear();
1379 return false;
1380}
1381#endif
1382
Ed Maste47e575e2013-08-29 18:44:27 +00001383#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001384uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001385Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001386{
1387 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001388 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001389}
1390
Greg Claytone996fd32011-03-08 22:40:15 +00001391bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001392Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001393{
Greg Claytone996fd32011-03-08 22:40:15 +00001394 process_info.Clear();
1395 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001396}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001397#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001398
Matt Kopec085d6ce2013-05-31 22:00:07 +00001399#if !defined(__linux__)
1400bool
1401Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1402{
1403 return false;
1404}
1405#endif
1406
Sean Callananc0a6e062011-10-27 21:22:25 +00001407lldb::TargetSP
1408Host::GetDummyTarget (lldb_private::Debugger &debugger)
1409{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001410 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001411
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001412 // FIXME: Maybe the dummy target should be per-Debugger
1413 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1414 {
1415 ArchSpec arch(Target::GetDefaultArchitecture());
1416 if (!arch.IsValid())
1417 arch = Host::GetArchitecture ();
1418 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001419 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001420 arch.GetTriple().getTriple().c_str(),
1421 false,
1422 NULL,
1423 g_dummy_target_sp);
1424 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001425
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001426 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001427}
1428
Greg Claytond1cf11a2012-04-14 01:42:46 +00001429struct ShellInfo
1430{
1431 ShellInfo () :
1432 process_reaped (false),
1433 can_delete (false),
1434 pid (LLDB_INVALID_PROCESS_ID),
1435 signo(-1),
1436 status(-1)
1437 {
1438 }
1439
1440 lldb_private::Predicate<bool> process_reaped;
1441 lldb_private::Predicate<bool> can_delete;
1442 lldb::pid_t pid;
1443 int signo;
1444 int status;
1445};
1446
1447static bool
1448MonitorShellCommand (void *callback_baton,
1449 lldb::pid_t pid,
1450 bool exited, // True if the process did exit
1451 int signo, // Zero for no signal
1452 int status) // Exit value of process if signal is zero
1453{
1454 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1455 shell_info->pid = pid;
1456 shell_info->signo = signo;
1457 shell_info->status = status;
1458 // Let the thread running Host::RunShellCommand() know that the process
1459 // exited and that ShellInfo has been filled in by broadcasting to it
1460 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1461 // Now wait for a handshake back from that thread running Host::RunShellCommand
1462 // so we know that we can delete shell_info_ptr
1463 shell_info->can_delete.WaitForValueEqualTo(true);
1464 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1465 usleep(1000);
1466 // Now delete the shell info that was passed into this function
1467 delete shell_info;
1468 return true;
1469}
1470
1471Error
1472Host::RunShellCommand (const char *command,
1473 const char *working_dir,
1474 int *status_ptr,
1475 int *signo_ptr,
1476 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001477 uint32_t timeout_sec,
1478 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001479{
1480 Error error;
1481 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001482 if (shell && shell[0])
1483 {
1484 // Run the command in a shell
1485 launch_info.SetShell(shell);
1486 launch_info.GetArguments().AppendArgument(command);
1487 const bool localhost = true;
1488 const bool will_debug = false;
1489 const bool first_arg_is_full_shell_command = true;
1490 launch_info.ConvertArgumentsForLaunchingInShell (error,
1491 localhost,
1492 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001493 first_arg_is_full_shell_command,
1494 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001495 }
1496 else
1497 {
1498 // No shell, just run it
1499 Args args (command);
1500 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001501 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001502 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001503
1504 if (working_dir)
1505 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001506 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001507 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001508
Greg Claytond1cf11a2012-04-14 01:42:46 +00001509 if (command_output_ptr)
1510 {
1511 // Create a temporary file to get the stdout/stderr and redirect the
1512 // output of the command into this file. We will later read this file
1513 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001514 FileSpec tmpdir_file_spec;
1515 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1516 {
1517 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1518 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1519 }
1520 else
1521 {
1522 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1523 }
1524
1525 output_file_path = ::mktemp(output_file_path_buffer);
1526 }
1527
1528 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1529 if (output_file_path)
1530 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001531 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001532 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001533 }
1534 else
1535 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001536 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1537 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1538 }
1539
1540 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001541 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001542
1543 const bool monitor_signals = false;
1544 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1545
1546 error = LaunchProcess (launch_info);
1547 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001548
1549 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1550 error.SetErrorString("failed to get process ID");
1551
1552 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001553 {
1554 // The process successfully launched, so we can defer ownership of
1555 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001556 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001557 // doesn't need to delete the ShellInfo anymore.
1558 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001559 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001560 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001561 if (timeout_sec > 0) {
1562 timeout_time.OffsetWithSeconds(timeout_sec);
1563 timeout_ptr = &timeout_time;
1564 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001565 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001566 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001567 if (timed_out)
1568 {
1569 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001570
Greg Claytond1cf11a2012-04-14 01:42:46 +00001571 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001572 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001573 // Wait for the monitor callback to get the message
1574 timeout_time = TimeValue::Now();
1575 timeout_time.OffsetWithSeconds(1);
1576 timed_out = false;
1577 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1578 }
1579 else
1580 {
1581 if (status_ptr)
1582 *status_ptr = shell_info->status;
1583
1584 if (signo_ptr)
1585 *signo_ptr = shell_info->signo;
1586
1587 if (command_output_ptr)
1588 {
1589 command_output_ptr->clear();
1590 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1591 uint64_t file_size = file_spec.GetByteSize();
1592 if (file_size > 0)
1593 {
1594 if (file_size > command_output_ptr->max_size())
1595 {
1596 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1597 }
1598 else
1599 {
1600 command_output_ptr->resize(file_size);
1601 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1602 }
1603 }
1604 }
1605 }
1606 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1607 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001608
1609 if (output_file_path)
1610 ::unlink (output_file_path);
1611 // Handshake with the monitor thread, or just let it know in advance that
1612 // it can delete "shell_info" in case we timed out and were not able to kill
1613 // the process...
1614 return error;
1615}
1616
Ed Maste991fe6c2013-12-09 01:35:42 +00001617#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001618// The functions below implement process launching via posix_spawn() for Linux
1619// and FreeBSD.
1620
1621// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1622static Error
1623LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1624{
1625 Error error;
1626 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1627
1628 assert(exe_path);
1629 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1630
1631 posix_spawnattr_t attr;
1632
1633 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1634 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1635 if (error.Fail())
1636 return error;
1637
1638 // Make a quick class that will cleanup the posix spawn attributes in case
1639 // we return in the middle of this function.
1640 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1641
1642 sigset_t no_signals;
1643 sigset_t all_signals;
1644 sigemptyset (&no_signals);
1645 sigfillset (&all_signals);
1646 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1647 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1648
1649 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1650
1651 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1652 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1653 if (error.Fail())
1654 return error;
1655
1656 const size_t num_file_actions = launch_info.GetNumFileActions ();
1657 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1658 // Make a quick class that will cleanup the posix spawn attributes in case
1659 // we return in the middle of this function.
1660 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1661 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1662
1663 if (num_file_actions > 0)
1664 {
1665 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1666 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1667 if (error.Fail())
1668 return error;
1669
1670 file_action_ptr = &file_actions;
1671 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1672
1673 for (size_t i = 0; i < num_file_actions; ++i)
1674 {
1675 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1676 if (launch_file_action &&
1677 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1678 launch_file_action,
1679 log,
1680 error))
1681 return error;
1682 }
1683 }
1684
1685 // Change working directory if neccessary.
1686 char current_dir[PATH_MAX];
1687 current_dir[0] = '\0';
1688
1689 const char *working_dir = launch_info.GetWorkingDirectory();
1690 if (working_dir != NULL)
1691 {
1692 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1693 {
1694 error.SetError(errno, eErrorTypePOSIX);
1695 error.LogIfError(log, "unable to save the current directory");
1696 return error;
1697 }
1698
1699 if (::chdir(working_dir) == -1)
1700 {
1701 error.SetError(errno, eErrorTypePOSIX);
1702 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1703 return error;
1704 }
1705 }
1706
1707 const char *tmp_argv[2];
1708 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1709 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1710
1711 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1712 // We must pass argv into posix_spawnp and it must contain at least two items -
1713 // pointer to an executable and NULL.
1714 if (argv == NULL)
1715 {
1716 tmp_argv[0] = exe_path;
1717 tmp_argv[1] = NULL;
1718 argv = (char * const*)tmp_argv;
1719 }
1720
1721 error.SetError (::posix_spawnp (&pid,
1722 exe_path,
1723 (num_file_actions > 0) ? &file_actions : NULL,
1724 &attr,
1725 argv,
1726 envp),
1727 eErrorTypePOSIX);
1728
1729 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1730 pid, exe_path, file_action_ptr, &attr, argv, envp);
1731
1732 // Change back the current directory.
1733 // NOTE: do not override previously established error from posix_spawnp.
1734 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1735 {
1736 error.SetError(errno, eErrorTypePOSIX);
1737 error.LogIfError(log, "unable to change current directory back to %s",
1738 current_dir);
1739 }
1740
1741 return error;
1742}
1743
1744
1745Error
1746Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1747{
1748 Error error;
1749 char exe_path[PATH_MAX];
1750
1751 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1752
1753 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1754
1755 FileSpec exe_spec(launch_info.GetExecutableFile());
1756
1757 FileSpec::FileType file_type = exe_spec.GetFileType();
1758 if (file_type != FileSpec::eFileTypeRegular)
1759 {
1760 lldb::ModuleSP exe_module_sp;
1761 error = host_platform_sp->ResolveExecutable (exe_spec,
1762 arch_spec,
1763 exe_module_sp,
1764 NULL);
1765
1766 if (error.Fail())
1767 return error;
1768
1769 if (exe_module_sp)
1770 exe_spec = exe_module_sp->GetFileSpec();
1771 }
1772
1773 if (exe_spec.Exists())
1774 {
1775 exe_spec.GetPath (exe_path, sizeof(exe_path));
1776 }
1777 else
1778 {
1779 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1780 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1781 return error;
1782 }
1783
1784 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1785
1786 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1787
1788 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1789
1790 if (pid != LLDB_INVALID_PROCESS_ID)
1791 {
1792 // If all went well, then set the process ID into the launch info
1793 launch_info.SetProcessID(pid);
1794
1795 // Make sure we reap any processes we spawn or we will have zombies.
1796 if (!launch_info.MonitorProcess())
1797 {
1798 const bool monitor_signals = false;
1799 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1800 NULL,
1801 pid,
1802 monitor_signals);
1803 }
1804 }
1805 else
1806 {
1807 // Invalid process ID, something didn't go well
1808 if (error.Success())
1809 error.SetErrorString ("process launch failed for unknown reasons");
1810 }
1811 return error;
1812}
1813
1814#endif // defined(__linux__) or defined(__FreeBSD__)
1815
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001816#ifndef _WIN32
1817
1818size_t
1819Host::GetPageSize()
1820{
1821 return ::getpagesize();
1822}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001823
Greg Claytone3e3fee2013-02-17 20:46:30 +00001824uint32_t
1825Host::GetNumberCPUS ()
1826{
1827 static uint32_t g_num_cores = UINT32_MAX;
1828 if (g_num_cores == UINT32_MAX)
1829 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001830#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001831
1832 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001833
Greg Claytone3e3fee2013-02-17 20:46:30 +00001834#else
1835
1836 // Assume POSIX support if a host specific case has not been supplied above
1837 g_num_cores = 0;
1838 int num_cores = 0;
1839 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001840#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001841 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001842#else
1843 int mib[] = { CTL_HW, HW_NCPU };
1844#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001845
1846 /* get the number of CPUs from the system */
1847 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1848 {
1849 g_num_cores = num_cores;
1850 }
1851 else
1852 {
1853 mib[1] = HW_NCPU;
1854 num_cores_len = sizeof(num_cores);
1855 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1856 {
1857 if (num_cores > 0)
1858 g_num_cores = num_cores;
1859 }
1860 }
1861#endif
1862 }
1863 return g_num_cores;
1864}
1865
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001866void
1867Host::Kill(lldb::pid_t pid, int signo)
1868{
1869 ::kill(pid, signo);
1870}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001871
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001872#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001873
Johnny Chen8f3d8382011-08-02 20:52:42 +00001874#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001875bool
Greg Clayton3b147632010-12-18 01:54:34 +00001876Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001877{
1878 return false;
1879}
Greg Claytondd36def2010-10-17 22:03:32 +00001880
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001881void
1882Host::SetCrashDescriptionWithFormat (const char *format, ...)
1883{
1884}
1885
1886void
1887Host::SetCrashDescription (const char *description)
1888{
1889}
Greg Claytondd36def2010-10-17 22:03:32 +00001890
1891lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001892Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001893{
1894 return LLDB_INVALID_PROCESS_ID;
1895}
1896
Greg Claytonfbb76342013-11-20 21:07:01 +00001897#endif
1898
1899
1900#ifdef LLDB_DISABLE_POSIX
1901
1902Error
1903Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001904{
Greg Claytonfbb76342013-11-20 21:07:01 +00001905 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001906 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001907 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001908}
Greg Claytonfbb76342013-11-20 21:07:01 +00001909
1910Error
1911Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1912{
1913 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001914 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001915 return error;
1916}
1917
1918Error
1919Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1920{
1921 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001922 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001923 return error;
1924}
1925
1926Error
1927Host::Symlink (const char *src, const char *dst)
1928{
1929 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001930 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001931 return error;
1932}
1933
1934Error
1935Host::Readlink (const char *path, char *buf, size_t buf_len)
1936{
1937 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001938 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001939 return error;
1940}
1941
1942Error
1943Host::Unlink (const char *path)
1944{
1945 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001946 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001947 return error;
1948}
1949
1950#else
1951
1952Error
1953Host::MakeDirectory (const char* path, uint32_t file_permissions)
1954{
1955 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00001956 if (path && path[0])
1957 {
Greg Claytonfb909312013-11-23 01:58:15 +00001958 if (::mkdir(path, file_permissions) != 0)
1959 {
1960 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001961 switch (error.GetError())
1962 {
1963 case ENOENT:
1964 {
1965 // Parent directory doesn't exist, so lets make it if we can
1966 FileSpec spec(path, false);
1967 if (spec.GetDirectory() && spec.GetFilename())
1968 {
1969 // Make the parent directory and try again
1970 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
1971 if (error2.Success())
1972 {
1973 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00001974 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00001975 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00001976 else
Greg Claytonfb909312013-11-23 01:58:15 +00001977 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001978 }
1979 }
1980 }
1981 break;
1982 case EEXIST:
1983 {
1984 FileSpec path_spec(path, false);
1985 if (path_spec.IsDirectory())
1986 error.Clear(); // It is a directory and it already exists
1987 }
1988 break;
1989 }
1990 }
Greg Claytonfb909312013-11-23 01:58:15 +00001991 }
1992 else
1993 {
1994 error.SetErrorString("empty path");
1995 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001996 return error;
1997}
1998
1999Error
2000Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2001{
2002 Error error;
2003 struct stat file_stats;
2004 if (::stat (path, &file_stats) == 0)
2005 {
2006 // The bits in "st_mode" currently match the definitions
2007 // for the file mode bits in unix.
2008 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2009 }
2010 else
2011 {
2012 error.SetErrorToErrno();
2013 }
2014 return error;
2015}
2016
2017Error
2018Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2019{
2020 Error error;
2021 if (::chmod(path, file_permissions) != 0)
2022 error.SetErrorToErrno();
2023 return error;
2024}
2025
2026Error
2027Host::Symlink (const char *src, const char *dst)
2028{
2029 Error error;
2030 if (::symlink(dst, src) == -1)
2031 error.SetErrorToErrno();
2032 return error;
2033}
2034
2035Error
2036Host::Unlink (const char *path)
2037{
2038 Error error;
2039 if (::unlink(path) == -1)
2040 error.SetErrorToErrno();
2041 return error;
2042}
2043
2044Error
2045Host::Readlink (const char *path, char *buf, size_t buf_len)
2046{
2047 Error error;
2048 ssize_t count = ::readlink(path, buf, buf_len);
2049 if (count < 0)
2050 error.SetErrorToErrno();
2051 else if (count < (buf_len-1))
2052 buf[count] = '\0'; // Success
2053 else
2054 error.SetErrorString("'buf' buffer is too small to contain link contents");
2055 return error;
2056}
2057
2058
Greg Clayton2bddd342010-09-07 20:11:56 +00002059#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002060
2061typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2062FDToFileMap& GetFDToFileMap()
2063{
2064 static FDToFileMap g_fd2filemap;
2065 return g_fd2filemap;
2066}
2067
2068lldb::user_id_t
2069Host::OpenFile (const FileSpec& file_spec,
2070 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002071 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002072 Error &error)
2073{
2074 std::string path (file_spec.GetPath());
2075 if (path.empty())
2076 {
2077 error.SetErrorString("empty path");
2078 return UINT64_MAX;
2079 }
2080 FileSP file_sp(new File());
2081 error = file_sp->Open(path.c_str(),flags,mode);
2082 if (file_sp->IsValid() == false)
2083 return UINT64_MAX;
2084 lldb::user_id_t fd = file_sp->GetDescriptor();
2085 GetFDToFileMap()[fd] = file_sp;
2086 return fd;
2087}
2088
2089bool
2090Host::CloseFile (lldb::user_id_t fd, Error &error)
2091{
2092 if (fd == UINT64_MAX)
2093 {
2094 error.SetErrorString ("invalid file descriptor");
2095 return false;
2096 }
2097 FDToFileMap& file_map = GetFDToFileMap();
2098 FDToFileMap::iterator pos = file_map.find(fd);
2099 if (pos == file_map.end())
2100 {
2101 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2102 return false;
2103 }
2104 FileSP file_sp = pos->second;
2105 if (!file_sp)
2106 {
2107 error.SetErrorString ("invalid host backing file");
2108 return false;
2109 }
2110 error = file_sp->Close();
2111 file_map.erase(pos);
2112 return error.Success();
2113}
2114
2115uint64_t
2116Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2117{
2118 if (fd == UINT64_MAX)
2119 {
2120 error.SetErrorString ("invalid file descriptor");
2121 return UINT64_MAX;
2122 }
2123 FDToFileMap& file_map = GetFDToFileMap();
2124 FDToFileMap::iterator pos = file_map.find(fd);
2125 if (pos == file_map.end())
2126 {
2127 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2128 return false;
2129 }
2130 FileSP file_sp = pos->second;
2131 if (!file_sp)
2132 {
2133 error.SetErrorString ("invalid host backing file");
2134 return UINT64_MAX;
2135 }
2136 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2137 return UINT64_MAX;
2138 size_t bytes_written = src_len;
2139 error = file_sp->Write(src, bytes_written);
2140 if (error.Fail())
2141 return UINT64_MAX;
2142 return bytes_written;
2143}
2144
2145uint64_t
2146Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2147{
2148 if (fd == UINT64_MAX)
2149 {
2150 error.SetErrorString ("invalid file descriptor");
2151 return UINT64_MAX;
2152 }
2153 FDToFileMap& file_map = GetFDToFileMap();
2154 FDToFileMap::iterator pos = file_map.find(fd);
2155 if (pos == file_map.end())
2156 {
2157 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2158 return false;
2159 }
2160 FileSP file_sp = pos->second;
2161 if (!file_sp)
2162 {
2163 error.SetErrorString ("invalid host backing file");
2164 return UINT64_MAX;
2165 }
2166 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2167 return UINT64_MAX;
2168 size_t bytes_read = dst_len;
2169 error = file_sp->Read(dst ,bytes_read);
2170 if (error.Fail())
2171 return UINT64_MAX;
2172 return bytes_read;
2173}
2174
2175lldb::user_id_t
2176Host::GetFileSize (const FileSpec& file_spec)
2177{
2178 return file_spec.GetByteSize();
2179}
2180
2181bool
2182Host::GetFileExists (const FileSpec& file_spec)
2183{
2184 return file_spec.Exists();
2185}
2186
2187bool
2188Host::CalculateMD5 (const FileSpec& file_spec,
2189 uint64_t &low,
2190 uint64_t &high)
2191{
2192#if defined (__APPLE__)
2193 StreamString md5_cmd_line;
2194 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2195 std::string hash_string;
2196 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2197 if (err.Fail())
2198 return false;
2199 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2200 // if the output is any other length it is probably wrong
2201 if (hash_string.size() != 32)
2202 return false;
2203 std::string part1(hash_string,0,16);
2204 std::string part2(hash_string,16);
2205 const char* part1_cstr = part1.c_str();
2206 const char* part2_cstr = part2.c_str();
2207 high = ::strtoull(part1_cstr, NULL, 16);
2208 low = ::strtoull(part2_cstr, NULL, 16);
2209 return true;
2210#else
2211 // your own MD5 implementation here
2212 return false;
2213#endif
2214}