blob: a2d8e9cfa100620bc28ac13584ae03e4d2004df4 [file] [log] [blame]
Greg Clayton2bddd342010-09-07 20:11:56 +00001//===-- Host.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Greg Claytone3e3fee2013-02-17 20:46:30 +000012// C includes
Greg Claytone3e3fee2013-02-17 20:46:30 +000013#include <errno.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000014#include <limits.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000015#include <sys/types.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#ifdef _WIN32
17#include "lldb/Host/windows/windows.h"
18#include <winsock2.h>
19#include <WS2tcpip.h>
20#else
Deepak Panickalb36da432014-01-13 14:55:15 +000021#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000022#include <dlfcn.h>
23#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000024#include <netdb.h>
25#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000026#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000027#endif
28
29#if !defined (__GNU__) && !defined (_WIN32)
30// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000031#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000032#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000033
34#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000035#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000036#include <mach/mach_init.h>
37#include <mach-o/dyld.h>
Jim Ingham1a7ee702013-11-22 00:51:36 +000038#include <AvailabilityMacros.h>
Ed Maste8b006c62013-06-25 18:58:11 +000039#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000040
Ed Maste8b006c62013-06-25 18:58:11 +000041#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000042#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000043#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000044#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000045#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000046
Ed Maste8b006c62013-06-25 18:58:11 +000047#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000048#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#endif
50
Greg Clayton2bddd342010-09-07 20:11:56 +000051#include "lldb/Host/Host.h"
52#include "lldb/Core/ArchSpec.h"
53#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000054#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000055#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000057#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000059#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000060#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000061#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000062#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000064#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000065#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000066#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000067
Daniel Maleafa7425d2013-08-06 21:40:08 +000068#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000069#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000070#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000071
Greg Clayton32e0a752011-03-30 18:16:51 +000072
Greg Clayton2bddd342010-09-07 20:11:56 +000073using namespace lldb;
74using namespace lldb_private;
75
Greg Claytone4e45922011-11-16 05:37:56 +000076
Virgile Bellob2f1fb22013-08-23 12:44:05 +000077#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000078struct MonitorInfo
79{
80 lldb::pid_t pid; // The process ID to monitor
81 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
82 void *callback_baton; // The callback baton for the callback function
83 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
84};
85
Virgile Bellob2f1fb22013-08-23 12:44:05 +000086static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000087MonitorChildProcessThreadFunction (void *arg);
88
89lldb::thread_t
90Host::StartMonitoringChildProcess
91(
92 Host::MonitorChildProcessCallback callback,
93 void *callback_baton,
94 lldb::pid_t pid,
95 bool monitor_signals
96)
97{
98 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +000099 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000100
Greg Claytone4e45922011-11-16 05:37:56 +0000101 info_ptr->pid = pid;
102 info_ptr->callback = callback;
103 info_ptr->callback_baton = callback_baton;
104 info_ptr->monitor_signals = monitor_signals;
105
106 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000107 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000108 thread = ThreadCreate (thread_name,
109 MonitorChildProcessThreadFunction,
110 info_ptr,
111 NULL);
112
Greg Clayton2bddd342010-09-07 20:11:56 +0000113 return thread;
114}
115
116//------------------------------------------------------------------
117// Scoped class that will disable thread canceling when it is
118// constructed, and exception safely restore the previous value it
119// when it goes out of scope.
120//------------------------------------------------------------------
121class ScopedPThreadCancelDisabler
122{
123public:
124 ScopedPThreadCancelDisabler()
125 {
126 // Disable the ability for this thread to be cancelled
127 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
128 if (err != 0)
129 m_old_state = -1;
130
131 }
132
133 ~ScopedPThreadCancelDisabler()
134 {
135 // Restore the ability for this thread to be cancelled to what it
136 // previously was.
137 if (m_old_state != -1)
138 ::pthread_setcancelstate (m_old_state, 0);
139 }
140private:
141 int m_old_state; // Save the old cancelability state.
142};
143
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000144static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000145MonitorChildProcessThreadFunction (void *arg)
146{
Greg Clayton5160ce52013-03-27 23:08:40 +0000147 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000148 const char *function = __FUNCTION__;
149 if (log)
150 log->Printf ("%s (arg = %p) thread starting...", function, arg);
151
152 MonitorInfo *info = (MonitorInfo *)arg;
153
154 const Host::MonitorChildProcessCallback callback = info->callback;
155 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000156 const bool monitor_signals = info->monitor_signals;
157
Daniel Malea4244cbd2013-08-27 20:58:59 +0000158 assert (info->pid <= UINT32_MAX);
159 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
160
Greg Clayton2bddd342010-09-07 20:11:56 +0000161 delete info;
162
163 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000164#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000165 #define __WALL 0
166#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000167 const int options = __WALL;
168
Greg Clayton2bddd342010-09-07 20:11:56 +0000169 while (1)
170 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000171 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000172 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000173 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000174
175 // Wait for all child processes
176 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000177 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000178 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000179 ::pthread_testcancel ();
180
181 if (wait_pid == -1)
182 {
183 if (errno == EINTR)
184 continue;
185 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000186 {
187 if (log)
188 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000189 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000190 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000191 }
Matt Kopec650648f2013-01-08 16:30:18 +0000192 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000193 {
194 bool exited = false;
195 int signal = 0;
196 int exit_status = 0;
197 const char *status_cstr = NULL;
198 if (WIFSTOPPED(status))
199 {
200 signal = WSTOPSIG(status);
201 status_cstr = "STOPPED";
202 }
203 else if (WIFEXITED(status))
204 {
205 exit_status = WEXITSTATUS(status);
206 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000207 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000208 }
209 else if (WIFSIGNALED(status))
210 {
211 signal = WTERMSIG(status);
212 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000213 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000214 exited = true;
215 exit_status = -1;
216 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000217 }
218 else
219 {
Johnny Chen44805302011-07-19 19:48:13 +0000220 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000221 }
222
223 // Scope for pthread_cancel_disabler
224 {
225 ScopedPThreadCancelDisabler pthread_cancel_disabler;
226
Caroline Tice20ad3c42010-10-29 21:48:37 +0000227 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000228 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000229 log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Greg Clayton2bddd342010-09-07 20:11:56 +0000230 function,
231 wait_pid,
232 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000233 pid,
234 status,
235 status_cstr,
236 signal,
237 exit_status);
238
239 if (exited || (signal != 0 && monitor_signals))
240 {
Greg Claytone4e45922011-11-16 05:37:56 +0000241 bool callback_return = false;
242 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000243 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000244
245 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000246 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000247 {
248 if (log)
249 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000250 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000251 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000252 // If the callback returns true, it means this process should
253 // exit
254 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000255 {
256 if (log)
257 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000259 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000260 }
261 }
262 }
263 }
264
Caroline Tice20ad3c42010-10-29 21:48:37 +0000265 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000266 if (log)
267 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
268
269 return NULL;
270}
271
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000272#endif // #if !defined (__APPLE__) && !defined (_WIN32)
273
274#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000275
276void
277Host::SystemLog (SystemLogType type, const char *format, va_list args)
278{
279 vfprintf (stderr, format, args);
280}
281
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000282#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000283
Greg Claytone38a5ed2012-01-05 03:57:59 +0000284void
285Host::SystemLog (SystemLogType type, const char *format, ...)
286{
287 va_list args;
288 va_start (args, format);
289 SystemLog (type, format, args);
290 va_end (args);
291}
292
Greg Clayton2bddd342010-09-07 20:11:56 +0000293const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000294Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000295{
Greg Clayton514487e2011-02-15 21:59:32 +0000296 static bool g_supports_32 = false;
297 static bool g_supports_64 = false;
298 static ArchSpec g_host_arch_32;
299 static ArchSpec g_host_arch_64;
300
Greg Clayton2bddd342010-09-07 20:11:56 +0000301#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000302
303 // Apple is different in that it can support both 32 and 64 bit executables
304 // in the same operating system running concurrently. Here we detect the
305 // correct host architectures for both 32 and 64 bit including if 64 bit
306 // executables are supported on the system.
307
308 if (g_supports_32 == false && g_supports_64 == false)
309 {
310 // All apple systems support 32 bit execution.
311 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000312 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000313 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000314 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000315 ArchSpec host_arch;
316 // These will tell us about the kernel architecture, which even on a 64
317 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000318 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
319 {
Greg Clayton514487e2011-02-15 21:59:32 +0000320 len = sizeof (cpusubtype);
321 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
322 cpusubtype = CPU_TYPE_ANY;
323
Greg Clayton2bddd342010-09-07 20:11:56 +0000324 len = sizeof (is_64_bit_capable);
325 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
326 {
327 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000328 g_supports_64 = true;
329 }
330
331 if (is_64_bit_capable)
332 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000333#if defined (__i386__) || defined (__x86_64__)
334 if (cpusubtype == CPU_SUBTYPE_486)
335 cpusubtype = CPU_SUBTYPE_I386_ALL;
336#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000337 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000338 {
Greg Clayton514487e2011-02-15 21:59:32 +0000339 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000340 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
341 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000342 }
343 else
344 {
345 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000346 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000347 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000348 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000349 }
350 }
Greg Clayton514487e2011-02-15 21:59:32 +0000351 else
352 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000353 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000354 g_host_arch_64.Clear();
355 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000356 }
Greg Clayton514487e2011-02-15 21:59:32 +0000357 }
358
359#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000360
Greg Clayton514487e2011-02-15 21:59:32 +0000361 if (g_supports_32 == false && g_supports_64 == false)
362 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000363 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000364
Stephen Wilsonbd588712011-02-24 19:15:09 +0000365 g_host_arch_32.Clear();
366 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000367
Greg Claytonb29e6c62012-10-11 17:38:58 +0000368 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
369 // for the default triple. It's probably an artifact of config.guess.
370 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000371 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000372
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000373 const char* distribution_id = GetDistributionId ().AsCString();
374
Stephen Wilsonbd588712011-02-24 19:15:09 +0000375 switch (triple.getArch())
376 {
377 default:
378 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000379 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000380 g_supports_32 = true;
381 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000382
Stephen Wilsonbd588712011-02-24 19:15:09 +0000383 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000384 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000385 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000386 g_supports_64 = true;
387 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000388 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000389 g_supports_32 = true;
390 break;
391
Stephen Wilsonbd588712011-02-24 19:15:09 +0000392 case llvm::Triple::sparcv9:
393 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000394 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000395 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000396 g_supports_64 = true;
397 break;
398 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000399
400 g_supports_32 = g_host_arch_32.IsValid();
401 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000402 }
Greg Clayton514487e2011-02-15 21:59:32 +0000403
404#endif // #else for #if defined (__APPLE__)
405
406 if (arch_kind == eSystemDefaultArchitecture32)
407 return g_host_arch_32;
408 else if (arch_kind == eSystemDefaultArchitecture64)
409 return g_host_arch_64;
410
411 if (g_supports_64)
412 return g_host_arch_64;
413
414 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000415}
416
417const ConstString &
418Host::GetVendorString()
419{
420 static ConstString g_vendor;
421 if (!g_vendor)
422 {
Greg Clayton950971f2012-05-12 00:01:21 +0000423 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
424 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
425 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000426 }
427 return g_vendor;
428}
429
430const ConstString &
431Host::GetOSString()
432{
433 static ConstString g_os_string;
434 if (!g_os_string)
435 {
Greg Clayton950971f2012-05-12 00:01:21 +0000436 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
437 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
438 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000439 }
440 return g_os_string;
441}
442
443const ConstString &
444Host::GetTargetTriple()
445{
446 static ConstString g_host_triple;
447 if (!(g_host_triple))
448 {
Greg Clayton950971f2012-05-12 00:01:21 +0000449 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
450 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000451 }
452 return g_host_triple;
453}
454
Todd Fialaf3d61de2014-01-17 20:18:59 +0000455// See linux/Host.cpp for Linux-based implementations of this.
456// Add your platform-specific implementation to the appropriate host file.
457#if !defined(__linux__)
458
459const ConstString &
460 Host::GetDistributionId ()
461{
462 static ConstString s_distribution_id;
463 return s_distribution_id;
464}
465
466#endif // #if !defined(__linux__)
467
Greg Clayton2bddd342010-09-07 20:11:56 +0000468lldb::pid_t
469Host::GetCurrentProcessID()
470{
471 return ::getpid();
472}
473
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000474#ifndef _WIN32
475
Greg Clayton2bddd342010-09-07 20:11:56 +0000476lldb::tid_t
477Host::GetCurrentThreadID()
478{
479#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000480 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000481 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
482 // count.
483 thread_port_t thread_self = mach_thread_self();
484 mach_port_deallocate(mach_task_self(), thread_self);
485 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000486#elif defined(__FreeBSD__)
487 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000488#elif defined(__linux__)
489 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000490#else
491 return lldb::tid_t(pthread_self());
492#endif
493}
494
Jim Ingham372787f2012-04-07 00:00:41 +0000495lldb::thread_t
496Host::GetCurrentThread ()
497{
498 return lldb::thread_t(pthread_self());
499}
500
Greg Clayton2bddd342010-09-07 20:11:56 +0000501const char *
502Host::GetSignalAsCString (int signo)
503{
504 switch (signo)
505 {
506 case SIGHUP: return "SIGHUP"; // 1 hangup
507 case SIGINT: return "SIGINT"; // 2 interrupt
508 case SIGQUIT: return "SIGQUIT"; // 3 quit
509 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
510 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
511 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000512#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000513#if !defined(SIGIO) || (SIGPOLL != SIGIO)
514// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
515// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000516 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000517#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000518#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000519#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000520 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000521#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000522 case SIGFPE: return "SIGFPE"; // 8 floating point exception
523 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
524 case SIGBUS: return "SIGBUS"; // 10 bus error
525 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
526 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
527 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
528 case SIGALRM: return "SIGALRM"; // 14 alarm clock
529 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
530 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
531 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
532 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
533 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
534 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
535 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
536 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000537#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000538 case SIGIO: return "SIGIO"; // 23 input/output possible signal
539#endif
540 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
541 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
542 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
543 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000544#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000545 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000546#endif
547#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000548 case SIGINFO: return "SIGINFO"; // 29 information request
549#endif
550 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
551 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
552 default:
553 break;
554 }
555 return NULL;
556}
557
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000558#endif
559
Greg Clayton2bddd342010-09-07 20:11:56 +0000560void
561Host::WillTerminate ()
562{
563}
564
Sylvestre Ledru59405832013-07-01 08:21:36 +0000565#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000566
Greg Clayton2bddd342010-09-07 20:11:56 +0000567void
568Host::ThreadCreated (const char *thread_name)
569{
570}
Greg Claytone5219662010-12-03 06:02:24 +0000571
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000572void
Greg Claytone5219662010-12-03 06:02:24 +0000573Host::Backtrace (Stream &strm, uint32_t max_frames)
574{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000575 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000576}
577
Greg Clayton85851dd2010-12-04 00:10:17 +0000578size_t
579Host::GetEnvironment (StringList &env)
580{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000581 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000582 return 0;
583}
584
Sylvestre Ledru59405832013-07-01 08:21:36 +0000585#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000586
587struct HostThreadCreateInfo
588{
589 std::string thread_name;
590 thread_func_t thread_fptr;
591 thread_arg_t thread_arg;
592
593 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
594 thread_name (name ? name : ""),
595 thread_fptr (fptr),
596 thread_arg (arg)
597 {
598 }
599};
600
601static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000602#ifdef _WIN32
603__stdcall
604#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000605ThreadCreateTrampoline (thread_arg_t arg)
606{
607 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
608 Host::ThreadCreated (info->thread_name.c_str());
609 thread_func_t thread_fptr = info->thread_fptr;
610 thread_arg_t thread_arg = info->thread_arg;
611
Greg Clayton5160ce52013-03-27 23:08:40 +0000612 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000613 if (log)
614 log->Printf("thread created");
615
616 delete info;
617 return thread_fptr (thread_arg);
618}
619
620lldb::thread_t
621Host::ThreadCreate
622(
623 const char *thread_name,
624 thread_func_t thread_fptr,
625 thread_arg_t thread_arg,
626 Error *error
627)
628{
629 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
630
631 // Host::ThreadCreateTrampoline will delete this pointer for us.
632 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
633
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000634#ifdef _WIN32
635 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
636 int err = thread <= 0 ? GetLastError() : 0;
637#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000638 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000639#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000640 if (err == 0)
641 {
642 if (error)
643 error->Clear();
644 return thread;
645 }
646
647 if (error)
648 error->SetError (err, eErrorTypePOSIX);
649
650 return LLDB_INVALID_HOST_THREAD;
651}
652
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000653#ifndef _WIN32
654
Greg Clayton2bddd342010-09-07 20:11:56 +0000655bool
656Host::ThreadCancel (lldb::thread_t thread, Error *error)
657{
658 int err = ::pthread_cancel (thread);
659 if (error)
660 error->SetError(err, eErrorTypePOSIX);
661 return err == 0;
662}
663
664bool
665Host::ThreadDetach (lldb::thread_t thread, Error *error)
666{
667 int err = ::pthread_detach (thread);
668 if (error)
669 error->SetError(err, eErrorTypePOSIX);
670 return err == 0;
671}
672
673bool
674Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
675{
676 int err = ::pthread_join (thread, thread_result_ptr);
677 if (error)
678 error->SetError(err, eErrorTypePOSIX);
679 return err == 0;
680}
681
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000682lldb::thread_key_t
683Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
684{
685 pthread_key_t key;
686 ::pthread_key_create (&key, callback);
687 return key;
688}
689
690void*
691Host::ThreadLocalStorageGet(lldb::thread_key_t key)
692{
693 return ::pthread_getspecific (key);
694}
695
696void
697Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
698{
699 ::pthread_setspecific (key, value);
700}
701
Matt Kopec62502c62013-05-13 19:33:58 +0000702bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000703Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
704{
Greg Clayton85719632013-02-27 22:51:58 +0000705#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000706 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
707 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
708 if (pid == LLDB_INVALID_PROCESS_ID)
709 pid = curr_pid;
710
711 if (tid == LLDB_INVALID_THREAD_ID)
712 tid = curr_tid;
713
Greg Clayton2bddd342010-09-07 20:11:56 +0000714 // Set the pthread name if possible
715 if (pid == curr_pid && tid == curr_tid)
716 {
Matt Kopec62502c62013-05-13 19:33:58 +0000717 if (::pthread_setname_np (name) == 0)
718 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000719 }
Matt Kopec62502c62013-05-13 19:33:58 +0000720 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000721#elif defined (__FreeBSD__)
722 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
723 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
724 if (pid == LLDB_INVALID_PROCESS_ID)
725 pid = curr_pid;
726
727 if (tid == LLDB_INVALID_THREAD_ID)
728 tid = curr_tid;
729
730 // Set the pthread name if possible
731 if (pid == curr_pid && tid == curr_tid)
732 {
Michael Sartainc2052432013-08-01 18:51:08 +0000733 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000734 return true;
735 }
736 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000737#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000738 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
739 if (fn)
740 {
Matt Kopec62502c62013-05-13 19:33:58 +0000741 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
742 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000743 if (pid == LLDB_INVALID_PROCESS_ID)
744 pid = curr_pid;
745
746 if (tid == LLDB_INVALID_THREAD_ID)
747 tid = curr_tid;
748
Michael Sartainc2052432013-08-01 18:51:08 +0000749 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000750 {
Michael Sartainc2052432013-08-01 18:51:08 +0000751 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
752 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
753
754 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000755 return true;
756 }
757 }
758 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000759#else
760 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000761#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000762}
763
Ed Maste02983be2013-07-25 19:10:32 +0000764bool
765Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
766 const char *thread_name, size_t len)
767{
768 char *namebuf = (char *)::malloc (len + 1);
769
770 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
771 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
772 // off leads to a lot of similar named threads. Go through the thread name
773 // and search for the last dot and use that.
774 const char *lastdot = ::strrchr (thread_name, '.');
775
776 if (lastdot && lastdot != thread_name)
777 thread_name = lastdot + 1;
778 ::strncpy (namebuf, thread_name, len);
779 namebuf[len] = 0;
780
781 int namebuflen = strlen(namebuf);
782 if (namebuflen > 0)
783 {
784 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
785 {
786 // Trim off trailing '(' and '>' characters for a bit more cleanup.
787 namebuflen--;
788 namebuf[namebuflen] = 0;
789 }
790 return Host::SetThreadName (pid, tid, namebuf);
791 }
Sylvestre Ledru6c9530b2013-09-28 15:50:23 +0000792
793 ::free(namebuf);
Ed Maste02983be2013-07-25 19:10:32 +0000794 return false;
795}
796
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000797#endif
798
Greg Clayton2bddd342010-09-07 20:11:56 +0000799FileSpec
800Host::GetProgramFileSpec ()
801{
802 static FileSpec g_program_filespec;
803 if (!g_program_filespec)
804 {
805#if defined (__APPLE__)
806 char program_fullpath[PATH_MAX];
807 // If DST is NULL, then return the number of bytes needed.
808 uint32_t len = sizeof(program_fullpath);
809 int err = _NSGetExecutablePath (program_fullpath, &len);
810 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000811 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000812 else if (err == -1)
813 {
814 char *large_program_fullpath = (char *)::malloc (len + 1);
815
816 err = _NSGetExecutablePath (large_program_fullpath, &len);
817 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000818 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000819
820 ::free (large_program_fullpath);
821 }
822#elif defined (__linux__)
823 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000824 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
825 if (len > 0) {
826 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000827 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000828 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000829#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000830 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
831 size_t exe_path_size;
832 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
833 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000834 char *exe_path = new char[exe_path_size];
835 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
836 g_program_filespec.SetFile(exe_path, false);
837 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000838 }
839#endif
840 }
841 return g_program_filespec;
842}
843
Greg Clayton2bddd342010-09-07 20:11:56 +0000844#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000845
846bool
847Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
848{
849 bundle.Clear();
850 return false;
851}
852
Greg Clayton2bddd342010-09-07 20:11:56 +0000853bool
Greg Claytondd36def2010-10-17 22:03:32 +0000854Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000855{
Greg Claytondd36def2010-10-17 22:03:32 +0000856 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000857}
858#endif
859
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000860#ifndef _WIN32
861
Greg Clayton45319462011-02-08 00:35:34 +0000862// Opaque info that tracks a dynamic library that was loaded
863struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000864{
Greg Clayton45319462011-02-08 00:35:34 +0000865 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
866 file_spec (fs),
867 open_options (o),
868 handle (h)
869 {
870 }
871
872 const FileSpec file_spec;
873 uint32_t open_options;
874 void * handle;
875};
876
877void *
878Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
879{
Greg Clayton4272cc72011-02-02 02:24:04 +0000880 char path[PATH_MAX];
881 if (file_spec.GetPath(path, sizeof(path)))
882 {
Greg Clayton45319462011-02-08 00:35:34 +0000883 int mode = 0;
884
885 if (options & eDynamicLibraryOpenOptionLazy)
886 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000887 else
888 mode |= RTLD_NOW;
889
Greg Clayton45319462011-02-08 00:35:34 +0000890
891 if (options & eDynamicLibraryOpenOptionLocal)
892 mode |= RTLD_LOCAL;
893 else
894 mode |= RTLD_GLOBAL;
895
896#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
897 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
898 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000899#endif
Greg Clayton45319462011-02-08 00:35:34 +0000900
901 void * opaque = ::dlopen (path, mode);
902
903 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000904 {
905 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000906 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000907 }
908 else
909 {
910 error.SetErrorString(::dlerror());
911 }
912 }
913 else
914 {
915 error.SetErrorString("failed to extract path");
916 }
Greg Clayton45319462011-02-08 00:35:34 +0000917 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000918}
919
920Error
Greg Clayton45319462011-02-08 00:35:34 +0000921Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000922{
923 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000924 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000925 {
926 error.SetErrorString ("invalid dynamic library handle");
927 }
Greg Clayton45319462011-02-08 00:35:34 +0000928 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000929 {
Greg Clayton45319462011-02-08 00:35:34 +0000930 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
931 if (::dlclose (dylib_info->handle) != 0)
932 {
933 error.SetErrorString(::dlerror());
934 }
935
936 dylib_info->open_options = 0;
937 dylib_info->handle = 0;
938 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000939 }
940 return error;
941}
942
943void *
Greg Clayton45319462011-02-08 00:35:34 +0000944Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000945{
Greg Clayton45319462011-02-08 00:35:34 +0000946 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000947 {
948 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000949 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000950 else
Greg Clayton45319462011-02-08 00:35:34 +0000951 {
952 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
953
954 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
955 if (symbol_addr)
956 {
957#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
958 // This host doesn't support limiting searches to this shared library
959 // so we need to verify that the match came from this shared library
960 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000961 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000962 {
963 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
964 if (match_dylib_spec != dylib_info->file_spec)
965 {
966 char dylib_path[PATH_MAX];
967 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
968 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
969 else
970 error.SetErrorString ("symbol not found");
971 return NULL;
972 }
973 }
974#endif
975 error.Clear();
976 return symbol_addr;
977 }
978 else
979 {
980 error.SetErrorString(::dlerror());
981 }
982 }
983 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000984}
Greg Claytondd36def2010-10-17 22:03:32 +0000985
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000986FileSpec
987Host::GetModuleFileSpecForHostAddress (const void *host_addr)
988{
989 FileSpec module_filespec;
990 Dl_info info;
991 if (::dladdr (host_addr, &info))
992 {
993 if (info.dli_fname)
994 module_filespec.SetFile(info.dli_fname, true);
995 }
996 return module_filespec;
997}
998
999#endif
1000
Greg Claytondd36def2010-10-17 22:03:32 +00001001bool
1002Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1003{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001004 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001005 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1006 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001007 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001008 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001009 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001010
1011 switch (path_type)
1012 {
1013 case ePathTypeLLDBShlibDir:
1014 {
1015 static ConstString g_lldb_so_dir;
1016 if (!g_lldb_so_dir)
1017 {
1018 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
1019 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001020 if (log)
1021 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001022 }
1023 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001024 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001025 }
1026 break;
1027
1028 case ePathTypeSupportExecutableDir:
1029 {
1030 static ConstString g_lldb_support_exe_dir;
1031 if (!g_lldb_support_exe_dir)
1032 {
1033 FileSpec lldb_file_spec;
1034 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1035 {
1036 char raw_path[PATH_MAX];
1037 char resolved_path[PATH_MAX];
1038 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1039
1040#if defined (__APPLE__)
1041 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1042 if (framework_pos)
1043 {
1044 framework_pos += strlen("LLDB.framework");
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001045#if defined (__arm__)
1046 // Shallow bundle
1047 *framework_pos = '\0';
1048#else
1049 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001050 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001051#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001052 }
1053#endif
1054 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1055 g_lldb_support_exe_dir.SetCString(resolved_path);
1056 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001057 if (log)
1058 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001059 }
1060 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001061 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001062 }
1063 break;
1064
1065 case ePathTypeHeaderDir:
1066 {
1067 static ConstString g_lldb_headers_dir;
1068 if (!g_lldb_headers_dir)
1069 {
1070#if defined (__APPLE__)
1071 FileSpec lldb_file_spec;
1072 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1073 {
1074 char raw_path[PATH_MAX];
1075 char resolved_path[PATH_MAX];
1076 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1077
1078 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1079 if (framework_pos)
1080 {
1081 framework_pos += strlen("LLDB.framework");
1082 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1083 }
1084 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1085 g_lldb_headers_dir.SetCString(resolved_path);
1086 }
1087#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001088 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001089 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1090#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001091 if (log)
1092 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001093 }
1094 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001095 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001096 }
1097 break;
1098
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001099#ifdef LLDB_DISABLE_PYTHON
1100 case ePathTypePythonDir:
1101 return false;
1102#else
1103 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001104 {
Greg Claytondd36def2010-10-17 22:03:32 +00001105 static ConstString g_lldb_python_dir;
1106 if (!g_lldb_python_dir)
1107 {
1108 FileSpec lldb_file_spec;
1109 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1110 {
1111 char raw_path[PATH_MAX];
1112 char resolved_path[PATH_MAX];
1113 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1114
1115#if defined (__APPLE__)
1116 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1117 if (framework_pos)
1118 {
1119 framework_pos += strlen("LLDB.framework");
1120 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001121 }
1122 else
1123 {
1124#endif
1125 llvm::SmallString<256> python_version_dir;
1126 llvm::raw_svector_ostream os(python_version_dir);
1127 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1128 os.flush();
1129
1130 // We may get our string truncated. Should we protect
1131 // this with an assert?
1132
1133 ::strncat(raw_path, python_version_dir.c_str(),
1134 sizeof(raw_path) - strlen(raw_path) - 1);
1135
1136#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001137 }
1138#endif
1139 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1140 g_lldb_python_dir.SetCString(resolved_path);
1141 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001142
1143 if (log)
1144 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1145
Greg Claytondd36def2010-10-17 22:03:32 +00001146 }
1147 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001148 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001149 }
1150 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001151#endif
1152
Greg Clayton4272cc72011-02-02 02:24:04 +00001153 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1154 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001155#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001156 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001157 static bool g_lldb_system_plugin_dir_located = false;
1158 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001159 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001160 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001161#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001162 FileSpec lldb_file_spec;
1163 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1164 {
1165 char raw_path[PATH_MAX];
1166 char resolved_path[PATH_MAX];
1167 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1168
1169 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1170 if (framework_pos)
1171 {
1172 framework_pos += strlen("LLDB.framework");
1173 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001174 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1175 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001176 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001177 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001178 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001179#elif defined (__linux__)
1180 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1181 if (lldb_file_spec.Exists())
1182 {
1183 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1184 }
1185#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001186
1187 if (log)
1188 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1189
Greg Clayton4272cc72011-02-02 02:24:04 +00001190 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001191
1192 if (g_lldb_system_plugin_dir)
1193 {
1194 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1195 return true;
1196 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001197#else
1198 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001199 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001200#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001201 }
1202 break;
1203
1204 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1205 {
1206#if defined (__APPLE__)
1207 static ConstString g_lldb_user_plugin_dir;
1208 if (!g_lldb_user_plugin_dir)
1209 {
1210 char user_plugin_path[PATH_MAX];
1211 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1212 user_plugin_path,
1213 sizeof(user_plugin_path)))
1214 {
1215 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1216 }
1217 }
1218 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001219 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001220#elif defined (__linux__)
1221 static ConstString g_lldb_user_plugin_dir;
1222 if (!g_lldb_user_plugin_dir)
1223 {
1224 // XDG Base Directory Specification
1225 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1226 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1227 FileSpec lldb_file_spec;
1228 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1229 if (xdg_data_home && xdg_data_home[0])
1230 {
1231 std::string user_plugin_dir (xdg_data_home);
1232 user_plugin_dir += "/lldb";
1233 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1234 }
1235 else
1236 {
1237 const char *home_dir = getenv("HOME");
1238 if (home_dir && home_dir[0])
1239 {
1240 std::string user_plugin_dir (home_dir);
1241 user_plugin_dir += "/.local/share/lldb";
1242 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1243 }
1244 }
1245
1246 if (lldb_file_spec.Exists())
1247 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001248 if (log)
1249 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001250 }
1251 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001252 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001253#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001254 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001255 return false;
1256 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001257
1258 case ePathTypeLLDBTempSystemDir:
1259 {
1260 static ConstString g_lldb_tmp_dir;
1261 if (!g_lldb_tmp_dir)
1262 {
1263 const char *tmpdir_cstr = getenv("TMPDIR");
1264 if (tmpdir_cstr == NULL)
1265 {
1266 tmpdir_cstr = getenv("TMP");
1267 if (tmpdir_cstr == NULL)
1268 tmpdir_cstr = getenv("TEMP");
1269 }
1270 if (tmpdir_cstr)
1271 {
1272 g_lldb_tmp_dir.SetCString(tmpdir_cstr);
1273 if (log)
1274 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1275 }
1276 }
1277 file_spec.GetDirectory() = g_lldb_tmp_dir;
1278 return (bool)file_spec.GetDirectory();
1279 }
Greg Claytondd36def2010-10-17 22:03:32 +00001280 }
1281
1282 return false;
1283}
1284
Greg Clayton1cb64962011-03-24 04:28:38 +00001285
1286bool
1287Host::GetHostname (std::string &s)
1288{
1289 char hostname[PATH_MAX];
1290 hostname[sizeof(hostname) - 1] = '\0';
1291 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1292 {
1293 struct hostent* h = ::gethostbyname (hostname);
1294 if (h)
1295 s.assign (h->h_name);
1296 else
1297 s.assign (hostname);
1298 return true;
1299 }
1300 return false;
1301}
1302
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001303#ifndef _WIN32
1304
Greg Clayton32e0a752011-03-30 18:16:51 +00001305const char *
1306Host::GetUserName (uint32_t uid, std::string &user_name)
1307{
1308 struct passwd user_info;
1309 struct passwd *user_info_ptr = &user_info;
1310 char user_buffer[PATH_MAX];
1311 size_t user_buffer_size = sizeof(user_buffer);
1312 if (::getpwuid_r (uid,
1313 &user_info,
1314 user_buffer,
1315 user_buffer_size,
1316 &user_info_ptr) == 0)
1317 {
1318 if (user_info_ptr)
1319 {
1320 user_name.assign (user_info_ptr->pw_name);
1321 return user_name.c_str();
1322 }
1323 }
1324 user_name.clear();
1325 return NULL;
1326}
1327
1328const char *
1329Host::GetGroupName (uint32_t gid, std::string &group_name)
1330{
1331 char group_buffer[PATH_MAX];
1332 size_t group_buffer_size = sizeof(group_buffer);
1333 struct group group_info;
1334 struct group *group_info_ptr = &group_info;
1335 // Try the threadsafe version first
1336 if (::getgrgid_r (gid,
1337 &group_info,
1338 group_buffer,
1339 group_buffer_size,
1340 &group_info_ptr) == 0)
1341 {
1342 if (group_info_ptr)
1343 {
1344 group_name.assign (group_info_ptr->gr_name);
1345 return group_name.c_str();
1346 }
1347 }
1348 else
1349 {
1350 // The threadsafe version isn't currently working
1351 // for me on darwin, but the non-threadsafe version
1352 // is, so I am calling it below.
1353 group_info_ptr = ::getgrgid (gid);
1354 if (group_info_ptr)
1355 {
1356 group_name.assign (group_info_ptr->gr_name);
1357 return group_name.c_str();
1358 }
1359 }
1360 group_name.clear();
1361 return NULL;
1362}
1363
Han Ming Ong84647042012-02-25 01:07:38 +00001364uint32_t
1365Host::GetUserID ()
1366{
1367 return getuid();
1368}
1369
1370uint32_t
1371Host::GetGroupID ()
1372{
1373 return getgid();
1374}
1375
1376uint32_t
1377Host::GetEffectiveUserID ()
1378{
1379 return geteuid();
1380}
1381
1382uint32_t
1383Host::GetEffectiveGroupID ()
1384{
1385 return getegid();
1386}
1387
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001388#endif
1389
1390#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1391bool
1392Host::GetOSBuildString (std::string &s)
1393{
1394 s.clear();
1395 return false;
1396}
1397
1398bool
1399Host::GetOSKernelDescription (std::string &s)
1400{
1401 s.clear();
1402 return false;
1403}
1404#endif
1405
Ed Maste47e575e2013-08-29 18:44:27 +00001406#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001407uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001408Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001409{
1410 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001411 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001412}
1413
Greg Claytone996fd32011-03-08 22:40:15 +00001414bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001415Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001416{
Greg Claytone996fd32011-03-08 22:40:15 +00001417 process_info.Clear();
1418 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001419}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001420#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001421
Matt Kopec085d6ce2013-05-31 22:00:07 +00001422#if !defined(__linux__)
1423bool
1424Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1425{
1426 return false;
1427}
1428#endif
1429
Sean Callananc0a6e062011-10-27 21:22:25 +00001430lldb::TargetSP
1431Host::GetDummyTarget (lldb_private::Debugger &debugger)
1432{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001433 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001434
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001435 // FIXME: Maybe the dummy target should be per-Debugger
1436 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1437 {
1438 ArchSpec arch(Target::GetDefaultArchitecture());
1439 if (!arch.IsValid())
1440 arch = Host::GetArchitecture ();
1441 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001442 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001443 arch.GetTriple().getTriple().c_str(),
1444 false,
1445 NULL,
1446 g_dummy_target_sp);
1447 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001448
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001449 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001450}
1451
Greg Claytond1cf11a2012-04-14 01:42:46 +00001452struct ShellInfo
1453{
1454 ShellInfo () :
1455 process_reaped (false),
1456 can_delete (false),
1457 pid (LLDB_INVALID_PROCESS_ID),
1458 signo(-1),
1459 status(-1)
1460 {
1461 }
1462
1463 lldb_private::Predicate<bool> process_reaped;
1464 lldb_private::Predicate<bool> can_delete;
1465 lldb::pid_t pid;
1466 int signo;
1467 int status;
1468};
1469
1470static bool
1471MonitorShellCommand (void *callback_baton,
1472 lldb::pid_t pid,
1473 bool exited, // True if the process did exit
1474 int signo, // Zero for no signal
1475 int status) // Exit value of process if signal is zero
1476{
1477 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1478 shell_info->pid = pid;
1479 shell_info->signo = signo;
1480 shell_info->status = status;
1481 // Let the thread running Host::RunShellCommand() know that the process
1482 // exited and that ShellInfo has been filled in by broadcasting to it
1483 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1484 // Now wait for a handshake back from that thread running Host::RunShellCommand
1485 // so we know that we can delete shell_info_ptr
1486 shell_info->can_delete.WaitForValueEqualTo(true);
1487 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1488 usleep(1000);
1489 // Now delete the shell info that was passed into this function
1490 delete shell_info;
1491 return true;
1492}
1493
1494Error
1495Host::RunShellCommand (const char *command,
1496 const char *working_dir,
1497 int *status_ptr,
1498 int *signo_ptr,
1499 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001500 uint32_t timeout_sec,
1501 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001502{
1503 Error error;
1504 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001505 if (shell && shell[0])
1506 {
1507 // Run the command in a shell
1508 launch_info.SetShell(shell);
1509 launch_info.GetArguments().AppendArgument(command);
1510 const bool localhost = true;
1511 const bool will_debug = false;
1512 const bool first_arg_is_full_shell_command = true;
1513 launch_info.ConvertArgumentsForLaunchingInShell (error,
1514 localhost,
1515 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001516 first_arg_is_full_shell_command,
1517 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001518 }
1519 else
1520 {
1521 // No shell, just run it
1522 Args args (command);
1523 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001524 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001525 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001526
1527 if (working_dir)
1528 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001529 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001530 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001531
Greg Claytond1cf11a2012-04-14 01:42:46 +00001532 if (command_output_ptr)
1533 {
1534 // Create a temporary file to get the stdout/stderr and redirect the
1535 // output of the command into this file. We will later read this file
1536 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001537 FileSpec tmpdir_file_spec;
1538 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1539 {
1540 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1541 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1542 }
1543 else
1544 {
1545 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1546 }
1547
1548 output_file_path = ::mktemp(output_file_path_buffer);
1549 }
1550
1551 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1552 if (output_file_path)
1553 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001554 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001555 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001556 }
1557 else
1558 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001559 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1560 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1561 }
1562
1563 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001564 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001565
1566 const bool monitor_signals = false;
1567 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1568
1569 error = LaunchProcess (launch_info);
1570 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001571
1572 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1573 error.SetErrorString("failed to get process ID");
1574
1575 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001576 {
1577 // The process successfully launched, so we can defer ownership of
1578 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001579 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001580 // doesn't need to delete the ShellInfo anymore.
1581 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001582 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001583 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001584 if (timeout_sec > 0) {
1585 timeout_time.OffsetWithSeconds(timeout_sec);
1586 timeout_ptr = &timeout_time;
1587 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001588 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001589 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001590 if (timed_out)
1591 {
1592 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001593
Greg Claytond1cf11a2012-04-14 01:42:46 +00001594 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001595 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001596 // Wait for the monitor callback to get the message
1597 timeout_time = TimeValue::Now();
1598 timeout_time.OffsetWithSeconds(1);
1599 timed_out = false;
1600 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1601 }
1602 else
1603 {
1604 if (status_ptr)
1605 *status_ptr = shell_info->status;
1606
1607 if (signo_ptr)
1608 *signo_ptr = shell_info->signo;
1609
1610 if (command_output_ptr)
1611 {
1612 command_output_ptr->clear();
1613 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1614 uint64_t file_size = file_spec.GetByteSize();
1615 if (file_size > 0)
1616 {
1617 if (file_size > command_output_ptr->max_size())
1618 {
1619 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1620 }
1621 else
1622 {
1623 command_output_ptr->resize(file_size);
1624 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1625 }
1626 }
1627 }
1628 }
1629 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1630 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001631
1632 if (output_file_path)
1633 ::unlink (output_file_path);
1634 // Handshake with the monitor thread, or just let it know in advance that
1635 // it can delete "shell_info" in case we timed out and were not able to kill
1636 // the process...
1637 return error;
1638}
1639
Ed Maste991fe6c2013-12-09 01:35:42 +00001640#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001641// The functions below implement process launching via posix_spawn() for Linux
1642// and FreeBSD.
1643
1644// The posix_spawn() and posix_spawnp() functions first appeared in FreeBSD 8.0,
1645static Error
1646LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
1647{
1648 Error error;
1649 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1650
1651 assert(exe_path);
1652 assert(!launch_info.GetFlags().Test (eLaunchFlagDebug));
1653
1654 posix_spawnattr_t attr;
1655
1656 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
1657 error.LogIfError(log, "::posix_spawnattr_init ( &attr )");
1658 if (error.Fail())
1659 return error;
1660
1661 // Make a quick class that will cleanup the posix spawn attributes in case
1662 // we return in the middle of this function.
1663 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1664
1665 sigset_t no_signals;
1666 sigset_t all_signals;
1667 sigemptyset (&no_signals);
1668 sigfillset (&all_signals);
1669 ::posix_spawnattr_setsigmask(&attr, &all_signals);
1670 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
1671
1672 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1673
1674 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1675 error.LogIfError(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1676 if (error.Fail())
1677 return error;
1678
1679 const size_t num_file_actions = launch_info.GetNumFileActions ();
1680 posix_spawn_file_actions_t file_actions, *file_action_ptr = NULL;
1681 // Make a quick class that will cleanup the posix spawn attributes in case
1682 // we return in the middle of this function.
1683 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int>
1684 posix_spawn_file_actions_cleanup (file_action_ptr, NULL, posix_spawn_file_actions_destroy);
1685
1686 if (num_file_actions > 0)
1687 {
1688 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1689 error.LogIfError(log, "::posix_spawn_file_actions_init ( &file_actions )");
1690 if (error.Fail())
1691 return error;
1692
1693 file_action_ptr = &file_actions;
1694 posix_spawn_file_actions_cleanup.set(file_action_ptr);
1695
1696 for (size_t i = 0; i < num_file_actions; ++i)
1697 {
1698 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1699 if (launch_file_action &&
1700 !ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1701 launch_file_action,
1702 log,
1703 error))
1704 return error;
1705 }
1706 }
1707
1708 // Change working directory if neccessary.
1709 char current_dir[PATH_MAX];
1710 current_dir[0] = '\0';
1711
1712 const char *working_dir = launch_info.GetWorkingDirectory();
1713 if (working_dir != NULL)
1714 {
1715 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1716 {
1717 error.SetError(errno, eErrorTypePOSIX);
1718 error.LogIfError(log, "unable to save the current directory");
1719 return error;
1720 }
1721
1722 if (::chdir(working_dir) == -1)
1723 {
1724 error.SetError(errno, eErrorTypePOSIX);
1725 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1726 return error;
1727 }
1728 }
1729
1730 const char *tmp_argv[2];
1731 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1732 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1733
1734 // Prepare minimal argument list if we didn't get it from the launch_info structure.
1735 // We must pass argv into posix_spawnp and it must contain at least two items -
1736 // pointer to an executable and NULL.
1737 if (argv == NULL)
1738 {
1739 tmp_argv[0] = exe_path;
1740 tmp_argv[1] = NULL;
1741 argv = (char * const*)tmp_argv;
1742 }
1743
1744 error.SetError (::posix_spawnp (&pid,
1745 exe_path,
1746 (num_file_actions > 0) ? &file_actions : NULL,
1747 &attr,
1748 argv,
1749 envp),
1750 eErrorTypePOSIX);
1751
1752 error.LogIfError(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1753 pid, exe_path, file_action_ptr, &attr, argv, envp);
1754
1755 // Change back the current directory.
1756 // NOTE: do not override previously established error from posix_spawnp.
1757 if (working_dir != NULL && ::chdir(current_dir) == -1 && error.Success())
1758 {
1759 error.SetError(errno, eErrorTypePOSIX);
1760 error.LogIfError(log, "unable to change current directory back to %s",
1761 current_dir);
1762 }
1763
1764 return error;
1765}
1766
1767
1768Error
1769Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1770{
1771 Error error;
1772 char exe_path[PATH_MAX];
1773
1774 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1775
1776 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1777
1778 FileSpec exe_spec(launch_info.GetExecutableFile());
1779
1780 FileSpec::FileType file_type = exe_spec.GetFileType();
1781 if (file_type != FileSpec::eFileTypeRegular)
1782 {
1783 lldb::ModuleSP exe_module_sp;
1784 error = host_platform_sp->ResolveExecutable (exe_spec,
1785 arch_spec,
1786 exe_module_sp,
1787 NULL);
1788
1789 if (error.Fail())
1790 return error;
1791
1792 if (exe_module_sp)
1793 exe_spec = exe_module_sp->GetFileSpec();
1794 }
1795
1796 if (exe_spec.Exists())
1797 {
1798 exe_spec.GetPath (exe_path, sizeof(exe_path));
1799 }
1800 else
1801 {
1802 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1803 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1804 return error;
1805 }
1806
1807 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1808
1809 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1810
1811 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1812
1813 if (pid != LLDB_INVALID_PROCESS_ID)
1814 {
1815 // If all went well, then set the process ID into the launch info
1816 launch_info.SetProcessID(pid);
1817
1818 // Make sure we reap any processes we spawn or we will have zombies.
1819 if (!launch_info.MonitorProcess())
1820 {
1821 const bool monitor_signals = false;
1822 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1823 NULL,
1824 pid,
1825 monitor_signals);
1826 }
1827 }
1828 else
1829 {
1830 // Invalid process ID, something didn't go well
1831 if (error.Success())
1832 error.SetErrorString ("process launch failed for unknown reasons");
1833 }
1834 return error;
1835}
1836
1837#endif // defined(__linux__) or defined(__FreeBSD__)
1838
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001839#ifndef _WIN32
1840
1841size_t
1842Host::GetPageSize()
1843{
1844 return ::getpagesize();
1845}
Greg Claytond1cf11a2012-04-14 01:42:46 +00001846
Greg Claytone3e3fee2013-02-17 20:46:30 +00001847uint32_t
1848Host::GetNumberCPUS ()
1849{
1850 static uint32_t g_num_cores = UINT32_MAX;
1851 if (g_num_cores == UINT32_MAX)
1852 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00001853#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00001854
1855 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001856
Greg Claytone3e3fee2013-02-17 20:46:30 +00001857#else
1858
1859 // Assume POSIX support if a host specific case has not been supplied above
1860 g_num_cores = 0;
1861 int num_cores = 0;
1862 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00001863#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00001864 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00001865#else
1866 int mib[] = { CTL_HW, HW_NCPU };
1867#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00001868
1869 /* get the number of CPUs from the system */
1870 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1871 {
1872 g_num_cores = num_cores;
1873 }
1874 else
1875 {
1876 mib[1] = HW_NCPU;
1877 num_cores_len = sizeof(num_cores);
1878 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
1879 {
1880 if (num_cores > 0)
1881 g_num_cores = num_cores;
1882 }
1883 }
1884#endif
1885 }
1886 return g_num_cores;
1887}
1888
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001889void
1890Host::Kill(lldb::pid_t pid, int signo)
1891{
1892 ::kill(pid, signo);
1893}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001894
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001895#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001896
Johnny Chen8f3d8382011-08-02 20:52:42 +00001897#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001898bool
Greg Clayton3b147632010-12-18 01:54:34 +00001899Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001900{
1901 return false;
1902}
Greg Claytondd36def2010-10-17 22:03:32 +00001903
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001904void
1905Host::SetCrashDescriptionWithFormat (const char *format, ...)
1906{
1907}
1908
1909void
1910Host::SetCrashDescription (const char *description)
1911{
1912}
Greg Claytondd36def2010-10-17 22:03:32 +00001913
1914lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001915Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001916{
1917 return LLDB_INVALID_PROCESS_ID;
1918}
1919
Greg Claytonfbb76342013-11-20 21:07:01 +00001920#endif
1921
1922
1923#ifdef LLDB_DISABLE_POSIX
1924
1925Error
1926Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00001927{
Greg Claytonfbb76342013-11-20 21:07:01 +00001928 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001929 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001930 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00001931}
Greg Claytonfbb76342013-11-20 21:07:01 +00001932
1933Error
1934Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
1935{
1936 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001937 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001938 return error;
1939}
1940
1941Error
1942Host::SetFilePermissions (const char* path, uint32_t file_permissions)
1943{
1944 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001945 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001946 return error;
1947}
1948
1949Error
1950Host::Symlink (const char *src, const char *dst)
1951{
1952 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001953 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001954 return error;
1955}
1956
1957Error
1958Host::Readlink (const char *path, char *buf, size_t buf_len)
1959{
1960 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001961 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001962 return error;
1963}
1964
1965Error
1966Host::Unlink (const char *path)
1967{
1968 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00001969 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00001970 return error;
1971}
1972
1973#else
1974
1975Error
1976Host::MakeDirectory (const char* path, uint32_t file_permissions)
1977{
1978 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00001979 if (path && path[0])
1980 {
Greg Claytonfb909312013-11-23 01:58:15 +00001981 if (::mkdir(path, file_permissions) != 0)
1982 {
1983 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00001984 switch (error.GetError())
1985 {
1986 case ENOENT:
1987 {
1988 // Parent directory doesn't exist, so lets make it if we can
1989 FileSpec spec(path, false);
1990 if (spec.GetDirectory() && spec.GetFilename())
1991 {
1992 // Make the parent directory and try again
1993 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
1994 if (error2.Success())
1995 {
1996 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00001997 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00001998 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00001999 else
Greg Claytonfb909312013-11-23 01:58:15 +00002000 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002001 }
2002 }
2003 }
2004 break;
2005 case EEXIST:
2006 {
2007 FileSpec path_spec(path, false);
2008 if (path_spec.IsDirectory())
2009 error.Clear(); // It is a directory and it already exists
2010 }
2011 break;
2012 }
2013 }
Greg Claytonfb909312013-11-23 01:58:15 +00002014 }
2015 else
2016 {
2017 error.SetErrorString("empty path");
2018 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002019 return error;
2020}
2021
2022Error
2023Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2024{
2025 Error error;
2026 struct stat file_stats;
2027 if (::stat (path, &file_stats) == 0)
2028 {
2029 // The bits in "st_mode" currently match the definitions
2030 // for the file mode bits in unix.
2031 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2032 }
2033 else
2034 {
2035 error.SetErrorToErrno();
2036 }
2037 return error;
2038}
2039
2040Error
2041Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2042{
2043 Error error;
2044 if (::chmod(path, file_permissions) != 0)
2045 error.SetErrorToErrno();
2046 return error;
2047}
2048
2049Error
2050Host::Symlink (const char *src, const char *dst)
2051{
2052 Error error;
2053 if (::symlink(dst, src) == -1)
2054 error.SetErrorToErrno();
2055 return error;
2056}
2057
2058Error
2059Host::Unlink (const char *path)
2060{
2061 Error error;
2062 if (::unlink(path) == -1)
2063 error.SetErrorToErrno();
2064 return error;
2065}
2066
2067Error
2068Host::Readlink (const char *path, char *buf, size_t buf_len)
2069{
2070 Error error;
2071 ssize_t count = ::readlink(path, buf, buf_len);
2072 if (count < 0)
2073 error.SetErrorToErrno();
2074 else if (count < (buf_len-1))
2075 buf[count] = '\0'; // Success
2076 else
2077 error.SetErrorString("'buf' buffer is too small to contain link contents");
2078 return error;
2079}
2080
2081
Greg Clayton2bddd342010-09-07 20:11:56 +00002082#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002083
2084typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2085FDToFileMap& GetFDToFileMap()
2086{
2087 static FDToFileMap g_fd2filemap;
2088 return g_fd2filemap;
2089}
2090
2091lldb::user_id_t
2092Host::OpenFile (const FileSpec& file_spec,
2093 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002094 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002095 Error &error)
2096{
2097 std::string path (file_spec.GetPath());
2098 if (path.empty())
2099 {
2100 error.SetErrorString("empty path");
2101 return UINT64_MAX;
2102 }
2103 FileSP file_sp(new File());
2104 error = file_sp->Open(path.c_str(),flags,mode);
2105 if (file_sp->IsValid() == false)
2106 return UINT64_MAX;
2107 lldb::user_id_t fd = file_sp->GetDescriptor();
2108 GetFDToFileMap()[fd] = file_sp;
2109 return fd;
2110}
2111
2112bool
2113Host::CloseFile (lldb::user_id_t fd, Error &error)
2114{
2115 if (fd == UINT64_MAX)
2116 {
2117 error.SetErrorString ("invalid file descriptor");
2118 return false;
2119 }
2120 FDToFileMap& file_map = GetFDToFileMap();
2121 FDToFileMap::iterator pos = file_map.find(fd);
2122 if (pos == file_map.end())
2123 {
2124 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2125 return false;
2126 }
2127 FileSP file_sp = pos->second;
2128 if (!file_sp)
2129 {
2130 error.SetErrorString ("invalid host backing file");
2131 return false;
2132 }
2133 error = file_sp->Close();
2134 file_map.erase(pos);
2135 return error.Success();
2136}
2137
2138uint64_t
2139Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2140{
2141 if (fd == UINT64_MAX)
2142 {
2143 error.SetErrorString ("invalid file descriptor");
2144 return UINT64_MAX;
2145 }
2146 FDToFileMap& file_map = GetFDToFileMap();
2147 FDToFileMap::iterator pos = file_map.find(fd);
2148 if (pos == file_map.end())
2149 {
2150 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2151 return false;
2152 }
2153 FileSP file_sp = pos->second;
2154 if (!file_sp)
2155 {
2156 error.SetErrorString ("invalid host backing file");
2157 return UINT64_MAX;
2158 }
2159 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2160 return UINT64_MAX;
2161 size_t bytes_written = src_len;
2162 error = file_sp->Write(src, bytes_written);
2163 if (error.Fail())
2164 return UINT64_MAX;
2165 return bytes_written;
2166}
2167
2168uint64_t
2169Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2170{
2171 if (fd == UINT64_MAX)
2172 {
2173 error.SetErrorString ("invalid file descriptor");
2174 return UINT64_MAX;
2175 }
2176 FDToFileMap& file_map = GetFDToFileMap();
2177 FDToFileMap::iterator pos = file_map.find(fd);
2178 if (pos == file_map.end())
2179 {
2180 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2181 return false;
2182 }
2183 FileSP file_sp = pos->second;
2184 if (!file_sp)
2185 {
2186 error.SetErrorString ("invalid host backing file");
2187 return UINT64_MAX;
2188 }
2189 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2190 return UINT64_MAX;
2191 size_t bytes_read = dst_len;
2192 error = file_sp->Read(dst ,bytes_read);
2193 if (error.Fail())
2194 return UINT64_MAX;
2195 return bytes_read;
2196}
2197
2198lldb::user_id_t
2199Host::GetFileSize (const FileSpec& file_spec)
2200{
2201 return file_spec.GetByteSize();
2202}
2203
2204bool
2205Host::GetFileExists (const FileSpec& file_spec)
2206{
2207 return file_spec.Exists();
2208}
2209
2210bool
2211Host::CalculateMD5 (const FileSpec& file_spec,
2212 uint64_t &low,
2213 uint64_t &high)
2214{
2215#if defined (__APPLE__)
2216 StreamString md5_cmd_line;
2217 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2218 std::string hash_string;
2219 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2220 if (err.Fail())
2221 return false;
2222 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2223 // if the output is any other length it is probably wrong
2224 if (hash_string.size() != 32)
2225 return false;
2226 std::string part1(hash_string,0,16);
2227 std::string part2(hash_string,16);
2228 const char* part1_cstr = part1.c_str();
2229 const char* part2_cstr = part2.c_str();
2230 high = ::strtoull(part1_cstr, NULL, 16);
2231 low = ::strtoull(part2_cstr, NULL, 16);
2232 return true;
2233#else
2234 // your own MD5 implementation here
2235 return false;
2236#endif
2237}