blob: 5c4bf39e6209a9b6134bb6a97ce944d03f764a9c [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)
Todd Fialae28f1d72014-01-17 22:21:22 +0000371 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000372
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
Todd Fialaf3d61de2014-01-17 20:18:59 +0000449// See linux/Host.cpp for Linux-based implementations of this.
450// Add your platform-specific implementation to the appropriate host file.
451#if !defined(__linux__)
452
453const ConstString &
454 Host::GetDistributionId ()
455{
456 static ConstString s_distribution_id;
457 return s_distribution_id;
458}
459
460#endif // #if !defined(__linux__)
461
Greg Clayton2bddd342010-09-07 20:11:56 +0000462lldb::pid_t
463Host::GetCurrentProcessID()
464{
465 return ::getpid();
466}
467
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000468#ifndef _WIN32
469
Greg Clayton2bddd342010-09-07 20:11:56 +0000470lldb::tid_t
471Host::GetCurrentThreadID()
472{
473#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000474 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000475 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
476 // count.
477 thread_port_t thread_self = mach_thread_self();
478 mach_port_deallocate(mach_task_self(), thread_self);
479 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000480#elif defined(__FreeBSD__)
481 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000482#elif defined(__linux__)
483 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000484#else
485 return lldb::tid_t(pthread_self());
486#endif
487}
488
Jim Ingham372787f2012-04-07 00:00:41 +0000489lldb::thread_t
490Host::GetCurrentThread ()
491{
492 return lldb::thread_t(pthread_self());
493}
494
Greg Clayton2bddd342010-09-07 20:11:56 +0000495const char *
496Host::GetSignalAsCString (int signo)
497{
498 switch (signo)
499 {
500 case SIGHUP: return "SIGHUP"; // 1 hangup
501 case SIGINT: return "SIGINT"; // 2 interrupt
502 case SIGQUIT: return "SIGQUIT"; // 3 quit
503 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
504 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
505 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000506#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000507#if !defined(SIGIO) || (SIGPOLL != SIGIO)
508// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
509// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000510 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000511#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000512#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000513#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000514 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000515#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000516 case SIGFPE: return "SIGFPE"; // 8 floating point exception
517 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
518 case SIGBUS: return "SIGBUS"; // 10 bus error
519 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
520 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
521 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
522 case SIGALRM: return "SIGALRM"; // 14 alarm clock
523 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
524 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
525 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
526 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
527 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
528 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
529 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
530 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000531#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000532 case SIGIO: return "SIGIO"; // 23 input/output possible signal
533#endif
534 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
535 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
536 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
537 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000538#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000539 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000540#endif
541#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000542 case SIGINFO: return "SIGINFO"; // 29 information request
543#endif
544 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
545 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
546 default:
547 break;
548 }
549 return NULL;
550}
551
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000552#endif
553
Greg Clayton2bddd342010-09-07 20:11:56 +0000554void
555Host::WillTerminate ()
556{
557}
558
Sylvestre Ledru59405832013-07-01 08:21:36 +0000559#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000560
Greg Clayton2bddd342010-09-07 20:11:56 +0000561void
562Host::ThreadCreated (const char *thread_name)
563{
564}
Greg Claytone5219662010-12-03 06:02:24 +0000565
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000566void
Greg Claytone5219662010-12-03 06:02:24 +0000567Host::Backtrace (Stream &strm, uint32_t max_frames)
568{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000569 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000570}
571
Greg Clayton85851dd2010-12-04 00:10:17 +0000572size_t
573Host::GetEnvironment (StringList &env)
574{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000575 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000576 return 0;
577}
578
Sylvestre Ledru59405832013-07-01 08:21:36 +0000579#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000580
581struct HostThreadCreateInfo
582{
583 std::string thread_name;
584 thread_func_t thread_fptr;
585 thread_arg_t thread_arg;
586
587 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
588 thread_name (name ? name : ""),
589 thread_fptr (fptr),
590 thread_arg (arg)
591 {
592 }
593};
594
595static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000596#ifdef _WIN32
597__stdcall
598#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000599ThreadCreateTrampoline (thread_arg_t arg)
600{
601 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
602 Host::ThreadCreated (info->thread_name.c_str());
603 thread_func_t thread_fptr = info->thread_fptr;
604 thread_arg_t thread_arg = info->thread_arg;
605
Greg Clayton5160ce52013-03-27 23:08:40 +0000606 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000607 if (log)
608 log->Printf("thread created");
609
610 delete info;
611 return thread_fptr (thread_arg);
612}
613
614lldb::thread_t
615Host::ThreadCreate
616(
617 const char *thread_name,
618 thread_func_t thread_fptr,
619 thread_arg_t thread_arg,
620 Error *error
621)
622{
623 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
624
625 // Host::ThreadCreateTrampoline will delete this pointer for us.
626 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
627
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000628#ifdef _WIN32
629 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
630 int err = thread <= 0 ? GetLastError() : 0;
631#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000632 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000633#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000634 if (err == 0)
635 {
636 if (error)
637 error->Clear();
638 return thread;
639 }
640
641 if (error)
642 error->SetError (err, eErrorTypePOSIX);
643
644 return LLDB_INVALID_HOST_THREAD;
645}
646
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000647#ifndef _WIN32
648
Greg Clayton2bddd342010-09-07 20:11:56 +0000649bool
650Host::ThreadCancel (lldb::thread_t thread, Error *error)
651{
652 int err = ::pthread_cancel (thread);
653 if (error)
654 error->SetError(err, eErrorTypePOSIX);
655 return err == 0;
656}
657
658bool
659Host::ThreadDetach (lldb::thread_t thread, Error *error)
660{
661 int err = ::pthread_detach (thread);
662 if (error)
663 error->SetError(err, eErrorTypePOSIX);
664 return err == 0;
665}
666
667bool
668Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
669{
670 int err = ::pthread_join (thread, thread_result_ptr);
671 if (error)
672 error->SetError(err, eErrorTypePOSIX);
673 return err == 0;
674}
675
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000676lldb::thread_key_t
677Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
678{
679 pthread_key_t key;
680 ::pthread_key_create (&key, callback);
681 return key;
682}
683
684void*
685Host::ThreadLocalStorageGet(lldb::thread_key_t key)
686{
687 return ::pthread_getspecific (key);
688}
689
690void
691Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
692{
693 ::pthread_setspecific (key, value);
694}
695
Matt Kopec62502c62013-05-13 19:33:58 +0000696bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000697Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
698{
Greg Clayton85719632013-02-27 22:51:58 +0000699#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000700 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
701 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
702 if (pid == LLDB_INVALID_PROCESS_ID)
703 pid = curr_pid;
704
705 if (tid == LLDB_INVALID_THREAD_ID)
706 tid = curr_tid;
707
Greg Clayton2bddd342010-09-07 20:11:56 +0000708 // Set the pthread name if possible
709 if (pid == curr_pid && tid == curr_tid)
710 {
Matt Kopec62502c62013-05-13 19:33:58 +0000711 if (::pthread_setname_np (name) == 0)
712 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000713 }
Matt Kopec62502c62013-05-13 19:33:58 +0000714 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000715#elif defined (__FreeBSD__)
716 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
717 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
718 if (pid == LLDB_INVALID_PROCESS_ID)
719 pid = curr_pid;
720
721 if (tid == LLDB_INVALID_THREAD_ID)
722 tid = curr_tid;
723
724 // Set the pthread name if possible
725 if (pid == curr_pid && tid == curr_tid)
726 {
Michael Sartainc2052432013-08-01 18:51:08 +0000727 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000728 return true;
729 }
730 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000731#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000732 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
733 if (fn)
734 {
Matt Kopec62502c62013-05-13 19:33:58 +0000735 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
736 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000737 if (pid == LLDB_INVALID_PROCESS_ID)
738 pid = curr_pid;
739
740 if (tid == LLDB_INVALID_THREAD_ID)
741 tid = curr_tid;
742
Michael Sartainc2052432013-08-01 18:51:08 +0000743 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000744 {
Michael Sartainc2052432013-08-01 18:51:08 +0000745 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
746 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
747
748 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000749 return true;
750 }
751 }
752 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000753#else
754 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000755#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000756}
757
Ed Maste02983be2013-07-25 19:10:32 +0000758bool
759Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
760 const char *thread_name, size_t len)
761{
762 char *namebuf = (char *)::malloc (len + 1);
763
764 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
765 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
766 // off leads to a lot of similar named threads. Go through the thread name
767 // and search for the last dot and use that.
768 const char *lastdot = ::strrchr (thread_name, '.');
769
770 if (lastdot && lastdot != thread_name)
771 thread_name = lastdot + 1;
772 ::strncpy (namebuf, thread_name, len);
773 namebuf[len] = 0;
774
775 int namebuflen = strlen(namebuf);
776 if (namebuflen > 0)
777 {
778 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
779 {
780 // Trim off trailing '(' and '>' characters for a bit more cleanup.
781 namebuflen--;
782 namebuf[namebuflen] = 0;
783 }
784 return Host::SetThreadName (pid, tid, namebuf);
785 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000786
787 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000788 return false;
789}
790
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000791#endif
792
Greg Clayton2bddd342010-09-07 20:11:56 +0000793FileSpec
794Host::GetProgramFileSpec ()
795{
796 static FileSpec g_program_filespec;
797 if (!g_program_filespec)
798 {
799#if defined (__APPLE__)
800 char program_fullpath[PATH_MAX];
801 // If DST is NULL, then return the number of bytes needed.
802 uint32_t len = sizeof(program_fullpath);
803 int err = _NSGetExecutablePath (program_fullpath, &len);
804 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000805 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000806 else if (err == -1)
807 {
808 char *large_program_fullpath = (char *)::malloc (len + 1);
809
810 err = _NSGetExecutablePath (large_program_fullpath, &len);
811 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000812 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000813
814 ::free (large_program_fullpath);
815 }
816#elif defined (__linux__)
817 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000818 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
819 if (len > 0) {
820 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000821 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000822 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000823#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000824 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
825 size_t exe_path_size;
826 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
827 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000828 char *exe_path = new char[exe_path_size];
829 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
830 g_program_filespec.SetFile(exe_path, false);
831 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000832 }
833#endif
834 }
835 return g_program_filespec;
836}
837
Greg Clayton2bddd342010-09-07 20:11:56 +0000838#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000839
840bool
841Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
842{
843 bundle.Clear();
844 return false;
845}
846
Greg Clayton2bddd342010-09-07 20:11:56 +0000847bool
Greg Claytondd36def2010-10-17 22:03:32 +0000848Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000849{
Greg Claytondd36def2010-10-17 22:03:32 +0000850 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000851}
852#endif
853
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000854#ifndef _WIN32
855
Greg Clayton45319462011-02-08 00:35:34 +0000856// Opaque info that tracks a dynamic library that was loaded
857struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000858{
Greg Clayton45319462011-02-08 00:35:34 +0000859 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
860 file_spec (fs),
861 open_options (o),
862 handle (h)
863 {
864 }
865
866 const FileSpec file_spec;
867 uint32_t open_options;
868 void * handle;
869};
870
871void *
872Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
873{
Greg Clayton4272cc72011-02-02 02:24:04 +0000874 char path[PATH_MAX];
875 if (file_spec.GetPath(path, sizeof(path)))
876 {
Greg Clayton45319462011-02-08 00:35:34 +0000877 int mode = 0;
878
879 if (options & eDynamicLibraryOpenOptionLazy)
880 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000881 else
882 mode |= RTLD_NOW;
883
Greg Clayton45319462011-02-08 00:35:34 +0000884
885 if (options & eDynamicLibraryOpenOptionLocal)
886 mode |= RTLD_LOCAL;
887 else
888 mode |= RTLD_GLOBAL;
889
890#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
891 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
892 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000893#endif
Greg Clayton45319462011-02-08 00:35:34 +0000894
895 void * opaque = ::dlopen (path, mode);
896
897 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000898 {
899 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000900 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000901 }
902 else
903 {
904 error.SetErrorString(::dlerror());
905 }
906 }
907 else
908 {
909 error.SetErrorString("failed to extract path");
910 }
Greg Clayton45319462011-02-08 00:35:34 +0000911 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000912}
913
914Error
Greg Clayton45319462011-02-08 00:35:34 +0000915Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000916{
917 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000918 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000919 {
920 error.SetErrorString ("invalid dynamic library handle");
921 }
Greg Clayton45319462011-02-08 00:35:34 +0000922 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000923 {
Greg Clayton45319462011-02-08 00:35:34 +0000924 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
925 if (::dlclose (dylib_info->handle) != 0)
926 {
927 error.SetErrorString(::dlerror());
928 }
929
930 dylib_info->open_options = 0;
931 dylib_info->handle = 0;
932 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000933 }
934 return error;
935}
936
937void *
Greg Clayton45319462011-02-08 00:35:34 +0000938Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000939{
Greg Clayton45319462011-02-08 00:35:34 +0000940 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000941 {
942 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000943 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000944 else
Greg Clayton45319462011-02-08 00:35:34 +0000945 {
946 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
947
948 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
949 if (symbol_addr)
950 {
951#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
952 // This host doesn't support limiting searches to this shared library
953 // so we need to verify that the match came from this shared library
954 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000955 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000956 {
957 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
958 if (match_dylib_spec != dylib_info->file_spec)
959 {
960 char dylib_path[PATH_MAX];
961 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
962 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
963 else
964 error.SetErrorString ("symbol not found");
965 return NULL;
966 }
967 }
968#endif
969 error.Clear();
970 return symbol_addr;
971 }
972 else
973 {
974 error.SetErrorString(::dlerror());
975 }
976 }
977 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000978}
Greg Claytondd36def2010-10-17 22:03:32 +0000979
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000980FileSpec
981Host::GetModuleFileSpecForHostAddress (const void *host_addr)
982{
983 FileSpec module_filespec;
984 Dl_info info;
985 if (::dladdr (host_addr, &info))
986 {
987 if (info.dli_fname)
988 module_filespec.SetFile(info.dli_fname, true);
989 }
990 return module_filespec;
991}
992
993#endif
994
Greg Claytondd36def2010-10-17 22:03:32 +0000995bool
996Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
997{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000998 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000999 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1000 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001001 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001002 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001003 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001004
1005 switch (path_type)
1006 {
1007 case ePathTypeLLDBShlibDir:
1008 {
1009 static ConstString g_lldb_so_dir;
1010 if (!g_lldb_so_dir)
1011 {
1012 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
1013 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001014 if (log)
1015 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001016 }
1017 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001018 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001019 }
1020 break;
1021
1022 case ePathTypeSupportExecutableDir:
1023 {
1024 static ConstString g_lldb_support_exe_dir;
1025 if (!g_lldb_support_exe_dir)
1026 {
1027 FileSpec lldb_file_spec;
1028 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1029 {
1030 char raw_path[PATH_MAX];
1031 char resolved_path[PATH_MAX];
1032 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1033
1034#if defined (__APPLE__)
1035 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1036 if (framework_pos)
1037 {
1038 framework_pos += strlen("LLDB.framework");
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001039#if defined (__arm__)
1040 // Shallow bundle
1041 *framework_pos = '\0';
1042#else
1043 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001044 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001045#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001046 }
1047#endif
1048 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1049 g_lldb_support_exe_dir.SetCString(resolved_path);
1050 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001051 if (log)
1052 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001053 }
1054 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001055 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001056 }
1057 break;
1058
1059 case ePathTypeHeaderDir:
1060 {
1061 static ConstString g_lldb_headers_dir;
1062 if (!g_lldb_headers_dir)
1063 {
1064#if defined (__APPLE__)
1065 FileSpec lldb_file_spec;
1066 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1067 {
1068 char raw_path[PATH_MAX];
1069 char resolved_path[PATH_MAX];
1070 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1071
1072 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1073 if (framework_pos)
1074 {
1075 framework_pos += strlen("LLDB.framework");
1076 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1077 }
1078 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1079 g_lldb_headers_dir.SetCString(resolved_path);
1080 }
1081#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001082 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001083 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1084#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001085 if (log)
1086 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001087 }
1088 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001089 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001090 }
1091 break;
1092
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001093#ifdef LLDB_DISABLE_PYTHON
1094 case ePathTypePythonDir:
1095 return false;
1096#else
1097 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001098 {
Greg Claytondd36def2010-10-17 22:03:32 +00001099 static ConstString g_lldb_python_dir;
1100 if (!g_lldb_python_dir)
1101 {
1102 FileSpec lldb_file_spec;
1103 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1104 {
1105 char raw_path[PATH_MAX];
1106 char resolved_path[PATH_MAX];
1107 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1108
1109#if defined (__APPLE__)
1110 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1111 if (framework_pos)
1112 {
1113 framework_pos += strlen("LLDB.framework");
1114 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1115 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001116#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001117 llvm::SmallString<256> python_version_dir;
1118 llvm::raw_svector_ostream os(python_version_dir);
1119 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1120 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001121
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001122 // We may get our string truncated. Should we protect
1123 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001124
Daniel Maleafa7425d2013-08-06 21:40:08 +00001125 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001126 sizeof(raw_path) - strlen(raw_path) - 1);
1127
Greg Claytondd36def2010-10-17 22:03:32 +00001128#endif
1129 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1130 g_lldb_python_dir.SetCString(resolved_path);
1131 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001132
1133 if (log)
1134 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1135
Greg Claytondd36def2010-10-17 22:03:32 +00001136 }
1137 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001138 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001139 }
1140 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001141#endif
1142
Greg Clayton4272cc72011-02-02 02:24:04 +00001143 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1144 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001145#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001146 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001147 static bool g_lldb_system_plugin_dir_located = false;
1148 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001149 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001150 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001151#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001152 FileSpec lldb_file_spec;
1153 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1154 {
1155 char raw_path[PATH_MAX];
1156 char resolved_path[PATH_MAX];
1157 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1158
1159 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1160 if (framework_pos)
1161 {
1162 framework_pos += strlen("LLDB.framework");
1163 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001164 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1165 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001166 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001167 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001168 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001169#elif defined (__linux__)
1170 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1171 if (lldb_file_spec.Exists())
1172 {
1173 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1174 }
1175#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001176
1177 if (log)
1178 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1179
Greg Clayton4272cc72011-02-02 02:24:04 +00001180 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001181
1182 if (g_lldb_system_plugin_dir)
1183 {
1184 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1185 return true;
1186 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001187#else
1188 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001189 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001190#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001191 }
1192 break;
1193
1194 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1195 {
1196#if defined (__APPLE__)
1197 static ConstString g_lldb_user_plugin_dir;
1198 if (!g_lldb_user_plugin_dir)
1199 {
1200 char user_plugin_path[PATH_MAX];
1201 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1202 user_plugin_path,
1203 sizeof(user_plugin_path)))
1204 {
1205 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1206 }
1207 }
1208 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001209 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001210#elif defined (__linux__)
1211 static ConstString g_lldb_user_plugin_dir;
1212 if (!g_lldb_user_plugin_dir)
1213 {
1214 // XDG Base Directory Specification
1215 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1216 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1217 FileSpec lldb_file_spec;
1218 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1219 if (xdg_data_home && xdg_data_home[0])
1220 {
1221 std::string user_plugin_dir (xdg_data_home);
1222 user_plugin_dir += "/lldb";
1223 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1224 }
1225 else
1226 {
1227 const char *home_dir = getenv("HOME");
1228 if (home_dir && home_dir[0])
1229 {
1230 std::string user_plugin_dir (home_dir);
1231 user_plugin_dir += "/.local/share/lldb";
1232 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1233 }
1234 }
1235
1236 if (lldb_file_spec.Exists())
1237 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001238 if (log)
1239 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001240 }
1241 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001242 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001243#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001244 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001245 return false;
1246 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001247
1248 case ePathTypeLLDBTempSystemDir:
1249 {
1250 static ConstString g_lldb_tmp_dir;
1251 if (!g_lldb_tmp_dir)
1252 {
1253 const char *tmpdir_cstr = getenv("TMPDIR");
1254 if (tmpdir_cstr == NULL)
1255 {
1256 tmpdir_cstr = getenv("TMP");
1257 if (tmpdir_cstr == NULL)
1258 tmpdir_cstr = getenv("TEMP");
1259 }
1260 if (tmpdir_cstr)
1261 {
1262 g_lldb_tmp_dir.SetCString(tmpdir_cstr);
1263 if (log)
1264 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1265 }
1266 }
1267 file_spec.GetDirectory() = g_lldb_tmp_dir;
1268 return (bool)file_spec.GetDirectory();
1269 }
Greg Claytondd36def2010-10-17 22:03:32 +00001270 }
1271
1272 return false;
1273}
1274
Greg Clayton1cb64962011-03-24 04:28:38 +00001275
1276bool
1277Host::GetHostname (std::string &s)
1278{
1279 char hostname[PATH_MAX];
1280 hostname[sizeof(hostname) - 1] = '\0';
1281 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1282 {
1283 struct hostent* h = ::gethostbyname (hostname);
1284 if (h)
1285 s.assign (h->h_name);
1286 else
1287 s.assign (hostname);
1288 return true;
1289 }
1290 return false;
1291}
1292
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001293#ifndef _WIN32
1294
Greg Clayton32e0a752011-03-30 18:16:51 +00001295const char *
1296Host::GetUserName (uint32_t uid, std::string &user_name)
1297{
1298 struct passwd user_info;
1299 struct passwd *user_info_ptr = &user_info;
1300 char user_buffer[PATH_MAX];
1301 size_t user_buffer_size = sizeof(user_buffer);
1302 if (::getpwuid_r (uid,
1303 &user_info,
1304 user_buffer,
1305 user_buffer_size,
1306 &user_info_ptr) == 0)
1307 {
1308 if (user_info_ptr)
1309 {
1310 user_name.assign (user_info_ptr->pw_name);
1311 return user_name.c_str();
1312 }
1313 }
1314 user_name.clear();
1315 return NULL;
1316}
1317
1318const char *
1319Host::GetGroupName (uint32_t gid, std::string &group_name)
1320{
1321 char group_buffer[PATH_MAX];
1322 size_t group_buffer_size = sizeof(group_buffer);
1323 struct group group_info;
1324 struct group *group_info_ptr = &group_info;
1325 // Try the threadsafe version first
1326 if (::getgrgid_r (gid,
1327 &group_info,
1328 group_buffer,
1329 group_buffer_size,
1330 &group_info_ptr) == 0)
1331 {
1332 if (group_info_ptr)
1333 {
1334 group_name.assign (group_info_ptr->gr_name);
1335 return group_name.c_str();
1336 }
1337 }
1338 else
1339 {
1340 // The threadsafe version isn't currently working
1341 // for me on darwin, but the non-threadsafe version
1342 // is, so I am calling it below.
1343 group_info_ptr = ::getgrgid (gid);
1344 if (group_info_ptr)
1345 {
1346 group_name.assign (group_info_ptr->gr_name);
1347 return group_name.c_str();
1348 }
1349 }
1350 group_name.clear();
1351 return NULL;
1352}
1353
Han Ming Ong84647042012-02-25 01:07:38 +00001354uint32_t
1355Host::GetUserID ()
1356{
1357 return getuid();
1358}
1359
1360uint32_t
1361Host::GetGroupID ()
1362{
1363 return getgid();
1364}
1365
1366uint32_t
1367Host::GetEffectiveUserID ()
1368{
1369 return geteuid();
1370}
1371
1372uint32_t
1373Host::GetEffectiveGroupID ()
1374{
1375 return getegid();
1376}
1377
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001378#endif
1379
1380#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1381bool
1382Host::GetOSBuildString (std::string &s)
1383{
1384 s.clear();
1385 return false;
1386}
1387
1388bool
1389Host::GetOSKernelDescription (std::string &s)
1390{
1391 s.clear();
1392 return false;
1393}
1394#endif
1395
Ed Maste47e575e2013-08-29 18:44:27 +00001396#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001397uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001398Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001399{
1400 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001401 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001402}
1403
Greg Claytone996fd32011-03-08 22:40:15 +00001404bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001405Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001406{
Greg Claytone996fd32011-03-08 22:40:15 +00001407 process_info.Clear();
1408 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001409}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001410#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001411
Matt Kopec085d6ce2013-05-31 22:00:07 +00001412#if !defined(__linux__)
1413bool
1414Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1415{
1416 return false;
1417}
1418#endif
1419
Sean Callananc0a6e062011-10-27 21:22:25 +00001420lldb::TargetSP
1421Host::GetDummyTarget (lldb_private::Debugger &debugger)
1422{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001423 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001424
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001425 // FIXME: Maybe the dummy target should be per-Debugger
1426 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1427 {
1428 ArchSpec arch(Target::GetDefaultArchitecture());
1429 if (!arch.IsValid())
1430 arch = Host::GetArchitecture ();
1431 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001432 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001433 arch.GetTriple().getTriple().c_str(),
1434 false,
1435 NULL,
1436 g_dummy_target_sp);
1437 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001438
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001439 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001440}
1441
Greg Claytond1cf11a2012-04-14 01:42:46 +00001442struct ShellInfo
1443{
1444 ShellInfo () :
1445 process_reaped (false),
1446 can_delete (false),
1447 pid (LLDB_INVALID_PROCESS_ID),
1448 signo(-1),
1449 status(-1)
1450 {
1451 }
1452
1453 lldb_private::Predicate<bool> process_reaped;
1454 lldb_private::Predicate<bool> can_delete;
1455 lldb::pid_t pid;
1456 int signo;
1457 int status;
1458};
1459
1460static bool
1461MonitorShellCommand (void *callback_baton,
1462 lldb::pid_t pid,
1463 bool exited, // True if the process did exit
1464 int signo, // Zero for no signal
1465 int status) // Exit value of process if signal is zero
1466{
1467 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1468 shell_info->pid = pid;
1469 shell_info->signo = signo;
1470 shell_info->status = status;
1471 // Let the thread running Host::RunShellCommand() know that the process
1472 // exited and that ShellInfo has been filled in by broadcasting to it
1473 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1474 // Now wait for a handshake back from that thread running Host::RunShellCommand
1475 // so we know that we can delete shell_info_ptr
1476 shell_info->can_delete.WaitForValueEqualTo(true);
1477 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1478 usleep(1000);
1479 // Now delete the shell info that was passed into this function
1480 delete shell_info;
1481 return true;
1482}
1483
1484Error
1485Host::RunShellCommand (const char *command,
1486 const char *working_dir,
1487 int *status_ptr,
1488 int *signo_ptr,
1489 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001490 uint32_t timeout_sec,
1491 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001492{
1493 Error error;
1494 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001495 if (shell && shell[0])
1496 {
1497 // Run the command in a shell
1498 launch_info.SetShell(shell);
1499 launch_info.GetArguments().AppendArgument(command);
1500 const bool localhost = true;
1501 const bool will_debug = false;
1502 const bool first_arg_is_full_shell_command = true;
1503 launch_info.ConvertArgumentsForLaunchingInShell (error,
1504 localhost,
1505 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001506 first_arg_is_full_shell_command,
1507 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001508 }
1509 else
1510 {
1511 // No shell, just run it
1512 Args args (command);
1513 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001514 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001515 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001516
1517 if (working_dir)
1518 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001519 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001520 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001521
Greg Claytond1cf11a2012-04-14 01:42:46 +00001522 if (command_output_ptr)
1523 {
1524 // Create a temporary file to get the stdout/stderr and redirect the
1525 // output of the command into this file. We will later read this file
1526 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001527 FileSpec tmpdir_file_spec;
1528 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1529 {
1530 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1531 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1532 }
1533 else
1534 {
1535 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1536 }
1537
1538 output_file_path = ::mktemp(output_file_path_buffer);
1539 }
1540
1541 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1542 if (output_file_path)
1543 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001544 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001545 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001546 }
1547 else
1548 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001549 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1550 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1551 }
1552
1553 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001554 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001555
1556 const bool monitor_signals = false;
1557 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1558
1559 error = LaunchProcess (launch_info);
1560 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001561
1562 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1563 error.SetErrorString("failed to get process ID");
1564
1565 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001566 {
1567 // The process successfully launched, so we can defer ownership of
1568 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001569 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001570 // doesn't need to delete the ShellInfo anymore.
1571 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001572 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001573 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001574 if (timeout_sec > 0) {
1575 timeout_time.OffsetWithSeconds(timeout_sec);
1576 timeout_ptr = &timeout_time;
1577 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001578 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001579 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001580 if (timed_out)
1581 {
1582 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001583
Greg Claytond1cf11a2012-04-14 01:42:46 +00001584 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001585 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001586 // Wait for the monitor callback to get the message
1587 timeout_time = TimeValue::Now();
1588 timeout_time.OffsetWithSeconds(1);
1589 timed_out = false;
1590 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1591 }
1592 else
1593 {
1594 if (status_ptr)
1595 *status_ptr = shell_info->status;
1596
1597 if (signo_ptr)
1598 *signo_ptr = shell_info->signo;
1599
1600 if (command_output_ptr)
1601 {
1602 command_output_ptr->clear();
1603 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1604 uint64_t file_size = file_spec.GetByteSize();
1605 if (file_size > 0)
1606 {
1607 if (file_size > command_output_ptr->max_size())
1608 {
1609 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1610 }
1611 else
1612 {
1613 command_output_ptr->resize(file_size);
1614 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1615 }
1616 }
1617 }
1618 }
1619 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1620 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001621
1622 if (output_file_path)
1623 ::unlink (output_file_path);
1624 // Handshake with the monitor thread, or just let it know in advance that
1625 // it can delete "shell_info" in case we timed out and were not able to kill
1626 // the process...
1627 return error;
1628}
1629
Ed Maste991fe6c2013-12-09 01:35:42 +00001630#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001631// The functions below implement process launching via posix_spawn() for Linux
1632// and FreeBSD.
1633
1634// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1635static Error
1636LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1637{
1638 Error error;
1639 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1640
1641 assert(exe_path);
1642 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1643
1644 posix_spawnattr_t attr;
1645
1646 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1647 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1648 if (error.Fail())
1649 return error;
1650
1651 // Make a quick class that will cleanup the posix spawn attributes in case
1652 // we return in the middle of this function.
1653 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1654
1655 sigset_t no_signals;
1656 sigset_t all_signals;
1657 sigemptyset (&no_signals);
1658 sigfillset (&all_signals);
1659 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1660 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1661
1662 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1663
1664 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1665 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1666 if (error.Fail())
1667 return error;
1668
1669 const size_t num_file_actions = launch_info.GetNumFileActions ();
1670 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1671 // Make a quick class that will cleanup the posix spawn attributes in case
1672 // we return in the middle of this function.
1673 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1674 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1675
1676 if (num_file_actions > 0)
1677 {
1678 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1679 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1680 if (error.Fail())
1681 return error;
1682
1683 file_action_ptr = &file_actions;
1684 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1685
1686 for (size_t i = 0; i < num_file_actions; ++i)
1687 {
1688 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1689 if (launch_file_action &&
1690 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1691 launch_file_action,
1692 log,
1693 error))
1694 return error;
1695 }
1696 }
1697
1698 // Change working directory if neccessary.
1699 char current_dir[PATH_MAX];
1700 current_dir[0] = '\0';
1701
1702 const char *working_dir = launch_info.GetWorkingDirectory();
1703 if (working_dir != NULL)
1704 {
1705 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1706 {
1707 error.SetError(errno, eErrorTypePOSIX);
1708 error.LogIfError(log, "unable to save the current directory");
1709 return error;
1710 }
1711
1712 if (::chdir(working_dir) == -1)
1713 {
1714 error.SetError(errno, eErrorTypePOSIX);
1715 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1716 return error;
1717 }
1718 }
1719
1720 const char *tmp_argv[2];
1721 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1722 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1723
1724 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1725 // We must pass argv into posix_spawnp and it must contain at least two items -
1726 // pointer to an executable and NULL.
1727 if (argv == NULL)
1728 {
1729 tmp_argv[0] = exe_path;
1730 tmp_argv[1] = NULL;
1731 argv = (char * const*)tmp_argv;
1732 }
1733
1734 error.SetError (::posix_spawnp (&pid,
1735 exe_path,
1736 (num_file_actions > 0) ? &file_actions : NULL,
1737 &attr,
1738 argv,
1739 envp),
1740 eErrorTypePOSIX);
1741
1742 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1743 pid, exe_path, file_action_ptr, &attr, argv, envp);
1744
1745 // Change back the current directory.
1746 // NOTE: do not override previously established error from posix_spawnp.
1747 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1748 {
1749 error.SetError(errno, eErrorTypePOSIX);
1750 error.LogIfError(log, "unable to change current directory back to %s",
1751 current_dir);
1752 }
1753
1754 return error;
1755}
1756
1757
1758Error
1759Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1760{
1761 Error error;
1762 char exe_path[PATH_MAX];
1763
1764 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1765
1766 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1767
1768 FileSpec exe_spec(launch_info.GetExecutableFile());
1769
1770 FileSpec::FileType file_type = exe_spec.GetFileType();
1771 if (file_type != FileSpec::eFileTypeRegular)
1772 {
1773 lldb::ModuleSP exe_module_sp;
1774 error = host_platform_sp->ResolveExecutable (exe_spec,
1775 arch_spec,
1776 exe_module_sp,
1777 NULL);
1778
1779 if (error.Fail())
1780 return error;
1781
1782 if (exe_module_sp)
1783 exe_spec = exe_module_sp->GetFileSpec();
1784 }
1785
1786 if (exe_spec.Exists())
1787 {
1788 exe_spec.GetPath (exe_path, sizeof(exe_path));
1789 }
1790 else
1791 {
1792 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1793 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1794 return error;
1795 }
1796
1797 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1798
1799 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1800
1801 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1802
1803 if (pid != LLDB_INVALID_PROCESS_ID)
1804 {
1805 // If all went well, then set the process ID into the launch info
1806 launch_info.SetProcessID(pid);
1807
1808 // Make sure we reap any processes we spawn or we will have zombies.
1809 if (!launch_info.MonitorProcess())
1810 {
1811 const bool monitor_signals = false;
1812 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1813 NULL,
1814 pid,
1815 monitor_signals);
1816 }
1817 }
1818 else
1819 {
1820 // Invalid process ID, something didn't go well
1821 if (error.Success())
1822 error.SetErrorString ("process launch failed for unknown reasons");
1823 }
1824 return error;
1825}
1826
1827#endif // defined(__linux__) or defined(__FreeBSD__)
1828
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001829#ifndef _WIN32
1830
1831size_t
1832Host::GetPageSize()
1833{
1834 return ::getpagesize();
1835}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001836
Greg Claytone3e3fee2013-02-17 20:46:30 +00001837uint32_t
1838Host::GetNumberCPUS ()
1839{
1840 static uint32_t g_num_cores = UINT32_MAX;
1841 if (g_num_cores == UINT32_MAX)
1842 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001843#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001844
1845 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001846
Greg Claytone3e3fee2013-02-17 20:46:30 +00001847#else
1848
1849 // Assume POSIX support if a host specific case has not been supplied above
1850 g_num_cores = 0;
1851 int num_cores = 0;
1852 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001853#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001854 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001855#else
1856 int mib[] = { CTL_HW, HW_NCPU };
1857#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001858
1859 /* get the number of CPUs from the system */
1860 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1861 {
1862 g_num_cores = num_cores;
1863 }
1864 else
1865 {
1866 mib[1] = HW_NCPU;
1867 num_cores_len = sizeof(num_cores);
1868 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1869 {
1870 if (num_cores > 0)
1871 g_num_cores = num_cores;
1872 }
1873 }
1874#endif
1875 }
1876 return g_num_cores;
1877}
1878
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001879void
1880Host::Kill(lldb::pid_t pid, int signo)
1881{
1882 ::kill(pid, signo);
1883}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001884
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001885#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001886
Johnny Chen8f3d8382011-08-02 20:52:42 +00001887#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001888bool
Greg Clayton3b147632010-12-18 01:54:34 +00001889Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001890{
1891 return false;
1892}
Greg Claytondd36def2010-10-17 22:03:32 +00001893
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001894void
1895Host::SetCrashDescriptionWithFormat (const char *format, ...)
1896{
1897}
1898
1899void
1900Host::SetCrashDescription (const char *description)
1901{
1902}
Greg Claytondd36def2010-10-17 22:03:32 +00001903
1904lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001905Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001906{
1907 return LLDB_INVALID_PROCESS_ID;
1908}
1909
Greg Claytonfbb76342013-11-20 21:07:01 +00001910#endif
1911
1912
1913#ifdef LLDB_DISABLE_POSIX
1914
1915Error
1916Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001917{
Greg Claytonfbb76342013-11-20 21:07:01 +00001918 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001919 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001920 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001921}
Greg Claytonfbb76342013-11-20 21:07:01 +00001922
1923Error
1924Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1925{
1926 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001927 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001928 return error;
1929}
1930
1931Error
1932Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1933{
1934 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001935 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001936 return error;
1937}
1938
1939Error
1940Host::Symlink (const char *src, const char *dst)
1941{
1942 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001943 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001944 return error;
1945}
1946
1947Error
1948Host::Readlink (const char *path, char *buf, size_t buf_len)
1949{
1950 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001951 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001952 return error;
1953}
1954
1955Error
1956Host::Unlink (const char *path)
1957{
1958 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001959 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001960 return error;
1961}
1962
1963#else
1964
1965Error
1966Host::MakeDirectory (const char* path, uint32_t file_permissions)
1967{
1968 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00001969 if (path && path[0])
1970 {
Greg Claytonfb909312013-11-23 01:58:15 +00001971 if (::mkdir(path, file_permissions) != 0)
1972 {
1973 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001974 switch (error.GetError())
1975 {
1976 case ENOENT:
1977 {
1978 // Parent directory doesn't exist, so lets make it if we can
1979 FileSpec spec(path, false);
1980 if (spec.GetDirectory() && spec.GetFilename())
1981 {
1982 // Make the parent directory and try again
1983 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
1984 if (error2.Success())
1985 {
1986 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00001987 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00001988 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00001989 else
Greg Claytonfb909312013-11-23 01:58:15 +00001990 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001991 }
1992 }
1993 }
1994 break;
1995 case EEXIST:
1996 {
1997 FileSpec path_spec(path, false);
1998 if (path_spec.IsDirectory())
1999 error.Clear(); // It is a directory and it already exists
2000 }
2001 break;
2002 }
2003 }
Greg Claytonfb909312013-11-23 01:58:15 +00002004 }
2005 else
2006 {
2007 error.SetErrorString("empty path");
2008 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002009 return error;
2010}
2011
2012Error
2013Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2014{
2015 Error error;
2016 struct stat file_stats;
2017 if (::stat (path, &file_stats) == 0)
2018 {
2019 // The bits in "st_mode" currently match the definitions
2020 // for the file mode bits in unix.
2021 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2022 }
2023 else
2024 {
2025 error.SetErrorToErrno();
2026 }
2027 return error;
2028}
2029
2030Error
2031Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2032{
2033 Error error;
2034 if (::chmod(path, file_permissions) != 0)
2035 error.SetErrorToErrno();
2036 return error;
2037}
2038
2039Error
2040Host::Symlink (const char *src, const char *dst)
2041{
2042 Error error;
2043 if (::symlink(dst, src) == -1)
2044 error.SetErrorToErrno();
2045 return error;
2046}
2047
2048Error
2049Host::Unlink (const char *path)
2050{
2051 Error error;
2052 if (::unlink(path) == -1)
2053 error.SetErrorToErrno();
2054 return error;
2055}
2056
2057Error
2058Host::Readlink (const char *path, char *buf, size_t buf_len)
2059{
2060 Error error;
2061 ssize_t count = ::readlink(path, buf, buf_len);
2062 if (count < 0)
2063 error.SetErrorToErrno();
2064 else if (count < (buf_len-1))
2065 buf[count] = '\0'; // Success
2066 else
2067 error.SetErrorString("'buf' buffer is too small to contain link contents");
2068 return error;
2069}
2070
2071
Greg Clayton2bddd342010-09-07 20:11:56 +00002072#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002073
2074typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2075FDToFileMap& GetFDToFileMap()
2076{
2077 static FDToFileMap g_fd2filemap;
2078 return g_fd2filemap;
2079}
2080
2081lldb::user_id_t
2082Host::OpenFile (const FileSpec& file_spec,
2083 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002084 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002085 Error &error)
2086{
2087 std::string path (file_spec.GetPath());
2088 if (path.empty())
2089 {
2090 error.SetErrorString("empty path");
2091 return UINT64_MAX;
2092 }
2093 FileSP file_sp(new File());
2094 error = file_sp->Open(path.c_str(),flags,mode);
2095 if (file_sp->IsValid() == false)
2096 return UINT64_MAX;
2097 lldb::user_id_t fd = file_sp->GetDescriptor();
2098 GetFDToFileMap()[fd] = file_sp;
2099 return fd;
2100}
2101
2102bool
2103Host::CloseFile (lldb::user_id_t fd, Error &error)
2104{
2105 if (fd == UINT64_MAX)
2106 {
2107 error.SetErrorString ("invalid file descriptor");
2108 return false;
2109 }
2110 FDToFileMap& file_map = GetFDToFileMap();
2111 FDToFileMap::iterator pos = file_map.find(fd);
2112 if (pos == file_map.end())
2113 {
2114 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2115 return false;
2116 }
2117 FileSP file_sp = pos->second;
2118 if (!file_sp)
2119 {
2120 error.SetErrorString ("invalid host backing file");
2121 return false;
2122 }
2123 error = file_sp->Close();
2124 file_map.erase(pos);
2125 return error.Success();
2126}
2127
2128uint64_t
2129Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2130{
2131 if (fd == UINT64_MAX)
2132 {
2133 error.SetErrorString ("invalid file descriptor");
2134 return UINT64_MAX;
2135 }
2136 FDToFileMap& file_map = GetFDToFileMap();
2137 FDToFileMap::iterator pos = file_map.find(fd);
2138 if (pos == file_map.end())
2139 {
2140 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2141 return false;
2142 }
2143 FileSP file_sp = pos->second;
2144 if (!file_sp)
2145 {
2146 error.SetErrorString ("invalid host backing file");
2147 return UINT64_MAX;
2148 }
2149 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2150 return UINT64_MAX;
2151 size_t bytes_written = src_len;
2152 error = file_sp->Write(src, bytes_written);
2153 if (error.Fail())
2154 return UINT64_MAX;
2155 return bytes_written;
2156}
2157
2158uint64_t
2159Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2160{
2161 if (fd == UINT64_MAX)
2162 {
2163 error.SetErrorString ("invalid file descriptor");
2164 return UINT64_MAX;
2165 }
2166 FDToFileMap& file_map = GetFDToFileMap();
2167 FDToFileMap::iterator pos = file_map.find(fd);
2168 if (pos == file_map.end())
2169 {
2170 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2171 return false;
2172 }
2173 FileSP file_sp = pos->second;
2174 if (!file_sp)
2175 {
2176 error.SetErrorString ("invalid host backing file");
2177 return UINT64_MAX;
2178 }
2179 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2180 return UINT64_MAX;
2181 size_t bytes_read = dst_len;
2182 error = file_sp->Read(dst ,bytes_read);
2183 if (error.Fail())
2184 return UINT64_MAX;
2185 return bytes_read;
2186}
2187
2188lldb::user_id_t
2189Host::GetFileSize (const FileSpec& file_spec)
2190{
2191 return file_spec.GetByteSize();
2192}
2193
2194bool
2195Host::GetFileExists (const FileSpec& file_spec)
2196{
2197 return file_spec.Exists();
2198}
2199
2200bool
2201Host::CalculateMD5 (const FileSpec& file_spec,
2202 uint64_t &low,
2203 uint64_t &high)
2204{
2205#if defined (__APPLE__)
2206 StreamString md5_cmd_line;
2207 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2208 std::string hash_string;
2209 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2210 if (err.Fail())
2211 return false;
2212 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2213 // if the output is any other length it is probably wrong
2214 if (hash_string.size() != 32)
2215 return false;
2216 std::string part1(hash_string,0,16);
2217 std::string part2(hash_string,16);
2218 const char* part1_cstr = part1.c_str();
2219 const char* part2_cstr = part2.c_str();
2220 high = ::strtoull(part1_cstr, NULL, 16);
2221 low = ::strtoull(part2_cstr, NULL, 16);
2222 return true;
2223#else
2224 // your own MD5 implementation here
2225 return false;
2226#endif
2227}