blob: 197be193e6bfa70d5a13ebd7485e9f6d5776f7cc [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>
Greg Clayton23f8c952014-03-24 23:10:19 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#include <sys/types.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000017#ifdef _WIN32
18#include "lldb/Host/windows/windows.h"
19#include <winsock2.h>
Hafiz Abid Qadeera6678752014-03-10 22:31:39 +000020#include <ws2tcpip.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000021#else
Deepak Panickalb36da432014-01-13 14:55:15 +000022#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000023#include <dlfcn.h>
24#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000025#include <netdb.h>
26#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000027#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000028#endif
29
30#if !defined (__GNU__) && !defined (_WIN32)
31// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000032#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000033#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000034
35#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000036#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000037#include <mach/mach_init.h>
38#include <mach-o/dyld.h>
Jim Ingham1a7ee702013-11-22 00:51:36 +000039#include <AvailabilityMacros.h>
Ed Maste8b006c62013-06-25 18:58:11 +000040#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000041
Todd Fiala76747122014-01-23 00:52:28 +000042#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000043#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000044#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000045#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000046#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000047
Ed Maste8b006c62013-06-25 18:58:11 +000048#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000050#endif
51
Greg Clayton2bddd342010-09-07 20:11:56 +000052#include "lldb/Host/Host.h"
53#include "lldb/Core/ArchSpec.h"
54#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000055#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000057#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000058#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000059#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000060#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000061#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000062#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000063#include "lldb/Host/FileSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000064#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000065#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000066#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000067#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000068
Daniel Maleafa7425d2013-08-06 21:40:08 +000069#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000070#include "llvm/Support/Host.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000071#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000072
Todd Fiala76747122014-01-23 00:52:28 +000073#if defined (__APPLE__)
74#ifndef _POSIX_SPAWN_DISABLE_ASLR
75#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
76#endif
77
78extern "C"
79{
80 int __pthread_chdir(const char *path);
81 int __pthread_fchdir (int fildes);
82}
83
84#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000085
Greg Clayton2bddd342010-09-07 20:11:56 +000086using namespace lldb;
87using namespace lldb_private;
88
Greg Claytone4e45922011-11-16 05:37:56 +000089
Virgile Bellob2f1fb22013-08-23 12:44:05 +000090#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000091struct MonitorInfo
92{
93 lldb::pid_t pid; // The process ID to monitor
94 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
95 void *callback_baton; // The callback baton for the callback function
96 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
97};
98
Virgile Bellob2f1fb22013-08-23 12:44:05 +000099static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000100MonitorChildProcessThreadFunction (void *arg);
101
102lldb::thread_t
103Host::StartMonitoringChildProcess
104(
105 Host::MonitorChildProcessCallback callback,
106 void *callback_baton,
107 lldb::pid_t pid,
108 bool monitor_signals
109)
110{
111 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000112 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000113
Greg Claytone4e45922011-11-16 05:37:56 +0000114 info_ptr->pid = pid;
115 info_ptr->callback = callback;
116 info_ptr->callback_baton = callback_baton;
117 info_ptr->monitor_signals = monitor_signals;
118
119 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000120 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000121 thread = ThreadCreate (thread_name,
122 MonitorChildProcessThreadFunction,
123 info_ptr,
124 NULL);
125
Greg Clayton2bddd342010-09-07 20:11:56 +0000126 return thread;
127}
128
129//------------------------------------------------------------------
130// Scoped class that will disable thread canceling when it is
131// constructed, and exception safely restore the previous value it
132// when it goes out of scope.
133//------------------------------------------------------------------
134class ScopedPThreadCancelDisabler
135{
136public:
137 ScopedPThreadCancelDisabler()
138 {
139 // Disable the ability for this thread to be cancelled
140 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
141 if (err != 0)
142 m_old_state = -1;
143
144 }
145
146 ~ScopedPThreadCancelDisabler()
147 {
148 // Restore the ability for this thread to be cancelled to what it
149 // previously was.
150 if (m_old_state != -1)
151 ::pthread_setcancelstate (m_old_state, 0);
152 }
153private:
154 int m_old_state; // Save the old cancelability state.
155};
156
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000157static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000158MonitorChildProcessThreadFunction (void *arg)
159{
Greg Clayton5160ce52013-03-27 23:08:40 +0000160 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000161 const char *function = __FUNCTION__;
162 if (log)
163 log->Printf ("%s (arg = %p) thread starting...", function, arg);
164
165 MonitorInfo *info = (MonitorInfo *)arg;
166
167 const Host::MonitorChildProcessCallback callback = info->callback;
168 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000169 const bool monitor_signals = info->monitor_signals;
170
Daniel Malea4244cbd2013-08-27 20:58:59 +0000171 assert (info->pid <= UINT32_MAX);
172 const ::pid_t pid = monitor_signals ? -1 * info->pid : info->pid;
173
Greg Clayton2bddd342010-09-07 20:11:56 +0000174 delete info;
175
176 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000177#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000178 #define __WALL 0
179#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000180 const int options = __WALL;
181
Greg Clayton2bddd342010-09-07 20:11:56 +0000182 while (1)
183 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000184 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000185 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000186 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000187
188 // Wait for all child processes
189 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000190 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000191 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000192 ::pthread_testcancel ();
193
194 if (wait_pid == -1)
195 {
196 if (errno == EINTR)
197 continue;
198 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000199 {
200 if (log)
201 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000202 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000203 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000204 }
Matt Kopec650648f2013-01-08 16:30:18 +0000205 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000206 {
207 bool exited = false;
208 int signal = 0;
209 int exit_status = 0;
210 const char *status_cstr = NULL;
211 if (WIFSTOPPED(status))
212 {
213 signal = WSTOPSIG(status);
214 status_cstr = "STOPPED";
215 }
216 else if (WIFEXITED(status))
217 {
218 exit_status = WEXITSTATUS(status);
219 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000220 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000221 }
222 else if (WIFSIGNALED(status))
223 {
224 signal = WTERMSIG(status);
225 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000226 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000227 exited = true;
228 exit_status = -1;
229 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000230 }
231 else
232 {
Johnny Chen44805302011-07-19 19:48:13 +0000233 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000234 }
235
236 // Scope for pthread_cancel_disabler
237 {
238 ScopedPThreadCancelDisabler pthread_cancel_disabler;
239
Caroline Tice20ad3c42010-10-29 21:48:37 +0000240 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000241 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000242 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 +0000243 function,
244 wait_pid,
245 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000246 pid,
247 status,
248 status_cstr,
249 signal,
250 exit_status);
251
252 if (exited || (signal != 0 && monitor_signals))
253 {
Greg Claytone4e45922011-11-16 05:37:56 +0000254 bool callback_return = false;
255 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000256 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000257
258 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000259 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000260 {
261 if (log)
262 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000263 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000264 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000265 // If the callback returns true, it means this process should
266 // exit
267 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000268 {
269 if (log)
270 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000271 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000272 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000273 }
274 }
275 }
276 }
277
Caroline Tice20ad3c42010-10-29 21:48:37 +0000278 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000279 if (log)
280 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
281
282 return NULL;
283}
284
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000285#endif // #if !defined (__APPLE__) && !defined (_WIN32)
286
287#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000288
289void
290Host::SystemLog (SystemLogType type, const char *format, va_list args)
291{
292 vfprintf (stderr, format, args);
293}
294
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000295#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000296
Greg Claytone38a5ed2012-01-05 03:57:59 +0000297void
298Host::SystemLog (SystemLogType type, const char *format, ...)
299{
300 va_list args;
301 va_start (args, format);
302 SystemLog (type, format, args);
303 va_end (args);
304}
305
Greg Clayton2bddd342010-09-07 20:11:56 +0000306const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000307Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000308{
Greg Clayton514487e2011-02-15 21:59:32 +0000309 static bool g_supports_32 = false;
310 static bool g_supports_64 = false;
311 static ArchSpec g_host_arch_32;
312 static ArchSpec g_host_arch_64;
313
Greg Clayton2bddd342010-09-07 20:11:56 +0000314#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000315
316 // Apple is different in that it can support both 32 and 64 bit executables
317 // in the same operating system running concurrently. Here we detect the
318 // correct host architectures for both 32 and 64 bit including if 64 bit
319 // executables are supported on the system.
320
321 if (g_supports_32 == false && g_supports_64 == false)
322 {
323 // All apple systems support 32 bit execution.
324 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000325 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000326 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000327 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000328 ArchSpec host_arch;
329 // These will tell us about the kernel architecture, which even on a 64
330 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000331 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
332 {
Greg Clayton514487e2011-02-15 21:59:32 +0000333 len = sizeof (cpusubtype);
334 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
335 cpusubtype = CPU_TYPE_ANY;
336
Greg Clayton2bddd342010-09-07 20:11:56 +0000337 len = sizeof (is_64_bit_capable);
338 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
339 {
340 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000341 g_supports_64 = true;
342 }
343
344 if (is_64_bit_capable)
345 {
Greg Clayton93d3c8332011-02-16 04:46:07 +0000346#if defined (__i386__) || defined (__x86_64__)
347 if (cpusubtype == CPU_SUBTYPE_486)
348 cpusubtype = CPU_SUBTYPE_I386_ALL;
349#endif
Greg Clayton514487e2011-02-15 21:59:32 +0000350 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000351 {
Greg Clayton514487e2011-02-15 21:59:32 +0000352 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000353 g_host_arch_32.SetArchitecture (eArchTypeMachO, ~(CPU_ARCH_MASK) & cputype, cpusubtype);
354 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000355 }
356 else
357 {
358 // We have a 32 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000359 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000360 cputype |= CPU_ARCH_ABI64;
Greg Claytone0d378b2011-03-24 21:19:54 +0000361 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000362 }
363 }
Greg Clayton514487e2011-02-15 21:59:32 +0000364 else
365 {
Greg Claytone0d378b2011-03-24 21:19:54 +0000366 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000367 g_host_arch_64.Clear();
368 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000369 }
Greg Clayton514487e2011-02-15 21:59:32 +0000370 }
371
372#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000373
Greg Clayton514487e2011-02-15 21:59:32 +0000374 if (g_supports_32 == false && g_supports_64 == false)
375 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000376 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000377
Stephen Wilsonbd588712011-02-24 19:15:09 +0000378 g_host_arch_32.Clear();
379 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000380
Greg Claytonb29e6c62012-10-11 17:38:58 +0000381 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
382 // for the default triple. It's probably an artifact of config.guess.
383 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000384 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000385
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000386 const char* distribution_id = GetDistributionId ().AsCString();
387
Stephen Wilsonbd588712011-02-24 19:15:09 +0000388 switch (triple.getArch())
389 {
390 default:
391 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000392 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000393 g_supports_32 = true;
394 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000395
Stephen Wilsonbd588712011-02-24 19:15:09 +0000396 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000397 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000398 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000399 g_supports_64 = true;
400 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000401 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000402 g_supports_32 = true;
403 break;
404
Stephen Wilsonbd588712011-02-24 19:15:09 +0000405 case llvm::Triple::sparcv9:
406 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000407 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000408 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000409 g_supports_64 = true;
410 break;
411 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000412
413 g_supports_32 = g_host_arch_32.IsValid();
414 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000415 }
Greg Clayton514487e2011-02-15 21:59:32 +0000416
417#endif // #else for #if defined (__APPLE__)
418
419 if (arch_kind == eSystemDefaultArchitecture32)
420 return g_host_arch_32;
421 else if (arch_kind == eSystemDefaultArchitecture64)
422 return g_host_arch_64;
423
424 if (g_supports_64)
425 return g_host_arch_64;
426
427 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000428}
429
430const ConstString &
431Host::GetVendorString()
432{
433 static ConstString g_vendor;
434 if (!g_vendor)
435 {
Greg Clayton950971f2012-05-12 00:01:21 +0000436 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
437 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
438 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000439 }
440 return g_vendor;
441}
442
443const ConstString &
444Host::GetOSString()
445{
446 static ConstString g_os_string;
447 if (!g_os_string)
448 {
Greg Clayton950971f2012-05-12 00:01:21 +0000449 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
450 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
451 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000452 }
453 return g_os_string;
454}
455
456const ConstString &
457Host::GetTargetTriple()
458{
459 static ConstString g_host_triple;
460 if (!(g_host_triple))
461 {
Greg Clayton950971f2012-05-12 00:01:21 +0000462 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
463 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000464 }
465 return g_host_triple;
466}
467
Todd Fialaf3d61de2014-01-17 20:18:59 +0000468// See linux/Host.cpp for Linux-based implementations of this.
469// Add your platform-specific implementation to the appropriate host file.
470#if !defined(__linux__)
471
472const ConstString &
473 Host::GetDistributionId ()
474{
475 static ConstString s_distribution_id;
476 return s_distribution_id;
477}
478
479#endif // #if !defined(__linux__)
480
Greg Clayton2bddd342010-09-07 20:11:56 +0000481lldb::pid_t
482Host::GetCurrentProcessID()
483{
484 return ::getpid();
485}
486
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000487#ifndef _WIN32
488
Greg Clayton2bddd342010-09-07 20:11:56 +0000489lldb::tid_t
490Host::GetCurrentThreadID()
491{
492#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000493 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000494 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
495 // count.
496 thread_port_t thread_self = mach_thread_self();
497 mach_port_deallocate(mach_task_self(), thread_self);
498 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000499#elif defined(__FreeBSD__)
500 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000501#elif defined(__linux__)
502 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000503#else
504 return lldb::tid_t(pthread_self());
505#endif
506}
507
Jim Ingham372787f2012-04-07 00:00:41 +0000508lldb::thread_t
509Host::GetCurrentThread ()
510{
511 return lldb::thread_t(pthread_self());
512}
513
Greg Clayton2bddd342010-09-07 20:11:56 +0000514const char *
515Host::GetSignalAsCString (int signo)
516{
517 switch (signo)
518 {
519 case SIGHUP: return "SIGHUP"; // 1 hangup
520 case SIGINT: return "SIGINT"; // 2 interrupt
521 case SIGQUIT: return "SIGQUIT"; // 3 quit
522 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
523 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
524 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000525#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000526#if !defined(SIGIO) || (SIGPOLL != SIGIO)
527// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
528// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000529 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000530#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000531#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000532#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000533 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000534#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000535 case SIGFPE: return "SIGFPE"; // 8 floating point exception
536 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
537 case SIGBUS: return "SIGBUS"; // 10 bus error
538 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
539 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
540 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
541 case SIGALRM: return "SIGALRM"; // 14 alarm clock
542 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
543 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
544 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
545 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
546 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
547 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
548 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
549 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000550#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000551 case SIGIO: return "SIGIO"; // 23 input/output possible signal
552#endif
553 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
554 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
555 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
556 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000557#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000558 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000559#endif
560#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000561 case SIGINFO: return "SIGINFO"; // 29 information request
562#endif
563 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
564 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
565 default:
566 break;
567 }
568 return NULL;
569}
570
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000571#endif
572
Greg Clayton2bddd342010-09-07 20:11:56 +0000573void
574Host::WillTerminate ()
575{
576}
577
Sylvestre Ledru59405832013-07-01 08:21:36 +0000578#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000579
Greg Clayton2bddd342010-09-07 20:11:56 +0000580void
581Host::ThreadCreated (const char *thread_name)
582{
583}
Greg Claytone5219662010-12-03 06:02:24 +0000584
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000585void
Greg Claytone5219662010-12-03 06:02:24 +0000586Host::Backtrace (Stream &strm, uint32_t max_frames)
587{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000588 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000589}
590
Greg Clayton85851dd2010-12-04 00:10:17 +0000591size_t
592Host::GetEnvironment (StringList &env)
593{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000594 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000595 return 0;
596}
597
Sylvestre Ledru59405832013-07-01 08:21:36 +0000598#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000599
600struct HostThreadCreateInfo
601{
602 std::string thread_name;
603 thread_func_t thread_fptr;
604 thread_arg_t thread_arg;
605
606 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
607 thread_name (name ? name : ""),
608 thread_fptr (fptr),
609 thread_arg (arg)
610 {
611 }
612};
613
614static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000615#ifdef _WIN32
616__stdcall
617#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000618ThreadCreateTrampoline (thread_arg_t arg)
619{
620 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
621 Host::ThreadCreated (info->thread_name.c_str());
622 thread_func_t thread_fptr = info->thread_fptr;
623 thread_arg_t thread_arg = info->thread_arg;
624
Greg Clayton5160ce52013-03-27 23:08:40 +0000625 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000626 if (log)
627 log->Printf("thread created");
628
629 delete info;
630 return thread_fptr (thread_arg);
631}
632
633lldb::thread_t
634Host::ThreadCreate
635(
636 const char *thread_name,
637 thread_func_t thread_fptr,
638 thread_arg_t thread_arg,
639 Error *error
640)
641{
642 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
643
644 // Host::ThreadCreateTrampoline will delete this pointer for us.
645 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
646
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000647#ifdef _WIN32
648 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
649 int err = thread <= 0 ? GetLastError() : 0;
650#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000651 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000652#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000653 if (err == 0)
654 {
655 if (error)
656 error->Clear();
657 return thread;
658 }
659
660 if (error)
661 error->SetError (err, eErrorTypePOSIX);
662
663 return LLDB_INVALID_HOST_THREAD;
664}
665
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000666#ifndef _WIN32
667
Greg Clayton2bddd342010-09-07 20:11:56 +0000668bool
669Host::ThreadCancel (lldb::thread_t thread, Error *error)
670{
671 int err = ::pthread_cancel (thread);
672 if (error)
673 error->SetError(err, eErrorTypePOSIX);
674 return err == 0;
675}
676
677bool
678Host::ThreadDetach (lldb::thread_t thread, Error *error)
679{
680 int err = ::pthread_detach (thread);
681 if (error)
682 error->SetError(err, eErrorTypePOSIX);
683 return err == 0;
684}
685
686bool
687Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
688{
689 int err = ::pthread_join (thread, thread_result_ptr);
690 if (error)
691 error->SetError(err, eErrorTypePOSIX);
692 return err == 0;
693}
694
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000695lldb::thread_key_t
696Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
697{
698 pthread_key_t key;
699 ::pthread_key_create (&key, callback);
700 return key;
701}
702
703void*
704Host::ThreadLocalStorageGet(lldb::thread_key_t key)
705{
706 return ::pthread_getspecific (key);
707}
708
709void
710Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
711{
712 ::pthread_setspecific (key, value);
713}
714
Matt Kopec62502c62013-05-13 19:33:58 +0000715bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000716Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
717{
Greg Clayton85719632013-02-27 22:51:58 +0000718#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000719 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
720 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
721 if (pid == LLDB_INVALID_PROCESS_ID)
722 pid = curr_pid;
723
724 if (tid == LLDB_INVALID_THREAD_ID)
725 tid = curr_tid;
726
Greg Clayton2bddd342010-09-07 20:11:56 +0000727 // Set the pthread name if possible
728 if (pid == curr_pid && tid == curr_tid)
729 {
Matt Kopec62502c62013-05-13 19:33:58 +0000730 if (::pthread_setname_np (name) == 0)
731 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000732 }
Matt Kopec62502c62013-05-13 19:33:58 +0000733 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000734#elif defined (__FreeBSD__)
735 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
736 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
737 if (pid == LLDB_INVALID_PROCESS_ID)
738 pid = curr_pid;
739
740 if (tid == LLDB_INVALID_THREAD_ID)
741 tid = curr_tid;
742
743 // Set the pthread name if possible
744 if (pid == curr_pid && tid == curr_tid)
745 {
Michael Sartainc2052432013-08-01 18:51:08 +0000746 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000747 return true;
748 }
749 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000750#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000751 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
752 if (fn)
753 {
Matt Kopec62502c62013-05-13 19:33:58 +0000754 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
755 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000756 if (pid == LLDB_INVALID_PROCESS_ID)
757 pid = curr_pid;
758
759 if (tid == LLDB_INVALID_THREAD_ID)
760 tid = curr_tid;
761
Michael Sartainc2052432013-08-01 18:51:08 +0000762 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000763 {
Michael Sartainc2052432013-08-01 18:51:08 +0000764 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
765 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
766
767 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000768 return true;
769 }
770 }
771 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000772#else
773 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000774#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000775}
776
Ed Maste02983be2013-07-25 19:10:32 +0000777bool
778Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
779 const char *thread_name, size_t len)
780{
Enrico Granata67530b62014-02-12 03:37:33 +0000781 std::unique_ptr<char[]> namebuf(new char[len+1]);
782
Ed Maste02983be2013-07-25 19:10:32 +0000783 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
784 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
785 // off leads to a lot of similar named threads. Go through the thread name
786 // and search for the last dot and use that.
787 const char *lastdot = ::strrchr (thread_name, '.');
788
789 if (lastdot && lastdot != thread_name)
790 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000791 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000792 namebuf[len] = 0;
793
Enrico Granata67530b62014-02-12 03:37:33 +0000794 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000795 if (namebuflen > 0)
796 {
797 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
798 {
799 // Trim off trailing '(' and '>' characters for a bit more cleanup.
800 namebuflen--;
801 namebuf[namebuflen] = 0;
802 }
Enrico Granata67530b62014-02-12 03:37:33 +0000803 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000804 }
805 return false;
806}
807
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000808#endif
809
Greg Clayton2bddd342010-09-07 20:11:56 +0000810FileSpec
811Host::GetProgramFileSpec ()
812{
813 static FileSpec g_program_filespec;
814 if (!g_program_filespec)
815 {
816#if defined (__APPLE__)
817 char program_fullpath[PATH_MAX];
818 // If DST is NULL, then return the number of bytes needed.
819 uint32_t len = sizeof(program_fullpath);
820 int err = _NSGetExecutablePath (program_fullpath, &len);
821 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000822 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000823 else if (err == -1)
824 {
825 char *large_program_fullpath = (char *)::malloc (len + 1);
826
827 err = _NSGetExecutablePath (large_program_fullpath, &len);
828 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000829 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000830
831 ::free (large_program_fullpath);
832 }
833#elif defined (__linux__)
834 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000835 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
836 if (len > 0) {
837 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000838 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000839 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000840#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000841 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
842 size_t exe_path_size;
843 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
844 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000845 char *exe_path = new char[exe_path_size];
846 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
847 g_program_filespec.SetFile(exe_path, false);
848 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000849 }
850#endif
851 }
852 return g_program_filespec;
853}
854
Greg Clayton2bddd342010-09-07 20:11:56 +0000855#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000856
857bool
858Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
859{
860 bundle.Clear();
861 return false;
862}
863
Greg Clayton2bddd342010-09-07 20:11:56 +0000864bool
Greg Claytondd36def2010-10-17 22:03:32 +0000865Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000866{
Greg Claytondd36def2010-10-17 22:03:32 +0000867 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000868}
869#endif
870
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000871#ifndef _WIN32
872
Greg Clayton45319462011-02-08 00:35:34 +0000873// Opaque info that tracks a dynamic library that was loaded
874struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000875{
Greg Clayton45319462011-02-08 00:35:34 +0000876 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
877 file_spec (fs),
878 open_options (o),
879 handle (h)
880 {
881 }
882
883 const FileSpec file_spec;
884 uint32_t open_options;
885 void * handle;
886};
887
888void *
889Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
890{
Greg Clayton4272cc72011-02-02 02:24:04 +0000891 char path[PATH_MAX];
892 if (file_spec.GetPath(path, sizeof(path)))
893 {
Greg Clayton45319462011-02-08 00:35:34 +0000894 int mode = 0;
895
896 if (options & eDynamicLibraryOpenOptionLazy)
897 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000898 else
899 mode |= RTLD_NOW;
900
Greg Clayton45319462011-02-08 00:35:34 +0000901
902 if (options & eDynamicLibraryOpenOptionLocal)
903 mode |= RTLD_LOCAL;
904 else
905 mode |= RTLD_GLOBAL;
906
907#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
908 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
909 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000910#endif
Greg Clayton45319462011-02-08 00:35:34 +0000911
912 void * opaque = ::dlopen (path, mode);
913
914 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000915 {
916 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000917 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000918 }
919 else
920 {
921 error.SetErrorString(::dlerror());
922 }
923 }
924 else
925 {
926 error.SetErrorString("failed to extract path");
927 }
Greg Clayton45319462011-02-08 00:35:34 +0000928 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000929}
930
931Error
Greg Clayton45319462011-02-08 00:35:34 +0000932Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000933{
934 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000935 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000936 {
937 error.SetErrorString ("invalid dynamic library handle");
938 }
Greg Clayton45319462011-02-08 00:35:34 +0000939 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000940 {
Greg Clayton45319462011-02-08 00:35:34 +0000941 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
942 if (::dlclose (dylib_info->handle) != 0)
943 {
944 error.SetErrorString(::dlerror());
945 }
946
947 dylib_info->open_options = 0;
948 dylib_info->handle = 0;
949 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000950 }
951 return error;
952}
953
954void *
Greg Clayton45319462011-02-08 00:35:34 +0000955Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000956{
Greg Clayton45319462011-02-08 00:35:34 +0000957 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000958 {
959 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000960 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000961 else
Greg Clayton45319462011-02-08 00:35:34 +0000962 {
963 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
964
965 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
966 if (symbol_addr)
967 {
968#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
969 // This host doesn't support limiting searches to this shared library
970 // so we need to verify that the match came from this shared library
971 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000972 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000973 {
974 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
975 if (match_dylib_spec != dylib_info->file_spec)
976 {
977 char dylib_path[PATH_MAX];
978 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
979 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
980 else
981 error.SetErrorString ("symbol not found");
982 return NULL;
983 }
984 }
985#endif
986 error.Clear();
987 return symbol_addr;
988 }
989 else
990 {
991 error.SetErrorString(::dlerror());
992 }
993 }
994 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000995}
Greg Claytondd36def2010-10-17 22:03:32 +0000996
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000997FileSpec
998Host::GetModuleFileSpecForHostAddress (const void *host_addr)
999{
1000 FileSpec module_filespec;
1001 Dl_info info;
1002 if (::dladdr (host_addr, &info))
1003 {
1004 if (info.dli_fname)
1005 module_filespec.SetFile(info.dli_fname, true);
1006 }
1007 return module_filespec;
1008}
1009
1010#endif
1011
Greg Clayton23f8c952014-03-24 23:10:19 +00001012
1013static void CleanupProcessSpecificLLDBTempDir ()
1014{
1015 // Get the process specific LLDB temporary directory and delete it.
1016 FileSpec tmpdir_file_spec;
1017 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1018 {
1019 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1020 // true to all files that were created for the LLDB process can be cleaned up.
1021 const bool recurse = true;
1022 Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1023 }
1024}
1025
Greg Claytondd36def2010-10-17 22:03:32 +00001026bool
1027Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1028{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001029 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001030 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1031 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001032 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001033 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001034 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001035
1036 switch (path_type)
1037 {
1038 case ePathTypeLLDBShlibDir:
1039 {
1040 static ConstString g_lldb_so_dir;
1041 if (!g_lldb_so_dir)
1042 {
1043 FileSpec lldb_file_spec (Host::GetModuleFileSpecForHostAddress ((void *)Host::GetLLDBPath));
1044 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001045 if (log)
1046 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001047 }
1048 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001049 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001050 }
1051 break;
1052
1053 case ePathTypeSupportExecutableDir:
1054 {
1055 static ConstString g_lldb_support_exe_dir;
1056 if (!g_lldb_support_exe_dir)
1057 {
1058 FileSpec lldb_file_spec;
1059 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1060 {
1061 char raw_path[PATH_MAX];
1062 char resolved_path[PATH_MAX];
1063 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1064
1065#if defined (__APPLE__)
1066 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1067 if (framework_pos)
1068 {
1069 framework_pos += strlen("LLDB.framework");
Jason Molendaa3329782014-03-29 18:54:20 +00001070#if defined (__arm__) || defined (__arm64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001071 // Shallow bundle
1072 *framework_pos = '\0';
1073#else
1074 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001075 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001076#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001077 }
Jason Molendaa3329782014-03-29 18:54:20 +00001078#endif // #if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001079 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1080 g_lldb_support_exe_dir.SetCString(resolved_path);
1081 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001082 if (log)
1083 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001084 }
1085 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001086 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001087 }
1088 break;
1089
1090 case ePathTypeHeaderDir:
1091 {
1092 static ConstString g_lldb_headers_dir;
1093 if (!g_lldb_headers_dir)
1094 {
1095#if defined (__APPLE__)
1096 FileSpec lldb_file_spec;
1097 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1098 {
1099 char raw_path[PATH_MAX];
1100 char resolved_path[PATH_MAX];
1101 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1102
1103 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1104 if (framework_pos)
1105 {
1106 framework_pos += strlen("LLDB.framework");
1107 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1108 }
1109 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1110 g_lldb_headers_dir.SetCString(resolved_path);
1111 }
1112#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001113 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001114 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1115#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001116 if (log)
1117 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001118 }
1119 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001120 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001121 }
1122 break;
1123
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001124#ifdef LLDB_DISABLE_PYTHON
1125 case ePathTypePythonDir:
1126 return false;
1127#else
1128 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001129 {
Greg Claytondd36def2010-10-17 22:03:32 +00001130 static ConstString g_lldb_python_dir;
1131 if (!g_lldb_python_dir)
1132 {
1133 FileSpec lldb_file_spec;
1134 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1135 {
1136 char raw_path[PATH_MAX];
1137 char resolved_path[PATH_MAX];
1138 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1139
1140#if defined (__APPLE__)
1141 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1142 if (framework_pos)
1143 {
1144 framework_pos += strlen("LLDB.framework");
1145 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001146 }
1147 else
1148 {
1149#endif
1150 llvm::SmallString<256> python_version_dir;
1151 llvm::raw_svector_ostream os(python_version_dir);
1152 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1153 os.flush();
1154
1155 // We may get our string truncated. Should we protect
1156 // this with an assert?
1157
1158 ::strncat(raw_path, python_version_dir.c_str(),
1159 sizeof(raw_path) - strlen(raw_path) - 1);
1160
1161#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001162 }
1163#endif
1164 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1165 g_lldb_python_dir.SetCString(resolved_path);
1166 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001167
1168 if (log)
1169 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1170
Greg Claytondd36def2010-10-17 22:03:32 +00001171 }
1172 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001173 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001174 }
1175 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001176#endif
1177
Greg Clayton4272cc72011-02-02 02:24:04 +00001178 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1179 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001180#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001181 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001182 static bool g_lldb_system_plugin_dir_located = false;
1183 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001184 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001185 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001186#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001187 FileSpec lldb_file_spec;
1188 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1189 {
1190 char raw_path[PATH_MAX];
1191 char resolved_path[PATH_MAX];
1192 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1193
1194 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1195 if (framework_pos)
1196 {
1197 framework_pos += strlen("LLDB.framework");
1198 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001199 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1200 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001201 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001202 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001203 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001204#elif defined (__linux__)
1205 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1206 if (lldb_file_spec.Exists())
1207 {
1208 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1209 }
1210#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001211
1212 if (log)
1213 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1214
Greg Clayton4272cc72011-02-02 02:24:04 +00001215 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001216
1217 if (g_lldb_system_plugin_dir)
1218 {
1219 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1220 return true;
1221 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001222#else
1223 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001224 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001225#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001226 }
1227 break;
1228
1229 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1230 {
1231#if defined (__APPLE__)
1232 static ConstString g_lldb_user_plugin_dir;
1233 if (!g_lldb_user_plugin_dir)
1234 {
1235 char user_plugin_path[PATH_MAX];
1236 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1237 user_plugin_path,
1238 sizeof(user_plugin_path)))
1239 {
1240 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1241 }
1242 }
1243 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001244 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001245#elif defined (__linux__)
1246 static ConstString g_lldb_user_plugin_dir;
1247 if (!g_lldb_user_plugin_dir)
1248 {
1249 // XDG Base Directory Specification
1250 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1251 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1252 FileSpec lldb_file_spec;
1253 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1254 if (xdg_data_home && xdg_data_home[0])
1255 {
1256 std::string user_plugin_dir (xdg_data_home);
1257 user_plugin_dir += "/lldb";
1258 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1259 }
1260 else
1261 {
1262 const char *home_dir = getenv("HOME");
1263 if (home_dir && home_dir[0])
1264 {
1265 std::string user_plugin_dir (home_dir);
1266 user_plugin_dir += "/.local/share/lldb";
1267 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1268 }
1269 }
1270
1271 if (lldb_file_spec.Exists())
1272 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001273 if (log)
1274 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001275 }
1276 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001277 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001278#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001279 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001280 return false;
1281 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001282
1283 case ePathTypeLLDBTempSystemDir:
1284 {
1285 static ConstString g_lldb_tmp_dir;
1286 if (!g_lldb_tmp_dir)
1287 {
1288 const char *tmpdir_cstr = getenv("TMPDIR");
1289 if (tmpdir_cstr == NULL)
1290 {
1291 tmpdir_cstr = getenv("TMP");
1292 if (tmpdir_cstr == NULL)
1293 tmpdir_cstr = getenv("TEMP");
1294 }
1295 if (tmpdir_cstr)
1296 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001297 StreamString pid_tmpdir;
1298 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1299 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1300 {
1301 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1302 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1303 {
1304 // Make an atexit handler to clean up the process specify LLDB temp dir
1305 // and all of its contents.
1306 ::atexit (CleanupProcessSpecificLLDBTempDir);
1307 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1308 if (log)
1309 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1310
1311 }
1312 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001313 }
1314 }
1315 file_spec.GetDirectory() = g_lldb_tmp_dir;
1316 return (bool)file_spec.GetDirectory();
1317 }
Greg Claytondd36def2010-10-17 22:03:32 +00001318 }
1319
1320 return false;
1321}
1322
Greg Clayton1cb64962011-03-24 04:28:38 +00001323
1324bool
1325Host::GetHostname (std::string &s)
1326{
1327 char hostname[PATH_MAX];
1328 hostname[sizeof(hostname) - 1] = '\0';
1329 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1330 {
1331 struct hostent* h = ::gethostbyname (hostname);
1332 if (h)
1333 s.assign (h->h_name);
1334 else
1335 s.assign (hostname);
1336 return true;
1337 }
1338 return false;
1339}
1340
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001341#ifndef _WIN32
1342
Greg Clayton32e0a752011-03-30 18:16:51 +00001343const char *
1344Host::GetUserName (uint32_t uid, std::string &user_name)
1345{
1346 struct passwd user_info;
1347 struct passwd *user_info_ptr = &user_info;
1348 char user_buffer[PATH_MAX];
1349 size_t user_buffer_size = sizeof(user_buffer);
1350 if (::getpwuid_r (uid,
1351 &user_info,
1352 user_buffer,
1353 user_buffer_size,
1354 &user_info_ptr) == 0)
1355 {
1356 if (user_info_ptr)
1357 {
1358 user_name.assign (user_info_ptr->pw_name);
1359 return user_name.c_str();
1360 }
1361 }
1362 user_name.clear();
1363 return NULL;
1364}
1365
1366const char *
1367Host::GetGroupName (uint32_t gid, std::string &group_name)
1368{
1369 char group_buffer[PATH_MAX];
1370 size_t group_buffer_size = sizeof(group_buffer);
1371 struct group group_info;
1372 struct group *group_info_ptr = &group_info;
1373 // Try the threadsafe version first
1374 if (::getgrgid_r (gid,
1375 &group_info,
1376 group_buffer,
1377 group_buffer_size,
1378 &group_info_ptr) == 0)
1379 {
1380 if (group_info_ptr)
1381 {
1382 group_name.assign (group_info_ptr->gr_name);
1383 return group_name.c_str();
1384 }
1385 }
1386 else
1387 {
1388 // The threadsafe version isn't currently working
1389 // for me on darwin, but the non-threadsafe version
1390 // is, so I am calling it below.
1391 group_info_ptr = ::getgrgid (gid);
1392 if (group_info_ptr)
1393 {
1394 group_name.assign (group_info_ptr->gr_name);
1395 return group_name.c_str();
1396 }
1397 }
1398 group_name.clear();
1399 return NULL;
1400}
1401
Han Ming Ong84647042012-02-25 01:07:38 +00001402uint32_t
1403Host::GetUserID ()
1404{
1405 return getuid();
1406}
1407
1408uint32_t
1409Host::GetGroupID ()
1410{
1411 return getgid();
1412}
1413
1414uint32_t
1415Host::GetEffectiveUserID ()
1416{
1417 return geteuid();
1418}
1419
1420uint32_t
1421Host::GetEffectiveGroupID ()
1422{
1423 return getegid();
1424}
1425
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001426#endif
1427
1428#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1429bool
1430Host::GetOSBuildString (std::string &s)
1431{
1432 s.clear();
1433 return false;
1434}
1435
1436bool
1437Host::GetOSKernelDescription (std::string &s)
1438{
1439 s.clear();
1440 return false;
1441}
1442#endif
1443
Ed Maste47e575e2013-08-29 18:44:27 +00001444#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined(__linux__)
Greg Claytone996fd32011-03-08 22:40:15 +00001445uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001446Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001447{
1448 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001449 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001450}
1451
Greg Claytone996fd32011-03-08 22:40:15 +00001452bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001453Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001454{
Greg Claytone996fd32011-03-08 22:40:15 +00001455 process_info.Clear();
1456 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001457}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001458#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001459
Matt Kopec085d6ce2013-05-31 22:00:07 +00001460#if !defined(__linux__)
1461bool
1462Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1463{
1464 return false;
1465}
1466#endif
1467
Sean Callananc0a6e062011-10-27 21:22:25 +00001468lldb::TargetSP
1469Host::GetDummyTarget (lldb_private::Debugger &debugger)
1470{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001471 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001472
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001473 // FIXME: Maybe the dummy target should be per-Debugger
1474 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1475 {
1476 ArchSpec arch(Target::GetDefaultArchitecture());
1477 if (!arch.IsValid())
1478 arch = Host::GetArchitecture ();
1479 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001480 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001481 arch.GetTriple().getTriple().c_str(),
1482 false,
1483 NULL,
1484 g_dummy_target_sp);
1485 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001486
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001487 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001488}
1489
Greg Claytond1cf11a2012-04-14 01:42:46 +00001490struct ShellInfo
1491{
1492 ShellInfo () :
1493 process_reaped (false),
1494 can_delete (false),
1495 pid (LLDB_INVALID_PROCESS_ID),
1496 signo(-1),
1497 status(-1)
1498 {
1499 }
1500
1501 lldb_private::Predicate<bool> process_reaped;
1502 lldb_private::Predicate<bool> can_delete;
1503 lldb::pid_t pid;
1504 int signo;
1505 int status;
1506};
1507
1508static bool
1509MonitorShellCommand (void *callback_baton,
1510 lldb::pid_t pid,
1511 bool exited, // True if the process did exit
1512 int signo, // Zero for no signal
1513 int status) // Exit value of process if signal is zero
1514{
1515 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1516 shell_info->pid = pid;
1517 shell_info->signo = signo;
1518 shell_info->status = status;
1519 // Let the thread running Host::RunShellCommand() know that the process
1520 // exited and that ShellInfo has been filled in by broadcasting to it
1521 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1522 // Now wait for a handshake back from that thread running Host::RunShellCommand
1523 // so we know that we can delete shell_info_ptr
1524 shell_info->can_delete.WaitForValueEqualTo(true);
1525 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1526 usleep(1000);
1527 // Now delete the shell info that was passed into this function
1528 delete shell_info;
1529 return true;
1530}
1531
1532Error
1533Host::RunShellCommand (const char *command,
1534 const char *working_dir,
1535 int *status_ptr,
1536 int *signo_ptr,
1537 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001538 uint32_t timeout_sec,
1539 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001540{
1541 Error error;
1542 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001543 if (shell && shell[0])
1544 {
1545 // Run the command in a shell
1546 launch_info.SetShell(shell);
1547 launch_info.GetArguments().AppendArgument(command);
1548 const bool localhost = true;
1549 const bool will_debug = false;
1550 const bool first_arg_is_full_shell_command = true;
1551 launch_info.ConvertArgumentsForLaunchingInShell (error,
1552 localhost,
1553 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001554 first_arg_is_full_shell_command,
1555 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001556 }
1557 else
1558 {
1559 // No shell, just run it
1560 Args args (command);
1561 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001562 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001563 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001564
1565 if (working_dir)
1566 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001567 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001568 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001569
Greg Claytond1cf11a2012-04-14 01:42:46 +00001570 if (command_output_ptr)
1571 {
1572 // Create a temporary file to get the stdout/stderr and redirect the
1573 // output of the command into this file. We will later read this file
1574 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001575 FileSpec tmpdir_file_spec;
1576 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1577 {
1578 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1579 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1580 }
1581 else
1582 {
1583 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1584 }
1585
1586 output_file_path = ::mktemp(output_file_path_buffer);
1587 }
1588
1589 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1590 if (output_file_path)
1591 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001592 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001593 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001594 }
1595 else
1596 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001597 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1598 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1599 }
1600
1601 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001602 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001603
1604 const bool monitor_signals = false;
1605 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1606
1607 error = LaunchProcess (launch_info);
1608 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001609
1610 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1611 error.SetErrorString("failed to get process ID");
1612
1613 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001614 {
1615 // The process successfully launched, so we can defer ownership of
1616 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001617 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001618 // doesn't need to delete the ShellInfo anymore.
1619 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001620 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001621 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001622 if (timeout_sec > 0) {
1623 timeout_time.OffsetWithSeconds(timeout_sec);
1624 timeout_ptr = &timeout_time;
1625 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001626 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001627 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001628 if (timed_out)
1629 {
1630 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001631
Greg Claytond1cf11a2012-04-14 01:42:46 +00001632 // Kill the process since it didn't complete withint the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001633 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001634 // Wait for the monitor callback to get the message
1635 timeout_time = TimeValue::Now();
1636 timeout_time.OffsetWithSeconds(1);
1637 timed_out = false;
1638 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1639 }
1640 else
1641 {
1642 if (status_ptr)
1643 *status_ptr = shell_info->status;
1644
1645 if (signo_ptr)
1646 *signo_ptr = shell_info->signo;
1647
1648 if (command_output_ptr)
1649 {
1650 command_output_ptr->clear();
1651 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1652 uint64_t file_size = file_spec.GetByteSize();
1653 if (file_size > 0)
1654 {
1655 if (file_size > command_output_ptr->max_size())
1656 {
1657 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1658 }
1659 else
1660 {
1661 command_output_ptr->resize(file_size);
1662 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1663 }
1664 }
1665 }
1666 }
1667 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1668 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001669
1670 if (output_file_path)
1671 ::unlink (output_file_path);
1672 // Handshake with the monitor thread, or just let it know in advance that
1673 // it can delete "shell_info" in case we timed out and were not able to kill
1674 // the process...
1675 return error;
1676}
1677
Daniel Malea4244cbd2013-08-27 20:58:59 +00001678
Todd Fiala76747122014-01-23 00:52:28 +00001679// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1680// systems
1681
1682#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__)
1683
1684// this method needs to be visible to macosx/Host.cpp and
1685// common/Host.cpp.
1686
1687short
1688Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1689{
1690 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1691
1692#if defined (__APPLE__)
1693 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1694 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1695
1696 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1697 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1698
1699 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1700 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1701
1702 if (launch_info.GetLaunchInSeparateProcessGroup())
1703 flags |= POSIX_SPAWN_SETPGROUP;
1704
1705#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1706#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1707 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1708 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1709 {
1710 g_use_close_on_exec_flag = eLazyBoolNo;
1711
1712 uint32_t major, minor, update;
1713 if (Host::GetOSVersion(major, minor, update))
1714 {
1715 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1716 if (major > 10 || (major == 10 && minor > 7))
1717 {
1718 // Only enable for 10.8 and later OS versions
1719 g_use_close_on_exec_flag = eLazyBoolYes;
1720 }
1721 }
1722 }
1723#else
1724 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1725#endif
1726 // Close all files exception those with file actions if this is supported.
1727 if (g_use_close_on_exec_flag == eLazyBoolYes)
1728 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1729#endif
1730#endif // #if defined (__APPLE__)
1731 return flags;
1732}
1733
1734Error
1735Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001736{
1737 Error error;
1738 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1739
Daniel Malea4244cbd2013-08-27 20:58:59 +00001740 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001741 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001742
1743 if (error.Fail() || log)
1744 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001745 if (error.Fail())
1746 return error;
1747
1748 // Make a quick class that will cleanup the posix spawn attributes in case
1749 // we return in the middle of this function.
1750 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1751
1752 sigset_t no_signals;
1753 sigset_t all_signals;
1754 sigemptyset (&no_signals);
1755 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001756 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001757#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001758 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001759#else
1760 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1761#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001762
Todd Fiala76747122014-01-23 00:52:28 +00001763 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001764
1765 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001766 if (error.Fail() || log)
1767 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001768 if (error.Fail())
1769 return error;
1770
Todd Fiala76747122014-01-23 00:52:28 +00001771 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1772 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1773#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001774
1775 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1776 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1777 // to do that job on OSX.
1778
1779 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001780 {
Jim Ingham90331d52014-02-21 01:25:21 +00001781 // We don't need to do this for ARM, and we really shouldn't now that we
1782 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1783 // to set which CPU subtype to launch...
1784 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1785 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1786 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1787 if (cpu != 0 &&
1788 cpu != UINT32_MAX &&
1789 cpu != LLDB_INVALID_CPUTYPE &&
1790 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1791 {
1792 size_t ocount = 0;
1793 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1794 if (error.Fail() || log)
1795 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu, (uint64_t)ocount);
Todd Fiala76747122014-01-23 00:52:28 +00001796
Jim Ingham90331d52014-02-21 01:25:21 +00001797 if (error.Fail() || ocount != 1)
1798 return error;
1799 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001800 }
1801
Todd Fiala76747122014-01-23 00:52:28 +00001802#endif
1803
1804 const char *tmp_argv[2];
1805 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1806 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1807 if (argv == NULL)
1808 {
1809 // posix_spawn gets very unhappy if it doesn't have at least the program
1810 // name in argv[0]. One of the side affects I have noticed is the environment
1811 // variables don't make it into the child process if "argv == NULL"!!!
1812 tmp_argv[0] = exe_path;
1813 tmp_argv[1] = NULL;
1814 argv = (char * const*)tmp_argv;
1815 }
1816
1817#if !defined (__APPLE__)
1818 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001819 char current_dir[PATH_MAX];
1820 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001821#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001822
1823 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001824 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001825 {
Todd Fiala76747122014-01-23 00:52:28 +00001826#if defined (__APPLE__)
1827 // Set the working directory on this thread only
1828 if (__pthread_chdir (working_dir) < 0) {
1829 if (errno == ENOENT) {
1830 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1831 } else if (errno == ENOTDIR) {
1832 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1833 } else {
1834 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1835 }
1836 return error;
1837 }
1838#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001839 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1840 {
1841 error.SetError(errno, eErrorTypePOSIX);
1842 error.LogIfError(log, "unable to save the current directory");
1843 return error;
1844 }
1845
1846 if (::chdir(working_dir) == -1)
1847 {
1848 error.SetError(errno, eErrorTypePOSIX);
1849 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1850 return error;
1851 }
Todd Fiala76747122014-01-23 00:52:28 +00001852#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001853 }
1854
Todd Fiala76747122014-01-23 00:52:28 +00001855 const size_t num_file_actions = launch_info.GetNumFileActions ();
1856 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001857 {
Todd Fiala76747122014-01-23 00:52:28 +00001858 posix_spawn_file_actions_t file_actions;
1859 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1860 if (error.Fail() || log)
1861 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1862 if (error.Fail())
1863 return error;
1864
1865 // Make a quick class that will cleanup the posix spawn attributes in case
1866 // we return in the middle of this function.
1867 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1868
1869 for (size_t i=0; i<num_file_actions; ++i)
1870 {
1871 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1872 if (launch_file_action)
1873 {
1874 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1875 launch_file_action,
1876 log,
1877 error))
1878 return error;
1879 }
1880 }
1881
1882 error.SetError (::posix_spawnp (&pid,
1883 exe_path,
1884 &file_actions,
1885 &attr,
1886 argv,
1887 envp),
1888 eErrorTypePOSIX);
1889
1890 if (error.Fail() || log)
1891 {
1892 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1893 pid,
1894 exe_path,
1895 &file_actions,
1896 &attr,
1897 argv,
1898 envp);
1899 if (log)
1900 {
1901 for (int ii=0; argv[ii]; ++ii)
1902 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1903 }
1904 }
1905
1906 }
1907 else
1908 {
1909 error.SetError (::posix_spawnp (&pid,
1910 exe_path,
1911 NULL,
1912 &attr,
1913 argv,
1914 envp),
1915 eErrorTypePOSIX);
1916
1917 if (error.Fail() || log)
1918 {
1919 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
1920 pid,
1921 exe_path,
1922 &attr,
1923 argv,
1924 envp);
1925 if (log)
1926 {
1927 for (int ii=0; argv[ii]; ++ii)
1928 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1929 }
1930 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001931 }
1932
Todd Fiala76747122014-01-23 00:52:28 +00001933 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001934 {
Todd Fiala76747122014-01-23 00:52:28 +00001935#if defined (__APPLE__)
1936 // No more thread specific current working directory
1937 __pthread_fchdir (-1);
1938#else
1939 if (::chdir(current_dir) == -1 && error.Success())
1940 {
1941 error.SetError(errno, eErrorTypePOSIX);
1942 error.LogIfError(log, "unable to change current directory back to %s",
1943 current_dir);
1944 }
1945#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001946 }
1947
1948 return error;
1949}
1950
Todd Fiala76747122014-01-23 00:52:28 +00001951#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1952
1953
1954#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__)
1955// The functions below implement process launching via posix_spawn() for Linux
1956// and FreeBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001957
1958Error
1959Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1960{
1961 Error error;
1962 char exe_path[PATH_MAX];
1963
1964 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1965
1966 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1967
1968 FileSpec exe_spec(launch_info.GetExecutableFile());
1969
1970 FileSpec::FileType file_type = exe_spec.GetFileType();
1971 if (file_type != FileSpec::eFileTypeRegular)
1972 {
1973 lldb::ModuleSP exe_module_sp;
1974 error = host_platform_sp->ResolveExecutable (exe_spec,
1975 arch_spec,
1976 exe_module_sp,
1977 NULL);
1978
1979 if (error.Fail())
1980 return error;
1981
1982 if (exe_module_sp)
1983 exe_spec = exe_module_sp->GetFileSpec();
1984 }
1985
1986 if (exe_spec.Exists())
1987 {
1988 exe_spec.GetPath (exe_path, sizeof(exe_path));
1989 }
1990 else
1991 {
1992 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1993 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1994 return error;
1995 }
1996
1997 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1998
1999 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2000
2001 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2002
2003 if (pid != LLDB_INVALID_PROCESS_ID)
2004 {
2005 // If all went well, then set the process ID into the launch info
2006 launch_info.SetProcessID(pid);
2007
Todd Fiala76747122014-01-23 00:52:28 +00002008 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2009
Daniel Malea4244cbd2013-08-27 20:58:59 +00002010 // Make sure we reap any processes we spawn or we will have zombies.
2011 if (!launch_info.MonitorProcess())
2012 {
2013 const bool monitor_signals = false;
2014 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2015 NULL,
2016 pid,
2017 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002018 if (log)
2019 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2020 }
2021 else
2022 {
2023 if (log)
2024 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002025 }
2026 }
2027 else
2028 {
2029 // Invalid process ID, something didn't go well
2030 if (error.Success())
2031 error.SetErrorString ("process launch failed for unknown reasons");
2032 }
2033 return error;
2034}
2035
2036#endif // defined(__linux__) or defined(__FreeBSD__)
2037
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002038#ifndef _WIN32
2039
2040size_t
2041Host::GetPageSize()
2042{
2043 return ::getpagesize();
2044}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002045
Greg Claytone3e3fee2013-02-17 20:46:30 +00002046uint32_t
2047Host::GetNumberCPUS ()
2048{
2049 static uint32_t g_num_cores = UINT32_MAX;
2050 if (g_num_cores == UINT32_MAX)
2051 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002052#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002053
2054 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002055
Greg Claytone3e3fee2013-02-17 20:46:30 +00002056#else
2057
2058 // Assume POSIX support if a host specific case has not been supplied above
2059 g_num_cores = 0;
2060 int num_cores = 0;
2061 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002062#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002063 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002064#else
2065 int mib[] = { CTL_HW, HW_NCPU };
2066#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002067
2068 /* get the number of CPUs from the system */
2069 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
2070 {
2071 g_num_cores = num_cores;
2072 }
2073 else
2074 {
2075 mib[1] = HW_NCPU;
2076 num_cores_len = sizeof(num_cores);
2077 if (sysctl(mib, sizeof(mib)/sizeof(int), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
2078 {
2079 if (num_cores > 0)
2080 g_num_cores = num_cores;
2081 }
2082 }
2083#endif
2084 }
2085 return g_num_cores;
2086}
2087
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002088void
2089Host::Kill(lldb::pid_t pid, int signo)
2090{
2091 ::kill(pid, signo);
2092}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002093
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002094#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002095
Johnny Chen8f3d8382011-08-02 20:52:42 +00002096#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002097bool
Greg Clayton3b147632010-12-18 01:54:34 +00002098Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002099{
2100 return false;
2101}
Greg Claytondd36def2010-10-17 22:03:32 +00002102
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002103void
2104Host::SetCrashDescriptionWithFormat (const char *format, ...)
2105{
2106}
2107
2108void
2109Host::SetCrashDescription (const char *description)
2110{
2111}
Greg Claytondd36def2010-10-17 22:03:32 +00002112
2113lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002114Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002115{
2116 return LLDB_INVALID_PROCESS_ID;
2117}
2118
Greg Claytonfbb76342013-11-20 21:07:01 +00002119#endif
2120
2121
2122#ifdef LLDB_DISABLE_POSIX
2123
2124Error
2125Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002126{
Greg Claytonfbb76342013-11-20 21:07:01 +00002127 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002128 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002129 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002130}
Greg Claytonfbb76342013-11-20 21:07:01 +00002131
2132Error
2133Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2134{
2135 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002136 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002137 return error;
2138}
2139
2140Error
2141Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2142{
2143 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002144 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002145 return error;
2146}
2147
2148Error
2149Host::Symlink (const char *src, const char *dst)
2150{
2151 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002152 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002153 return error;
2154}
2155
2156Error
2157Host::Readlink (const char *path, char *buf, size_t buf_len)
2158{
2159 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002160 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002161 return error;
2162}
2163
2164Error
2165Host::Unlink (const char *path)
2166{
2167 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002168 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002169 return error;
2170}
2171
Greg Clayton23f8c952014-03-24 23:10:19 +00002172Error
2173Host::RemoveDirectory (const char* path, bool recurse)
2174{
2175 Error error;
2176 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2177 return error;
2178}
2179
Greg Claytonfbb76342013-11-20 21:07:01 +00002180#else
2181
2182Error
2183Host::MakeDirectory (const char* path, uint32_t file_permissions)
2184{
2185 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002186 if (path && path[0])
2187 {
Greg Claytonfb909312013-11-23 01:58:15 +00002188 if (::mkdir(path, file_permissions) != 0)
2189 {
2190 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002191 switch (error.GetError())
2192 {
2193 case ENOENT:
2194 {
2195 // Parent directory doesn't exist, so lets make it if we can
2196 FileSpec spec(path, false);
2197 if (spec.GetDirectory() && spec.GetFilename())
2198 {
2199 // Make the parent directory and try again
2200 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2201 if (error2.Success())
2202 {
2203 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002204 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002205 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002206 else
Greg Claytonfb909312013-11-23 01:58:15 +00002207 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002208 }
2209 }
2210 }
2211 break;
2212 case EEXIST:
2213 {
2214 FileSpec path_spec(path, false);
2215 if (path_spec.IsDirectory())
2216 error.Clear(); // It is a directory and it already exists
2217 }
2218 break;
2219 }
2220 }
Greg Claytonfb909312013-11-23 01:58:15 +00002221 }
2222 else
2223 {
2224 error.SetErrorString("empty path");
2225 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002226 return error;
2227}
Greg Clayton23f8c952014-03-24 23:10:19 +00002228
2229Error
2230Host::RemoveDirectory (const char* path, bool recurse)
2231{
2232 Error error;
2233 if (path && path[0])
2234 {
2235 if (recurse)
2236 {
2237 StreamString command;
2238 command.Printf("rm -rf \"%s\"", path);
2239 int status = ::system(command.GetString().c_str());
2240 if (status != 0)
2241 error.SetError(status, eErrorTypeGeneric);
2242 }
2243 else
2244 {
2245 if (::rmdir(path) != 0)
2246 error.SetErrorToErrno();
2247 }
2248 }
2249 else
2250 {
2251 error.SetErrorString("empty path");
2252 }
2253 return error;
2254}
Greg Claytonfbb76342013-11-20 21:07:01 +00002255
2256Error
2257Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2258{
2259 Error error;
2260 struct stat file_stats;
2261 if (::stat (path, &file_stats) == 0)
2262 {
2263 // The bits in "st_mode" currently match the definitions
2264 // for the file mode bits in unix.
2265 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2266 }
2267 else
2268 {
2269 error.SetErrorToErrno();
2270 }
2271 return error;
2272}
2273
2274Error
2275Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2276{
2277 Error error;
2278 if (::chmod(path, file_permissions) != 0)
2279 error.SetErrorToErrno();
2280 return error;
2281}
2282
2283Error
2284Host::Symlink (const char *src, const char *dst)
2285{
2286 Error error;
2287 if (::symlink(dst, src) == -1)
2288 error.SetErrorToErrno();
2289 return error;
2290}
2291
2292Error
2293Host::Unlink (const char *path)
2294{
2295 Error error;
2296 if (::unlink(path) == -1)
2297 error.SetErrorToErrno();
2298 return error;
2299}
2300
2301Error
2302Host::Readlink (const char *path, char *buf, size_t buf_len)
2303{
2304 Error error;
2305 ssize_t count = ::readlink(path, buf, buf_len);
2306 if (count < 0)
2307 error.SetErrorToErrno();
2308 else if (count < (buf_len-1))
2309 buf[count] = '\0'; // Success
2310 else
2311 error.SetErrorString("'buf' buffer is too small to contain link contents");
2312 return error;
2313}
2314
2315
Greg Clayton2bddd342010-09-07 20:11:56 +00002316#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002317
2318typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2319FDToFileMap& GetFDToFileMap()
2320{
2321 static FDToFileMap g_fd2filemap;
2322 return g_fd2filemap;
2323}
2324
2325lldb::user_id_t
2326Host::OpenFile (const FileSpec& file_spec,
2327 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002328 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002329 Error &error)
2330{
2331 std::string path (file_spec.GetPath());
2332 if (path.empty())
2333 {
2334 error.SetErrorString("empty path");
2335 return UINT64_MAX;
2336 }
2337 FileSP file_sp(new File());
2338 error = file_sp->Open(path.c_str(),flags,mode);
2339 if (file_sp->IsValid() == false)
2340 return UINT64_MAX;
2341 lldb::user_id_t fd = file_sp->GetDescriptor();
2342 GetFDToFileMap()[fd] = file_sp;
2343 return fd;
2344}
2345
2346bool
2347Host::CloseFile (lldb::user_id_t fd, Error &error)
2348{
2349 if (fd == UINT64_MAX)
2350 {
2351 error.SetErrorString ("invalid file descriptor");
2352 return false;
2353 }
2354 FDToFileMap& file_map = GetFDToFileMap();
2355 FDToFileMap::iterator pos = file_map.find(fd);
2356 if (pos == file_map.end())
2357 {
2358 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2359 return false;
2360 }
2361 FileSP file_sp = pos->second;
2362 if (!file_sp)
2363 {
2364 error.SetErrorString ("invalid host backing file");
2365 return false;
2366 }
2367 error = file_sp->Close();
2368 file_map.erase(pos);
2369 return error.Success();
2370}
2371
2372uint64_t
2373Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2374{
2375 if (fd == UINT64_MAX)
2376 {
2377 error.SetErrorString ("invalid file descriptor");
2378 return UINT64_MAX;
2379 }
2380 FDToFileMap& file_map = GetFDToFileMap();
2381 FDToFileMap::iterator pos = file_map.find(fd);
2382 if (pos == file_map.end())
2383 {
2384 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2385 return false;
2386 }
2387 FileSP file_sp = pos->second;
2388 if (!file_sp)
2389 {
2390 error.SetErrorString ("invalid host backing file");
2391 return UINT64_MAX;
2392 }
2393 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2394 return UINT64_MAX;
2395 size_t bytes_written = src_len;
2396 error = file_sp->Write(src, bytes_written);
2397 if (error.Fail())
2398 return UINT64_MAX;
2399 return bytes_written;
2400}
2401
2402uint64_t
2403Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2404{
2405 if (fd == UINT64_MAX)
2406 {
2407 error.SetErrorString ("invalid file descriptor");
2408 return UINT64_MAX;
2409 }
2410 FDToFileMap& file_map = GetFDToFileMap();
2411 FDToFileMap::iterator pos = file_map.find(fd);
2412 if (pos == file_map.end())
2413 {
2414 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2415 return false;
2416 }
2417 FileSP file_sp = pos->second;
2418 if (!file_sp)
2419 {
2420 error.SetErrorString ("invalid host backing file");
2421 return UINT64_MAX;
2422 }
2423 if (file_sp->SeekFromStart(offset, &error) != offset || error.Fail())
2424 return UINT64_MAX;
2425 size_t bytes_read = dst_len;
2426 error = file_sp->Read(dst ,bytes_read);
2427 if (error.Fail())
2428 return UINT64_MAX;
2429 return bytes_read;
2430}
2431
2432lldb::user_id_t
2433Host::GetFileSize (const FileSpec& file_spec)
2434{
2435 return file_spec.GetByteSize();
2436}
2437
2438bool
2439Host::GetFileExists (const FileSpec& file_spec)
2440{
2441 return file_spec.Exists();
2442}
2443
2444bool
2445Host::CalculateMD5 (const FileSpec& file_spec,
2446 uint64_t &low,
2447 uint64_t &high)
2448{
2449#if defined (__APPLE__)
2450 StreamString md5_cmd_line;
2451 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2452 std::string hash_string;
2453 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2454 if (err.Fail())
2455 return false;
2456 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2457 // if the output is any other length it is probably wrong
2458 if (hash_string.size() != 32)
2459 return false;
2460 std::string part1(hash_string,0,16);
2461 std::string part2(hash_string,16);
2462 const char* part1_cstr = part1.c_str();
2463 const char* part2_cstr = part2.c_str();
2464 high = ::strtoull(part1_cstr, NULL, 16);
2465 low = ::strtoull(part2_cstr, NULL, 16);
2466 return true;
2467#else
2468 // your own MD5 implementation here
2469 return false;
2470#endif
2471}