blob: 1dc4b9e472c81c3501af781f648e765bf7c1f744 [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>
Greg Claytonc6931fc2013-12-04 18:53:50 +000016#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000017#ifdef _WIN32
18#include "lldb/Host/windows/windows.h"
19#include <winsock2.h>
20#include <WS2tcpip.h>
21#else
22#include <dlfcn.h>
23#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000024#include <netdb.h>
25#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000026#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000027#endif
28
29#if !defined (__GNU__) && !defined (_WIN32)
30// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000031#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000032#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000033
34#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000035#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000036#include <mach/mach_init.h>
37#include <mach-o/dyld.h>
Jim Ingham1a7ee702013-11-22 00:51:36 +000038#include <AvailabilityMacros.h>
Ed Maste8b006c62013-06-25 18:58:11 +000039#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000040
Ed Maste8b006c62013-06-25 18:58:11 +000041#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000042#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000043#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000044#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000045#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000046
Ed Maste8b006c62013-06-25 18:58:11 +000047#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000048#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#endif
50
Greg Clayton2bddd342010-09-07 20:11:56 +000051#include "lldb/Host/Host.h"
52#include "lldb/Core/ArchSpec.h"
53#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000054#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000055#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000057#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000059#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000060#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000061#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000062#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000064#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000065#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000066#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000067
Daniel Maleafa7425d2013-08-06 21:40:08 +000068#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000069#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000070#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000071
Greg Clayton32e0a752011-03-30 18:16:51 +000072
Greg Clayton2bddd342010-09-07 20:11:56 +000073using namespace lldb;
74using namespace lldb_private;
75
Greg Claytone4e45922011-11-16 05:37:56 +000076
Virgile Bellob2f1fb22013-08-23 12:44:05 +000077#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000078struct MonitorInfo
79{
80 lldb::pid_t pid; // The process ID to monitor
81 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
82 void *callback_baton; // The callback baton for the callback function
83 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
84};
85
Virgile Bellob2f1fb22013-08-23 12:44:05 +000086static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000087MonitorChildProcessThreadFunction (void *arg);
88
89lldb::thread_t
90Host::StartMonitoringChildProcess
91(
92 Host::MonitorChildProcessCallback callback,
93 void *callback_baton,
94 lldb::pid_t pid,
95 bool monitor_signals
96)
97{
98 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +000099 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000100
Greg Claytone4e45922011-11-16 05:37:56 +0000101 info_ptr->pid = pid;
102 info_ptr->callback = callback;
103 info_ptr->callback_baton = callback_baton;
104 info_ptr->monitor_signals = monitor_signals;
105
106 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000107 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000108 thread = ThreadCreate (thread_name,
109 MonitorChildProcessThreadFunction,
110 info_ptr,
111 NULL);
112
Greg Clayton2bddd342010-09-07 20:11:56 +0000113 return thread;
114}
115
116//------------------------------------------------------------------
117// Scoped class that will disable thread canceling when it is
118// constructed, and exception safely restore the previous value it
119// when it goes out of scope.
120//------------------------------------------------------------------
121class ScopedPThreadCancelDisabler
122{
123public:
124 ScopedPThreadCancelDisabler()
125 {
126 // Disable the ability for this thread to be cancelled
127 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
128 if (err != 0)
129 m_old_state = -1;
130
131 }
132
133 ~ScopedPThreadCancelDisabler()
134 {
135 // Restore the ability for this thread to be cancelled to what it
136 // previously was.
137 if (m_old_state != -1)
138 ::pthread_setcancelstate (m_old_state, 0);
139 }
140private:
141 int m_old_state; // Save the old cancelability state.
142};
143
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000144static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000145MonitorChildProcessThreadFunction (void *arg)
146{
Greg Clayton5160ce52013-03-27 23:08:40 +0000147 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000148 const char *function = __FUNCTION__;
149 if (log)
150 log->Printf ("%s (arg = %p) thread starting...", function, arg);
151
152 MonitorInfo *info = (MonitorInfo *)arg;
153
154 const Host::MonitorChildProcessCallback callback = info->callback;
155 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000156 const bool monitor_signals = info->monitor_signals;
157
Daniel Malea4244cbd2013-08-27 20:58:59 +0000158 assert (info->pid <= UINT32_MAX);
159 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
160
Greg Clayton2bddd342010-09-07 20:11:56 +0000161 delete info;
162
163 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000164#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000165 #define __WALL 0
166#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000167 const int options = __WALL;
168
Greg Clayton2bddd342010-09-07 20:11:56 +0000169 while (1)
170 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000171 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000172 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000173 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000174
175 // Wait for all child processes
176 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000177 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000178 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000179 ::pthread_testcancel ();
180
181 if (wait_pid == -1)
182 {
183 if (errno == EINTR)
184 continue;
185 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000186 {
187 if (log)
188 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000189 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000190 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000191 }
Matt Kopec650648f2013-01-08 16:30:18 +0000192 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000193 {
194 bool exited = false;
195 int signal = 0;
196 int exit_status = 0;
197 const char *status_cstr = NULL;
198 if (WIFSTOPPED(status))
199 {
200 signal = WSTOPSIG(status);
201 status_cstr = "STOPPED";
202 }
203 else if (WIFEXITED(status))
204 {
205 exit_status = WEXITSTATUS(status);
206 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000207 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000208 }
209 else if (WIFSIGNALED(status))
210 {
211 signal = WTERMSIG(status);
212 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000213 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000214 exited = true;
215 exit_status = -1;
216 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000217 }
218 else
219 {
Johnny Chen44805302011-07-19 19:48:13 +0000220 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000221 }
222
223 // Scope for pthread_cancel_disabler
224 {
225 ScopedPThreadCancelDisabler pthread_cancel_disabler;
226
Caroline Tice20ad3c42010-10-29 21:48:37 +0000227 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000228 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000229 log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Greg Clayton2bddd342010-09-07 20:11:56 +0000230 function,
231 wait_pid,
232 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000233 pid,
234 status,
235 status_cstr,
236 signal,
237 exit_status);
238
239 if (exited || (signal != 0 && monitor_signals))
240 {
Greg Claytone4e45922011-11-16 05:37:56 +0000241 bool callback_return = false;
242 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000243 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000244
245 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000246 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000247 {
248 if (log)
249 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000250 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000251 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000252 // If the callback returns true, it means this process should
253 // exit
254 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000255 {
256 if (log)
257 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000259 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000260 }
261 }
262 }
263 }
264
Caroline Tice20ad3c42010-10-29 21:48:37 +0000265 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000266 if (log)
267 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
268
269 return NULL;
270}
271
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000272#endif // #if !defined (__APPLE__) && !defined (_WIN32)
273
274#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000275
276void
277Host::SystemLog (SystemLogType type, const char *format, va_list args)
278{
279 vfprintf (stderr, format, args);
280}
281
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000282#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000283
Greg Claytone38a5ed2012-01-05 03:57:59 +0000284void
285Host::SystemLog (SystemLogType type, const char *format, ...)
286{
287 va_list args;
288 va_start (args, format);
289 SystemLog (type, format, args);
290 va_end (args);
291}
292
Greg Clayton2bddd342010-09-07 20:11:56 +0000293const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000294Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000295{
Greg Clayton514487e2011-02-15 21:59:32 +0000296 static bool g_supports_32 = false;
297 static bool g_supports_64 = false;
298 static ArchSpec g_host_arch_32;
299 static ArchSpec g_host_arch_64;
300
Greg Clayton2bddd342010-09-07 20:11:56 +0000301#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000302
303 // Apple is different in that it can support both 32 and 64 bit executables
304 // in the same operating system running concurrently. Here we detect the
305 // correct host architectures for both 32 and 64 bit including if 64 bit
306 // executables are supported on the system.
307
308 if (g_supports_32 == false && g_supports_64 == false)
309 {
310 // All apple systems support 32 bit execution.
311 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000312 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000313 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000314 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000315 ArchSpec host_arch;
316 // These will tell us about the kernel architecture, which even on a 64
317 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000318 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
319 {
Greg Clayton514487e2011-02-15 21:59:32 +0000320 len = sizeof (cpusubtype);
321 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
322 cpusubtype = CPU_TYPE_ANY;
323
Greg Clayton2bddd342010-09-07 20:11:56 +0000324 len = sizeof (is_64_bit_capable);
325 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
326 {
327 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000328 g_supports_64 = true;
329 }
330
331 if (is_64_bit_capable)
332 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000333#if defined (__i386__) || defined (__x86_64__)
334 if (cpusubtype == CPU_SUBTYPE_486)
335 cpusubtype = CPU_SUBTYPE_I386_ALL;
336#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000337 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000338 {
Greg Clayton514487e2011-02-15 21:59:32 +0000339 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000340 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
341 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000342 }
343 else
344 {
345 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000346 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000347 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000348 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000349 }
350 }
Greg Clayton514487e2011-02-15 21:59:32 +0000351 else
352 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000353 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000354 g_host_arch_64.Clear();
355 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000356 }
Greg Clayton514487e2011-02-15 21:59:32 +0000357 }
358
359#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000360
Greg Clayton514487e2011-02-15 21:59:32 +0000361 if (g_supports_32 == false && g_supports_64 == false)
362 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000363 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000364
Stephen Wilsonbd588712011-02-24 19:15:09 +0000365 g_host_arch_32.Clear();
366 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000367
Greg Claytonb29e6c62012-10-11 17:38:58 +0000368 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
369 // for the default triple. It's probably an artifact of config.guess.
370 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
371 triple.setVendorName("");
372
Stephen Wilsonbd588712011-02-24 19:15:09 +0000373 switch (triple.getArch())
374 {
375 default:
376 g_host_arch_32.SetTriple(triple);
377 g_supports_32 = true;
378 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000379
Stephen Wilsonbd588712011-02-24 19:15:09 +0000380 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000381 g_host_arch_64.SetTriple(triple);
382 g_supports_64 = true;
383 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
384 g_supports_32 = true;
385 break;
386
Stephen Wilsonbd588712011-02-24 19:15:09 +0000387 case llvm::Triple::sparcv9:
388 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000389 g_host_arch_64.SetTriple(triple);
390 g_supports_64 = true;
391 break;
392 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000393
394 g_supports_32 = g_host_arch_32.IsValid();
395 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000396 }
Greg Clayton514487e2011-02-15 21:59:32 +0000397
398#endif // #else for #if defined (__APPLE__)
399
400 if (arch_kind == eSystemDefaultArchitecture32)
401 return g_host_arch_32;
402 else if (arch_kind == eSystemDefaultArchitecture64)
403 return g_host_arch_64;
404
405 if (g_supports_64)
406 return g_host_arch_64;
407
408 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000409}
410
411const ConstString &
412Host::GetVendorString()
413{
414 static ConstString g_vendor;
415 if (!g_vendor)
416 {
Greg Clayton950971f2012-05-12 00:01:21 +0000417 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
418 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
419 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000420 }
421 return g_vendor;
422}
423
424const ConstString &
425Host::GetOSString()
426{
427 static ConstString g_os_string;
428 if (!g_os_string)
429 {
Greg Clayton950971f2012-05-12 00:01:21 +0000430 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
431 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
432 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000433 }
434 return g_os_string;
435}
436
437const ConstString &
438Host::GetTargetTriple()
439{
440 static ConstString g_host_triple;
441 if (!(g_host_triple))
442 {
Greg Clayton950971f2012-05-12 00:01:21 +0000443 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
444 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000445 }
446 return g_host_triple;
447}
448
449lldb::pid_t
450Host::GetCurrentProcessID()
451{
452 return ::getpid();
453}
454
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000455#ifndef _WIN32
456
Greg Clayton2bddd342010-09-07 20:11:56 +0000457lldb::tid_t
458Host::GetCurrentThreadID()
459{
460#if defined (__APPLE__)
Greg Clayton813ddfc2012-09-18 18:19:49 +0000461 // Calling "mach_port_deallocate()" bumps the reference count on the thread
462 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
463 // count.
464 thread_port_t thread_self = mach_thread_self();
465 mach_port_deallocate(mach_task_self(), thread_self);
466 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000467#elif defined(__FreeBSD__)
468 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000469#elif defined(__linux__)
470 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000471#else
472 return lldb::tid_t(pthread_self());
473#endif
474}
475
Jim Ingham372787f2012-04-07 00:00:41 +0000476lldb::thread_t
477Host::GetCurrentThread ()
478{
479 return lldb::thread_t(pthread_self());
480}
481
Greg Clayton2bddd342010-09-07 20:11:56 +0000482const char *
483Host::GetSignalAsCString (int signo)
484{
485 switch (signo)
486 {
487 case SIGHUP: return "SIGHUP"; // 1 hangup
488 case SIGINT: return "SIGINT"; // 2 interrupt
489 case SIGQUIT: return "SIGQUIT"; // 3 quit
490 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
491 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
492 case SIGABRT: return "SIGABRT"; // 6 abort()
Greg Clayton0ddf6be2011-11-04 03:42:38 +0000493#if (defined(_POSIX_C_SOURCE) && !defined(_DARWIN_C_SOURCE))
Greg Clayton2bddd342010-09-07 20:11:56 +0000494 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000495#endif
496#if !defined(_POSIX_C_SOURCE)
Greg Clayton2bddd342010-09-07 20:11:56 +0000497 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000498#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000499 case SIGFPE: return "SIGFPE"; // 8 floating point exception
500 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
501 case SIGBUS: return "SIGBUS"; // 10 bus error
502 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
503 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
504 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
505 case SIGALRM: return "SIGALRM"; // 14 alarm clock
506 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
507 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
508 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
509 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
510 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
511 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
512 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
513 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
514#if !defined(_POSIX_C_SOURCE)
515 case SIGIO: return "SIGIO"; // 23 input/output possible signal
516#endif
517 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
518 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
519 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
520 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
521#if !defined(_POSIX_C_SOURCE)
522 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
523 case SIGINFO: return "SIGINFO"; // 29 information request
524#endif
525 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
526 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
527 default:
528 break;
529 }
530 return NULL;
531}
532
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000533#endif
534
Greg Clayton2bddd342010-09-07 20:11:56 +0000535void
536Host::WillTerminate ()
537{
538}
539
Sylvestre Ledru59405832013-07-01 08:21:36 +0000540#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000541
Greg Clayton2bddd342010-09-07 20:11:56 +0000542void
543Host::ThreadCreated (const char *thread_name)
544{
545}
Greg Claytone5219662010-12-03 06:02:24 +0000546
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000547void
Greg Claytone5219662010-12-03 06:02:24 +0000548Host::Backtrace (Stream &strm, uint32_t max_frames)
549{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000550 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000551}
552
Greg Clayton85851dd2010-12-04 00:10:17 +0000553size_t
554Host::GetEnvironment (StringList &env)
555{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000556 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000557 return 0;
558}
559
Sylvestre Ledru59405832013-07-01 08:21:36 +0000560#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000561
562struct HostThreadCreateInfo
563{
564 std::string thread_name;
565 thread_func_t thread_fptr;
566 thread_arg_t thread_arg;
567
568 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
569 thread_name (name ? name : ""),
570 thread_fptr (fptr),
571 thread_arg (arg)
572 {
573 }
574};
575
576static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000577#ifdef _WIN32
578__stdcall
579#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000580ThreadCreateTrampoline (thread_arg_t arg)
581{
582 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
583 Host::ThreadCreated (info->thread_name.c_str());
584 thread_func_t thread_fptr = info->thread_fptr;
585 thread_arg_t thread_arg = info->thread_arg;
586
Greg Clayton5160ce52013-03-27 23:08:40 +0000587 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000588 if (log)
589 log->Printf("thread created");
590
591 delete info;
592 return thread_fptr (thread_arg);
593}
594
595lldb::thread_t
596Host::ThreadCreate
597(
598 const char *thread_name,
599 thread_func_t thread_fptr,
600 thread_arg_t thread_arg,
601 Error *error
602)
603{
604 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
605
606 // Host::ThreadCreateTrampoline will delete this pointer for us.
607 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
608
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000609#ifdef _WIN32
610 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
611 int err = thread <= 0 ? GetLastError() : 0;
612#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000613 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000614#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000615 if (err == 0)
616 {
617 if (error)
618 error->Clear();
619 return thread;
620 }
621
622 if (error)
623 error->SetError (err, eErrorTypePOSIX);
624
625 return LLDB_INVALID_HOST_THREAD;
626}
627
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000628#ifndef _WIN32
629
Greg Clayton2bddd342010-09-07 20:11:56 +0000630bool
631Host::ThreadCancel (lldb::thread_t thread, Error *error)
632{
633 int err = ::pthread_cancel (thread);
634 if (error)
635 error->SetError(err, eErrorTypePOSIX);
636 return err == 0;
637}
638
639bool
640Host::ThreadDetach (lldb::thread_t thread, Error *error)
641{
642 int err = ::pthread_detach (thread);
643 if (error)
644 error->SetError(err, eErrorTypePOSIX);
645 return err == 0;
646}
647
648bool
649Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
650{
651 int err = ::pthread_join (thread, thread_result_ptr);
652 if (error)
653 error->SetError(err, eErrorTypePOSIX);
654 return err == 0;
655}
656
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000657lldb::thread_key_t
658Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
659{
660 pthread_key_t key;
661 ::pthread_key_create (&key, callback);
662 return key;
663}
664
665void*
666Host::ThreadLocalStorageGet(lldb::thread_key_t key)
667{
668 return ::pthread_getspecific (key);
669}
670
671void
672Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
673{
674 ::pthread_setspecific (key, value);
675}
676
Matt Kopec62502c62013-05-13 19:33:58 +0000677bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000678Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
679{
Greg Clayton85719632013-02-27 22:51:58 +0000680#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000681 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
682 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
683 if (pid == LLDB_INVALID_PROCESS_ID)
684 pid = curr_pid;
685
686 if (tid == LLDB_INVALID_THREAD_ID)
687 tid = curr_tid;
688
Greg Clayton2bddd342010-09-07 20:11:56 +0000689 // Set the pthread name if possible
690 if (pid == curr_pid && tid == curr_tid)
691 {
Matt Kopec62502c62013-05-13 19:33:58 +0000692 if (::pthread_setname_np (name) == 0)
693 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000694 }
Matt Kopec62502c62013-05-13 19:33:58 +0000695 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000696#elif defined (__FreeBSD__)
697 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
698 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
699 if (pid == LLDB_INVALID_PROCESS_ID)
700 pid = curr_pid;
701
702 if (tid == LLDB_INVALID_THREAD_ID)
703 tid = curr_tid;
704
705 // Set the pthread name if possible
706 if (pid == curr_pid && tid == curr_tid)
707 {
Michael Sartainc2052432013-08-01 18:51:08 +0000708 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000709 return true;
710 }
711 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000712#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000713 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
714 if (fn)
715 {
Matt Kopec62502c62013-05-13 19:33:58 +0000716 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
717 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000718 if (pid == LLDB_INVALID_PROCESS_ID)
719 pid = curr_pid;
720
721 if (tid == LLDB_INVALID_THREAD_ID)
722 tid = curr_tid;
723
Michael Sartainc2052432013-08-01 18:51:08 +0000724 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000725 {
Michael Sartainc2052432013-08-01 18:51:08 +0000726 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
727 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
728
729 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000730 return true;
731 }
732 }
733 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000734#else
735 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000736#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000737}
738
Ed Maste02983be2013-07-25 19:10:32 +0000739bool
740Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
741 const char *thread_name, size_t len)
742{
743 char *namebuf = (char *)::malloc (len + 1);
744
745 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
746 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
747 // off leads to a lot of similar named threads. Go through the thread name
748 // and search for the last dot and use that.
749 const char *lastdot = ::strrchr (thread_name, '.');
750
751 if (lastdot && lastdot != thread_name)
752 thread_name = lastdot + 1;
753 ::strncpy (namebuf, thread_name, len);
754 namebuf[len] = 0;
755
756 int namebuflen = strlen(namebuf);
757 if (namebuflen > 0)
758 {
759 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
760 {
761 // Trim off trailing '(' and '>' characters for a bit more cleanup.
762 namebuflen--;
763 namebuf[namebuflen] = 0;
764 }
765 return Host::SetThreadName (pid, tid, namebuf);
766 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000767
768 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000769 return false;
770}
771
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000772#endif
773
Greg Clayton2bddd342010-09-07 20:11:56 +0000774FileSpec
775Host::GetProgramFileSpec ()
776{
777 static FileSpec g_program_filespec;
778 if (!g_program_filespec)
779 {
780#if defined (__APPLE__)
781 char program_fullpath[PATH_MAX];
782 // If DST is NULL, then return the number of bytes needed.
783 uint32_t len = sizeof(program_fullpath);
784 int err = _NSGetExecutablePath (program_fullpath, &len);
785 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000786 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000787 else if (err == -1)
788 {
789 char *large_program_fullpath = (char *)::malloc (len + 1);
790
791 err = _NSGetExecutablePath (large_program_fullpath, &len);
792 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000793 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000794
795 ::free (large_program_fullpath);
796 }
797#elif defined (__linux__)
798 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000799 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
800 if (len > 0) {
801 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000802 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000803 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000804#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000805 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
806 size_t exe_path_size;
807 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
808 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000809 char *exe_path = new char[exe_path_size];
810 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
811 g_program_filespec.SetFile(exe_path, false);
812 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000813 }
814#endif
815 }
816 return g_program_filespec;
817}
818
Greg Clayton2bddd342010-09-07 20:11:56 +0000819#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000820
821bool
822Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
823{
824 bundle.Clear();
825 return false;
826}
827
Greg Clayton2bddd342010-09-07 20:11:56 +0000828bool
Greg Claytondd36def2010-10-17 22:03:32 +0000829Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000830{
Greg Claytondd36def2010-10-17 22:03:32 +0000831 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000832}
833#endif
834
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000835#ifndef _WIN32
836
Greg Clayton45319462011-02-08 00:35:34 +0000837// Opaque info that tracks a dynamic library that was loaded
838struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000839{
Greg Clayton45319462011-02-08 00:35:34 +0000840 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
841 file_spec (fs),
842 open_options (o),
843 handle (h)
844 {
845 }
846
847 const FileSpec file_spec;
848 uint32_t open_options;
849 void * handle;
850};
851
852void *
853Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
854{
Greg Clayton4272cc72011-02-02 02:24:04 +0000855 char path[PATH_MAX];
856 if (file_spec.GetPath(path, sizeof(path)))
857 {
Greg Clayton45319462011-02-08 00:35:34 +0000858 int mode = 0;
859
860 if (options & eDynamicLibraryOpenOptionLazy)
861 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000862 else
863 mode |= RTLD_NOW;
864
Greg Clayton45319462011-02-08 00:35:34 +0000865
866 if (options & eDynamicLibraryOpenOptionLocal)
867 mode |= RTLD_LOCAL;
868 else
869 mode |= RTLD_GLOBAL;
870
871#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
872 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
873 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000874#endif
Greg Clayton45319462011-02-08 00:35:34 +0000875
876 void * opaque = ::dlopen (path, mode);
877
878 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000879 {
880 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000881 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000882 }
883 else
884 {
885 error.SetErrorString(::dlerror());
886 }
887 }
888 else
889 {
890 error.SetErrorString("failed to extract path");
891 }
Greg Clayton45319462011-02-08 00:35:34 +0000892 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000893}
894
895Error
Greg Clayton45319462011-02-08 00:35:34 +0000896Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000897{
898 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000899 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000900 {
901 error.SetErrorString ("invalid dynamic library handle");
902 }
Greg Clayton45319462011-02-08 00:35:34 +0000903 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000904 {
Greg Clayton45319462011-02-08 00:35:34 +0000905 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
906 if (::dlclose (dylib_info->handle) != 0)
907 {
908 error.SetErrorString(::dlerror());
909 }
910
911 dylib_info->open_options = 0;
912 dylib_info->handle = 0;
913 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000914 }
915 return error;
916}
917
918void *
Greg Clayton45319462011-02-08 00:35:34 +0000919Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000920{
Greg Clayton45319462011-02-08 00:35:34 +0000921 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000922 {
923 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000924 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000925 else
Greg Clayton45319462011-02-08 00:35:34 +0000926 {
927 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
928
929 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
930 if (symbol_addr)
931 {
932#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
933 // This host doesn't support limiting searches to this shared library
934 // so we need to verify that the match came from this shared library
935 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000936 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000937 {
938 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
939 if (match_dylib_spec != dylib_info->file_spec)
940 {
941 char dylib_path[PATH_MAX];
942 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
943 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
944 else
945 error.SetErrorString ("symbol not found");
946 return NULL;
947 }
948 }
949#endif
950 error.Clear();
951 return symbol_addr;
952 }
953 else
954 {
955 error.SetErrorString(::dlerror());
956 }
957 }
958 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000959}
Greg Claytondd36def2010-10-17 22:03:32 +0000960
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000961FileSpec
962Host::GetModuleFileSpecForHostAddress (const void *host_addr)
963{
964 FileSpec module_filespec;
965 Dl_info info;
966 if (::dladdr (host_addr, &info))
967 {
968 if (info.dli_fname)
969 module_filespec.SetFile(info.dli_fname, true);
970 }
971 return module_filespec;
972}
973
974#endif
975
Greg Claytondd36def2010-10-17 22:03:32 +0000976bool
977Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
978{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000979 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000980 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
981 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000982 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000983 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000984 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +0000985
986 switch (path_type)
987 {
988 case ePathTypeLLDBShlibDir:
989 {
990 static ConstString g_lldb_so_dir;
991 if (!g_lldb_so_dir)
992 {
993 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
994 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000995 if (log)
996 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +0000997 }
998 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +0000999 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001000 }
1001 break;
1002
1003 case ePathTypeSupportExecutableDir:
1004 {
1005 static ConstString g_lldb_support_exe_dir;
1006 if (!g_lldb_support_exe_dir)
1007 {
1008 FileSpec lldb_file_spec;
1009 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1010 {
1011 char raw_path[PATH_MAX];
1012 char resolved_path[PATH_MAX];
1013 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1014
1015#if defined (__APPLE__)
1016 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1017 if (framework_pos)
1018 {
1019 framework_pos += strlen("LLDB.framework");
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001020#if defined (__arm__)
1021 // Shallow bundle
1022 *framework_pos = '\0';
1023#else
1024 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001025 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001026#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001027 }
1028#endif
1029 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1030 g_lldb_support_exe_dir.SetCString(resolved_path);
1031 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001032 if (log)
1033 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001034 }
1035 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001036 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001037 }
1038 break;
1039
1040 case ePathTypeHeaderDir:
1041 {
1042 static ConstString g_lldb_headers_dir;
1043 if (!g_lldb_headers_dir)
1044 {
1045#if defined (__APPLE__)
1046 FileSpec lldb_file_spec;
1047 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1048 {
1049 char raw_path[PATH_MAX];
1050 char resolved_path[PATH_MAX];
1051 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1052
1053 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1054 if (framework_pos)
1055 {
1056 framework_pos += strlen("LLDB.framework");
1057 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1058 }
1059 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1060 g_lldb_headers_dir.SetCString(resolved_path);
1061 }
1062#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001063 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001064 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1065#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001066 if (log)
1067 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001068 }
1069 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001070 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001071 }
1072 break;
1073
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001074#ifdef LLDB_DISABLE_PYTHON
1075 case ePathTypePythonDir:
1076 return false;
1077#else
1078 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001079 {
Greg Claytondd36def2010-10-17 22:03:32 +00001080 static ConstString g_lldb_python_dir;
1081 if (!g_lldb_python_dir)
1082 {
1083 FileSpec lldb_file_spec;
1084 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1085 {
1086 char raw_path[PATH_MAX];
1087 char resolved_path[PATH_MAX];
1088 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1089
1090#if defined (__APPLE__)
1091 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1092 if (framework_pos)
1093 {
1094 framework_pos += strlen("LLDB.framework");
1095 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1096 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001097#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001098 llvm::SmallString<256> python_version_dir;
1099 llvm::raw_svector_ostream os(python_version_dir);
1100 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1101 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001102
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001103 // We may get our string truncated. Should we protect
1104 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001105
Daniel Maleafa7425d2013-08-06 21:40:08 +00001106 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001107 sizeof(raw_path) - strlen(raw_path) - 1);
1108
Greg Claytondd36def2010-10-17 22:03:32 +00001109#endif
1110 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1111 g_lldb_python_dir.SetCString(resolved_path);
1112 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001113
1114 if (log)
1115 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1116
Greg Claytondd36def2010-10-17 22:03:32 +00001117 }
1118 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001119 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001120 }
1121 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001122#endif
1123
Greg Clayton4272cc72011-02-02 02:24:04 +00001124 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1125 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001126#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001127 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001128 static bool g_lldb_system_plugin_dir_located = false;
1129 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001130 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001131 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001132#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001133 FileSpec lldb_file_spec;
1134 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1135 {
1136 char raw_path[PATH_MAX];
1137 char resolved_path[PATH_MAX];
1138 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1139
1140 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1141 if (framework_pos)
1142 {
1143 framework_pos += strlen("LLDB.framework");
1144 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001145 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1146 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001147 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001148 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001149 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001150#elif defined (__linux__)
1151 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1152 if (lldb_file_spec.Exists())
1153 {
1154 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1155 }
1156#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001157
1158 if (log)
1159 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1160
Greg Clayton4272cc72011-02-02 02:24:04 +00001161 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001162
1163 if (g_lldb_system_plugin_dir)
1164 {
1165 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1166 return true;
1167 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001168#else
1169 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001170 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001171#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001172 }
1173 break;
1174
1175 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1176 {
1177#if defined (__APPLE__)
1178 static ConstString g_lldb_user_plugin_dir;
1179 if (!g_lldb_user_plugin_dir)
1180 {
1181 char user_plugin_path[PATH_MAX];
1182 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1183 user_plugin_path,
1184 sizeof(user_plugin_path)))
1185 {
1186 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1187 }
1188 }
1189 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001190 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001191#elif defined (__linux__)
1192 static ConstString g_lldb_user_plugin_dir;
1193 if (!g_lldb_user_plugin_dir)
1194 {
1195 // XDG Base Directory Specification
1196 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1197 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1198 FileSpec lldb_file_spec;
1199 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1200 if (xdg_data_home && xdg_data_home[0])
1201 {
1202 std::string user_plugin_dir (xdg_data_home);
1203 user_plugin_dir += "/lldb";
1204 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1205 }
1206 else
1207 {
1208 const char *home_dir = getenv("HOME");
1209 if (home_dir && home_dir[0])
1210 {
1211 std::string user_plugin_dir (home_dir);
1212 user_plugin_dir += "/.local/share/lldb";
1213 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1214 }
1215 }
1216
1217 if (lldb_file_spec.Exists())
1218 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001219 if (log)
1220 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001221 }
1222 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001223 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001224#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001225 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001226 return false;
1227 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001228
1229 case ePathTypeLLDBTempSystemDir:
1230 {
1231 static ConstString g_lldb_tmp_dir;
1232 if (!g_lldb_tmp_dir)
1233 {
1234 const char *tmpdir_cstr = getenv("TMPDIR");
1235 if (tmpdir_cstr == NULL)
1236 {
1237 tmpdir_cstr = getenv("TMP");
1238 if (tmpdir_cstr == NULL)
1239 tmpdir_cstr = getenv("TEMP");
1240 }
1241 if (tmpdir_cstr)
1242 {
1243 g_lldb_tmp_dir.SetCString(tmpdir_cstr);
1244 if (log)
1245 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1246 }
1247 }
1248 file_spec.GetDirectory() = g_lldb_tmp_dir;
1249 return (bool)file_spec.GetDirectory();
1250 }
Greg Claytondd36def2010-10-17 22:03:32 +00001251 }
1252
1253 return false;
1254}
1255
Greg Clayton1cb64962011-03-24 04:28:38 +00001256
1257bool
1258Host::GetHostname (std::string &s)
1259{
1260 char hostname[PATH_MAX];
1261 hostname[sizeof(hostname) - 1] = '\0';
1262 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1263 {
1264 struct hostent* h = ::gethostbyname (hostname);
1265 if (h)
1266 s.assign (h->h_name);
1267 else
1268 s.assign (hostname);
1269 return true;
1270 }
1271 return false;
1272}
1273
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001274#ifndef _WIN32
1275
Greg Clayton32e0a752011-03-30 18:16:51 +00001276const char *
1277Host::GetUserName (uint32_t uid, std::string &user_name)
1278{
1279 struct passwd user_info;
1280 struct passwd *user_info_ptr = &user_info;
1281 char user_buffer[PATH_MAX];
1282 size_t user_buffer_size = sizeof(user_buffer);
1283 if (::getpwuid_r (uid,
1284 &user_info,
1285 user_buffer,
1286 user_buffer_size,
1287 &user_info_ptr) == 0)
1288 {
1289 if (user_info_ptr)
1290 {
1291 user_name.assign (user_info_ptr->pw_name);
1292 return user_name.c_str();
1293 }
1294 }
1295 user_name.clear();
1296 return NULL;
1297}
1298
1299const char *
1300Host::GetGroupName (uint32_t gid, std::string &group_name)
1301{
1302 char group_buffer[PATH_MAX];
1303 size_t group_buffer_size = sizeof(group_buffer);
1304 struct group group_info;
1305 struct group *group_info_ptr = &group_info;
1306 // Try the threadsafe version first
1307 if (::getgrgid_r (gid,
1308 &group_info,
1309 group_buffer,
1310 group_buffer_size,
1311 &group_info_ptr) == 0)
1312 {
1313 if (group_info_ptr)
1314 {
1315 group_name.assign (group_info_ptr->gr_name);
1316 return group_name.c_str();
1317 }
1318 }
1319 else
1320 {
1321 // The threadsafe version isn't currently working
1322 // for me on darwin, but the non-threadsafe version
1323 // is, so I am calling it below.
1324 group_info_ptr = ::getgrgid (gid);
1325 if (group_info_ptr)
1326 {
1327 group_name.assign (group_info_ptr->gr_name);
1328 return group_name.c_str();
1329 }
1330 }
1331 group_name.clear();
1332 return NULL;
1333}
1334
Han Ming Ong84647042012-02-25 01:07:38 +00001335uint32_t
1336Host::GetUserID ()
1337{
1338 return getuid();
1339}
1340
1341uint32_t
1342Host::GetGroupID ()
1343{
1344 return getgid();
1345}
1346
1347uint32_t
1348Host::GetEffectiveUserID ()
1349{
1350 return geteuid();
1351}
1352
1353uint32_t
1354Host::GetEffectiveGroupID ()
1355{
1356 return getegid();
1357}
1358
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001359#endif
1360
1361#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1362bool
1363Host::GetOSBuildString (std::string &s)
1364{
1365 s.clear();
1366 return false;
1367}
1368
1369bool
1370Host::GetOSKernelDescription (std::string &s)
1371{
1372 s.clear();
1373 return false;
1374}
1375#endif
1376
Ed Maste47e575e2013-08-29 18:44:27 +00001377#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001378uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001379Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001380{
1381 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001382 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001383}
1384
Greg Claytone996fd32011-03-08 22:40:15 +00001385bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001386Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001387{
Greg Claytone996fd32011-03-08 22:40:15 +00001388 process_info.Clear();
1389 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001390}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001391#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001392
Matt Kopec085d6ce2013-05-31 22:00:07 +00001393#if !defined(__linux__)
1394bool
1395Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1396{
1397 return false;
1398}
1399#endif
1400
Sean Callananc0a6e062011-10-27 21:22:25 +00001401lldb::TargetSP
1402Host::GetDummyTarget (lldb_private::Debugger &debugger)
1403{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001404 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001405
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001406 // FIXME: Maybe the dummy target should be per-Debugger
1407 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1408 {
1409 ArchSpec arch(Target::GetDefaultArchitecture());
1410 if (!arch.IsValid())
1411 arch = Host::GetArchitecture ();
1412 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001413 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001414 arch.GetTriple().getTriple().c_str(),
1415 false,
1416 NULL,
1417 g_dummy_target_sp);
1418 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001419
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001420 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001421}
1422
Greg Claytond1cf11a2012-04-14 01:42:46 +00001423struct ShellInfo
1424{
1425 ShellInfo () :
1426 process_reaped (false),
1427 can_delete (false),
1428 pid (LLDB_INVALID_PROCESS_ID),
1429 signo(-1),
1430 status(-1)
1431 {
1432 }
1433
1434 lldb_private::Predicate<bool> process_reaped;
1435 lldb_private::Predicate<bool> can_delete;
1436 lldb::pid_t pid;
1437 int signo;
1438 int status;
1439};
1440
1441static bool
1442MonitorShellCommand (void *callback_baton,
1443 lldb::pid_t pid,
1444 bool exited, // True if the process did exit
1445 int signo, // Zero for no signal
1446 int status) // Exit value of process if signal is zero
1447{
1448 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1449 shell_info->pid = pid;
1450 shell_info->signo = signo;
1451 shell_info->status = status;
1452 // Let the thread running Host::RunShellCommand() know that the process
1453 // exited and that ShellInfo has been filled in by broadcasting to it
1454 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1455 // Now wait for a handshake back from that thread running Host::RunShellCommand
1456 // so we know that we can delete shell_info_ptr
1457 shell_info->can_delete.WaitForValueEqualTo(true);
1458 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1459 usleep(1000);
1460 // Now delete the shell info that was passed into this function
1461 delete shell_info;
1462 return true;
1463}
1464
1465Error
1466Host::RunShellCommand (const char *command,
1467 const char *working_dir,
1468 int *status_ptr,
1469 int *signo_ptr,
1470 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001471 uint32_t timeout_sec,
1472 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001473{
1474 Error error;
1475 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001476 if (shell && shell[0])
1477 {
1478 // Run the command in a shell
1479 launch_info.SetShell(shell);
1480 launch_info.GetArguments().AppendArgument(command);
1481 const bool localhost = true;
1482 const bool will_debug = false;
1483 const bool first_arg_is_full_shell_command = true;
1484 launch_info.ConvertArgumentsForLaunchingInShell (error,
1485 localhost,
1486 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001487 first_arg_is_full_shell_command,
1488 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001489 }
1490 else
1491 {
1492 // No shell, just run it
1493 Args args (command);
1494 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001495 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001496 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001497
1498 if (working_dir)
1499 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001500 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001501 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001502
Greg Claytond1cf11a2012-04-14 01:42:46 +00001503 if (command_output_ptr)
1504 {
1505 // Create a temporary file to get the stdout/stderr and redirect the
1506 // output of the command into this file. We will later read this file
1507 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001508 FileSpec tmpdir_file_spec;
1509 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1510 {
1511 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1512 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1513 }
1514 else
1515 {
1516 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1517 }
1518
1519 output_file_path = ::mktemp(output_file_path_buffer);
1520 }
1521
1522 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1523 if (output_file_path)
1524 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001525 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001526 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001527 }
1528 else
1529 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001530 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1531 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1532 }
1533
1534 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001535 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001536
1537 const bool monitor_signals = false;
1538 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1539
1540 error = LaunchProcess (launch_info);
1541 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001542
1543 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1544 error.SetErrorString("failed to get process ID");
1545
1546 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001547 {
1548 // The process successfully launched, so we can defer ownership of
1549 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001550 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001551 // doesn't need to delete the ShellInfo anymore.
1552 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001553 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001554 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001555 if (timeout_sec > 0) {
1556 timeout_time.OffsetWithSeconds(timeout_sec);
1557 timeout_ptr = &timeout_time;
1558 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001559 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001560 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001561 if (timed_out)
1562 {
1563 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001564
Greg Claytond1cf11a2012-04-14 01:42:46 +00001565 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001566 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001567 // Wait for the monitor callback to get the message
1568 timeout_time = TimeValue::Now();
1569 timeout_time.OffsetWithSeconds(1);
1570 timed_out = false;
1571 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1572 }
1573 else
1574 {
1575 if (status_ptr)
1576 *status_ptr = shell_info->status;
1577
1578 if (signo_ptr)
1579 *signo_ptr = shell_info->signo;
1580
1581 if (command_output_ptr)
1582 {
1583 command_output_ptr->clear();
1584 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1585 uint64_t file_size = file_spec.GetByteSize();
1586 if (file_size > 0)
1587 {
1588 if (file_size > command_output_ptr->max_size())
1589 {
1590 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1591 }
1592 else
1593 {
1594 command_output_ptr->resize(file_size);
1595 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1596 }
1597 }
1598 }
1599 }
1600 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1601 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001602
1603 if (output_file_path)
1604 ::unlink (output_file_path);
1605 // Handshake with the monitor thread, or just let it know in advance that
1606 // it can delete "shell_info" in case we timed out and were not able to kill
1607 // the process...
1608 return error;
1609}
1610
Colin Riley909bb7a2013-11-26 15:10:46 +00001611#if defined(__linux__) || defined(__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001612// The functions below implement process launching via posix_spawn() for Linux
1613// and FreeBSD.
1614
1615// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1616static Error
1617LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1618{
1619 Error error;
1620 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1621
1622 assert(exe_path);
1623 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1624
1625 posix_spawnattr_t attr;
1626
1627 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1628 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1629 if (error.Fail())
1630 return error;
1631
1632 // Make a quick class that will cleanup the posix spawn attributes in case
1633 // we return in the middle of this function.
1634 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1635
1636 sigset_t no_signals;
1637 sigset_t all_signals;
1638 sigemptyset (&no_signals);
1639 sigfillset (&all_signals);
1640 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1641 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1642
1643 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1644
1645 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1646 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1647 if (error.Fail())
1648 return error;
1649
1650 const size_t num_file_actions = launch_info.GetNumFileActions ();
1651 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1652 // Make a quick class that will cleanup the posix spawn attributes in case
1653 // we return in the middle of this function.
1654 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1655 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1656
1657 if (num_file_actions > 0)
1658 {
1659 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1660 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1661 if (error.Fail())
1662 return error;
1663
1664 file_action_ptr = &file_actions;
1665 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1666
1667 for (size_t i = 0; i < num_file_actions; ++i)
1668 {
1669 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1670 if (launch_file_action &&
1671 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1672 launch_file_action,
1673 log,
1674 error))
1675 return error;
1676 }
1677 }
1678
1679 // Change working directory if neccessary.
1680 char current_dir[PATH_MAX];
1681 current_dir[0] = '\0';
1682
1683 const char *working_dir = launch_info.GetWorkingDirectory();
1684 if (working_dir != NULL)
1685 {
1686 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1687 {
1688 error.SetError(errno, eErrorTypePOSIX);
1689 error.LogIfError(log, "unable to save the current directory");
1690 return error;
1691 }
1692
1693 if (::chdir(working_dir) == -1)
1694 {
1695 error.SetError(errno, eErrorTypePOSIX);
1696 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1697 return error;
1698 }
1699 }
1700
1701 const char *tmp_argv[2];
1702 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1703 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1704
1705 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1706 // We must pass argv into posix_spawnp and it must contain at least two items -
1707 // pointer to an executable and NULL.
1708 if (argv == NULL)
1709 {
1710 tmp_argv[0] = exe_path;
1711 tmp_argv[1] = NULL;
1712 argv = (char * const*)tmp_argv;
1713 }
1714
1715 error.SetError (::posix_spawnp (&pid,
1716 exe_path,
1717 (num_file_actions > 0) ? &file_actions : NULL,
1718 &attr,
1719 argv,
1720 envp),
1721 eErrorTypePOSIX);
1722
1723 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1724 pid, exe_path, file_action_ptr, &attr, argv, envp);
1725
1726 // Change back the current directory.
1727 // NOTE: do not override previously established error from posix_spawnp.
1728 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1729 {
1730 error.SetError(errno, eErrorTypePOSIX);
1731 error.LogIfError(log, "unable to change current directory back to %s",
1732 current_dir);
1733 }
1734
1735 return error;
1736}
1737
1738
1739Error
1740Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1741{
1742 Error error;
1743 char exe_path[PATH_MAX];
1744
1745 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1746
1747 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1748
1749 FileSpec exe_spec(launch_info.GetExecutableFile());
1750
1751 FileSpec::FileType file_type = exe_spec.GetFileType();
1752 if (file_type != FileSpec::eFileTypeRegular)
1753 {
1754 lldb::ModuleSP exe_module_sp;
1755 error = host_platform_sp->ResolveExecutable (exe_spec,
1756 arch_spec,
1757 exe_module_sp,
1758 NULL);
1759
1760 if (error.Fail())
1761 return error;
1762
1763 if (exe_module_sp)
1764 exe_spec = exe_module_sp->GetFileSpec();
1765 }
1766
1767 if (exe_spec.Exists())
1768 {
1769 exe_spec.GetPath (exe_path, sizeof(exe_path));
1770 }
1771 else
1772 {
1773 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1774 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1775 return error;
1776 }
1777
1778 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1779
1780 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1781
1782 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1783
1784 if (pid != LLDB_INVALID_PROCESS_ID)
1785 {
1786 // If all went well, then set the process ID into the launch info
1787 launch_info.SetProcessID(pid);
1788
1789 // Make sure we reap any processes we spawn or we will have zombies.
1790 if (!launch_info.MonitorProcess())
1791 {
1792 const bool monitor_signals = false;
1793 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1794 NULL,
1795 pid,
1796 monitor_signals);
1797 }
1798 }
1799 else
1800 {
1801 // Invalid process ID, something didn't go well
1802 if (error.Success())
1803 error.SetErrorString ("process launch failed for unknown reasons");
1804 }
1805 return error;
1806}
1807
1808#endif // defined(__linux__) or defined(__FreeBSD__)
1809
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001810#ifndef _WIN32
1811
1812size_t
1813Host::GetPageSize()
1814{
1815 return ::getpagesize();
1816}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001817
Greg Claytone3e3fee2013-02-17 20:46:30 +00001818uint32_t
1819Host::GetNumberCPUS ()
1820{
1821 static uint32_t g_num_cores = UINT32_MAX;
1822 if (g_num_cores == UINT32_MAX)
1823 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001824#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001825
1826 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001827
Greg Claytone3e3fee2013-02-17 20:46:30 +00001828#else
1829
1830 // Assume POSIX support if a host specific case has not been supplied above
1831 g_num_cores = 0;
1832 int num_cores = 0;
1833 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001834#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001835 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001836#else
1837 int mib[] = { CTL_HW, HW_NCPU };
1838#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001839
1840 /* get the number of CPUs from the system */
1841 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1842 {
1843 g_num_cores = num_cores;
1844 }
1845 else
1846 {
1847 mib[1] = HW_NCPU;
1848 num_cores_len = sizeof(num_cores);
1849 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1850 {
1851 if (num_cores > 0)
1852 g_num_cores = num_cores;
1853 }
1854 }
1855#endif
1856 }
1857 return g_num_cores;
1858}
1859
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001860void
1861Host::Kill(lldb::pid_t pid, int signo)
1862{
1863 ::kill(pid, signo);
1864}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001865
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001866#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001867
Johnny Chen8f3d8382011-08-02 20:52:42 +00001868#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001869bool
Greg Clayton3b147632010-12-18 01:54:34 +00001870Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001871{
1872 return false;
1873}
Greg Claytondd36def2010-10-17 22:03:32 +00001874
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001875void
1876Host::SetCrashDescriptionWithFormat (const char *format, ...)
1877{
1878}
1879
1880void
1881Host::SetCrashDescription (const char *description)
1882{
1883}
Greg Claytondd36def2010-10-17 22:03:32 +00001884
1885lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001886Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001887{
1888 return LLDB_INVALID_PROCESS_ID;
1889}
1890
Greg Claytonfbb76342013-11-20 21:07:01 +00001891#endif
1892
1893
1894#ifdef LLDB_DISABLE_POSIX
1895
1896Error
1897Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001898{
Greg Claytonfbb76342013-11-20 21:07:01 +00001899 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001900 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001901 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001902}
Greg Claytonfbb76342013-11-20 21:07:01 +00001903
1904Error
1905Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1906{
1907 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001908 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001909 return error;
1910}
1911
1912Error
1913Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1914{
1915 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001916 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001917 return error;
1918}
1919
1920Error
1921Host::Symlink (const char *src, const char *dst)
1922{
1923 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001924 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001925 return error;
1926}
1927
1928Error
1929Host::Readlink (const char *path, char *buf, size_t buf_len)
1930{
1931 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001932 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001933 return error;
1934}
1935
1936Error
1937Host::Unlink (const char *path)
1938{
1939 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001940 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001941 return error;
1942}
1943
1944#else
1945
1946Error
1947Host::MakeDirectory (const char* path, uint32_t file_permissions)
1948{
1949 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00001950 if (path && path[0])
1951 {
Greg Claytonfb909312013-11-23 01:58:15 +00001952 if (::mkdir(path, file_permissions) != 0)
1953 {
1954 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001955 switch (error.GetError())
1956 {
1957 case ENOENT:
1958 {
1959 // Parent directory doesn't exist, so lets make it if we can
1960 FileSpec spec(path, false);
1961 if (spec.GetDirectory() && spec.GetFilename())
1962 {
1963 // Make the parent directory and try again
1964 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
1965 if (error2.Success())
1966 {
1967 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00001968 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00001969 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00001970 else
Greg Claytonfb909312013-11-23 01:58:15 +00001971 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001972 }
1973 }
1974 }
1975 break;
1976 case EEXIST:
1977 {
1978 FileSpec path_spec(path, false);
1979 if (path_spec.IsDirectory())
1980 error.Clear(); // It is a directory and it already exists
1981 }
1982 break;
1983 }
1984 }
Greg Claytonfb909312013-11-23 01:58:15 +00001985 }
1986 else
1987 {
1988 error.SetErrorString("empty path");
1989 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001990 return error;
1991}
1992
1993Error
1994Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1995{
1996 Error error;
1997 struct stat file_stats;
1998 if (::stat (path, &file_stats) == 0)
1999 {
2000 // The bits in "st_mode" currently match the definitions
2001 // for the file mode bits in unix.
2002 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2003 }
2004 else
2005 {
2006 error.SetErrorToErrno();
2007 }
2008 return error;
2009}
2010
2011Error
2012Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2013{
2014 Error error;
2015 if (::chmod(path, file_permissions) != 0)
2016 error.SetErrorToErrno();
2017 return error;
2018}
2019
2020Error
2021Host::Symlink (const char *src, const char *dst)
2022{
2023 Error error;
2024 if (::symlink(dst, src) == -1)
2025 error.SetErrorToErrno();
2026 return error;
2027}
2028
2029Error
2030Host::Unlink (const char *path)
2031{
2032 Error error;
2033 if (::unlink(path) == -1)
2034 error.SetErrorToErrno();
2035 return error;
2036}
2037
2038Error
2039Host::Readlink (const char *path, char *buf, size_t buf_len)
2040{
2041 Error error;
2042 ssize_t count = ::readlink(path, buf, buf_len);
2043 if (count < 0)
2044 error.SetErrorToErrno();
2045 else if (count < (buf_len-1))
2046 buf[count] = '\0'; // Success
2047 else
2048 error.SetErrorString("'buf' buffer is too small to contain link contents");
2049 return error;
2050}
2051
2052
Greg Clayton2bddd342010-09-07 20:11:56 +00002053#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002054
2055typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2056FDToFileMap& GetFDToFileMap()
2057{
2058 static FDToFileMap g_fd2filemap;
2059 return g_fd2filemap;
2060}
2061
2062lldb::user_id_t
2063Host::OpenFile (const FileSpec& file_spec,
2064 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002065 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002066 Error &error)
2067{
2068 std::string path (file_spec.GetPath());
2069 if (path.empty())
2070 {
2071 error.SetErrorString("empty path");
2072 return UINT64_MAX;
2073 }
2074 FileSP file_sp(new File());
2075 error = file_sp->Open(path.c_str(),flags,mode);
2076 if (file_sp->IsValid() == false)
2077 return UINT64_MAX;
2078 lldb::user_id_t fd = file_sp->GetDescriptor();
2079 GetFDToFileMap()[fd] = file_sp;
2080 return fd;
2081}
2082
2083bool
2084Host::CloseFile (lldb::user_id_t fd, Error &error)
2085{
2086 if (fd == UINT64_MAX)
2087 {
2088 error.SetErrorString ("invalid file descriptor");
2089 return false;
2090 }
2091 FDToFileMap& file_map = GetFDToFileMap();
2092 FDToFileMap::iterator pos = file_map.find(fd);
2093 if (pos == file_map.end())
2094 {
2095 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2096 return false;
2097 }
2098 FileSP file_sp = pos->second;
2099 if (!file_sp)
2100 {
2101 error.SetErrorString ("invalid host backing file");
2102 return false;
2103 }
2104 error = file_sp->Close();
2105 file_map.erase(pos);
2106 return error.Success();
2107}
2108
2109uint64_t
2110Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2111{
2112 if (fd == UINT64_MAX)
2113 {
2114 error.SetErrorString ("invalid file descriptor");
2115 return UINT64_MAX;
2116 }
2117 FDToFileMap& file_map = GetFDToFileMap();
2118 FDToFileMap::iterator pos = file_map.find(fd);
2119 if (pos == file_map.end())
2120 {
2121 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2122 return false;
2123 }
2124 FileSP file_sp = pos->second;
2125 if (!file_sp)
2126 {
2127 error.SetErrorString ("invalid host backing file");
2128 return UINT64_MAX;
2129 }
2130 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2131 return UINT64_MAX;
2132 size_t bytes_written = src_len;
2133 error = file_sp->Write(src, bytes_written);
2134 if (error.Fail())
2135 return UINT64_MAX;
2136 return bytes_written;
2137}
2138
2139uint64_t
2140Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2141{
2142 if (fd == UINT64_MAX)
2143 {
2144 error.SetErrorString ("invalid file descriptor");
2145 return UINT64_MAX;
2146 }
2147 FDToFileMap& file_map = GetFDToFileMap();
2148 FDToFileMap::iterator pos = file_map.find(fd);
2149 if (pos == file_map.end())
2150 {
2151 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2152 return false;
2153 }
2154 FileSP file_sp = pos->second;
2155 if (!file_sp)
2156 {
2157 error.SetErrorString ("invalid host backing file");
2158 return UINT64_MAX;
2159 }
2160 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2161 return UINT64_MAX;
2162 size_t bytes_read = dst_len;
2163 error = file_sp->Read(dst ,bytes_read);
2164 if (error.Fail())
2165 return UINT64_MAX;
2166 return bytes_read;
2167}
2168
2169lldb::user_id_t
2170Host::GetFileSize (const FileSpec& file_spec)
2171{
2172 return file_spec.GetByteSize();
2173}
2174
2175bool
2176Host::GetFileExists (const FileSpec& file_spec)
2177{
2178 return file_spec.Exists();
2179}
2180
2181bool
2182Host::CalculateMD5 (const FileSpec& file_spec,
2183 uint64_t &low,
2184 uint64_t &high)
2185{
2186#if defined (__APPLE__)
2187 StreamString md5_cmd_line;
2188 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2189 std::string hash_string;
2190 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2191 if (err.Fail())
2192 return false;
2193 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2194 // if the output is any other length it is probably wrong
2195 if (hash_string.size() != 32)
2196 return false;
2197 std::string part1(hash_string,0,16);
2198 std::string part2(hash_string,16);
2199 const char* part1_cstr = part1.c_str();
2200 const char* part2_cstr = part2.c_str();
2201 high = ::strtoull(part1_cstr, NULL, 16);
2202 low = ::strtoull(part2_cstr, NULL, 16);
2203 return true;
2204#else
2205 // your own MD5 implementation here
2206 return false;
2207#endif
2208}