blob: fc6d69709737a0cb62521f9a61057bba3339faf0 [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__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000461 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000462 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
463 // count.
464 thread_port_t thread_self = mach_thread_self();
465 mach_port_deallocate(mach_task_self(), thread_self);
466 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000467#elif defined(__FreeBSD__)
468 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000469#elif defined(__linux__)
470 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000471#else
472 return lldb::tid_t(pthread_self());
473#endif
474}
475
Jim Ingham372787f2012-04-07 00:00:41 +0000476lldb::thread_t
477Host::GetCurrentThread ()
478{
479 return lldb::thread_t(pthread_self());
480}
481
Greg Clayton2bddd342010-09-07 20:11:56 +0000482const char *
483Host::GetSignalAsCString (int signo)
484{
485 switch (signo)
486 {
487 case SIGHUP: return "SIGHUP"; // 1 hangup
488 case SIGINT: return "SIGINT"; // 2 interrupt
489 case SIGQUIT: return "SIGQUIT"; // 3 quit
490 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
491 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
492 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000493#if defined(SIGPOLL)
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
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000496#if defined(SIGEMT)
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)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000514#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000515 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
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000521#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000522 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000523#endif
524#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000525 case SIGINFO: return "SIGINFO"; // 29 information request
526#endif
527 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
528 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
529 default:
530 break;
531 }
532 return NULL;
533}
534
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000535#endif
536
Greg Clayton2bddd342010-09-07 20:11:56 +0000537void
538Host::WillTerminate ()
539{
540}
541
Sylvestre Ledru59405832013-07-01 08:21:36 +0000542#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000543
Greg Clayton2bddd342010-09-07 20:11:56 +0000544void
545Host::ThreadCreated (const char *thread_name)
546{
547}
Greg Claytone5219662010-12-03 06:02:24 +0000548
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000549void
Greg Claytone5219662010-12-03 06:02:24 +0000550Host::Backtrace (Stream &strm, uint32_t max_frames)
551{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000552 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000553}
554
Greg Clayton85851dd2010-12-04 00:10:17 +0000555size_t
556Host::GetEnvironment (StringList &env)
557{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000558 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000559 return 0;
560}
561
Sylvestre Ledru59405832013-07-01 08:21:36 +0000562#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000563
564struct HostThreadCreateInfo
565{
566 std::string thread_name;
567 thread_func_t thread_fptr;
568 thread_arg_t thread_arg;
569
570 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
571 thread_name (name ? name : ""),
572 thread_fptr (fptr),
573 thread_arg (arg)
574 {
575 }
576};
577
578static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000579#ifdef _WIN32
580__stdcall
581#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000582ThreadCreateTrampoline (thread_arg_t arg)
583{
584 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
585 Host::ThreadCreated (info->thread_name.c_str());
586 thread_func_t thread_fptr = info->thread_fptr;
587 thread_arg_t thread_arg = info->thread_arg;
588
Greg Clayton5160ce52013-03-27 23:08:40 +0000589 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000590 if (log)
591 log->Printf("thread created");
592
593 delete info;
594 return thread_fptr (thread_arg);
595}
596
597lldb::thread_t
598Host::ThreadCreate
599(
600 const char *thread_name,
601 thread_func_t thread_fptr,
602 thread_arg_t thread_arg,
603 Error *error
604)
605{
606 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
607
608 // Host::ThreadCreateTrampoline will delete this pointer for us.
609 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
610
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000611#ifdef _WIN32
612 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
613 int err = thread <= 0 ? GetLastError() : 0;
614#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000615 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000616#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000617 if (err == 0)
618 {
619 if (error)
620 error->Clear();
621 return thread;
622 }
623
624 if (error)
625 error->SetError (err, eErrorTypePOSIX);
626
627 return LLDB_INVALID_HOST_THREAD;
628}
629
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000630#ifndef _WIN32
631
Greg Clayton2bddd342010-09-07 20:11:56 +0000632bool
633Host::ThreadCancel (lldb::thread_t thread, Error *error)
634{
635 int err = ::pthread_cancel (thread);
636 if (error)
637 error->SetError(err, eErrorTypePOSIX);
638 return err == 0;
639}
640
641bool
642Host::ThreadDetach (lldb::thread_t thread, Error *error)
643{
644 int err = ::pthread_detach (thread);
645 if (error)
646 error->SetError(err, eErrorTypePOSIX);
647 return err == 0;
648}
649
650bool
651Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
652{
653 int err = ::pthread_join (thread, thread_result_ptr);
654 if (error)
655 error->SetError(err, eErrorTypePOSIX);
656 return err == 0;
657}
658
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000659lldb::thread_key_t
660Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
661{
662 pthread_key_t key;
663 ::pthread_key_create (&key, callback);
664 return key;
665}
666
667void*
668Host::ThreadLocalStorageGet(lldb::thread_key_t key)
669{
670 return ::pthread_getspecific (key);
671}
672
673void
674Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
675{
676 ::pthread_setspecific (key, value);
677}
678
Matt Kopec62502c62013-05-13 19:33:58 +0000679bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000680Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
681{
Greg Clayton85719632013-02-27 22:51:58 +0000682#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000683 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
684 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
685 if (pid == LLDB_INVALID_PROCESS_ID)
686 pid = curr_pid;
687
688 if (tid == LLDB_INVALID_THREAD_ID)
689 tid = curr_tid;
690
Greg Clayton2bddd342010-09-07 20:11:56 +0000691 // Set the pthread name if possible
692 if (pid == curr_pid && tid == curr_tid)
693 {
Matt Kopec62502c62013-05-13 19:33:58 +0000694 if (::pthread_setname_np (name) == 0)
695 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000696 }
Matt Kopec62502c62013-05-13 19:33:58 +0000697 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000698#elif defined (__FreeBSD__)
699 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
700 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
701 if (pid == LLDB_INVALID_PROCESS_ID)
702 pid = curr_pid;
703
704 if (tid == LLDB_INVALID_THREAD_ID)
705 tid = curr_tid;
706
707 // Set the pthread name if possible
708 if (pid == curr_pid && tid == curr_tid)
709 {
Michael Sartainc2052432013-08-01 18:51:08 +0000710 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000711 return true;
712 }
713 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000714#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000715 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
716 if (fn)
717 {
Matt Kopec62502c62013-05-13 19:33:58 +0000718 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
719 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000720 if (pid == LLDB_INVALID_PROCESS_ID)
721 pid = curr_pid;
722
723 if (tid == LLDB_INVALID_THREAD_ID)
724 tid = curr_tid;
725
Michael Sartainc2052432013-08-01 18:51:08 +0000726 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000727 {
Michael Sartainc2052432013-08-01 18:51:08 +0000728 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
729 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
730
731 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000732 return true;
733 }
734 }
735 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000736#else
737 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000738#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000739}
740
Ed Maste02983be2013-07-25 19:10:32 +0000741bool
742Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
743 const char *thread_name, size_t len)
744{
745 char *namebuf = (char *)::malloc (len + 1);
746
747 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
748 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
749 // off leads to a lot of similar named threads. Go through the thread name
750 // and search for the last dot and use that.
751 const char *lastdot = ::strrchr (thread_name, '.');
752
753 if (lastdot && lastdot != thread_name)
754 thread_name = lastdot + 1;
755 ::strncpy (namebuf, thread_name, len);
756 namebuf[len] = 0;
757
758 int namebuflen = strlen(namebuf);
759 if (namebuflen > 0)
760 {
761 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
762 {
763 // Trim off trailing '(' and '>' characters for a bit more cleanup.
764 namebuflen--;
765 namebuf[namebuflen] = 0;
766 }
767 return Host::SetThreadName (pid, tid, namebuf);
768 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000769
770 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000771 return false;
772}
773
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000774#endif
775
Greg Clayton2bddd342010-09-07 20:11:56 +0000776FileSpec
777Host::GetProgramFileSpec ()
778{
779 static FileSpec g_program_filespec;
780 if (!g_program_filespec)
781 {
782#if defined (__APPLE__)
783 char program_fullpath[PATH_MAX];
784 // If DST is NULL, then return the number of bytes needed.
785 uint32_t len = sizeof(program_fullpath);
786 int err = _NSGetExecutablePath (program_fullpath, &len);
787 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000788 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000789 else if (err == -1)
790 {
791 char *large_program_fullpath = (char *)::malloc (len + 1);
792
793 err = _NSGetExecutablePath (large_program_fullpath, &len);
794 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000795 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000796
797 ::free (large_program_fullpath);
798 }
799#elif defined (__linux__)
800 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000801 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
802 if (len > 0) {
803 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000804 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000805 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000806#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000807 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
808 size_t exe_path_size;
809 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
810 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000811 char *exe_path = new char[exe_path_size];
812 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
813 g_program_filespec.SetFile(exe_path, false);
814 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000815 }
816#endif
817 }
818 return g_program_filespec;
819}
820
Greg Clayton2bddd342010-09-07 20:11:56 +0000821#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000822
823bool
824Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
825{
826 bundle.Clear();
827 return false;
828}
829
Greg Clayton2bddd342010-09-07 20:11:56 +0000830bool
Greg Claytondd36def2010-10-17 22:03:32 +0000831Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000832{
Greg Claytondd36def2010-10-17 22:03:32 +0000833 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000834}
835#endif
836
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000837#ifndef _WIN32
838
Greg Clayton45319462011-02-08 00:35:34 +0000839// Opaque info that tracks a dynamic library that was loaded
840struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000841{
Greg Clayton45319462011-02-08 00:35:34 +0000842 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
843 file_spec (fs),
844 open_options (o),
845 handle (h)
846 {
847 }
848
849 const FileSpec file_spec;
850 uint32_t open_options;
851 void * handle;
852};
853
854void *
855Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
856{
Greg Clayton4272cc72011-02-02 02:24:04 +0000857 char path[PATH_MAX];
858 if (file_spec.GetPath(path, sizeof(path)))
859 {
Greg Clayton45319462011-02-08 00:35:34 +0000860 int mode = 0;
861
862 if (options & eDynamicLibraryOpenOptionLazy)
863 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000864 else
865 mode |= RTLD_NOW;
866
Greg Clayton45319462011-02-08 00:35:34 +0000867
868 if (options & eDynamicLibraryOpenOptionLocal)
869 mode |= RTLD_LOCAL;
870 else
871 mode |= RTLD_GLOBAL;
872
873#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
874 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
875 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000876#endif
Greg Clayton45319462011-02-08 00:35:34 +0000877
878 void * opaque = ::dlopen (path, mode);
879
880 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000881 {
882 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000883 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000884 }
885 else
886 {
887 error.SetErrorString(::dlerror());
888 }
889 }
890 else
891 {
892 error.SetErrorString("failed to extract path");
893 }
Greg Clayton45319462011-02-08 00:35:34 +0000894 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000895}
896
897Error
Greg Clayton45319462011-02-08 00:35:34 +0000898Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000899{
900 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000901 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000902 {
903 error.SetErrorString ("invalid dynamic library handle");
904 }
Greg Clayton45319462011-02-08 00:35:34 +0000905 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000906 {
Greg Clayton45319462011-02-08 00:35:34 +0000907 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
908 if (::dlclose (dylib_info->handle) != 0)
909 {
910 error.SetErrorString(::dlerror());
911 }
912
913 dylib_info->open_options = 0;
914 dylib_info->handle = 0;
915 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000916 }
917 return error;
918}
919
920void *
Greg Clayton45319462011-02-08 00:35:34 +0000921Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000922{
Greg Clayton45319462011-02-08 00:35:34 +0000923 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000924 {
925 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000926 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000927 else
Greg Clayton45319462011-02-08 00:35:34 +0000928 {
929 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
930
931 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
932 if (symbol_addr)
933 {
934#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
935 // This host doesn't support limiting searches to this shared library
936 // so we need to verify that the match came from this shared library
937 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000938 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000939 {
940 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
941 if (match_dylib_spec != dylib_info->file_spec)
942 {
943 char dylib_path[PATH_MAX];
944 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
945 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
946 else
947 error.SetErrorString ("symbol not found");
948 return NULL;
949 }
950 }
951#endif
952 error.Clear();
953 return symbol_addr;
954 }
955 else
956 {
957 error.SetErrorString(::dlerror());
958 }
959 }
960 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000961}
Greg Claytondd36def2010-10-17 22:03:32 +0000962
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000963FileSpec
964Host::GetModuleFileSpecForHostAddress (const void *host_addr)
965{
966 FileSpec module_filespec;
967 Dl_info info;
968 if (::dladdr (host_addr, &info))
969 {
970 if (info.dli_fname)
971 module_filespec.SetFile(info.dli_fname, true);
972 }
973 return module_filespec;
974}
975
976#endif
977
Greg Claytondd36def2010-10-17 22:03:32 +0000978bool
979Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
980{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000981 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000982 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
983 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000984 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000985 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000986 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +0000987
988 switch (path_type)
989 {
990 case ePathTypeLLDBShlibDir:
991 {
992 static ConstString g_lldb_so_dir;
993 if (!g_lldb_so_dir)
994 {
995 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
996 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000997 if (log)
998 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +0000999 }
1000 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001001 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001002 }
1003 break;
1004
1005 case ePathTypeSupportExecutableDir:
1006 {
1007 static ConstString g_lldb_support_exe_dir;
1008 if (!g_lldb_support_exe_dir)
1009 {
1010 FileSpec lldb_file_spec;
1011 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1012 {
1013 char raw_path[PATH_MAX];
1014 char resolved_path[PATH_MAX];
1015 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1016
1017#if defined (__APPLE__)
1018 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1019 if (framework_pos)
1020 {
1021 framework_pos += strlen("LLDB.framework");
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001022#if defined (__arm__)
1023 // Shallow bundle
1024 *framework_pos = '\0';
1025#else
1026 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001027 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001028#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001029 }
1030#endif
1031 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1032 g_lldb_support_exe_dir.SetCString(resolved_path);
1033 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001034 if (log)
1035 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001036 }
1037 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001038 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001039 }
1040 break;
1041
1042 case ePathTypeHeaderDir:
1043 {
1044 static ConstString g_lldb_headers_dir;
1045 if (!g_lldb_headers_dir)
1046 {
1047#if defined (__APPLE__)
1048 FileSpec lldb_file_spec;
1049 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1050 {
1051 char raw_path[PATH_MAX];
1052 char resolved_path[PATH_MAX];
1053 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1054
1055 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1056 if (framework_pos)
1057 {
1058 framework_pos += strlen("LLDB.framework");
1059 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1060 }
1061 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1062 g_lldb_headers_dir.SetCString(resolved_path);
1063 }
1064#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001065 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001066 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1067#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001068 if (log)
1069 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001070 }
1071 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001072 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001073 }
1074 break;
1075
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001076#ifdef LLDB_DISABLE_PYTHON
1077 case ePathTypePythonDir:
1078 return false;
1079#else
1080 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001081 {
Greg Claytondd36def2010-10-17 22:03:32 +00001082 static ConstString g_lldb_python_dir;
1083 if (!g_lldb_python_dir)
1084 {
1085 FileSpec lldb_file_spec;
1086 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1087 {
1088 char raw_path[PATH_MAX];
1089 char resolved_path[PATH_MAX];
1090 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1091
1092#if defined (__APPLE__)
1093 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1094 if (framework_pos)
1095 {
1096 framework_pos += strlen("LLDB.framework");
1097 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
1098 }
Filipe Cabecinhas0b751162012-07-30 16:46:32 +00001099#else
Daniel Maleafa7425d2013-08-06 21:40:08 +00001100 llvm::SmallString<256> python_version_dir;
1101 llvm::raw_svector_ostream os(python_version_dir);
1102 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1103 os.flush();
Daniel Malea53430eb2013-01-04 23:35:13 +00001104
Filipe Cabecinhascffbd092012-07-30 18:56:10 +00001105 // We may get our string truncated. Should we protect
1106 // this with an assert?
Daniel Malea53430eb2013-01-04 23:35:13 +00001107
Daniel Maleafa7425d2013-08-06 21:40:08 +00001108 ::strncat(raw_path, python_version_dir.c_str(),
Daniel Malea53430eb2013-01-04 23:35:13 +00001109 sizeof(raw_path) - strlen(raw_path) - 1);
1110
Greg Claytondd36def2010-10-17 22:03:32 +00001111#endif
1112 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1113 g_lldb_python_dir.SetCString(resolved_path);
1114 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001115
1116 if (log)
1117 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1118
Greg Claytondd36def2010-10-17 22:03:32 +00001119 }
1120 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001121 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001122 }
1123 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001124#endif
1125
Greg Clayton4272cc72011-02-02 02:24:04 +00001126 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1127 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001128#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001129 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001130 static bool g_lldb_system_plugin_dir_located = false;
1131 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001132 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001133 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001134#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001135 FileSpec lldb_file_spec;
1136 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1137 {
1138 char raw_path[PATH_MAX];
1139 char resolved_path[PATH_MAX];
1140 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1141
1142 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1143 if (framework_pos)
1144 {
1145 framework_pos += strlen("LLDB.framework");
1146 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001147 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1148 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001149 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001150 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001151 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001152#elif defined (__linux__)
1153 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1154 if (lldb_file_spec.Exists())
1155 {
1156 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1157 }
1158#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001159
1160 if (log)
1161 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1162
Greg Clayton4272cc72011-02-02 02:24:04 +00001163 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001164
1165 if (g_lldb_system_plugin_dir)
1166 {
1167 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1168 return true;
1169 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001170#else
1171 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001172 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001173#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001174 }
1175 break;
1176
1177 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1178 {
1179#if defined (__APPLE__)
1180 static ConstString g_lldb_user_plugin_dir;
1181 if (!g_lldb_user_plugin_dir)
1182 {
1183 char user_plugin_path[PATH_MAX];
1184 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1185 user_plugin_path,
1186 sizeof(user_plugin_path)))
1187 {
1188 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1189 }
1190 }
1191 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001192 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001193#elif defined (__linux__)
1194 static ConstString g_lldb_user_plugin_dir;
1195 if (!g_lldb_user_plugin_dir)
1196 {
1197 // XDG Base Directory Specification
1198 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1199 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1200 FileSpec lldb_file_spec;
1201 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1202 if (xdg_data_home && xdg_data_home[0])
1203 {
1204 std::string user_plugin_dir (xdg_data_home);
1205 user_plugin_dir += "/lldb";
1206 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1207 }
1208 else
1209 {
1210 const char *home_dir = getenv("HOME");
1211 if (home_dir && home_dir[0])
1212 {
1213 std::string user_plugin_dir (home_dir);
1214 user_plugin_dir += "/.local/share/lldb";
1215 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1216 }
1217 }
1218
1219 if (lldb_file_spec.Exists())
1220 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001221 if (log)
1222 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001223 }
1224 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001225 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001226#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001227 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001228 return false;
1229 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001230
1231 case ePathTypeLLDBTempSystemDir:
1232 {
1233 static ConstString g_lldb_tmp_dir;
1234 if (!g_lldb_tmp_dir)
1235 {
1236 const char *tmpdir_cstr = getenv("TMPDIR");
1237 if (tmpdir_cstr == NULL)
1238 {
1239 tmpdir_cstr = getenv("TMP");
1240 if (tmpdir_cstr == NULL)
1241 tmpdir_cstr = getenv("TEMP");
1242 }
1243 if (tmpdir_cstr)
1244 {
1245 g_lldb_tmp_dir.SetCString(tmpdir_cstr);
1246 if (log)
1247 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1248 }
1249 }
1250 file_spec.GetDirectory() = g_lldb_tmp_dir;
1251 return (bool)file_spec.GetDirectory();
1252 }
Greg Claytondd36def2010-10-17 22:03:32 +00001253 }
1254
1255 return false;
1256}
1257
Greg Clayton1cb64962011-03-24 04:28:38 +00001258
1259bool
1260Host::GetHostname (std::string &s)
1261{
1262 char hostname[PATH_MAX];
1263 hostname[sizeof(hostname) - 1] = '\0';
1264 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1265 {
1266 struct hostent* h = ::gethostbyname (hostname);
1267 if (h)
1268 s.assign (h->h_name);
1269 else
1270 s.assign (hostname);
1271 return true;
1272 }
1273 return false;
1274}
1275
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001276#ifndef _WIN32
1277
Greg Clayton32e0a752011-03-30 18:16:51 +00001278const char *
1279Host::GetUserName (uint32_t uid, std::string &user_name)
1280{
1281 struct passwd user_info;
1282 struct passwd *user_info_ptr = &user_info;
1283 char user_buffer[PATH_MAX];
1284 size_t user_buffer_size = sizeof(user_buffer);
1285 if (::getpwuid_r (uid,
1286 &user_info,
1287 user_buffer,
1288 user_buffer_size,
1289 &user_info_ptr) == 0)
1290 {
1291 if (user_info_ptr)
1292 {
1293 user_name.assign (user_info_ptr->pw_name);
1294 return user_name.c_str();
1295 }
1296 }
1297 user_name.clear();
1298 return NULL;
1299}
1300
1301const char *
1302Host::GetGroupName (uint32_t gid, std::string &group_name)
1303{
1304 char group_buffer[PATH_MAX];
1305 size_t group_buffer_size = sizeof(group_buffer);
1306 struct group group_info;
1307 struct group *group_info_ptr = &group_info;
1308 // Try the threadsafe version first
1309 if (::getgrgid_r (gid,
1310 &group_info,
1311 group_buffer,
1312 group_buffer_size,
1313 &group_info_ptr) == 0)
1314 {
1315 if (group_info_ptr)
1316 {
1317 group_name.assign (group_info_ptr->gr_name);
1318 return group_name.c_str();
1319 }
1320 }
1321 else
1322 {
1323 // The threadsafe version isn't currently working
1324 // for me on darwin, but the non-threadsafe version
1325 // is, so I am calling it below.
1326 group_info_ptr = ::getgrgid (gid);
1327 if (group_info_ptr)
1328 {
1329 group_name.assign (group_info_ptr->gr_name);
1330 return group_name.c_str();
1331 }
1332 }
1333 group_name.clear();
1334 return NULL;
1335}
1336
Han Ming Ong84647042012-02-25 01:07:38 +00001337uint32_t
1338Host::GetUserID ()
1339{
1340 return getuid();
1341}
1342
1343uint32_t
1344Host::GetGroupID ()
1345{
1346 return getgid();
1347}
1348
1349uint32_t
1350Host::GetEffectiveUserID ()
1351{
1352 return geteuid();
1353}
1354
1355uint32_t
1356Host::GetEffectiveGroupID ()
1357{
1358 return getegid();
1359}
1360
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001361#endif
1362
1363#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1364bool
1365Host::GetOSBuildString (std::string &s)
1366{
1367 s.clear();
1368 return false;
1369}
1370
1371bool
1372Host::GetOSKernelDescription (std::string &s)
1373{
1374 s.clear();
1375 return false;
1376}
1377#endif
1378
Ed Maste47e575e2013-08-29 18:44:27 +00001379#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001380uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001381Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001382{
1383 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001384 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001385}
1386
Greg Claytone996fd32011-03-08 22:40:15 +00001387bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001388Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001389{
Greg Claytone996fd32011-03-08 22:40:15 +00001390 process_info.Clear();
1391 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001392}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001393#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001394
Matt Kopec085d6ce2013-05-31 22:00:07 +00001395#if !defined(__linux__)
1396bool
1397Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1398{
1399 return false;
1400}
1401#endif
1402
Sean Callananc0a6e062011-10-27 21:22:25 +00001403lldb::TargetSP
1404Host::GetDummyTarget (lldb_private::Debugger &debugger)
1405{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001406 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001407
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001408 // FIXME: Maybe the dummy target should be per-Debugger
1409 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1410 {
1411 ArchSpec arch(Target::GetDefaultArchitecture());
1412 if (!arch.IsValid())
1413 arch = Host::GetArchitecture ();
1414 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001415 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001416 arch.GetTriple().getTriple().c_str(),
1417 false,
1418 NULL,
1419 g_dummy_target_sp);
1420 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001421
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001422 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001423}
1424
Greg Claytond1cf11a2012-04-14 01:42:46 +00001425struct ShellInfo
1426{
1427 ShellInfo () :
1428 process_reaped (false),
1429 can_delete (false),
1430 pid (LLDB_INVALID_PROCESS_ID),
1431 signo(-1),
1432 status(-1)
1433 {
1434 }
1435
1436 lldb_private::Predicate<bool> process_reaped;
1437 lldb_private::Predicate<bool> can_delete;
1438 lldb::pid_t pid;
1439 int signo;
1440 int status;
1441};
1442
1443static bool
1444MonitorShellCommand (void *callback_baton,
1445 lldb::pid_t pid,
1446 bool exited, // True if the process did exit
1447 int signo, // Zero for no signal
1448 int status) // Exit value of process if signal is zero
1449{
1450 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1451 shell_info->pid = pid;
1452 shell_info->signo = signo;
1453 shell_info->status = status;
1454 // Let the thread running Host::RunShellCommand() know that the process
1455 // exited and that ShellInfo has been filled in by broadcasting to it
1456 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1457 // Now wait for a handshake back from that thread running Host::RunShellCommand
1458 // so we know that we can delete shell_info_ptr
1459 shell_info->can_delete.WaitForValueEqualTo(true);
1460 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1461 usleep(1000);
1462 // Now delete the shell info that was passed into this function
1463 delete shell_info;
1464 return true;
1465}
1466
1467Error
1468Host::RunShellCommand (const char *command,
1469 const char *working_dir,
1470 int *status_ptr,
1471 int *signo_ptr,
1472 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001473 uint32_t timeout_sec,
1474 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001475{
1476 Error error;
1477 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001478 if (shell && shell[0])
1479 {
1480 // Run the command in a shell
1481 launch_info.SetShell(shell);
1482 launch_info.GetArguments().AppendArgument(command);
1483 const bool localhost = true;
1484 const bool will_debug = false;
1485 const bool first_arg_is_full_shell_command = true;
1486 launch_info.ConvertArgumentsForLaunchingInShell (error,
1487 localhost,
1488 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001489 first_arg_is_full_shell_command,
1490 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001491 }
1492 else
1493 {
1494 // No shell, just run it
1495 Args args (command);
1496 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001497 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001498 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001499
1500 if (working_dir)
1501 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001502 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001503 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001504
Greg Claytond1cf11a2012-04-14 01:42:46 +00001505 if (command_output_ptr)
1506 {
1507 // Create a temporary file to get the stdout/stderr and redirect the
1508 // output of the command into this file. We will later read this file
1509 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001510 FileSpec tmpdir_file_spec;
1511 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1512 {
1513 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1514 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1515 }
1516 else
1517 {
1518 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1519 }
1520
1521 output_file_path = ::mktemp(output_file_path_buffer);
1522 }
1523
1524 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1525 if (output_file_path)
1526 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001527 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001528 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001529 }
1530 else
1531 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001532 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1533 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1534 }
1535
1536 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001537 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001538
1539 const bool monitor_signals = false;
1540 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1541
1542 error = LaunchProcess (launch_info);
1543 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001544
1545 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1546 error.SetErrorString("failed to get process ID");
1547
1548 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001549 {
1550 // The process successfully launched, so we can defer ownership of
1551 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001552 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001553 // doesn't need to delete the ShellInfo anymore.
1554 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001555 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001556 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001557 if (timeout_sec > 0) {
1558 timeout_time.OffsetWithSeconds(timeout_sec);
1559 timeout_ptr = &timeout_time;
1560 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001561 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001562 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001563 if (timed_out)
1564 {
1565 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001566
Greg Claytond1cf11a2012-04-14 01:42:46 +00001567 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001568 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001569 // Wait for the monitor callback to get the message
1570 timeout_time = TimeValue::Now();
1571 timeout_time.OffsetWithSeconds(1);
1572 timed_out = false;
1573 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1574 }
1575 else
1576 {
1577 if (status_ptr)
1578 *status_ptr = shell_info->status;
1579
1580 if (signo_ptr)
1581 *signo_ptr = shell_info->signo;
1582
1583 if (command_output_ptr)
1584 {
1585 command_output_ptr->clear();
1586 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1587 uint64_t file_size = file_spec.GetByteSize();
1588 if (file_size > 0)
1589 {
1590 if (file_size > command_output_ptr->max_size())
1591 {
1592 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1593 }
1594 else
1595 {
1596 command_output_ptr->resize(file_size);
1597 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1598 }
1599 }
1600 }
1601 }
1602 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1603 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001604
1605 if (output_file_path)
1606 ::unlink (output_file_path);
1607 // Handshake with the monitor thread, or just let it know in advance that
1608 // it can delete "shell_info" in case we timed out and were not able to kill
1609 // the process...
1610 return error;
1611}
1612
Ed Maste991fe6c2013-12-09 01:35:42 +00001613#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001614// The functions below implement process launching via posix_spawn() for Linux
1615// and FreeBSD.
1616
1617// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1618static Error
1619LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1620{
1621 Error error;
1622 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1623
1624 assert(exe_path);
1625 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1626
1627 posix_spawnattr_t attr;
1628
1629 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1630 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1631 if (error.Fail())
1632 return error;
1633
1634 // Make a quick class that will cleanup the posix spawn attributes in case
1635 // we return in the middle of this function.
1636 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1637
1638 sigset_t no_signals;
1639 sigset_t all_signals;
1640 sigemptyset (&no_signals);
1641 sigfillset (&all_signals);
1642 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1643 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1644
1645 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1646
1647 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1648 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1649 if (error.Fail())
1650 return error;
1651
1652 const size_t num_file_actions = launch_info.GetNumFileActions ();
1653 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1654 // Make a quick class that will cleanup the posix spawn attributes in case
1655 // we return in the middle of this function.
1656 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1657 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1658
1659 if (num_file_actions > 0)
1660 {
1661 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1662 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1663 if (error.Fail())
1664 return error;
1665
1666 file_action_ptr = &file_actions;
1667 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1668
1669 for (size_t i = 0; i < num_file_actions; ++i)
1670 {
1671 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1672 if (launch_file_action &&
1673 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1674 launch_file_action,
1675 log,
1676 error))
1677 return error;
1678 }
1679 }
1680
1681 // Change working directory if neccessary.
1682 char current_dir[PATH_MAX];
1683 current_dir[0] = '\0';
1684
1685 const char *working_dir = launch_info.GetWorkingDirectory();
1686 if (working_dir != NULL)
1687 {
1688 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1689 {
1690 error.SetError(errno, eErrorTypePOSIX);
1691 error.LogIfError(log, "unable to save the current directory");
1692 return error;
1693 }
1694
1695 if (::chdir(working_dir) == -1)
1696 {
1697 error.SetError(errno, eErrorTypePOSIX);
1698 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1699 return error;
1700 }
1701 }
1702
1703 const char *tmp_argv[2];
1704 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1705 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1706
1707 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1708 // We must pass argv into posix_spawnp and it must contain at least two items -
1709 // pointer to an executable and NULL.
1710 if (argv == NULL)
1711 {
1712 tmp_argv[0] = exe_path;
1713 tmp_argv[1] = NULL;
1714 argv = (char * const*)tmp_argv;
1715 }
1716
1717 error.SetError (::posix_spawnp (&pid,
1718 exe_path,
1719 (num_file_actions > 0) ? &file_actions : NULL,
1720 &attr,
1721 argv,
1722 envp),
1723 eErrorTypePOSIX);
1724
1725 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1726 pid, exe_path, file_action_ptr, &attr, argv, envp);
1727
1728 // Change back the current directory.
1729 // NOTE: do not override previously established error from posix_spawnp.
1730 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1731 {
1732 error.SetError(errno, eErrorTypePOSIX);
1733 error.LogIfError(log, "unable to change current directory back to %s",
1734 current_dir);
1735 }
1736
1737 return error;
1738}
1739
1740
1741Error
1742Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1743{
1744 Error error;
1745 char exe_path[PATH_MAX];
1746
1747 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1748
1749 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1750
1751 FileSpec exe_spec(launch_info.GetExecutableFile());
1752
1753 FileSpec::FileType file_type = exe_spec.GetFileType();
1754 if (file_type != FileSpec::eFileTypeRegular)
1755 {
1756 lldb::ModuleSP exe_module_sp;
1757 error = host_platform_sp->ResolveExecutable (exe_spec,
1758 arch_spec,
1759 exe_module_sp,
1760 NULL);
1761
1762 if (error.Fail())
1763 return error;
1764
1765 if (exe_module_sp)
1766 exe_spec = exe_module_sp->GetFileSpec();
1767 }
1768
1769 if (exe_spec.Exists())
1770 {
1771 exe_spec.GetPath (exe_path, sizeof(exe_path));
1772 }
1773 else
1774 {
1775 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1776 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1777 return error;
1778 }
1779
1780 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1781
1782 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1783
1784 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1785
1786 if (pid != LLDB_INVALID_PROCESS_ID)
1787 {
1788 // If all went well, then set the process ID into the launch info
1789 launch_info.SetProcessID(pid);
1790
1791 // Make sure we reap any processes we spawn or we will have zombies.
1792 if (!launch_info.MonitorProcess())
1793 {
1794 const bool monitor_signals = false;
1795 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1796 NULL,
1797 pid,
1798 monitor_signals);
1799 }
1800 }
1801 else
1802 {
1803 // Invalid process ID, something didn't go well
1804 if (error.Success())
1805 error.SetErrorString ("process launch failed for unknown reasons");
1806 }
1807 return error;
1808}
1809
1810#endif // defined(__linux__) or defined(__FreeBSD__)
1811
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001812#ifndef _WIN32
1813
1814size_t
1815Host::GetPageSize()
1816{
1817 return ::getpagesize();
1818}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001819
Greg Claytone3e3fee2013-02-17 20:46:30 +00001820uint32_t
1821Host::GetNumberCPUS ()
1822{
1823 static uint32_t g_num_cores = UINT32_MAX;
1824 if (g_num_cores == UINT32_MAX)
1825 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001826#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001827
1828 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001829
Greg Claytone3e3fee2013-02-17 20:46:30 +00001830#else
1831
1832 // Assume POSIX support if a host specific case has not been supplied above
1833 g_num_cores = 0;
1834 int num_cores = 0;
1835 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001836#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001837 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001838#else
1839 int mib[] = { CTL_HW, HW_NCPU };
1840#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001841
1842 /* get the number of CPUs from the system */
1843 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1844 {
1845 g_num_cores = num_cores;
1846 }
1847 else
1848 {
1849 mib[1] = HW_NCPU;
1850 num_cores_len = sizeof(num_cores);
1851 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1852 {
1853 if (num_cores > 0)
1854 g_num_cores = num_cores;
1855 }
1856 }
1857#endif
1858 }
1859 return g_num_cores;
1860}
1861
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001862void
1863Host::Kill(lldb::pid_t pid, int signo)
1864{
1865 ::kill(pid, signo);
1866}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001867
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001868#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001869
Johnny Chen8f3d8382011-08-02 20:52:42 +00001870#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001871bool
Greg Clayton3b147632010-12-18 01:54:34 +00001872Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001873{
1874 return false;
1875}
Greg Claytondd36def2010-10-17 22:03:32 +00001876
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001877void
1878Host::SetCrashDescriptionWithFormat (const char *format, ...)
1879{
1880}
1881
1882void
1883Host::SetCrashDescription (const char *description)
1884{
1885}
Greg Claytondd36def2010-10-17 22:03:32 +00001886
1887lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001888Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001889{
1890 return LLDB_INVALID_PROCESS_ID;
1891}
1892
Greg Claytonfbb76342013-11-20 21:07:01 +00001893#endif
1894
1895
1896#ifdef LLDB_DISABLE_POSIX
1897
1898Error
1899Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001900{
Greg Claytonfbb76342013-11-20 21:07:01 +00001901 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001902 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001903 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001904}
Greg Claytonfbb76342013-11-20 21:07:01 +00001905
1906Error
1907Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1908{
1909 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001910 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001911 return error;
1912}
1913
1914Error
1915Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1916{
1917 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001918 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001919 return error;
1920}
1921
1922Error
1923Host::Symlink (const char *src, const char *dst)
1924{
1925 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001926 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001927 return error;
1928}
1929
1930Error
1931Host::Readlink (const char *path, char *buf, size_t buf_len)
1932{
1933 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001934 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001935 return error;
1936}
1937
1938Error
1939Host::Unlink (const char *path)
1940{
1941 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001942 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001943 return error;
1944}
1945
1946#else
1947
1948Error
1949Host::MakeDirectory (const char* path, uint32_t file_permissions)
1950{
1951 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00001952 if (path && path[0])
1953 {
Greg Claytonfb909312013-11-23 01:58:15 +00001954 if (::mkdir(path, file_permissions) != 0)
1955 {
1956 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001957 switch (error.GetError())
1958 {
1959 case ENOENT:
1960 {
1961 // Parent directory doesn't exist, so lets make it if we can
1962 FileSpec spec(path, false);
1963 if (spec.GetDirectory() && spec.GetFilename())
1964 {
1965 // Make the parent directory and try again
1966 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
1967 if (error2.Success())
1968 {
1969 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00001970 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00001971 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00001972 else
Greg Claytonfb909312013-11-23 01:58:15 +00001973 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001974 }
1975 }
1976 }
1977 break;
1978 case EEXIST:
1979 {
1980 FileSpec path_spec(path, false);
1981 if (path_spec.IsDirectory())
1982 error.Clear(); // It is a directory and it already exists
1983 }
1984 break;
1985 }
1986 }
Greg Claytonfb909312013-11-23 01:58:15 +00001987 }
1988 else
1989 {
1990 error.SetErrorString("empty path");
1991 }
Greg Claytonfbb76342013-11-20 21:07:01 +00001992 return error;
1993}
1994
1995Error
1996Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1997{
1998 Error error;
1999 struct stat file_stats;
2000 if (::stat (path, &file_stats) == 0)
2001 {
2002 // The bits in "st_mode" currently match the definitions
2003 // for the file mode bits in unix.
2004 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2005 }
2006 else
2007 {
2008 error.SetErrorToErrno();
2009 }
2010 return error;
2011}
2012
2013Error
2014Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2015{
2016 Error error;
2017 if (::chmod(path, file_permissions) != 0)
2018 error.SetErrorToErrno();
2019 return error;
2020}
2021
2022Error
2023Host::Symlink (const char *src, const char *dst)
2024{
2025 Error error;
2026 if (::symlink(dst, src) == -1)
2027 error.SetErrorToErrno();
2028 return error;
2029}
2030
2031Error
2032Host::Unlink (const char *path)
2033{
2034 Error error;
2035 if (::unlink(path) == -1)
2036 error.SetErrorToErrno();
2037 return error;
2038}
2039
2040Error
2041Host::Readlink (const char *path, char *buf, size_t buf_len)
2042{
2043 Error error;
2044 ssize_t count = ::readlink(path, buf, buf_len);
2045 if (count < 0)
2046 error.SetErrorToErrno();
2047 else if (count < (buf_len-1))
2048 buf[count] = '\0'; // Success
2049 else
2050 error.SetErrorString("'buf' buffer is too small to contain link contents");
2051 return error;
2052}
2053
2054
Greg Clayton2bddd342010-09-07 20:11:56 +00002055#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002056
2057typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2058FDToFileMap& GetFDToFileMap()
2059{
2060 static FDToFileMap g_fd2filemap;
2061 return g_fd2filemap;
2062}
2063
2064lldb::user_id_t
2065Host::OpenFile (const FileSpec& file_spec,
2066 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002067 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002068 Error &error)
2069{
2070 std::string path (file_spec.GetPath());
2071 if (path.empty())
2072 {
2073 error.SetErrorString("empty path");
2074 return UINT64_MAX;
2075 }
2076 FileSP file_sp(new File());
2077 error = file_sp->Open(path.c_str(),flags,mode);
2078 if (file_sp->IsValid() == false)
2079 return UINT64_MAX;
2080 lldb::user_id_t fd = file_sp->GetDescriptor();
2081 GetFDToFileMap()[fd] = file_sp;
2082 return fd;
2083}
2084
2085bool
2086Host::CloseFile (lldb::user_id_t fd, Error &error)
2087{
2088 if (fd == UINT64_MAX)
2089 {
2090 error.SetErrorString ("invalid file descriptor");
2091 return false;
2092 }
2093 FDToFileMap& file_map = GetFDToFileMap();
2094 FDToFileMap::iterator pos = file_map.find(fd);
2095 if (pos == file_map.end())
2096 {
2097 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2098 return false;
2099 }
2100 FileSP file_sp = pos->second;
2101 if (!file_sp)
2102 {
2103 error.SetErrorString ("invalid host backing file");
2104 return false;
2105 }
2106 error = file_sp->Close();
2107 file_map.erase(pos);
2108 return error.Success();
2109}
2110
2111uint64_t
2112Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2113{
2114 if (fd == UINT64_MAX)
2115 {
2116 error.SetErrorString ("invalid file descriptor");
2117 return UINT64_MAX;
2118 }
2119 FDToFileMap& file_map = GetFDToFileMap();
2120 FDToFileMap::iterator pos = file_map.find(fd);
2121 if (pos == file_map.end())
2122 {
2123 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2124 return false;
2125 }
2126 FileSP file_sp = pos->second;
2127 if (!file_sp)
2128 {
2129 error.SetErrorString ("invalid host backing file");
2130 return UINT64_MAX;
2131 }
2132 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2133 return UINT64_MAX;
2134 size_t bytes_written = src_len;
2135 error = file_sp->Write(src, bytes_written);
2136 if (error.Fail())
2137 return UINT64_MAX;
2138 return bytes_written;
2139}
2140
2141uint64_t
2142Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2143{
2144 if (fd == UINT64_MAX)
2145 {
2146 error.SetErrorString ("invalid file descriptor");
2147 return UINT64_MAX;
2148 }
2149 FDToFileMap& file_map = GetFDToFileMap();
2150 FDToFileMap::iterator pos = file_map.find(fd);
2151 if (pos == file_map.end())
2152 {
2153 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2154 return false;
2155 }
2156 FileSP file_sp = pos->second;
2157 if (!file_sp)
2158 {
2159 error.SetErrorString ("invalid host backing file");
2160 return UINT64_MAX;
2161 }
2162 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2163 return UINT64_MAX;
2164 size_t bytes_read = dst_len;
2165 error = file_sp->Read(dst ,bytes_read);
2166 if (error.Fail())
2167 return UINT64_MAX;
2168 return bytes_read;
2169}
2170
2171lldb::user_id_t
2172Host::GetFileSize (const FileSpec& file_spec)
2173{
2174 return file_spec.GetByteSize();
2175}
2176
2177bool
2178Host::GetFileExists (const FileSpec& file_spec)
2179{
2180 return file_spec.Exists();
2181}
2182
2183bool
2184Host::CalculateMD5 (const FileSpec& file_spec,
2185 uint64_t &low,
2186 uint64_t &high)
2187{
2188#if defined (__APPLE__)
2189 StreamString md5_cmd_line;
2190 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2191 std::string hash_string;
2192 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2193 if (err.Fail())
2194 return false;
2195 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2196 // if the output is any other length it is probably wrong
2197 if (hash_string.size() != 32)
2198 return false;
2199 std::string part1(hash_string,0,16);
2200 std::string part2(hash_string,16);
2201 const char* part1_cstr = part1.c_str();
2202 const char* part2_cstr = part2.c_str();
2203 high = ::strtoull(part1_cstr, NULL, 16);
2204 low = ::strtoull(part2_cstr, NULL, 16);
2205 return true;
2206#else
2207 // your own MD5 implementation here
2208 return false;
2209#endif
2210}