blob: 2d9989730b82dd50b2032701552b3e68b11acef6 [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 Fialaf3d61de2014-01-17 20:18:59 +0000371 {
372 const char *const dist_c_str = GetDistributionId ().AsCString ();
373 if (dist_c_str)
374 triple.setVendorName (dist_c_str);
375 else
376 triple.setVendorName ("");
377 }
Greg Claytonb29e6c62012-10-11 17:38:58 +0000378
Stephen Wilsonbd588712011-02-24 19:15:09 +0000379 switch (triple.getArch())
380 {
381 default:
382 g_host_arch_32.SetTriple(triple);
383 g_supports_32 = true;
384 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000385
Stephen Wilsonbd588712011-02-24 19:15:09 +0000386 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000387 g_host_arch_64.SetTriple(triple);
388 g_supports_64 = true;
389 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
390 g_supports_32 = true;
391 break;
392
Stephen Wilsonbd588712011-02-24 19:15:09 +0000393 case llvm::Triple::sparcv9:
394 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000395 g_host_arch_64.SetTriple(triple);
396 g_supports_64 = true;
397 break;
398 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000399
400 g_supports_32 = g_host_arch_32.IsValid();
401 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000402 }
Greg Clayton514487e2011-02-15 21:59:32 +0000403
404#endif // #else for #if defined (__APPLE__)
405
406 if (arch_kind == eSystemDefaultArchitecture32)
407 return g_host_arch_32;
408 else if (arch_kind == eSystemDefaultArchitecture64)
409 return g_host_arch_64;
410
411 if (g_supports_64)
412 return g_host_arch_64;
413
414 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000415}
416
417const ConstString &
418Host::GetVendorString()
419{
420 static ConstString g_vendor;
421 if (!g_vendor)
422 {
Greg Clayton950971f2012-05-12 00:01:21 +0000423 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
424 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
425 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000426 }
427 return g_vendor;
428}
429
430const ConstString &
431Host::GetOSString()
432{
433 static ConstString g_os_string;
434 if (!g_os_string)
435 {
Greg Clayton950971f2012-05-12 00:01:21 +0000436 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
437 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
438 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000439 }
440 return g_os_string;
441}
442
443const ConstString &
444Host::GetTargetTriple()
445{
446 static ConstString g_host_triple;
447 if (!(g_host_triple))
448 {
Greg Clayton950971f2012-05-12 00:01:21 +0000449 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
450 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000451 }
452 return g_host_triple;
453}
454
Todd Fialaf3d61de2014-01-17 20:18:59 +0000455// See linux/Host.cpp for Linux-based implementations of this.
456// Add your platform-specific implementation to the appropriate host file.
457#if !defined(__linux__)
458
459const ConstString &
460 Host::GetDistributionId ()
461{
462 static ConstString s_distribution_id;
463 return s_distribution_id;
464}
465
466#endif // #if !defined(__linux__)
467
Greg Clayton2bddd342010-09-07 20:11:56 +0000468lldb::pid_t
469Host::GetCurrentProcessID()
470{
471 return ::getpid();
472}
473
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000474#ifndef _WIN32
475
Greg Clayton2bddd342010-09-07 20:11:56 +0000476lldb::tid_t
477Host::GetCurrentThreadID()
478{
479#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000480 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000481 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
482 // count.
483 thread_port_t thread_self = mach_thread_self();
484 mach_port_deallocate(mach_task_self(), thread_self);
485 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000486#elif defined(__FreeBSD__)
487 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000488#elif defined(__linux__)
489 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000490#else
491 return lldb::tid_t(pthread_self());
492#endif
493}
494
Jim Ingham372787f2012-04-07 00:00:41 +0000495lldb::thread_t
496Host::GetCurrentThread ()
497{
498 return lldb::thread_t(pthread_self());
499}
500
Greg Clayton2bddd342010-09-07 20:11:56 +0000501const char *
502Host::GetSignalAsCString (int signo)
503{
504 switch (signo)
505 {
506 case SIGHUP: return "SIGHUP"; // 1 hangup
507 case SIGINT: return "SIGINT"; // 2 interrupt
508 case SIGQUIT: return "SIGQUIT"; // 3 quit
509 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
510 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
511 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000512#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000513#if !defined(SIGIO) || (SIGPOLL != SIGIO)
514// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
515// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000516 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000517#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000518#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000519#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000520 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000521#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000522 case SIGFPE: return "SIGFPE"; // 8 floating point exception
523 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
524 case SIGBUS: return "SIGBUS"; // 10 bus error
525 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
526 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
527 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
528 case SIGALRM: return "SIGALRM"; // 14 alarm clock
529 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
530 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
531 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
532 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
533 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
534 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
535 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
536 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000537#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000538 case SIGIO: return "SIGIO"; // 23 input/output possible signal
539#endif
540 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
541 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
542 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
543 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000544#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000545 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000546#endif
547#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000548 case SIGINFO: return "SIGINFO"; // 29 information request
549#endif
550 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
551 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
552 default:
553 break;
554 }
555 return NULL;
556}
557
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000558#endif
559
Greg Clayton2bddd342010-09-07 20:11:56 +0000560void
561Host::WillTerminate ()
562{
563}
564
Sylvestre Ledru59405832013-07-01 08:21:36 +0000565#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000566
Greg Clayton2bddd342010-09-07 20:11:56 +0000567void
568Host::ThreadCreated (const char *thread_name)
569{
570}
Greg Claytone5219662010-12-03 06:02:24 +0000571
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000572void
Greg Claytone5219662010-12-03 06:02:24 +0000573Host::Backtrace (Stream &strm, uint32_t max_frames)
574{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000575 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000576}
577
Greg Clayton85851dd2010-12-04 00:10:17 +0000578size_t
579Host::GetEnvironment (StringList &env)
580{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000581 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000582 return 0;
583}
584
Sylvestre Ledru59405832013-07-01 08:21:36 +0000585#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000586
587struct HostThreadCreateInfo
588{
589 std::string thread_name;
590 thread_func_t thread_fptr;
591 thread_arg_t thread_arg;
592
593 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
594 thread_name (name ? name : ""),
595 thread_fptr (fptr),
596 thread_arg (arg)
597 {
598 }
599};
600
601static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000602#ifdef _WIN32
603__stdcall
604#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000605ThreadCreateTrampoline (thread_arg_t arg)
606{
607 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
608 Host::ThreadCreated (info->thread_name.c_str());
609 thread_func_t thread_fptr = info->thread_fptr;
610 thread_arg_t thread_arg = info->thread_arg;
611
Greg Clayton5160ce52013-03-27 23:08:40 +0000612 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000613 if (log)
614 log->Printf("thread created");
615
616 delete info;
617 return thread_fptr (thread_arg);
618}
619
620lldb::thread_t
621Host::ThreadCreate
622(
623 const char *thread_name,
624 thread_func_t thread_fptr,
625 thread_arg_t thread_arg,
626 Error *error
627)
628{
629 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
630
631 // Host::ThreadCreateTrampoline will delete this pointer for us.
632 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
633
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000634#ifdef _WIN32
635 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
636 int err = thread <= 0 ? GetLastError() : 0;
637#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000638 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000639#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000640 if (err == 0)
641 {
642 if (error)
643 error->Clear();
644 return thread;
645 }
646
647 if (error)
648 error->SetError (err, eErrorTypePOSIX);
649
650 return LLDB_INVALID_HOST_THREAD;
651}
652
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000653#ifndef _WIN32
654
Greg Clayton2bddd342010-09-07 20:11:56 +0000655bool
656Host::ThreadCancel (lldb::thread_t thread, Error *error)
657{
658 int err = ::pthread_cancel (thread);
659 if (error)
660 error->SetError(err, eErrorTypePOSIX);
661 return err == 0;
662}
663
664bool
665Host::ThreadDetach (lldb::thread_t thread, Error *error)
666{
667 int err = ::pthread_detach (thread);
668 if (error)
669 error->SetError(err, eErrorTypePOSIX);
670 return err == 0;
671}
672
673bool
674Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
675{
676 int err = ::pthread_join (thread, thread_result_ptr);
677 if (error)
678 error->SetError(err, eErrorTypePOSIX);
679 return err == 0;
680}
681
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000682lldb::thread_key_t
683Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
684{
685 pthread_key_t key;
686 ::pthread_key_create (&key, callback);
687 return key;
688}
689
690void*
691Host::ThreadLocalStorageGet(lldb::thread_key_t key)
692{
693 return ::pthread_getspecific (key);
694}
695
696void
697Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
698{
699 ::pthread_setspecific (key, value);
700}
701
Matt Kopec62502c62013-05-13 19:33:58 +0000702bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000703Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
704{
Greg Clayton85719632013-02-27 22:51:58 +0000705#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000706 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
707 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
708 if (pid == LLDB_INVALID_PROCESS_ID)
709 pid = curr_pid;
710
711 if (tid == LLDB_INVALID_THREAD_ID)
712 tid = curr_tid;
713
Greg Clayton2bddd342010-09-07 20:11:56 +0000714 // Set the pthread name if possible
715 if (pid == curr_pid && tid == curr_tid)
716 {
Matt Kopec62502c62013-05-13 19:33:58 +0000717 if (::pthread_setname_np (name) == 0)
718 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000719 }
Matt Kopec62502c62013-05-13 19:33:58 +0000720 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000721#elif defined (__FreeBSD__)
722 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
723 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
724 if (pid == LLDB_INVALID_PROCESS_ID)
725 pid = curr_pid;
726
727 if (tid == LLDB_INVALID_THREAD_ID)
728 tid = curr_tid;
729
730 // Set the pthread name if possible
731 if (pid == curr_pid && tid == curr_tid)
732 {
Michael Sartainc2052432013-08-01 18:51:08 +0000733 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000734 return true;
735 }
736 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000737#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000738 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
739 if (fn)
740 {
Matt Kopec62502c62013-05-13 19:33:58 +0000741 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
742 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000743 if (pid == LLDB_INVALID_PROCESS_ID)
744 pid = curr_pid;
745
746 if (tid == LLDB_INVALID_THREAD_ID)
747 tid = curr_tid;
748
Michael Sartainc2052432013-08-01 18:51:08 +0000749 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000750 {
Michael Sartainc2052432013-08-01 18:51:08 +0000751 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
752 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
753
754 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000755 return true;
756 }
757 }
758 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000759#else
760 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000761#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000762}
763
Ed Maste02983be2013-07-25 19:10:32 +0000764bool
765Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
766 const char *thread_name, size_t len)
767{
768 char *namebuf = (char *)::malloc (len + 1);
769
770 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
771 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
772 // off leads to a lot of similar named threads. Go through the thread name
773 // and search for the last dot and use that.
774 const char *lastdot = ::strrchr (thread_name, '.');
775
776 if (lastdot && lastdot != thread_name)
777 thread_name = lastdot + 1;
778 ::strncpy (namebuf, thread_name, len);
779 namebuf[len] = 0;
780
781 int namebuflen = strlen(namebuf);
782 if (namebuflen > 0)
783 {
784 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
785 {
786 // Trim off trailing '(' and '>' characters for a bit more cleanup.
787 namebuflen--;
788 namebuf[namebuflen] = 0;
789 }
790 return Host::SetThreadName (pid, tid, namebuf);
791 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000792
793 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000794 return false;
795}
796
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000797#endif
798
Greg Clayton2bddd342010-09-07 20:11:56 +0000799FileSpec
800Host::GetProgramFileSpec ()
801{
802 static FileSpec g_program_filespec;
803 if (!g_program_filespec)
804 {
805#if defined (__APPLE__)
806 char program_fullpath[PATH_MAX];
807 // If DST is NULL, then return the number of bytes needed.
808 uint32_t len = sizeof(program_fullpath);
809 int err = _NSGetExecutablePath (program_fullpath, &len);
810 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000811 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000812 else if (err == -1)
813 {
814 char *large_program_fullpath = (char *)::malloc (len + 1);
815
816 err = _NSGetExecutablePath (large_program_fullpath, &len);
817 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000818 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000819
820 ::free (large_program_fullpath);
821 }
822#elif defined (__linux__)
823 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000824 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
825 if (len > 0) {
826 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000827 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000828 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000829#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000830 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
831 size_t exe_path_size;
832 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
833 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000834 char *exe_path = new char[exe_path_size];
835 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
836 g_program_filespec.SetFile(exe_path, false);
837 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000838 }
839#endif
840 }
841 return g_program_filespec;
842}
843
Greg Clayton2bddd342010-09-07 20:11:56 +0000844#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000845
846bool
847Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
848{
849 bundle.Clear();
850 return false;
851}
852
Greg Clayton2bddd342010-09-07 20:11:56 +0000853bool
Greg Claytondd36def2010-10-17 22:03:32 +0000854Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000855{
Greg Claytondd36def2010-10-17 22:03:32 +0000856 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000857}
858#endif
859
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000860#ifndef _WIN32
861
Greg Clayton45319462011-02-08 00:35:34 +0000862// Opaque info that tracks a dynamic library that was loaded
863struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000864{
Greg Clayton45319462011-02-08 00:35:34 +0000865 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
866 file_spec (fs),
867 open_options (o),
868 handle (h)
869 {
870 }
871
872 const FileSpec file_spec;
873 uint32_t open_options;
874 void * handle;
875};
876
877void *
878Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
879{
Greg Clayton4272cc72011-02-02 02:24:04 +0000880 char path[PATH_MAX];
881 if (file_spec.GetPath(path, sizeof(path)))
882 {
Greg Clayton45319462011-02-08 00:35:34 +0000883 int mode = 0;
884
885 if (options & eDynamicLibraryOpenOptionLazy)
886 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000887 else
888 mode |= RTLD_NOW;
889
Greg Clayton45319462011-02-08 00:35:34 +0000890
891 if (options & eDynamicLibraryOpenOptionLocal)
892 mode |= RTLD_LOCAL;
893 else
894 mode |= RTLD_GLOBAL;
895
896#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
897 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
898 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000899#endif
Greg Clayton45319462011-02-08 00:35:34 +0000900
901 void * opaque = ::dlopen (path, mode);
902
903 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000904 {
905 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000906 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000907 }
908 else
909 {
910 error.SetErrorString(::dlerror());
911 }
912 }
913 else
914 {
915 error.SetErrorString("failed to extract path");
916 }
Greg Clayton45319462011-02-08 00:35:34 +0000917 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000918}
919
920Error
Greg Clayton45319462011-02-08 00:35:34 +0000921Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000922{
923 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000924 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000925 {
926 error.SetErrorString ("invalid dynamic library handle");
927 }
Greg Clayton45319462011-02-08 00:35:34 +0000928 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000929 {
Greg Clayton45319462011-02-08 00:35:34 +0000930 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
931 if (::dlclose (dylib_info->handle) != 0)
932 {
933 error.SetErrorString(::dlerror());
934 }
935
936 dylib_info->open_options = 0;
937 dylib_info->handle = 0;
938 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000939 }
940 return error;
941}
942
943void *
Greg Clayton45319462011-02-08 00:35:34 +0000944Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000945{
Greg Clayton45319462011-02-08 00:35:34 +0000946 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000947 {
948 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000949 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000950 else
Greg Clayton45319462011-02-08 00:35:34 +0000951 {
952 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
953
954 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
955 if (symbol_addr)
956 {
957#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
958 // This host doesn't support limiting searches to this shared library
959 // so we need to verify that the match came from this shared library
960 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000961 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000962 {
963 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
964 if (match_dylib_spec != dylib_info->file_spec)
965 {
966 char dylib_path[PATH_MAX];
967 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
968 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
969 else
970 error.SetErrorString ("symbol not found");
971 return NULL;
972 }
973 }
974#endif
975 error.Clear();
976 return symbol_addr;
977 }
978 else
979 {
980 error.SetErrorString(::dlerror());
981 }
982 }
983 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000984}
Greg Claytondd36def2010-10-17 22:03:32 +0000985
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000986FileSpec
987Host::GetModuleFileSpecForHostAddress (const void *host_addr)
988{
989 FileSpec module_filespec;
990 Dl_info info;
991 if (::dladdr (host_addr, &info))
992 {
993 if (info.dli_fname)
994 module_filespec.SetFile(info.dli_fname, true);
995 }
996 return module_filespec;
997}
998
999#endif
1000
Greg Claytondd36def2010-10-17 22:03:32 +00001001bool
1002Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1003{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001004 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001005 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1006 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001007 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001008 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001009 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001010
1011 switch (path_type)
1012 {
1013 case ePathTypeLLDBShlibDir:
1014 {
1015 static ConstString g_lldb_so_dir;
1016 if (!g_lldb_so_dir)
1017 {
1018 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
1019 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001020 if (log)
1021 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001022 }
1023 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001024 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001025 }
1026 break;
1027
1028 case ePathTypeSupportExecutableDir:
1029 {
1030 static ConstString g_lldb_support_exe_dir;
1031 if (!g_lldb_support_exe_dir)
1032 {
1033 FileSpec lldb_file_spec;
1034 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1035 {
1036 char raw_path[PATH_MAX];
1037 char resolved_path[PATH_MAX];
1038 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1039
1040#if defined (__APPLE__)
1041 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1042 if (framework_pos)
1043 {
1044 framework_pos += strlen("LLDB.framework");
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001045#if defined (__arm__)
1046 // Shallow bundle
1047 *framework_pos = '\0';
1048#else
1049 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001050 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001051#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001052 }
1053#endif
1054 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1055 g_lldb_support_exe_dir.SetCString(resolved_path);
1056 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001057 if (log)
1058 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001059 }
1060 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001061 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001062 }
1063 break;
1064
1065 case ePathTypeHeaderDir:
1066 {
1067 static ConstString g_lldb_headers_dir;
1068 if (!g_lldb_headers_dir)
1069 {
1070#if defined (__APPLE__)
1071 FileSpec lldb_file_spec;
1072 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1073 {
1074 char raw_path[PATH_MAX];
1075 char resolved_path[PATH_MAX];
1076 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1077
1078 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1079 if (framework_pos)
1080 {
1081 framework_pos += strlen("LLDB.framework");
1082 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1083 }
1084 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1085 g_lldb_headers_dir.SetCString(resolved_path);
1086 }
1087#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001088 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001089 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1090#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001091 if (log)
1092 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001093 }
1094 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001095 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001096 }
1097 break;
1098
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001099#ifdef LLDB_DISABLE_PYTHON
1100 case ePathTypePythonDir:
1101 return false;
1102#else
1103 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001104 {
Greg Claytondd36def2010-10-17 22:03:32 +00001105 static ConstString g_lldb_python_dir;
1106 if (!g_lldb_python_dir)
1107 {
1108 FileSpec lldb_file_spec;
1109 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1110 {
1111 char raw_path[PATH_MAX];
1112 char resolved_path[PATH_MAX];
1113 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1114
1115#if defined (__APPLE__)
1116 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1117 if (framework_pos)
1118 {
1119 framework_pos += strlen("LLDB.framework");
1120 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1121 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001122#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001123 llvm::SmallString<256> python_version_dir;
1124 llvm::raw_svector_ostream os(python_version_dir);
1125 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1126 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001127
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001128 // We may get our string truncated. Should we protect
1129 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001130
Daniel Maleafa7425d2013-08-06 21:40:08 +00001131 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001132 sizeof(raw_path) - strlen(raw_path) - 1);
1133
Greg Claytondd36def2010-10-17 22:03:32 +00001134#endif
1135 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1136 g_lldb_python_dir.SetCString(resolved_path);
1137 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001138
1139 if (log)
1140 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1141
Greg Claytondd36def2010-10-17 22:03:32 +00001142 }
1143 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001144 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001145 }
1146 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001147#endif
1148
Greg Clayton4272cc72011-02-02 02:24:04 +00001149 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1150 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001151#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001152 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001153 static bool g_lldb_system_plugin_dir_located = false;
1154 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001155 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001156 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001157#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001158 FileSpec lldb_file_spec;
1159 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1160 {
1161 char raw_path[PATH_MAX];
1162 char resolved_path[PATH_MAX];
1163 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1164
1165 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1166 if (framework_pos)
1167 {
1168 framework_pos += strlen("LLDB.framework");
1169 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001170 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1171 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001172 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001173 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001174 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001175#elif defined (__linux__)
1176 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1177 if (lldb_file_spec.Exists())
1178 {
1179 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1180 }
1181#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001182
1183 if (log)
1184 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1185
Greg Clayton4272cc72011-02-02 02:24:04 +00001186 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001187
1188 if (g_lldb_system_plugin_dir)
1189 {
1190 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1191 return true;
1192 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001193#else
1194 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001195 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001196#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001197 }
1198 break;
1199
1200 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1201 {
1202#if defined (__APPLE__)
1203 static ConstString g_lldb_user_plugin_dir;
1204 if (!g_lldb_user_plugin_dir)
1205 {
1206 char user_plugin_path[PATH_MAX];
1207 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1208 user_plugin_path,
1209 sizeof(user_plugin_path)))
1210 {
1211 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1212 }
1213 }
1214 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001215 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001216#elif defined (__linux__)
1217 static ConstString g_lldb_user_plugin_dir;
1218 if (!g_lldb_user_plugin_dir)
1219 {
1220 // XDG Base Directory Specification
1221 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1222 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1223 FileSpec lldb_file_spec;
1224 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1225 if (xdg_data_home && xdg_data_home[0])
1226 {
1227 std::string user_plugin_dir (xdg_data_home);
1228 user_plugin_dir += "/lldb";
1229 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1230 }
1231 else
1232 {
1233 const char *home_dir = getenv("HOME");
1234 if (home_dir && home_dir[0])
1235 {
1236 std::string user_plugin_dir (home_dir);
1237 user_plugin_dir += "/.local/share/lldb";
1238 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1239 }
1240 }
1241
1242 if (lldb_file_spec.Exists())
1243 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001244 if (log)
1245 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001246 }
1247 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001248 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001249#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001250 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001251 return false;
1252 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001253
1254 case ePathTypeLLDBTempSystemDir:
1255 {
1256 static ConstString g_lldb_tmp_dir;
1257 if (!g_lldb_tmp_dir)
1258 {
1259 const char *tmpdir_cstr = getenv("TMPDIR");
1260 if (tmpdir_cstr == NULL)
1261 {
1262 tmpdir_cstr = getenv("TMP");
1263 if (tmpdir_cstr == NULL)
1264 tmpdir_cstr = getenv("TEMP");
1265 }
1266 if (tmpdir_cstr)
1267 {
1268 g_lldb_tmp_dir.SetCString(tmpdir_cstr);
1269 if (log)
1270 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1271 }
1272 }
1273 file_spec.GetDirectory() = g_lldb_tmp_dir;
1274 return (bool)file_spec.GetDirectory();
1275 }
Greg Claytondd36def2010-10-17 22:03:32 +00001276 }
1277
1278 return false;
1279}
1280
Greg Clayton1cb64962011-03-24 04:28:38 +00001281
1282bool
1283Host::GetHostname (std::string &s)
1284{
1285 char hostname[PATH_MAX];
1286 hostname[sizeof(hostname) - 1] = '\0';
1287 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1288 {
1289 struct hostent* h = ::gethostbyname (hostname);
1290 if (h)
1291 s.assign (h->h_name);
1292 else
1293 s.assign (hostname);
1294 return true;
1295 }
1296 return false;
1297}
1298
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001299#ifndef _WIN32
1300
Greg Clayton32e0a752011-03-30 18:16:51 +00001301const char *
1302Host::GetUserName (uint32_t uid, std::string &user_name)
1303{
1304 struct passwd user_info;
1305 struct passwd *user_info_ptr = &user_info;
1306 char user_buffer[PATH_MAX];
1307 size_t user_buffer_size = sizeof(user_buffer);
1308 if (::getpwuid_r (uid,
1309 &user_info,
1310 user_buffer,
1311 user_buffer_size,
1312 &user_info_ptr) == 0)
1313 {
1314 if (user_info_ptr)
1315 {
1316 user_name.assign (user_info_ptr->pw_name);
1317 return user_name.c_str();
1318 }
1319 }
1320 user_name.clear();
1321 return NULL;
1322}
1323
1324const char *
1325Host::GetGroupName (uint32_t gid, std::string &group_name)
1326{
1327 char group_buffer[PATH_MAX];
1328 size_t group_buffer_size = sizeof(group_buffer);
1329 struct group group_info;
1330 struct group *group_info_ptr = &group_info;
1331 // Try the threadsafe version first
1332 if (::getgrgid_r (gid,
1333 &group_info,
1334 group_buffer,
1335 group_buffer_size,
1336 &group_info_ptr) == 0)
1337 {
1338 if (group_info_ptr)
1339 {
1340 group_name.assign (group_info_ptr->gr_name);
1341 return group_name.c_str();
1342 }
1343 }
1344 else
1345 {
1346 // The threadsafe version isn't currently working
1347 // for me on darwin, but the non-threadsafe version
1348 // is, so I am calling it below.
1349 group_info_ptr = ::getgrgid (gid);
1350 if (group_info_ptr)
1351 {
1352 group_name.assign (group_info_ptr->gr_name);
1353 return group_name.c_str();
1354 }
1355 }
1356 group_name.clear();
1357 return NULL;
1358}
1359
Han Ming Ong84647042012-02-25 01:07:38 +00001360uint32_t
1361Host::GetUserID ()
1362{
1363 return getuid();
1364}
1365
1366uint32_t
1367Host::GetGroupID ()
1368{
1369 return getgid();
1370}
1371
1372uint32_t
1373Host::GetEffectiveUserID ()
1374{
1375 return geteuid();
1376}
1377
1378uint32_t
1379Host::GetEffectiveGroupID ()
1380{
1381 return getegid();
1382}
1383
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001384#endif
1385
1386#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1387bool
1388Host::GetOSBuildString (std::string &s)
1389{
1390 s.clear();
1391 return false;
1392}
1393
1394bool
1395Host::GetOSKernelDescription (std::string &s)
1396{
1397 s.clear();
1398 return false;
1399}
1400#endif
1401
Ed Maste47e575e2013-08-29 18:44:27 +00001402#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001403uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001404Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001405{
1406 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001407 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001408}
1409
Greg Claytone996fd32011-03-08 22:40:15 +00001410bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001411Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001412{
Greg Claytone996fd32011-03-08 22:40:15 +00001413 process_info.Clear();
1414 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001415}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001416#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001417
Matt Kopec085d6ce2013-05-31 22:00:07 +00001418#if !defined(__linux__)
1419bool
1420Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1421{
1422 return false;
1423}
1424#endif
1425
Sean Callananc0a6e062011-10-27 21:22:25 +00001426lldb::TargetSP
1427Host::GetDummyTarget (lldb_private::Debugger &debugger)
1428{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001429 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001430
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001431 // FIXME: Maybe the dummy target should be per-Debugger
1432 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1433 {
1434 ArchSpec arch(Target::GetDefaultArchitecture());
1435 if (!arch.IsValid())
1436 arch = Host::GetArchitecture ();
1437 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001438 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001439 arch.GetTriple().getTriple().c_str(),
1440 false,
1441 NULL,
1442 g_dummy_target_sp);
1443 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001444
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001445 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001446}
1447
Greg Claytond1cf11a2012-04-14 01:42:46 +00001448struct ShellInfo
1449{
1450 ShellInfo () :
1451 process_reaped (false),
1452 can_delete (false),
1453 pid (LLDB_INVALID_PROCESS_ID),
1454 signo(-1),
1455 status(-1)
1456 {
1457 }
1458
1459 lldb_private::Predicate<bool> process_reaped;
1460 lldb_private::Predicate<bool> can_delete;
1461 lldb::pid_t pid;
1462 int signo;
1463 int status;
1464};
1465
1466static bool
1467MonitorShellCommand (void *callback_baton,
1468 lldb::pid_t pid,
1469 bool exited, // True if the process did exit
1470 int signo, // Zero for no signal
1471 int status) // Exit value of process if signal is zero
1472{
1473 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1474 shell_info->pid = pid;
1475 shell_info->signo = signo;
1476 shell_info->status = status;
1477 // Let the thread running Host::RunShellCommand() know that the process
1478 // exited and that ShellInfo has been filled in by broadcasting to it
1479 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1480 // Now wait for a handshake back from that thread running Host::RunShellCommand
1481 // so we know that we can delete shell_info_ptr
1482 shell_info->can_delete.WaitForValueEqualTo(true);
1483 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1484 usleep(1000);
1485 // Now delete the shell info that was passed into this function
1486 delete shell_info;
1487 return true;
1488}
1489
1490Error
1491Host::RunShellCommand (const char *command,
1492 const char *working_dir,
1493 int *status_ptr,
1494 int *signo_ptr,
1495 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001496 uint32_t timeout_sec,
1497 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001498{
1499 Error error;
1500 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001501 if (shell && shell[0])
1502 {
1503 // Run the command in a shell
1504 launch_info.SetShell(shell);
1505 launch_info.GetArguments().AppendArgument(command);
1506 const bool localhost = true;
1507 const bool will_debug = false;
1508 const bool first_arg_is_full_shell_command = true;
1509 launch_info.ConvertArgumentsForLaunchingInShell (error,
1510 localhost,
1511 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001512 first_arg_is_full_shell_command,
1513 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001514 }
1515 else
1516 {
1517 // No shell, just run it
1518 Args args (command);
1519 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001520 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001521 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001522
1523 if (working_dir)
1524 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001525 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001526 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001527
Greg Claytond1cf11a2012-04-14 01:42:46 +00001528 if (command_output_ptr)
1529 {
1530 // Create a temporary file to get the stdout/stderr and redirect the
1531 // output of the command into this file. We will later read this file
1532 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001533 FileSpec tmpdir_file_spec;
1534 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1535 {
1536 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1537 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1538 }
1539 else
1540 {
1541 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1542 }
1543
1544 output_file_path = ::mktemp(output_file_path_buffer);
1545 }
1546
1547 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1548 if (output_file_path)
1549 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001550 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001551 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001552 }
1553 else
1554 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001555 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1556 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1557 }
1558
1559 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001560 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001561
1562 const bool monitor_signals = false;
1563 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1564
1565 error = LaunchProcess (launch_info);
1566 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001567
1568 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1569 error.SetErrorString("failed to get process ID");
1570
1571 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001572 {
1573 // The process successfully launched, so we can defer ownership of
1574 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001575 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001576 // doesn't need to delete the ShellInfo anymore.
1577 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001578 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001579 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001580 if (timeout_sec > 0) {
1581 timeout_time.OffsetWithSeconds(timeout_sec);
1582 timeout_ptr = &timeout_time;
1583 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001584 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001585 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001586 if (timed_out)
1587 {
1588 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001589
Greg Claytond1cf11a2012-04-14 01:42:46 +00001590 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001591 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001592 // Wait for the monitor callback to get the message
1593 timeout_time = TimeValue::Now();
1594 timeout_time.OffsetWithSeconds(1);
1595 timed_out = false;
1596 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1597 }
1598 else
1599 {
1600 if (status_ptr)
1601 *status_ptr = shell_info->status;
1602
1603 if (signo_ptr)
1604 *signo_ptr = shell_info->signo;
1605
1606 if (command_output_ptr)
1607 {
1608 command_output_ptr->clear();
1609 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1610 uint64_t file_size = file_spec.GetByteSize();
1611 if (file_size > 0)
1612 {
1613 if (file_size > command_output_ptr->max_size())
1614 {
1615 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1616 }
1617 else
1618 {
1619 command_output_ptr->resize(file_size);
1620 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1621 }
1622 }
1623 }
1624 }
1625 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1626 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001627
1628 if (output_file_path)
1629 ::unlink (output_file_path);
1630 // Handshake with the monitor thread, or just let it know in advance that
1631 // it can delete "shell_info" in case we timed out and were not able to kill
1632 // the process...
1633 return error;
1634}
1635
Ed Maste991fe6c2013-12-09 01:35:42 +00001636#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001637// The functions below implement process launching via posix_spawn() for Linux
1638// and FreeBSD.
1639
1640// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1641static Error
1642LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1643{
1644 Error error;
1645 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1646
1647 assert(exe_path);
1648 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1649
1650 posix_spawnattr_t attr;
1651
1652 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1653 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1654 if (error.Fail())
1655 return error;
1656
1657 // Make a quick class that will cleanup the posix spawn attributes in case
1658 // we return in the middle of this function.
1659 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1660
1661 sigset_t no_signals;
1662 sigset_t all_signals;
1663 sigemptyset (&no_signals);
1664 sigfillset (&all_signals);
1665 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1666 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1667
1668 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1669
1670 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1671 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1672 if (error.Fail())
1673 return error;
1674
1675 const size_t num_file_actions = launch_info.GetNumFileActions ();
1676 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1677 // Make a quick class that will cleanup the posix spawn attributes in case
1678 // we return in the middle of this function.
1679 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1680 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1681
1682 if (num_file_actions > 0)
1683 {
1684 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1685 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1686 if (error.Fail())
1687 return error;
1688
1689 file_action_ptr = &file_actions;
1690 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1691
1692 for (size_t i = 0; i < num_file_actions; ++i)
1693 {
1694 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1695 if (launch_file_action &&
1696 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1697 launch_file_action,
1698 log,
1699 error))
1700 return error;
1701 }
1702 }
1703
1704 // Change working directory if neccessary.
1705 char current_dir[PATH_MAX];
1706 current_dir[0] = '\0';
1707
1708 const char *working_dir = launch_info.GetWorkingDirectory();
1709 if (working_dir != NULL)
1710 {
1711 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1712 {
1713 error.SetError(errno, eErrorTypePOSIX);
1714 error.LogIfError(log, "unable to save the current directory");
1715 return error;
1716 }
1717
1718 if (::chdir(working_dir) == -1)
1719 {
1720 error.SetError(errno, eErrorTypePOSIX);
1721 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1722 return error;
1723 }
1724 }
1725
1726 const char *tmp_argv[2];
1727 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1728 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1729
1730 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1731 // We must pass argv into posix_spawnp and it must contain at least two items -
1732 // pointer to an executable and NULL.
1733 if (argv == NULL)
1734 {
1735 tmp_argv[0] = exe_path;
1736 tmp_argv[1] = NULL;
1737 argv = (char * const*)tmp_argv;
1738 }
1739
1740 error.SetError (::posix_spawnp (&pid,
1741 exe_path,
1742 (num_file_actions > 0) ? &file_actions : NULL,
1743 &attr,
1744 argv,
1745 envp),
1746 eErrorTypePOSIX);
1747
1748 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1749 pid, exe_path, file_action_ptr, &attr, argv, envp);
1750
1751 // Change back the current directory.
1752 // NOTE: do not override previously established error from posix_spawnp.
1753 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1754 {
1755 error.SetError(errno, eErrorTypePOSIX);
1756 error.LogIfError(log, "unable to change current directory back to %s",
1757 current_dir);
1758 }
1759
1760 return error;
1761}
1762
1763
1764Error
1765Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1766{
1767 Error error;
1768 char exe_path[PATH_MAX];
1769
1770 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1771
1772 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1773
1774 FileSpec exe_spec(launch_info.GetExecutableFile());
1775
1776 FileSpec::FileType file_type = exe_spec.GetFileType();
1777 if (file_type != FileSpec::eFileTypeRegular)
1778 {
1779 lldb::ModuleSP exe_module_sp;
1780 error = host_platform_sp->ResolveExecutable (exe_spec,
1781 arch_spec,
1782 exe_module_sp,
1783 NULL);
1784
1785 if (error.Fail())
1786 return error;
1787
1788 if (exe_module_sp)
1789 exe_spec = exe_module_sp->GetFileSpec();
1790 }
1791
1792 if (exe_spec.Exists())
1793 {
1794 exe_spec.GetPath (exe_path, sizeof(exe_path));
1795 }
1796 else
1797 {
1798 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1799 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1800 return error;
1801 }
1802
1803 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1804
1805 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1806
1807 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1808
1809 if (pid != LLDB_INVALID_PROCESS_ID)
1810 {
1811 // If all went well, then set the process ID into the launch info
1812 launch_info.SetProcessID(pid);
1813
1814 // Make sure we reap any processes we spawn or we will have zombies.
1815 if (!launch_info.MonitorProcess())
1816 {
1817 const bool monitor_signals = false;
1818 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1819 NULL,
1820 pid,
1821 monitor_signals);
1822 }
1823 }
1824 else
1825 {
1826 // Invalid process ID, something didn't go well
1827 if (error.Success())
1828 error.SetErrorString ("process launch failed for unknown reasons");
1829 }
1830 return error;
1831}
1832
1833#endif // defined(__linux__) or defined(__FreeBSD__)
1834
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001835#ifndef _WIN32
1836
1837size_t
1838Host::GetPageSize()
1839{
1840 return ::getpagesize();
1841}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001842
Greg Claytone3e3fee2013-02-17 20:46:30 +00001843uint32_t
1844Host::GetNumberCPUS ()
1845{
1846 static uint32_t g_num_cores = UINT32_MAX;
1847 if (g_num_cores == UINT32_MAX)
1848 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001849#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001850
1851 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001852
Greg Claytone3e3fee2013-02-17 20:46:30 +00001853#else
1854
1855 // Assume POSIX support if a host specific case has not been supplied above
1856 g_num_cores = 0;
1857 int num_cores = 0;
1858 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001859#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001860 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001861#else
1862 int mib[] = { CTL_HW, HW_NCPU };
1863#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001864
1865 /* get the number of CPUs from the system */
1866 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1867 {
1868 g_num_cores = num_cores;
1869 }
1870 else
1871 {
1872 mib[1] = HW_NCPU;
1873 num_cores_len = sizeof(num_cores);
1874 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1875 {
1876 if (num_cores > 0)
1877 g_num_cores = num_cores;
1878 }
1879 }
1880#endif
1881 }
1882 return g_num_cores;
1883}
1884
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001885void
1886Host::Kill(lldb::pid_t pid, int signo)
1887{
1888 ::kill(pid, signo);
1889}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001890
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001891#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001892
Johnny Chen8f3d8382011-08-02 20:52:42 +00001893#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001894bool
Greg Clayton3b147632010-12-18 01:54:34 +00001895Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001896{
1897 return false;
1898}
Greg Claytondd36def2010-10-17 22:03:32 +00001899
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001900void
1901Host::SetCrashDescriptionWithFormat (const char *format, ...)
1902{
1903}
1904
1905void
1906Host::SetCrashDescription (const char *description)
1907{
1908}
Greg Claytondd36def2010-10-17 22:03:32 +00001909
1910lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001911Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001912{
1913 return LLDB_INVALID_PROCESS_ID;
1914}
1915
Greg Claytonfbb76342013-11-20 21:07:01 +00001916#endif
1917
1918
1919#ifdef LLDB_DISABLE_POSIX
1920
1921Error
1922Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001923{
Greg Claytonfbb76342013-11-20 21:07:01 +00001924 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001925 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001926 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001927}
Greg Claytonfbb76342013-11-20 21:07:01 +00001928
1929Error
1930Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1931{
1932 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001933 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001934 return error;
1935}
1936
1937Error
1938Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1939{
1940 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001941 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001942 return error;
1943}
1944
1945Error
1946Host::Symlink (const char *src, const char *dst)
1947{
1948 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001949 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001950 return error;
1951}
1952
1953Error
1954Host::Readlink (const char *path, char *buf, size_t buf_len)
1955{
1956 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001957 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001958 return error;
1959}
1960
1961Error
1962Host::Unlink (const char *path)
1963{
1964 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001965 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001966 return error;
1967}
1968
1969#else
1970
1971Error
1972Host::MakeDirectory (const char* path, uint32_t file_permissions)
1973{
1974 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00001975 if (path && path[0])
1976 {
Greg Claytonfb909312013-11-23 01:58:15 +00001977 if (::mkdir(path, file_permissions) != 0)
1978 {
1979 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001980 switch (error.GetError())
1981 {
1982 case ENOENT:
1983 {
1984 // Parent directory doesn't exist, so lets make it if we can
1985 FileSpec spec(path, false);
1986 if (spec.GetDirectory() && spec.GetFilename())
1987 {
1988 // Make the parent directory and try again
1989 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
1990 if (error2.Success())
1991 {
1992 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00001993 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00001994 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00001995 else
Greg Claytonfb909312013-11-23 01:58:15 +00001996 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001997 }
1998 }
1999 }
2000 break;
2001 case EEXIST:
2002 {
2003 FileSpec path_spec(path, false);
2004 if (path_spec.IsDirectory())
2005 error.Clear(); // It is a directory and it already exists
2006 }
2007 break;
2008 }
2009 }
Greg Claytonfb909312013-11-23 01:58:15 +00002010 }
2011 else
2012 {
2013 error.SetErrorString("empty path");
2014 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002015 return error;
2016}
2017
2018Error
2019Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2020{
2021 Error error;
2022 struct stat file_stats;
2023 if (::stat (path, &file_stats) == 0)
2024 {
2025 // The bits in "st_mode" currently match the definitions
2026 // for the file mode bits in unix.
2027 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2028 }
2029 else
2030 {
2031 error.SetErrorToErrno();
2032 }
2033 return error;
2034}
2035
2036Error
2037Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2038{
2039 Error error;
2040 if (::chmod(path, file_permissions) != 0)
2041 error.SetErrorToErrno();
2042 return error;
2043}
2044
2045Error
2046Host::Symlink (const char *src, const char *dst)
2047{
2048 Error error;
2049 if (::symlink(dst, src) == -1)
2050 error.SetErrorToErrno();
2051 return error;
2052}
2053
2054Error
2055Host::Unlink (const char *path)
2056{
2057 Error error;
2058 if (::unlink(path) == -1)
2059 error.SetErrorToErrno();
2060 return error;
2061}
2062
2063Error
2064Host::Readlink (const char *path, char *buf, size_t buf_len)
2065{
2066 Error error;
2067 ssize_t count = ::readlink(path, buf, buf_len);
2068 if (count < 0)
2069 error.SetErrorToErrno();
2070 else if (count < (buf_len-1))
2071 buf[count] = '\0'; // Success
2072 else
2073 error.SetErrorString("'buf' buffer is too small to contain link contents");
2074 return error;
2075}
2076
2077
Greg Clayton2bddd342010-09-07 20:11:56 +00002078#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002079
2080typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2081FDToFileMap& GetFDToFileMap()
2082{
2083 static FDToFileMap g_fd2filemap;
2084 return g_fd2filemap;
2085}
2086
2087lldb::user_id_t
2088Host::OpenFile (const FileSpec& file_spec,
2089 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002090 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002091 Error &error)
2092{
2093 std::string path (file_spec.GetPath());
2094 if (path.empty())
2095 {
2096 error.SetErrorString("empty path");
2097 return UINT64_MAX;
2098 }
2099 FileSP file_sp(new File());
2100 error = file_sp->Open(path.c_str(),flags,mode);
2101 if (file_sp->IsValid() == false)
2102 return UINT64_MAX;
2103 lldb::user_id_t fd = file_sp->GetDescriptor();
2104 GetFDToFileMap()[fd] = file_sp;
2105 return fd;
2106}
2107
2108bool
2109Host::CloseFile (lldb::user_id_t fd, Error &error)
2110{
2111 if (fd == UINT64_MAX)
2112 {
2113 error.SetErrorString ("invalid file descriptor");
2114 return false;
2115 }
2116 FDToFileMap& file_map = GetFDToFileMap();
2117 FDToFileMap::iterator pos = file_map.find(fd);
2118 if (pos == file_map.end())
2119 {
2120 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2121 return false;
2122 }
2123 FileSP file_sp = pos->second;
2124 if (!file_sp)
2125 {
2126 error.SetErrorString ("invalid host backing file");
2127 return false;
2128 }
2129 error = file_sp->Close();
2130 file_map.erase(pos);
2131 return error.Success();
2132}
2133
2134uint64_t
2135Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2136{
2137 if (fd == UINT64_MAX)
2138 {
2139 error.SetErrorString ("invalid file descriptor");
2140 return UINT64_MAX;
2141 }
2142 FDToFileMap& file_map = GetFDToFileMap();
2143 FDToFileMap::iterator pos = file_map.find(fd);
2144 if (pos == file_map.end())
2145 {
2146 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2147 return false;
2148 }
2149 FileSP file_sp = pos->second;
2150 if (!file_sp)
2151 {
2152 error.SetErrorString ("invalid host backing file");
2153 return UINT64_MAX;
2154 }
2155 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2156 return UINT64_MAX;
2157 size_t bytes_written = src_len;
2158 error = file_sp->Write(src, bytes_written);
2159 if (error.Fail())
2160 return UINT64_MAX;
2161 return bytes_written;
2162}
2163
2164uint64_t
2165Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2166{
2167 if (fd == UINT64_MAX)
2168 {
2169 error.SetErrorString ("invalid file descriptor");
2170 return UINT64_MAX;
2171 }
2172 FDToFileMap& file_map = GetFDToFileMap();
2173 FDToFileMap::iterator pos = file_map.find(fd);
2174 if (pos == file_map.end())
2175 {
2176 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2177 return false;
2178 }
2179 FileSP file_sp = pos->second;
2180 if (!file_sp)
2181 {
2182 error.SetErrorString ("invalid host backing file");
2183 return UINT64_MAX;
2184 }
2185 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2186 return UINT64_MAX;
2187 size_t bytes_read = dst_len;
2188 error = file_sp->Read(dst ,bytes_read);
2189 if (error.Fail())
2190 return UINT64_MAX;
2191 return bytes_read;
2192}
2193
2194lldb::user_id_t
2195Host::GetFileSize (const FileSpec& file_spec)
2196{
2197 return file_spec.GetByteSize();
2198}
2199
2200bool
2201Host::GetFileExists (const FileSpec& file_spec)
2202{
2203 return file_spec.Exists();
2204}
2205
2206bool
2207Host::CalculateMD5 (const FileSpec& file_spec,
2208 uint64_t &low,
2209 uint64_t &high)
2210{
2211#if defined (__APPLE__)
2212 StreamString md5_cmd_line;
2213 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2214 std::string hash_string;
2215 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2216 if (err.Fail())
2217 return false;
2218 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2219 // if the output is any other length it is probably wrong
2220 if (hash_string.size() != 32)
2221 return false;
2222 std::string part1(hash_string,0,16);
2223 std::string part2(hash_string,16);
2224 const char* part1_cstr = part1.c_str();
2225 const char* part2_cstr = part2.c_str();
2226 high = ::strtoull(part1_cstr, NULL, 16);
2227 low = ::strtoull(part2_cstr, NULL, 16);
2228 return true;
2229#else
2230 // your own MD5 implementation here
2231 return false;
2232#endif
2233}