blob: 885104fecbfdabe1f5617eef66098d252038bb4a [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>
Todd Fialae88aea32014-07-24 23:22:58 +000040#ifndef CPU_SUBTYPE_X86_64_H
41#define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t)8)
42#endif
Ed Maste8b006c62013-06-25 18:58:11 +000043#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000044
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +000045#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000046#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000047#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000048#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000049#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000050
Ed Maste8b006c62013-06-25 18:58:11 +000051#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000052#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000053#endif
54
Todd Fiala17096d72014-07-16 19:03:16 +000055// C++ includes
56#include <limits>
57
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Host/Host.h"
59#include "lldb/Core/ArchSpec.h"
60#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000061#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000062#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000064#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000065#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000066#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000067#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000068#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000069#include "lldb/Host/FileSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000070#include "lldb/Host/FileSystem.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000071#include "lldb/Host/Mutex.h"
Zachary Turner696b5282014-08-14 16:01:25 +000072#include "lldb/Target/FileAction.h"
Greg Claytone996fd32011-03-08 22:40:15 +000073#include "lldb/Target/Process.h"
Zachary Turner696b5282014-08-14 16:01:25 +000074#include "lldb/Target/ProcessLaunchInfo.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000075#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000076#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000077
Saleem Abdulrasool28606952014-06-27 05:17:41 +000078#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000079#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000080#include "llvm/Support/Host.h"
Zachary Turner9e757b72014-07-28 16:45:05 +000081#include "llvm/Support/Path.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000082#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000083
Todd Fiala76747122014-01-23 00:52:28 +000084#if defined (__APPLE__)
85#ifndef _POSIX_SPAWN_DISABLE_ASLR
86#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
87#endif
88
89extern "C"
90{
91 int __pthread_chdir(const char *path);
92 int __pthread_fchdir (int fildes);
93}
94
95#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000096
Greg Clayton2bddd342010-09-07 20:11:56 +000097using namespace lldb;
98using namespace lldb_private;
99
Todd Fiala17096d72014-07-16 19:03:16 +0000100// Define maximum thread name length
101#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
102uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
103#else
104uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
105#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000106
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000107#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000108struct MonitorInfo
109{
110 lldb::pid_t pid; // The process ID to monitor
111 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
112 void *callback_baton; // The callback baton for the callback function
113 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
114};
115
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000116static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000117MonitorChildProcessThreadFunction (void *arg);
118
119lldb::thread_t
120Host::StartMonitoringChildProcess
121(
122 Host::MonitorChildProcessCallback callback,
123 void *callback_baton,
124 lldb::pid_t pid,
125 bool monitor_signals
126)
127{
128 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000129 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000130
Greg Claytone4e45922011-11-16 05:37:56 +0000131 info_ptr->pid = pid;
132 info_ptr->callback = callback;
133 info_ptr->callback_baton = callback_baton;
134 info_ptr->monitor_signals = monitor_signals;
135
136 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000137 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000138 thread = ThreadCreate (thread_name,
139 MonitorChildProcessThreadFunction,
140 info_ptr,
141 NULL);
142
Greg Clayton2bddd342010-09-07 20:11:56 +0000143 return thread;
144}
145
146//------------------------------------------------------------------
147// Scoped class that will disable thread canceling when it is
148// constructed, and exception safely restore the previous value it
149// when it goes out of scope.
150//------------------------------------------------------------------
151class ScopedPThreadCancelDisabler
152{
153public:
154 ScopedPThreadCancelDisabler()
155 {
156 // Disable the ability for this thread to be cancelled
157 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
158 if (err != 0)
159 m_old_state = -1;
160
161 }
162
163 ~ScopedPThreadCancelDisabler()
164 {
165 // Restore the ability for this thread to be cancelled to what it
166 // previously was.
167 if (m_old_state != -1)
168 ::pthread_setcancelstate (m_old_state, 0);
169 }
170private:
171 int m_old_state; // Save the old cancelability state.
172};
173
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000174static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000175MonitorChildProcessThreadFunction (void *arg)
176{
Greg Clayton5160ce52013-03-27 23:08:40 +0000177 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000178 const char *function = __FUNCTION__;
179 if (log)
180 log->Printf ("%s (arg = %p) thread starting...", function, arg);
181
182 MonitorInfo *info = (MonitorInfo *)arg;
183
184 const Host::MonitorChildProcessCallback callback = info->callback;
185 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000186 const bool monitor_signals = info->monitor_signals;
187
Daniel Malea4244cbd2013-08-27 20:58:59 +0000188 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000189 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000190
Greg Clayton2bddd342010-09-07 20:11:56 +0000191 delete info;
192
193 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000194#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000195 #define __WALL 0
196#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000197 const int options = __WALL;
198
Greg Clayton2bddd342010-09-07 20:11:56 +0000199 while (1)
200 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000201 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000202 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000203 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000204
205 // Wait for all child processes
206 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000207 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000208 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000209 ::pthread_testcancel ();
210
211 if (wait_pid == -1)
212 {
213 if (errno == EINTR)
214 continue;
215 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000216 {
217 if (log)
218 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000219 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000220 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000221 }
Matt Kopec650648f2013-01-08 16:30:18 +0000222 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000223 {
224 bool exited = false;
225 int signal = 0;
226 int exit_status = 0;
227 const char *status_cstr = NULL;
228 if (WIFSTOPPED(status))
229 {
230 signal = WSTOPSIG(status);
231 status_cstr = "STOPPED";
232 }
233 else if (WIFEXITED(status))
234 {
235 exit_status = WEXITSTATUS(status);
236 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000237 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000238 }
239 else if (WIFSIGNALED(status))
240 {
241 signal = WTERMSIG(status);
242 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000243 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000244 exited = true;
245 exit_status = -1;
246 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000247 }
248 else
249 {
Johnny Chen44805302011-07-19 19:48:13 +0000250 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000251 }
252
253 // Scope for pthread_cancel_disabler
254 {
255 ScopedPThreadCancelDisabler pthread_cancel_disabler;
256
Caroline Tice20ad3c42010-10-29 21:48:37 +0000257 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000259 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 +0000260 function,
261 wait_pid,
262 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000263 pid,
264 status,
265 status_cstr,
266 signal,
267 exit_status);
268
269 if (exited || (signal != 0 && monitor_signals))
270 {
Greg Claytone4e45922011-11-16 05:37:56 +0000271 bool callback_return = false;
272 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000273 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000274
275 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000276 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000277 {
278 if (log)
279 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000280 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000281 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000282 // If the callback returns true, it means this process should
283 // exit
284 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000285 {
286 if (log)
287 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000288 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000289 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000290 }
291 }
292 }
293 }
294
Caroline Tice20ad3c42010-10-29 21:48:37 +0000295 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000296 if (log)
297 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
298
299 return NULL;
300}
301
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000302#endif // #if !defined (__APPLE__) && !defined (_WIN32)
303
304#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000305
306void
307Host::SystemLog (SystemLogType type, const char *format, va_list args)
308{
309 vfprintf (stderr, format, args);
310}
311
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000312#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000313
Greg Claytone38a5ed2012-01-05 03:57:59 +0000314void
315Host::SystemLog (SystemLogType type, const char *format, ...)
316{
317 va_list args;
318 va_start (args, format);
319 SystemLog (type, format, args);
320 va_end (args);
321}
322
Greg Clayton2bddd342010-09-07 20:11:56 +0000323const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000324Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000325{
Greg Clayton514487e2011-02-15 21:59:32 +0000326 static bool g_supports_32 = false;
327 static bool g_supports_64 = false;
328 static ArchSpec g_host_arch_32;
329 static ArchSpec g_host_arch_64;
330
Greg Clayton2bddd342010-09-07 20:11:56 +0000331#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000332
333 // Apple is different in that it can support both 32 and 64 bit executables
334 // in the same operating system running concurrently. Here we detect the
335 // correct host architectures for both 32 and 64 bit including if 64 bit
336 // executables are supported on the system.
337
338 if (g_supports_32 == false && g_supports_64 == false)
339 {
340 // All apple systems support 32 bit execution.
341 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000342 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000343 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000344 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000345 ArchSpec host_arch;
346 // These will tell us about the kernel architecture, which even on a 64
347 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000348 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
349 {
Greg Clayton514487e2011-02-15 21:59:32 +0000350 len = sizeof (cpusubtype);
351 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
352 cpusubtype = CPU_TYPE_ANY;
353
Greg Clayton2bddd342010-09-07 20:11:56 +0000354 len = sizeof (is_64_bit_capable);
355 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
356 {
357 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000358 g_supports_64 = true;
359 }
360
361 if (is_64_bit_capable)
362 {
363 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000364 {
Greg Clayton514487e2011-02-15 21:59:32 +0000365 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000366 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000367 }
368 else
369 {
Greg Clayton52edb362014-07-14 22:53:02 +0000370 // We have a 64 bit kernel that is returning a 32 bit cputype, the
371 // cpusubtype will be correct as if it were for a 64 bit architecture
372 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype | CPU_ARCH_ABI64, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000373 }
Greg Clayton52edb362014-07-14 22:53:02 +0000374
375 // Now we need modify the cpusubtype for the 32 bit slices.
376 uint32_t cpusubtype32 = cpusubtype;
377#if defined (__i386__) || defined (__x86_64__)
378 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
379 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
380#elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
381 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
382 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
383#endif
384 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype & ~(CPU_ARCH_MASK), cpusubtype32);
Greg Claytonc76fa8a2014-07-29 21:27:21 +0000385
386 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
387 {
388 g_host_arch_32.GetTriple().setOS(llvm::Triple::IOS);
389 g_host_arch_64.GetTriple().setOS(llvm::Triple::IOS);
390 }
391 else
392 {
393 g_host_arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
394 g_host_arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
395 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000396 }
Greg Clayton514487e2011-02-15 21:59:32 +0000397 else
398 {
Greg Clayton52edb362014-07-14 22:53:02 +0000399 // We have a 32 bit kernel on a 32 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000400 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000401 g_host_arch_64.Clear();
402 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000403 }
Greg Clayton514487e2011-02-15 21:59:32 +0000404 }
405
406#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000407
Greg Clayton514487e2011-02-15 21:59:32 +0000408 if (g_supports_32 == false && g_supports_64 == false)
409 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000410 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000411
Stephen Wilsonbd588712011-02-24 19:15:09 +0000412 g_host_arch_32.Clear();
413 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000414
Greg Claytonb29e6c62012-10-11 17:38:58 +0000415 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
416 // for the default triple. It's probably an artifact of config.guess.
417 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000418 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000419
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000420 const char* distribution_id = GetDistributionId ().AsCString();
421
Stephen Wilsonbd588712011-02-24 19:15:09 +0000422 switch (triple.getArch())
423 {
424 default:
425 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000426 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000427 g_supports_32 = true;
428 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000429
Stephen Wilsonbd588712011-02-24 19:15:09 +0000430 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000431 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000432 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000433 g_supports_64 = true;
434 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000435 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000436 g_supports_32 = true;
437 break;
438
Ed Mastea8375762014-04-01 18:06:45 +0000439 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000440 case llvm::Triple::sparcv9:
441 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000442 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000443 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000444 g_supports_64 = true;
445 break;
446 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000447
448 g_supports_32 = g_host_arch_32.IsValid();
449 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000450 }
Greg Clayton514487e2011-02-15 21:59:32 +0000451
452#endif // #else for #if defined (__APPLE__)
453
454 if (arch_kind == eSystemDefaultArchitecture32)
455 return g_host_arch_32;
456 else if (arch_kind == eSystemDefaultArchitecture64)
457 return g_host_arch_64;
458
459 if (g_supports_64)
460 return g_host_arch_64;
461
462 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000463}
464
465const ConstString &
466Host::GetVendorString()
467{
468 static ConstString g_vendor;
469 if (!g_vendor)
470 {
Greg Clayton950971f2012-05-12 00:01:21 +0000471 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
472 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
473 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000474 }
475 return g_vendor;
476}
477
478const ConstString &
479Host::GetOSString()
480{
481 static ConstString g_os_string;
482 if (!g_os_string)
483 {
Greg Clayton950971f2012-05-12 00:01:21 +0000484 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
485 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
486 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000487 }
488 return g_os_string;
489}
490
491const ConstString &
492Host::GetTargetTriple()
493{
494 static ConstString g_host_triple;
495 if (!(g_host_triple))
496 {
Greg Clayton950971f2012-05-12 00:01:21 +0000497 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
498 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000499 }
500 return g_host_triple;
501}
502
Todd Fialaf3d61de2014-01-17 20:18:59 +0000503// See linux/Host.cpp for Linux-based implementations of this.
504// Add your platform-specific implementation to the appropriate host file.
505#if !defined(__linux__)
506
507const ConstString &
508 Host::GetDistributionId ()
509{
510 static ConstString s_distribution_id;
511 return s_distribution_id;
512}
513
514#endif // #if !defined(__linux__)
515
Greg Clayton2bddd342010-09-07 20:11:56 +0000516lldb::pid_t
517Host::GetCurrentProcessID()
518{
519 return ::getpid();
520}
521
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000522#ifndef _WIN32
523
Greg Clayton2bddd342010-09-07 20:11:56 +0000524lldb::tid_t
525Host::GetCurrentThreadID()
526{
527#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000528 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000529 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
530 // count.
531 thread_port_t thread_self = mach_thread_self();
532 mach_port_deallocate(mach_task_self(), thread_self);
533 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000534#elif defined(__FreeBSD__)
535 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000536#elif defined(__linux__)
537 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000538#else
539 return lldb::tid_t(pthread_self());
540#endif
541}
542
Jim Ingham372787f2012-04-07 00:00:41 +0000543lldb::thread_t
544Host::GetCurrentThread ()
545{
546 return lldb::thread_t(pthread_self());
547}
548
Greg Clayton2bddd342010-09-07 20:11:56 +0000549const char *
550Host::GetSignalAsCString (int signo)
551{
552 switch (signo)
553 {
554 case SIGHUP: return "SIGHUP"; // 1 hangup
555 case SIGINT: return "SIGINT"; // 2 interrupt
556 case SIGQUIT: return "SIGQUIT"; // 3 quit
557 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
558 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
559 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000560#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000561#if !defined(SIGIO) || (SIGPOLL != SIGIO)
562// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
563// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000564 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000565#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000566#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000567#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000568 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000569#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000570 case SIGFPE: return "SIGFPE"; // 8 floating point exception
571 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
572 case SIGBUS: return "SIGBUS"; // 10 bus error
573 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
574 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
575 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
576 case SIGALRM: return "SIGALRM"; // 14 alarm clock
577 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
578 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
579 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
580 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
581 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
582 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
583 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
584 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000585#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000586 case SIGIO: return "SIGIO"; // 23 input/output possible signal
587#endif
588 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
589 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
590 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
591 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000592#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000593 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000594#endif
595#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000596 case SIGINFO: return "SIGINFO"; // 29 information request
597#endif
598 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
599 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
600 default:
601 break;
602 }
603 return NULL;
604}
605
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000606#endif
607
Greg Clayton2bddd342010-09-07 20:11:56 +0000608void
609Host::WillTerminate ()
610{
611}
612
Sylvestre Ledru59405832013-07-01 08:21:36 +0000613#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000614
Greg Clayton2bddd342010-09-07 20:11:56 +0000615void
616Host::ThreadCreated (const char *thread_name)
617{
618}
Greg Claytone5219662010-12-03 06:02:24 +0000619
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000620void
Greg Claytone5219662010-12-03 06:02:24 +0000621Host::Backtrace (Stream &strm, uint32_t max_frames)
622{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000623 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000624}
625
Greg Clayton85851dd2010-12-04 00:10:17 +0000626size_t
627Host::GetEnvironment (StringList &env)
628{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000629 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000630 return 0;
631}
632
Sylvestre Ledru59405832013-07-01 08:21:36 +0000633#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000634
635struct HostThreadCreateInfo
636{
637 std::string thread_name;
638 thread_func_t thread_fptr;
639 thread_arg_t thread_arg;
640
641 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
642 thread_name (name ? name : ""),
643 thread_fptr (fptr),
644 thread_arg (arg)
645 {
646 }
647};
648
649static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000650#ifdef _WIN32
651__stdcall
652#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000653ThreadCreateTrampoline (thread_arg_t arg)
654{
655 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
656 Host::ThreadCreated (info->thread_name.c_str());
657 thread_func_t thread_fptr = info->thread_fptr;
658 thread_arg_t thread_arg = info->thread_arg;
659
Greg Clayton5160ce52013-03-27 23:08:40 +0000660 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000661 if (log)
662 log->Printf("thread created");
663
664 delete info;
665 return thread_fptr (thread_arg);
666}
667
668lldb::thread_t
669Host::ThreadCreate
670(
671 const char *thread_name,
672 thread_func_t thread_fptr,
673 thread_arg_t thread_arg,
674 Error *error
675)
676{
677 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
678
679 // Host::ThreadCreateTrampoline will delete this pointer for us.
680 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
681
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000682#ifdef _WIN32
683 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
684 int err = thread <= 0 ? GetLastError() : 0;
685#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000686 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000687#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000688 if (err == 0)
689 {
690 if (error)
691 error->Clear();
692 return thread;
693 }
694
695 if (error)
696 error->SetError (err, eErrorTypePOSIX);
697
698 return LLDB_INVALID_HOST_THREAD;
699}
700
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000701#ifndef _WIN32
702
Greg Clayton2bddd342010-09-07 20:11:56 +0000703bool
704Host::ThreadCancel (lldb::thread_t thread, Error *error)
705{
706 int err = ::pthread_cancel (thread);
707 if (error)
708 error->SetError(err, eErrorTypePOSIX);
709 return err == 0;
710}
711
712bool
713Host::ThreadDetach (lldb::thread_t thread, Error *error)
714{
715 int err = ::pthread_detach (thread);
716 if (error)
717 error->SetError(err, eErrorTypePOSIX);
718 return err == 0;
719}
720
721bool
722Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
723{
724 int err = ::pthread_join (thread, thread_result_ptr);
725 if (error)
726 error->SetError(err, eErrorTypePOSIX);
727 return err == 0;
728}
729
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000730lldb::thread_key_t
731Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
732{
733 pthread_key_t key;
734 ::pthread_key_create (&key, callback);
735 return key;
736}
737
738void*
739Host::ThreadLocalStorageGet(lldb::thread_key_t key)
740{
741 return ::pthread_getspecific (key);
742}
743
744void
745Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
746{
747 ::pthread_setspecific (key, value);
748}
749
Matt Kopec62502c62013-05-13 19:33:58 +0000750bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000751Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
752{
Greg Clayton85719632013-02-27 22:51:58 +0000753#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000754 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
755 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
756 if (pid == LLDB_INVALID_PROCESS_ID)
757 pid = curr_pid;
758
759 if (tid == LLDB_INVALID_THREAD_ID)
760 tid = curr_tid;
761
Greg Clayton2bddd342010-09-07 20:11:56 +0000762 // Set the pthread name if possible
763 if (pid == curr_pid && tid == curr_tid)
764 {
Matt Kopec62502c62013-05-13 19:33:58 +0000765 if (::pthread_setname_np (name) == 0)
766 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000767 }
Matt Kopec62502c62013-05-13 19:33:58 +0000768 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000769#elif defined (__FreeBSD__)
770 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
771 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
772 if (pid == LLDB_INVALID_PROCESS_ID)
773 pid = curr_pid;
774
775 if (tid == LLDB_INVALID_THREAD_ID)
776 tid = curr_tid;
777
778 // Set the pthread name if possible
779 if (pid == curr_pid && tid == curr_tid)
780 {
Michael Sartainc2052432013-08-01 18:51:08 +0000781 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000782 return true;
783 }
784 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000785#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000786 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
787 if (fn)
788 {
Matt Kopec62502c62013-05-13 19:33:58 +0000789 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
790 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000791 if (pid == LLDB_INVALID_PROCESS_ID)
792 pid = curr_pid;
793
794 if (tid == LLDB_INVALID_THREAD_ID)
795 tid = curr_tid;
796
Michael Sartainc2052432013-08-01 18:51:08 +0000797 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000798 {
Michael Sartainc2052432013-08-01 18:51:08 +0000799 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
800 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
801
802 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000803 return true;
804 }
805 }
806 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000807#else
808 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000809#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000810}
811
Ed Maste02983be2013-07-25 19:10:32 +0000812bool
813Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
814 const char *thread_name, size_t len)
815{
Enrico Granata67530b62014-02-12 03:37:33 +0000816 std::unique_ptr<char[]> namebuf(new char[len+1]);
817
Ed Maste02983be2013-07-25 19:10:32 +0000818 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
819 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
820 // off leads to a lot of similar named threads. Go through the thread name
821 // and search for the last dot and use that.
822 const char *lastdot = ::strrchr (thread_name, '.');
823
824 if (lastdot && lastdot != thread_name)
825 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000826 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000827 namebuf[len] = 0;
828
Enrico Granata67530b62014-02-12 03:37:33 +0000829 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000830 if (namebuflen > 0)
831 {
832 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
833 {
834 // Trim off trailing '(' and '>' characters for a bit more cleanup.
835 namebuflen--;
836 namebuf[namebuflen] = 0;
837 }
Enrico Granata67530b62014-02-12 03:37:33 +0000838 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000839 }
840 return false;
841}
842
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000843#endif
844
Greg Clayton2bddd342010-09-07 20:11:56 +0000845FileSpec
Zachary Turner9e757b72014-07-28 16:45:05 +0000846Host::GetUserProfileFileSpec ()
847{
848 static FileSpec g_profile_filespec;
849 if (!g_profile_filespec)
850 {
851 llvm::SmallString<64> path;
852 llvm::sys::path::home_directory(path);
853 return FileSpec(path.c_str(), false);
854 }
855 return g_profile_filespec;
856}
857
858FileSpec
Greg Clayton2bddd342010-09-07 20:11:56 +0000859Host::GetProgramFileSpec ()
860{
861 static FileSpec g_program_filespec;
862 if (!g_program_filespec)
863 {
864#if defined (__APPLE__)
865 char program_fullpath[PATH_MAX];
866 // If DST is NULL, then return the number of bytes needed.
867 uint32_t len = sizeof(program_fullpath);
868 int err = _NSGetExecutablePath (program_fullpath, &len);
869 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000870 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000871 else if (err == -1)
872 {
873 char *large_program_fullpath = (char *)::malloc (len + 1);
874
875 err = _NSGetExecutablePath (large_program_fullpath, &len);
876 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000877 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000878
879 ::free (large_program_fullpath);
880 }
881#elif defined (__linux__)
882 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000883 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
884 if (len > 0) {
885 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000886 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000887 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000888#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000889 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
890 size_t exe_path_size;
891 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
892 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000893 char *exe_path = new char[exe_path_size];
894 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
895 g_program_filespec.SetFile(exe_path, false);
896 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000897 }
Zachary Turner9e757b72014-07-28 16:45:05 +0000898#elif defined(_WIN32)
899 std::vector<char> buffer(PATH_MAX);
900 ::GetModuleFileName(NULL, &buffer[0], buffer.size());
Zachary Turnerd8a52732014-07-29 05:39:21 +0000901 g_program_filespec.SetFile(&buffer[0], false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000902#endif
903 }
904 return g_program_filespec;
905}
906
Greg Clayton2bddd342010-09-07 20:11:56 +0000907#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000908
909bool
910Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
911{
912 bundle.Clear();
913 return false;
914}
915
Greg Clayton2bddd342010-09-07 20:11:56 +0000916bool
Greg Claytondd36def2010-10-17 22:03:32 +0000917Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000918{
Greg Claytondd36def2010-10-17 22:03:32 +0000919 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000920}
921#endif
922
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000923#ifndef _WIN32
924
Greg Clayton45319462011-02-08 00:35:34 +0000925// Opaque info that tracks a dynamic library that was loaded
926struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000927{
Greg Clayton45319462011-02-08 00:35:34 +0000928 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
929 file_spec (fs),
930 open_options (o),
931 handle (h)
932 {
933 }
934
935 const FileSpec file_spec;
936 uint32_t open_options;
937 void * handle;
938};
939
940void *
941Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
942{
Greg Clayton4272cc72011-02-02 02:24:04 +0000943 char path[PATH_MAX];
944 if (file_spec.GetPath(path, sizeof(path)))
945 {
Greg Clayton45319462011-02-08 00:35:34 +0000946 int mode = 0;
947
948 if (options & eDynamicLibraryOpenOptionLazy)
949 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000950 else
951 mode |= RTLD_NOW;
952
Greg Clayton45319462011-02-08 00:35:34 +0000953
954 if (options & eDynamicLibraryOpenOptionLocal)
955 mode |= RTLD_LOCAL;
956 else
957 mode |= RTLD_GLOBAL;
958
959#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
960 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
961 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000962#endif
Greg Clayton45319462011-02-08 00:35:34 +0000963
964 void * opaque = ::dlopen (path, mode);
965
966 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000967 {
968 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000969 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000970 }
971 else
972 {
973 error.SetErrorString(::dlerror());
974 }
975 }
976 else
977 {
978 error.SetErrorString("failed to extract path");
979 }
Greg Clayton45319462011-02-08 00:35:34 +0000980 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000981}
982
983Error
Greg Clayton45319462011-02-08 00:35:34 +0000984Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000985{
986 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000987 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000988 {
989 error.SetErrorString ("invalid dynamic library handle");
990 }
Greg Clayton45319462011-02-08 00:35:34 +0000991 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000992 {
Greg Clayton45319462011-02-08 00:35:34 +0000993 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
994 if (::dlclose (dylib_info->handle) != 0)
995 {
996 error.SetErrorString(::dlerror());
997 }
998
999 dylib_info->open_options = 0;
1000 dylib_info->handle = 0;
1001 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +00001002 }
1003 return error;
1004}
1005
1006void *
Greg Clayton45319462011-02-08 00:35:34 +00001007Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +00001008{
Greg Clayton45319462011-02-08 00:35:34 +00001009 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +00001010 {
1011 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +00001012 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001013 else
Greg Clayton45319462011-02-08 00:35:34 +00001014 {
1015 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1016
1017 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
1018 if (symbol_addr)
1019 {
1020#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
1021 // This host doesn't support limiting searches to this shared library
1022 // so we need to verify that the match came from this shared library
1023 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +00001024 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +00001025 {
1026 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
1027 if (match_dylib_spec != dylib_info->file_spec)
1028 {
1029 char dylib_path[PATH_MAX];
1030 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
1031 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
1032 else
1033 error.SetErrorString ("symbol not found");
1034 return NULL;
1035 }
1036 }
1037#endif
1038 error.Clear();
1039 return symbol_addr;
1040 }
1041 else
1042 {
1043 error.SetErrorString(::dlerror());
1044 }
1045 }
1046 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +00001047}
Greg Claytondd36def2010-10-17 22:03:32 +00001048
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001049FileSpec
1050Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1051{
1052 FileSpec module_filespec;
1053 Dl_info info;
1054 if (::dladdr (host_addr, &info))
1055 {
1056 if (info.dli_fname)
1057 module_filespec.SetFile(info.dli_fname, true);
1058 }
1059 return module_filespec;
1060}
1061
1062#endif
1063
Greg Clayton23f8c952014-03-24 23:10:19 +00001064
1065static void CleanupProcessSpecificLLDBTempDir ()
1066{
1067 // Get the process specific LLDB temporary directory and delete it.
1068 FileSpec tmpdir_file_spec;
1069 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1070 {
1071 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1072 // true to all files that were created for the LLDB process can be cleaned up.
1073 const bool recurse = true;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001074 FileSystem::DeleteDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
Greg Clayton23f8c952014-03-24 23:10:19 +00001075 }
1076}
1077
Greg Claytondd36def2010-10-17 22:03:32 +00001078bool
1079Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1080{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001081 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001082 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1083 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001084 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001085 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001086 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001087
1088 switch (path_type)
1089 {
1090 case ePathTypeLLDBShlibDir:
1091 {
1092 static ConstString g_lldb_so_dir;
1093 if (!g_lldb_so_dir)
1094 {
David Majnemer8490da12014-07-22 22:00:42 +00001095 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1096 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +00001097 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001098 if (log)
1099 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001100 }
1101 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001102 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001103 }
1104 break;
1105
1106 case ePathTypeSupportExecutableDir:
1107 {
1108 static ConstString g_lldb_support_exe_dir;
1109 if (!g_lldb_support_exe_dir)
1110 {
1111 FileSpec lldb_file_spec;
1112 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1113 {
1114 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001115 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1116
1117#if defined (__APPLE__)
1118 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1119 if (framework_pos)
1120 {
1121 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +00001122#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001123 // Shallow bundle
1124 *framework_pos = '\0';
1125#else
1126 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001127 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001128#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001129 }
Todd Fiala015d8182014-07-22 23:41:36 +00001130#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1131 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1132 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
1133 // different trees.
1134 if (log)
1135 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1136 char *lib_pos = ::strstr (raw_path, "/lib");
1137 if (lib_pos != nullptr)
1138 {
1139 // First terminate the raw path at the start of lib.
1140 *lib_pos = '\0';
1141
1142 // Now write in bin in place of lib.
1143 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1144
1145 if (log)
1146 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1147 }
1148 else
1149 {
1150 if (log)
1151 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1152 }
Jason Molendaa3329782014-03-29 18:54:20 +00001153#endif // #if defined (__APPLE__)
Zachary Turner3f559742014-08-07 17:33:36 +00001154 llvm::SmallString<64> resolved_path(raw_path);
1155 FileSpec::Resolve (resolved_path);
1156 g_lldb_support_exe_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001157 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001158 if (log)
1159 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001160 }
1161 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001162 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001163 }
1164 break;
1165
1166 case ePathTypeHeaderDir:
1167 {
1168 static ConstString g_lldb_headers_dir;
1169 if (!g_lldb_headers_dir)
1170 {
1171#if defined (__APPLE__)
1172 FileSpec lldb_file_spec;
1173 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1174 {
1175 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001176 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1177
1178 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1179 if (framework_pos)
1180 {
1181 framework_pos += strlen("LLDB.framework");
1182 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1183 }
Jim Inghame1d263e2014-08-07 22:37:43 +00001184 llvm::SmallString<64> resolved_path(raw_path);
1185 FileSpec::Resolve (resolved_path);
1186 g_lldb_headers_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001187 }
1188#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001189 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001190 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1191#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001192 if (log)
1193 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001194 }
1195 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001196 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001197 }
1198 break;
1199
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001200#ifdef LLDB_DISABLE_PYTHON
1201 case ePathTypePythonDir:
1202 return false;
1203#else
1204 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001205 {
Greg Claytondd36def2010-10-17 22:03:32 +00001206 static ConstString g_lldb_python_dir;
1207 if (!g_lldb_python_dir)
1208 {
1209 FileSpec lldb_file_spec;
1210 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1211 {
1212 char raw_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001213#if defined(_WIN32)
1214 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1215 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1216#else
Greg Claytondd36def2010-10-17 22:03:32 +00001217 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1218
1219#if defined (__APPLE__)
1220 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1221 if (framework_pos)
1222 {
1223 framework_pos += strlen("LLDB.framework");
1224 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001225 }
1226 else
1227 {
1228#endif
1229 llvm::SmallString<256> python_version_dir;
1230 llvm::raw_svector_ostream os(python_version_dir);
1231 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1232 os.flush();
1233
1234 // We may get our string truncated. Should we protect
1235 // this with an assert?
1236
1237 ::strncat(raw_path, python_version_dir.c_str(),
1238 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001239#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001240#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001241 }
1242#endif
Zachary Turner3f559742014-08-07 17:33:36 +00001243 llvm::SmallString<64> resolved_path(raw_path);
1244 FileSpec::Resolve (resolved_path);
1245 g_lldb_python_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001246 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001247
1248 if (log)
1249 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1250
Greg Claytondd36def2010-10-17 22:03:32 +00001251 }
1252 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001253 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001254 }
1255 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001256#endif
1257
Greg Clayton4272cc72011-02-02 02:24:04 +00001258 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1259 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001260#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001261 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001262 static bool g_lldb_system_plugin_dir_located = false;
1263 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001264 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001265 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001266#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001267 FileSpec lldb_file_spec;
1268 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1269 {
1270 char raw_path[PATH_MAX];
Greg Clayton4272cc72011-02-02 02:24:04 +00001271 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1272
1273 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1274 if (framework_pos)
1275 {
1276 framework_pos += strlen("LLDB.framework");
1277 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Jim Inghame1d263e2014-08-07 22:37:43 +00001278 llvm::SmallString<64> resolved_path(raw_path);
1279 FileSpec::Resolve (resolved_path);
1280 g_lldb_system_plugin_dir.SetCString(resolved_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001281 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001282 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001283 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001284#elif defined (__linux__)
1285 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1286 if (lldb_file_spec.Exists())
1287 {
1288 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1289 }
1290#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001291
1292 if (log)
1293 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1294
Greg Clayton4272cc72011-02-02 02:24:04 +00001295 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001296
1297 if (g_lldb_system_plugin_dir)
1298 {
1299 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1300 return true;
1301 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001302#else
1303 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001304 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001305#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001306 }
1307 break;
1308
1309 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1310 {
1311#if defined (__APPLE__)
1312 static ConstString g_lldb_user_plugin_dir;
1313 if (!g_lldb_user_plugin_dir)
1314 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001315 llvm::SmallString<64> user_plugin_path("~/Library/Application Support/LLDB/PlugIns");
1316 FileSpec::Resolve (user_plugin_path);
1317 if (user_plugin_path.size())
Greg Clayton4272cc72011-02-02 02:24:04 +00001318 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001319 g_lldb_user_plugin_dir.SetCString(user_plugin_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001320 }
1321 }
1322 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001323 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001324#elif defined (__linux__)
1325 static ConstString g_lldb_user_plugin_dir;
1326 if (!g_lldb_user_plugin_dir)
1327 {
1328 // XDG Base Directory Specification
1329 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1330 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1331 FileSpec lldb_file_spec;
1332 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1333 if (xdg_data_home && xdg_data_home[0])
1334 {
1335 std::string user_plugin_dir (xdg_data_home);
1336 user_plugin_dir += "/lldb";
1337 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1338 }
1339 else
1340 {
1341 const char *home_dir = getenv("HOME");
1342 if (home_dir && home_dir[0])
1343 {
1344 std::string user_plugin_dir (home_dir);
1345 user_plugin_dir += "/.local/share/lldb";
1346 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1347 }
1348 }
1349
1350 if (lldb_file_spec.Exists())
1351 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001352 if (log)
1353 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001354 }
1355 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001356 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001357#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001358 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001359 return false;
1360 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001361
1362 case ePathTypeLLDBTempSystemDir:
1363 {
1364 static ConstString g_lldb_tmp_dir;
1365 if (!g_lldb_tmp_dir)
1366 {
1367 const char *tmpdir_cstr = getenv("TMPDIR");
1368 if (tmpdir_cstr == NULL)
1369 {
1370 tmpdir_cstr = getenv("TMP");
1371 if (tmpdir_cstr == NULL)
1372 tmpdir_cstr = getenv("TEMP");
1373 }
1374 if (tmpdir_cstr)
1375 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001376 StreamString pid_tmpdir;
1377 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001378 if (FileSystem::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault)
1379 .Success())
Greg Clayton23f8c952014-03-24 23:10:19 +00001380 {
1381 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001382 if (FileSystem::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault)
1383 .Success())
Greg Clayton23f8c952014-03-24 23:10:19 +00001384 {
1385 // Make an atexit handler to clean up the process specify LLDB temp dir
1386 // and all of its contents.
1387 ::atexit (CleanupProcessSpecificLLDBTempDir);
1388 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1389 if (log)
1390 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1391
1392 }
1393 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001394 }
1395 }
1396 file_spec.GetDirectory() = g_lldb_tmp_dir;
1397 return (bool)file_spec.GetDirectory();
1398 }
Greg Claytondd36def2010-10-17 22:03:32 +00001399 }
1400
1401 return false;
1402}
1403
Greg Clayton1cb64962011-03-24 04:28:38 +00001404
1405bool
1406Host::GetHostname (std::string &s)
1407{
1408 char hostname[PATH_MAX];
1409 hostname[sizeof(hostname) - 1] = '\0';
1410 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1411 {
1412 struct hostent* h = ::gethostbyname (hostname);
1413 if (h)
1414 s.assign (h->h_name);
1415 else
1416 s.assign (hostname);
1417 return true;
1418 }
1419 return false;
1420}
1421
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001422#ifndef _WIN32
1423
Greg Clayton32e0a752011-03-30 18:16:51 +00001424const char *
1425Host::GetUserName (uint32_t uid, std::string &user_name)
1426{
1427 struct passwd user_info;
1428 struct passwd *user_info_ptr = &user_info;
1429 char user_buffer[PATH_MAX];
1430 size_t user_buffer_size = sizeof(user_buffer);
1431 if (::getpwuid_r (uid,
1432 &user_info,
1433 user_buffer,
1434 user_buffer_size,
1435 &user_info_ptr) == 0)
1436 {
1437 if (user_info_ptr)
1438 {
1439 user_name.assign (user_info_ptr->pw_name);
1440 return user_name.c_str();
1441 }
1442 }
1443 user_name.clear();
1444 return NULL;
1445}
1446
1447const char *
1448Host::GetGroupName (uint32_t gid, std::string &group_name)
1449{
1450 char group_buffer[PATH_MAX];
1451 size_t group_buffer_size = sizeof(group_buffer);
1452 struct group group_info;
1453 struct group *group_info_ptr = &group_info;
1454 // Try the threadsafe version first
1455 if (::getgrgid_r (gid,
1456 &group_info,
1457 group_buffer,
1458 group_buffer_size,
1459 &group_info_ptr) == 0)
1460 {
1461 if (group_info_ptr)
1462 {
1463 group_name.assign (group_info_ptr->gr_name);
1464 return group_name.c_str();
1465 }
1466 }
1467 else
1468 {
1469 // The threadsafe version isn't currently working
1470 // for me on darwin, but the non-threadsafe version
1471 // is, so I am calling it below.
1472 group_info_ptr = ::getgrgid (gid);
1473 if (group_info_ptr)
1474 {
1475 group_name.assign (group_info_ptr->gr_name);
1476 return group_name.c_str();
1477 }
1478 }
1479 group_name.clear();
1480 return NULL;
1481}
1482
Han Ming Ong84647042012-02-25 01:07:38 +00001483uint32_t
1484Host::GetUserID ()
1485{
1486 return getuid();
1487}
1488
1489uint32_t
1490Host::GetGroupID ()
1491{
1492 return getgid();
1493}
1494
1495uint32_t
1496Host::GetEffectiveUserID ()
1497{
1498 return geteuid();
1499}
1500
1501uint32_t
1502Host::GetEffectiveGroupID ()
1503{
1504 return getegid();
1505}
1506
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001507#endif
1508
1509#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1510bool
1511Host::GetOSBuildString (std::string &s)
1512{
1513 s.clear();
1514 return false;
1515}
1516
1517bool
1518Host::GetOSKernelDescription (std::string &s)
1519{
1520 s.clear();
1521 return false;
1522}
1523#endif
1524
Zachary Turner310035a2014-07-08 04:52:15 +00001525#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1526 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001527uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001528Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001529{
1530 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001531 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001532}
1533
Greg Claytone996fd32011-03-08 22:40:15 +00001534bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001535Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001536{
Greg Claytone996fd32011-03-08 22:40:15 +00001537 process_info.Clear();
1538 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001539}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001540#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001541
Matt Kopec085d6ce2013-05-31 22:00:07 +00001542#if !defined(__linux__)
1543bool
1544Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1545{
1546 return false;
1547}
1548#endif
1549
Sean Callananc0a6e062011-10-27 21:22:25 +00001550lldb::TargetSP
1551Host::GetDummyTarget (lldb_private::Debugger &debugger)
1552{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001553 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001554
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001555 // FIXME: Maybe the dummy target should be per-Debugger
1556 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1557 {
1558 ArchSpec arch(Target::GetDefaultArchitecture());
1559 if (!arch.IsValid())
1560 arch = Host::GetArchitecture ();
1561 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001562 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001563 arch.GetTriple().getTriple().c_str(),
1564 false,
1565 NULL,
1566 g_dummy_target_sp);
1567 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001568
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001569 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001570}
1571
Greg Claytond1cf11a2012-04-14 01:42:46 +00001572struct ShellInfo
1573{
1574 ShellInfo () :
1575 process_reaped (false),
1576 can_delete (false),
1577 pid (LLDB_INVALID_PROCESS_ID),
1578 signo(-1),
1579 status(-1)
1580 {
1581 }
1582
1583 lldb_private::Predicate<bool> process_reaped;
1584 lldb_private::Predicate<bool> can_delete;
1585 lldb::pid_t pid;
1586 int signo;
1587 int status;
1588};
1589
1590static bool
1591MonitorShellCommand (void *callback_baton,
1592 lldb::pid_t pid,
1593 bool exited, // True if the process did exit
1594 int signo, // Zero for no signal
1595 int status) // Exit value of process if signal is zero
1596{
1597 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1598 shell_info->pid = pid;
1599 shell_info->signo = signo;
1600 shell_info->status = status;
1601 // Let the thread running Host::RunShellCommand() know that the process
1602 // exited and that ShellInfo has been filled in by broadcasting to it
1603 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1604 // Now wait for a handshake back from that thread running Host::RunShellCommand
1605 // so we know that we can delete shell_info_ptr
1606 shell_info->can_delete.WaitForValueEqualTo(true);
1607 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1608 usleep(1000);
1609 // Now delete the shell info that was passed into this function
1610 delete shell_info;
1611 return true;
1612}
1613
1614Error
1615Host::RunShellCommand (const char *command,
1616 const char *working_dir,
1617 int *status_ptr,
1618 int *signo_ptr,
1619 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001620 uint32_t timeout_sec,
1621 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001622{
1623 Error error;
1624 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001625 if (shell && shell[0])
1626 {
1627 // Run the command in a shell
1628 launch_info.SetShell(shell);
1629 launch_info.GetArguments().AppendArgument(command);
1630 const bool localhost = true;
1631 const bool will_debug = false;
1632 const bool first_arg_is_full_shell_command = true;
1633 launch_info.ConvertArgumentsForLaunchingInShell (error,
1634 localhost,
1635 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001636 first_arg_is_full_shell_command,
1637 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001638 }
1639 else
1640 {
1641 // No shell, just run it
1642 Args args (command);
1643 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001644 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001645 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001646
1647 if (working_dir)
1648 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001649 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001650 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001651
Greg Claytond1cf11a2012-04-14 01:42:46 +00001652 if (command_output_ptr)
1653 {
1654 // Create a temporary file to get the stdout/stderr and redirect the
1655 // output of the command into this file. We will later read this file
1656 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001657 FileSpec tmpdir_file_spec;
1658 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1659 {
1660 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1661 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1662 }
1663 else
1664 {
1665 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1666 }
1667
1668 output_file_path = ::mktemp(output_file_path_buffer);
1669 }
1670
1671 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1672 if (output_file_path)
1673 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001674 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001675 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001676 }
1677 else
1678 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001679 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1680 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1681 }
1682
1683 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001684 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001685
1686 const bool monitor_signals = false;
1687 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1688
1689 error = LaunchProcess (launch_info);
1690 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001691
1692 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1693 error.SetErrorString("failed to get process ID");
1694
1695 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001696 {
1697 // The process successfully launched, so we can defer ownership of
1698 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001699 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001700 // doesn't need to delete the ShellInfo anymore.
1701 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001702 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001703 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001704 if (timeout_sec > 0) {
1705 timeout_time.OffsetWithSeconds(timeout_sec);
1706 timeout_ptr = &timeout_time;
1707 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001708 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001709 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001710 if (timed_out)
1711 {
1712 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001713
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001714 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001715 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001716 // Wait for the monitor callback to get the message
1717 timeout_time = TimeValue::Now();
1718 timeout_time.OffsetWithSeconds(1);
1719 timed_out = false;
1720 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1721 }
1722 else
1723 {
1724 if (status_ptr)
1725 *status_ptr = shell_info->status;
1726
1727 if (signo_ptr)
1728 *signo_ptr = shell_info->signo;
1729
1730 if (command_output_ptr)
1731 {
1732 command_output_ptr->clear();
1733 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1734 uint64_t file_size = file_spec.GetByteSize();
1735 if (file_size > 0)
1736 {
1737 if (file_size > command_output_ptr->max_size())
1738 {
1739 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1740 }
1741 else
1742 {
1743 command_output_ptr->resize(file_size);
1744 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1745 }
1746 }
1747 }
1748 }
1749 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1750 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001751
1752 if (output_file_path)
1753 ::unlink (output_file_path);
1754 // Handshake with the monitor thread, or just let it know in advance that
1755 // it can delete "shell_info" in case we timed out and were not able to kill
1756 // the process...
1757 return error;
1758}
1759
Daniel Malea4244cbd2013-08-27 20:58:59 +00001760
Todd Fiala76747122014-01-23 00:52:28 +00001761// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1762// systems
1763
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001764#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001765
1766// this method needs to be visible to macosx/Host.cpp and
1767// common/Host.cpp.
1768
1769short
1770Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1771{
1772 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1773
1774#if defined (__APPLE__)
1775 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1776 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1777
1778 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1779 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1780
1781 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1782 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1783
1784 if (launch_info.GetLaunchInSeparateProcessGroup())
1785 flags |= POSIX_SPAWN_SETPGROUP;
1786
1787#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1788#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1789 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1790 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1791 {
1792 g_use_close_on_exec_flag = eLazyBoolNo;
1793
1794 uint32_t major, minor, update;
1795 if (Host::GetOSVersion(major, minor, update))
1796 {
1797 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1798 if (major > 10 || (major == 10 && minor > 7))
1799 {
1800 // Only enable for 10.8 and later OS versions
1801 g_use_close_on_exec_flag = eLazyBoolYes;
1802 }
1803 }
1804 }
1805#else
1806 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1807#endif
1808 // Close all files exception those with file actions if this is supported.
1809 if (g_use_close_on_exec_flag == eLazyBoolYes)
1810 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1811#endif
1812#endif // #if defined (__APPLE__)
1813 return flags;
1814}
1815
1816Error
1817Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001818{
1819 Error error;
1820 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1821
Daniel Malea4244cbd2013-08-27 20:58:59 +00001822 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001823 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001824
1825 if (error.Fail() || log)
1826 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001827 if (error.Fail())
1828 return error;
1829
1830 // Make a quick class that will cleanup the posix spawn attributes in case
1831 // we return in the middle of this function.
1832 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1833
1834 sigset_t no_signals;
1835 sigset_t all_signals;
1836 sigemptyset (&no_signals);
1837 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001838 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001839#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001840 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001841#else
1842 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1843#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001844
Todd Fiala76747122014-01-23 00:52:28 +00001845 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001846
1847 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001848 if (error.Fail() || log)
1849 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001850 if (error.Fail())
1851 return error;
1852
Todd Fiala76747122014-01-23 00:52:28 +00001853 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1854 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1855#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001856
1857 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1858 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1859 // to do that job on OSX.
1860
1861 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001862 {
Jim Ingham90331d52014-02-21 01:25:21 +00001863 // We don't need to do this for ARM, and we really shouldn't now that we
1864 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1865 // to set which CPU subtype to launch...
1866 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1867 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1868 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1869 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001870 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1871 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001872 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1873 {
1874 size_t ocount = 0;
1875 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1876 if (error.Fail() || log)
1877 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 +00001878
Jim Ingham90331d52014-02-21 01:25:21 +00001879 if (error.Fail() || ocount != 1)
1880 return error;
1881 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001882 }
1883
Todd Fiala76747122014-01-23 00:52:28 +00001884#endif
1885
1886 const char *tmp_argv[2];
1887 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1888 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1889 if (argv == NULL)
1890 {
1891 // posix_spawn gets very unhappy if it doesn't have at least the program
1892 // name in argv[0]. One of the side affects I have noticed is the environment
1893 // variables don't make it into the child process if "argv == NULL"!!!
1894 tmp_argv[0] = exe_path;
1895 tmp_argv[1] = NULL;
1896 argv = (char * const*)tmp_argv;
1897 }
1898
1899#if !defined (__APPLE__)
1900 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001901 char current_dir[PATH_MAX];
1902 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001903#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001904
1905 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001906 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001907 {
Todd Fiala76747122014-01-23 00:52:28 +00001908#if defined (__APPLE__)
1909 // Set the working directory on this thread only
1910 if (__pthread_chdir (working_dir) < 0) {
1911 if (errno == ENOENT) {
1912 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1913 } else if (errno == ENOTDIR) {
1914 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1915 } else {
1916 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1917 }
1918 return error;
1919 }
1920#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001921 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1922 {
1923 error.SetError(errno, eErrorTypePOSIX);
1924 error.LogIfError(log, "unable to save the current directory");
1925 return error;
1926 }
1927
1928 if (::chdir(working_dir) == -1)
1929 {
1930 error.SetError(errno, eErrorTypePOSIX);
1931 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1932 return error;
1933 }
Todd Fiala76747122014-01-23 00:52:28 +00001934#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001935 }
1936
Todd Fiala76747122014-01-23 00:52:28 +00001937 const size_t num_file_actions = launch_info.GetNumFileActions ();
1938 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001939 {
Todd Fiala76747122014-01-23 00:52:28 +00001940 posix_spawn_file_actions_t file_actions;
1941 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1942 if (error.Fail() || log)
1943 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1944 if (error.Fail())
1945 return error;
1946
1947 // Make a quick class that will cleanup the posix spawn attributes in case
1948 // we return in the middle of this function.
1949 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1950
1951 for (size_t i=0; i<num_file_actions; ++i)
1952 {
Zachary Turner696b5282014-08-14 16:01:25 +00001953 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +00001954 if (launch_file_action)
1955 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001956 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
Todd Fiala76747122014-01-23 00:52:28 +00001957 return error;
1958 }
1959 }
1960
1961 error.SetError (::posix_spawnp (&pid,
1962 exe_path,
1963 &file_actions,
1964 &attr,
1965 argv,
1966 envp),
1967 eErrorTypePOSIX);
1968
1969 if (error.Fail() || log)
1970 {
1971 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001972 pid, exe_path, static_cast<void*>(&file_actions),
1973 static_cast<void*>(&attr),
1974 reinterpret_cast<const void*>(argv),
1975 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001976 if (log)
1977 {
1978 for (int ii=0; argv[ii]; ++ii)
1979 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1980 }
1981 }
1982
1983 }
1984 else
1985 {
1986 error.SetError (::posix_spawnp (&pid,
1987 exe_path,
1988 NULL,
1989 &attr,
1990 argv,
1991 envp),
1992 eErrorTypePOSIX);
1993
1994 if (error.Fail() || log)
1995 {
1996 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +00001997 pid, exe_path, static_cast<void*>(&attr),
1998 reinterpret_cast<const void*>(argv),
1999 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00002000 if (log)
2001 {
2002 for (int ii=0; argv[ii]; ++ii)
2003 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
2004 }
2005 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00002006 }
2007
Todd Fiala76747122014-01-23 00:52:28 +00002008 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002009 {
Todd Fiala76747122014-01-23 00:52:28 +00002010#if defined (__APPLE__)
2011 // No more thread specific current working directory
2012 __pthread_fchdir (-1);
2013#else
2014 if (::chdir(current_dir) == -1 && error.Success())
2015 {
2016 error.SetError(errno, eErrorTypePOSIX);
2017 error.LogIfError(log, "unable to change current directory back to %s",
2018 current_dir);
2019 }
2020#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00002021 }
2022
2023 return error;
2024}
2025
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002026bool
2027Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
Zachary Turner696b5282014-08-14 16:01:25 +00002028{
2029 if (info == NULL)
2030 return false;
2031
2032 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
2033
2034 switch (info->GetAction())
2035 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002036 case FileAction::eFileActionNone:
2037 error.Clear();
2038 break;
Zachary Turner696b5282014-08-14 16:01:25 +00002039
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002040 case FileAction::eFileActionClose:
2041 if (info->GetFD() == -1)
2042 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
2043 else
2044 {
2045 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
2046 if (log && (error.Fail() || log))
2047 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
2048 static_cast<void *>(file_actions), info->GetFD());
2049 }
2050 break;
Zachary Turner696b5282014-08-14 16:01:25 +00002051
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002052 case FileAction::eFileActionDuplicate:
2053 if (info->GetFD() == -1)
2054 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
2055 else if (info->GetActionArgument() == -1)
2056 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
2057 else
2058 {
2059 error.SetError(
2060 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
2061 eErrorTypePOSIX);
2062 if (log && (error.Fail() || log))
2063 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
2064 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
2065 }
2066 break;
Zachary Turner696b5282014-08-14 16:01:25 +00002067
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002068 case FileAction::eFileActionOpen:
2069 if (info->GetFD() == -1)
2070 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
2071 else
2072 {
2073 int oflag = info->GetActionArgument();
Zachary Turner696b5282014-08-14 16:01:25 +00002074
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002075 mode_t mode = 0;
Zachary Turner696b5282014-08-14 16:01:25 +00002076
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002077 if (oflag & O_CREAT)
2078 mode = 0640;
Zachary Turner696b5282014-08-14 16:01:25 +00002079
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00002080 error.SetError(
2081 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
2082 eErrorTypePOSIX);
2083 if (error.Fail() || log)
2084 error.PutToLog(log,
2085 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
2086 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
2087 }
2088 break;
Zachary Turner696b5282014-08-14 16:01:25 +00002089 }
2090 return error.Success();
2091}
2092
Todd Fiala76747122014-01-23 00:52:28 +00002093#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2094
2095
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002096#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2097// The functions below implement process launching via posix_spawn() for Linux,
2098// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00002099
2100Error
2101Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2102{
2103 Error error;
2104 char exe_path[PATH_MAX];
2105
2106 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2107
2108 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2109
2110 FileSpec exe_spec(launch_info.GetExecutableFile());
2111
2112 FileSpec::FileType file_type = exe_spec.GetFileType();
2113 if (file_type != FileSpec::eFileTypeRegular)
2114 {
2115 lldb::ModuleSP exe_module_sp;
2116 error = host_platform_sp->ResolveExecutable (exe_spec,
2117 arch_spec,
2118 exe_module_sp,
2119 NULL);
2120
2121 if (error.Fail())
2122 return error;
2123
2124 if (exe_module_sp)
2125 exe_spec = exe_module_sp->GetFileSpec();
2126 }
2127
2128 if (exe_spec.Exists())
2129 {
2130 exe_spec.GetPath (exe_path, sizeof(exe_path));
2131 }
2132 else
2133 {
2134 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2135 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2136 return error;
2137 }
2138
2139 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2140
2141 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2142
2143 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2144
2145 if (pid != LLDB_INVALID_PROCESS_ID)
2146 {
2147 // If all went well, then set the process ID into the launch info
2148 launch_info.SetProcessID(pid);
2149
Todd Fiala76747122014-01-23 00:52:28 +00002150 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2151
Daniel Malea4244cbd2013-08-27 20:58:59 +00002152 // Make sure we reap any processes we spawn or we will have zombies.
2153 if (!launch_info.MonitorProcess())
2154 {
2155 const bool monitor_signals = false;
2156 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2157 NULL,
2158 pid,
2159 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002160 if (log)
2161 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2162 }
2163 else
2164 {
2165 if (log)
2166 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002167 }
2168 }
2169 else
2170 {
2171 // Invalid process ID, something didn't go well
2172 if (error.Success())
2173 error.SetErrorString ("process launch failed for unknown reasons");
2174 }
2175 return error;
2176}
2177
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002178#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002179
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002180#ifndef _WIN32
2181
2182size_t
2183Host::GetPageSize()
2184{
2185 return ::getpagesize();
2186}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002187
Greg Claytone3e3fee2013-02-17 20:46:30 +00002188uint32_t
2189Host::GetNumberCPUS ()
2190{
2191 static uint32_t g_num_cores = UINT32_MAX;
2192 if (g_num_cores == UINT32_MAX)
2193 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002194#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002195
2196 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002197
Greg Claytone3e3fee2013-02-17 20:46:30 +00002198#else
2199
2200 // Assume POSIX support if a host specific case has not been supplied above
2201 g_num_cores = 0;
2202 int num_cores = 0;
2203 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002204#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002205 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002206#else
2207 int mib[] = { CTL_HW, HW_NCPU };
2208#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002209
2210 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002211 if (sysctl(mib, llvm::array_lengthof(mib), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
Greg Claytone3e3fee2013-02-17 20:46:30 +00002212 {
2213 g_num_cores = num_cores;
2214 }
2215 else
2216 {
2217 mib[1] = HW_NCPU;
2218 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002219 if (sysctl(mib, llvm::array_lengthof(mib), &num_cores, &num_cores_len, NULL, 0) == 0 && (num_cores > 0))
Greg Claytone3e3fee2013-02-17 20:46:30 +00002220 {
2221 if (num_cores > 0)
2222 g_num_cores = num_cores;
2223 }
2224 }
2225#endif
2226 }
2227 return g_num_cores;
2228}
2229
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002230void
2231Host::Kill(lldb::pid_t pid, int signo)
2232{
2233 ::kill(pid, signo);
2234}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002235
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002236#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002237
Johnny Chen8f3d8382011-08-02 20:52:42 +00002238#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002239bool
Greg Clayton3b147632010-12-18 01:54:34 +00002240Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002241{
2242 return false;
2243}
Greg Claytondd36def2010-10-17 22:03:32 +00002244
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002245void
2246Host::SetCrashDescriptionWithFormat (const char *format, ...)
2247{
2248}
2249
2250void
2251Host::SetCrashDescription (const char *description)
2252{
2253}
Greg Claytondd36def2010-10-17 22:03:32 +00002254
2255lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002256Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002257{
2258 return LLDB_INVALID_PROCESS_ID;
2259}
2260
Greg Claytonfbb76342013-11-20 21:07:01 +00002261#endif