blob: 43aa5bacfe03f9bb67a2dfad873000665c49f7f8 [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"
Zachary Turner97a14e62014-08-19 17:18:29 +000059#include "lldb/Host/HostInfo.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000060#include "lldb/Core/ArchSpec.h"
61#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000062#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000064#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000065#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000066#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000067#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000068#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000069#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000070#include "lldb/Host/FileSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000071#include "lldb/Host/FileSystem.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000072#include "lldb/Host/Mutex.h"
Zachary Turner696b5282014-08-14 16:01:25 +000073#include "lldb/Target/FileAction.h"
Greg Claytone996fd32011-03-08 22:40:15 +000074#include "lldb/Target/Process.h"
Zachary Turner696b5282014-08-14 16:01:25 +000075#include "lldb/Target/ProcessLaunchInfo.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000076#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000077#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000078
Saleem Abdulrasool28606952014-06-27 05:17:41 +000079#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000080#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000081#include "llvm/Support/Host.h"
Zachary Turner9e757b72014-07-28 16:45:05 +000082#include "llvm/Support/Path.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000083#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000084
Todd Fiala76747122014-01-23 00:52:28 +000085#if defined (__APPLE__)
86#ifndef _POSIX_SPAWN_DISABLE_ASLR
87#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
88#endif
89
90extern "C"
91{
92 int __pthread_chdir(const char *path);
93 int __pthread_fchdir (int fildes);
94}
95
96#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000097
Greg Clayton2bddd342010-09-07 20:11:56 +000098using namespace lldb;
99using namespace lldb_private;
100
Todd Fiala17096d72014-07-16 19:03:16 +0000101// Define maximum thread name length
102#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
103uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
104#else
105uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
106#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000107
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000108#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000109struct MonitorInfo
110{
111 lldb::pid_t pid; // The process ID to monitor
112 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
113 void *callback_baton; // The callback baton for the callback function
114 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
115};
116
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000117static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000118MonitorChildProcessThreadFunction (void *arg);
119
120lldb::thread_t
121Host::StartMonitoringChildProcess
122(
123 Host::MonitorChildProcessCallback callback,
124 void *callback_baton,
125 lldb::pid_t pid,
126 bool monitor_signals
127)
128{
129 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000130 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000131
Greg Claytone4e45922011-11-16 05:37:56 +0000132 info_ptr->pid = pid;
133 info_ptr->callback = callback;
134 info_ptr->callback_baton = callback_baton;
135 info_ptr->monitor_signals = monitor_signals;
136
137 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000138 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000139 thread = ThreadCreate (thread_name,
140 MonitorChildProcessThreadFunction,
141 info_ptr,
142 NULL);
143
Greg Clayton2bddd342010-09-07 20:11:56 +0000144 return thread;
145}
146
147//------------------------------------------------------------------
148// Scoped class that will disable thread canceling when it is
149// constructed, and exception safely restore the previous value it
150// when it goes out of scope.
151//------------------------------------------------------------------
152class ScopedPThreadCancelDisabler
153{
154public:
155 ScopedPThreadCancelDisabler()
156 {
157 // Disable the ability for this thread to be cancelled
158 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
159 if (err != 0)
160 m_old_state = -1;
161
162 }
163
164 ~ScopedPThreadCancelDisabler()
165 {
166 // Restore the ability for this thread to be cancelled to what it
167 // previously was.
168 if (m_old_state != -1)
169 ::pthread_setcancelstate (m_old_state, 0);
170 }
171private:
172 int m_old_state; // Save the old cancelability state.
173};
174
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000175static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000176MonitorChildProcessThreadFunction (void *arg)
177{
Greg Clayton5160ce52013-03-27 23:08:40 +0000178 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000179 const char *function = __FUNCTION__;
180 if (log)
181 log->Printf ("%s (arg = %p) thread starting...", function, arg);
182
183 MonitorInfo *info = (MonitorInfo *)arg;
184
185 const Host::MonitorChildProcessCallback callback = info->callback;
186 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000187 const bool monitor_signals = info->monitor_signals;
188
Daniel Malea4244cbd2013-08-27 20:58:59 +0000189 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000190 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000191
Greg Clayton2bddd342010-09-07 20:11:56 +0000192 delete info;
193
194 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000195#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000196 #define __WALL 0
197#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000198 const int options = __WALL;
199
Greg Clayton2bddd342010-09-07 20:11:56 +0000200 while (1)
201 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000202 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000203 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000204 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000205
206 // Wait for all child processes
207 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000208 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000209 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000210 ::pthread_testcancel ();
211
212 if (wait_pid == -1)
213 {
214 if (errno == EINTR)
215 continue;
216 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000217 {
218 if (log)
219 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000220 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000221 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000222 }
Matt Kopec650648f2013-01-08 16:30:18 +0000223 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000224 {
225 bool exited = false;
226 int signal = 0;
227 int exit_status = 0;
228 const char *status_cstr = NULL;
229 if (WIFSTOPPED(status))
230 {
231 signal = WSTOPSIG(status);
232 status_cstr = "STOPPED";
233 }
234 else if (WIFEXITED(status))
235 {
236 exit_status = WEXITSTATUS(status);
237 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000238 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000239 }
240 else if (WIFSIGNALED(status))
241 {
242 signal = WTERMSIG(status);
243 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000244 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000245 exited = true;
246 exit_status = -1;
247 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000248 }
249 else
250 {
Johnny Chen44805302011-07-19 19:48:13 +0000251 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000252 }
253
254 // Scope for pthread_cancel_disabler
255 {
256 ScopedPThreadCancelDisabler pthread_cancel_disabler;
257
Caroline Tice20ad3c42010-10-29 21:48:37 +0000258 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000259 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000260 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 +0000261 function,
262 wait_pid,
263 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000264 pid,
265 status,
266 status_cstr,
267 signal,
268 exit_status);
269
270 if (exited || (signal != 0 && monitor_signals))
271 {
Greg Claytone4e45922011-11-16 05:37:56 +0000272 bool callback_return = false;
273 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000274 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000275
276 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000277 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000278 {
279 if (log)
280 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000281 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000282 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000283 // If the callback returns true, it means this process should
284 // exit
285 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000286 {
287 if (log)
288 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000289 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000290 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000291 }
292 }
293 }
294 }
295
Caroline Tice20ad3c42010-10-29 21:48:37 +0000296 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000297 if (log)
298 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
299
300 return NULL;
301}
302
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000303#endif // #if !defined (__APPLE__) && !defined (_WIN32)
304
305#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000306
307void
308Host::SystemLog (SystemLogType type, const char *format, va_list args)
309{
310 vfprintf (stderr, format, args);
311}
312
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000313#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000314
Greg Claytone38a5ed2012-01-05 03:57:59 +0000315void
316Host::SystemLog (SystemLogType type, const char *format, ...)
317{
318 va_list args;
319 va_start (args, format);
320 SystemLog (type, format, args);
321 va_end (args);
322}
323
Greg Clayton2bddd342010-09-07 20:11:56 +0000324const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000325Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000326{
Greg Clayton514487e2011-02-15 21:59:32 +0000327 static bool g_supports_32 = false;
328 static bool g_supports_64 = false;
329 static ArchSpec g_host_arch_32;
330 static ArchSpec g_host_arch_64;
331
Greg Clayton2bddd342010-09-07 20:11:56 +0000332#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000333
334 // Apple is different in that it can support both 32 and 64 bit executables
335 // in the same operating system running concurrently. Here we detect the
336 // correct host architectures for both 32 and 64 bit including if 64 bit
337 // executables are supported on the system.
338
339 if (g_supports_32 == false && g_supports_64 == false)
340 {
341 // All apple systems support 32 bit execution.
342 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000343 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000344 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000345 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000346 ArchSpec host_arch;
347 // These will tell us about the kernel architecture, which even on a 64
348 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000349 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
350 {
Greg Clayton514487e2011-02-15 21:59:32 +0000351 len = sizeof (cpusubtype);
352 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
353 cpusubtype = CPU_TYPE_ANY;
354
Greg Clayton2bddd342010-09-07 20:11:56 +0000355 len = sizeof (is_64_bit_capable);
356 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
357 {
358 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000359 g_supports_64 = true;
360 }
361
362 if (is_64_bit_capable)
363 {
364 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000365 {
Greg Clayton514487e2011-02-15 21:59:32 +0000366 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000367 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000368 }
369 else
370 {
Greg Clayton52edb362014-07-14 22:53:02 +0000371 // We have a 64 bit kernel that is returning a 32 bit cputype, the
372 // cpusubtype will be correct as if it were for a 64 bit architecture
373 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype | CPU_ARCH_ABI64, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000374 }
Greg Clayton52edb362014-07-14 22:53:02 +0000375
376 // Now we need modify the cpusubtype for the 32 bit slices.
377 uint32_t cpusubtype32 = cpusubtype;
378#if defined (__i386__) || defined (__x86_64__)
379 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
380 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
381#elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
382 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
383 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
384#endif
385 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype & ~(CPU_ARCH_MASK), cpusubtype32);
Greg Claytonc76fa8a2014-07-29 21:27:21 +0000386
387 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
388 {
389 g_host_arch_32.GetTriple().setOS(llvm::Triple::IOS);
390 g_host_arch_64.GetTriple().setOS(llvm::Triple::IOS);
391 }
392 else
393 {
394 g_host_arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
395 g_host_arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
396 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000397 }
Greg Clayton514487e2011-02-15 21:59:32 +0000398 else
399 {
Greg Clayton52edb362014-07-14 22:53:02 +0000400 // We have a 32 bit kernel on a 32 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000401 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000402 g_host_arch_64.Clear();
403 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000404 }
Greg Clayton514487e2011-02-15 21:59:32 +0000405 }
406
407#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000408
Greg Clayton514487e2011-02-15 21:59:32 +0000409 if (g_supports_32 == false && g_supports_64 == false)
410 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000411 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000412
Stephen Wilsonbd588712011-02-24 19:15:09 +0000413 g_host_arch_32.Clear();
414 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000415
Greg Claytonb29e6c62012-10-11 17:38:58 +0000416 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
417 // for the default triple. It's probably an artifact of config.guess.
418 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000419 triple.setVendorName ("");
Zachary Turner97a14e62014-08-19 17:18:29 +0000420#if defined(__linux__)
421 const char *distribution_id = HostInfo::GetDistributionId().data();
422#else
423 const char *distribution_id = "";
424#endif
Stephen Wilsonbd588712011-02-24 19:15:09 +0000425 switch (triple.getArch())
426 {
427 default:
428 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000429 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000430 g_supports_32 = true;
431 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000432
Stephen Wilsonbd588712011-02-24 19:15:09 +0000433 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000434 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000435 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000436 g_supports_64 = true;
437 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000438 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000439 g_supports_32 = true;
440 break;
441
Ed Mastea8375762014-04-01 18:06:45 +0000442 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000443 case llvm::Triple::sparcv9:
444 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000445 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000446 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000447 g_supports_64 = true;
448 break;
449 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000450
451 g_supports_32 = g_host_arch_32.IsValid();
452 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000453 }
Zachary Turner97a14e62014-08-19 17:18:29 +0000454
Greg Clayton514487e2011-02-15 21:59:32 +0000455#endif // #else for #if defined (__APPLE__)
456
457 if (arch_kind == eSystemDefaultArchitecture32)
458 return g_host_arch_32;
459 else if (arch_kind == eSystemDefaultArchitecture64)
460 return g_host_arch_64;
461
462 if (g_supports_64)
463 return g_host_arch_64;
464
465 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000466}
467
Greg Clayton2bddd342010-09-07 20:11:56 +0000468lldb::pid_t
469Host::GetCurrentProcessID()
470{
471 return ::getpid();
472}
473
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000474#ifndef _WIN32
475
Greg Clayton2bddd342010-09-07 20:11:56 +0000476lldb::tid_t
477Host::GetCurrentThreadID()
478{
479#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000480 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000481 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
482 // count.
483 thread_port_t thread_self = mach_thread_self();
484 mach_port_deallocate(mach_task_self(), thread_self);
485 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000486#elif defined(__FreeBSD__)
487 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000488#elif defined(__linux__)
489 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000490#else
491 return lldb::tid_t(pthread_self());
492#endif
493}
494
Jim Ingham372787f2012-04-07 00:00:41 +0000495lldb::thread_t
496Host::GetCurrentThread ()
497{
498 return lldb::thread_t(pthread_self());
499}
500
Greg Clayton2bddd342010-09-07 20:11:56 +0000501const char *
502Host::GetSignalAsCString (int signo)
503{
504 switch (signo)
505 {
506 case SIGHUP: return "SIGHUP"; // 1 hangup
507 case SIGINT: return "SIGINT"; // 2 interrupt
508 case SIGQUIT: return "SIGQUIT"; // 3 quit
509 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
510 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
511 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000512#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000513#if !defined(SIGIO) || (SIGPOLL != SIGIO)
514// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
515// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000516 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000517#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000518#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000519#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000520 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000521#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000522 case SIGFPE: return "SIGFPE"; // 8 floating point exception
523 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
524 case SIGBUS: return "SIGBUS"; // 10 bus error
525 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
526 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
527 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
528 case SIGALRM: return "SIGALRM"; // 14 alarm clock
529 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
530 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
531 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
532 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
533 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
534 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
535 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
536 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000537#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000538 case SIGIO: return "SIGIO"; // 23 input/output possible signal
539#endif
540 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
541 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
542 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
543 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000544#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000545 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000546#endif
547#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000548 case SIGINFO: return "SIGINFO"; // 29 information request
549#endif
550 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
551 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
552 default:
553 break;
554 }
555 return NULL;
556}
557
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000558#endif
559
Greg Clayton2bddd342010-09-07 20:11:56 +0000560void
561Host::WillTerminate ()
562{
563}
564
Sylvestre Ledru59405832013-07-01 08:21:36 +0000565#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000566
Greg Clayton2bddd342010-09-07 20:11:56 +0000567void
568Host::ThreadCreated (const char *thread_name)
569{
570}
Greg Claytone5219662010-12-03 06:02:24 +0000571
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000572void
Greg Claytone5219662010-12-03 06:02:24 +0000573Host::Backtrace (Stream &strm, uint32_t max_frames)
574{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000575 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000576}
577
Greg Clayton85851dd2010-12-04 00:10:17 +0000578size_t
579Host::GetEnvironment (StringList &env)
580{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000581 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000582 return 0;
583}
584
Sylvestre Ledru59405832013-07-01 08:21:36 +0000585#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000586
587struct HostThreadCreateInfo
588{
589 std::string thread_name;
590 thread_func_t thread_fptr;
591 thread_arg_t thread_arg;
592
593 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
594 thread_name (name ? name : ""),
595 thread_fptr (fptr),
596 thread_arg (arg)
597 {
598 }
599};
600
601static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000602#ifdef _WIN32
603__stdcall
604#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000605ThreadCreateTrampoline (thread_arg_t arg)
606{
607 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
608 Host::ThreadCreated (info->thread_name.c_str());
609 thread_func_t thread_fptr = info->thread_fptr;
610 thread_arg_t thread_arg = info->thread_arg;
611
Greg Clayton5160ce52013-03-27 23:08:40 +0000612 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000613 if (log)
614 log->Printf("thread created");
615
616 delete info;
617 return thread_fptr (thread_arg);
618}
619
620lldb::thread_t
621Host::ThreadCreate
622(
623 const char *thread_name,
624 thread_func_t thread_fptr,
625 thread_arg_t thread_arg,
626 Error *error
627)
628{
629 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
630
631 // Host::ThreadCreateTrampoline will delete this pointer for us.
632 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
633
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000634#ifdef _WIN32
635 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
636 int err = thread <= 0 ? GetLastError() : 0;
637#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000638 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000639#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000640 if (err == 0)
641 {
642 if (error)
643 error->Clear();
644 return thread;
645 }
646
647 if (error)
648 error->SetError (err, eErrorTypePOSIX);
649
650 return LLDB_INVALID_HOST_THREAD;
651}
652
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000653#ifndef _WIN32
654
Greg Clayton2bddd342010-09-07 20:11:56 +0000655bool
656Host::ThreadCancel (lldb::thread_t thread, Error *error)
657{
658 int err = ::pthread_cancel (thread);
659 if (error)
660 error->SetError(err, eErrorTypePOSIX);
661 return err == 0;
662}
663
664bool
665Host::ThreadDetach (lldb::thread_t thread, Error *error)
666{
667 int err = ::pthread_detach (thread);
668 if (error)
669 error->SetError(err, eErrorTypePOSIX);
670 return err == 0;
671}
672
673bool
674Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
675{
676 int err = ::pthread_join (thread, thread_result_ptr);
677 if (error)
678 error->SetError(err, eErrorTypePOSIX);
679 return err == 0;
680}
681
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000682lldb::thread_key_t
683Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
684{
685 pthread_key_t key;
686 ::pthread_key_create (&key, callback);
687 return key;
688}
689
690void*
691Host::ThreadLocalStorageGet(lldb::thread_key_t key)
692{
693 return ::pthread_getspecific (key);
694}
695
696void
697Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
698{
699 ::pthread_setspecific (key, value);
700}
701
Matt Kopec62502c62013-05-13 19:33:58 +0000702bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000703Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
704{
Greg Clayton85719632013-02-27 22:51:58 +0000705#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000706 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
707 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
708 if (pid == LLDB_INVALID_PROCESS_ID)
709 pid = curr_pid;
710
711 if (tid == LLDB_INVALID_THREAD_ID)
712 tid = curr_tid;
713
Greg Clayton2bddd342010-09-07 20:11:56 +0000714 // Set the pthread name if possible
715 if (pid == curr_pid && tid == curr_tid)
716 {
Matt Kopec62502c62013-05-13 19:33:58 +0000717 if (::pthread_setname_np (name) == 0)
718 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000719 }
Matt Kopec62502c62013-05-13 19:33:58 +0000720 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000721#elif defined (__FreeBSD__)
722 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
723 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
724 if (pid == LLDB_INVALID_PROCESS_ID)
725 pid = curr_pid;
726
727 if (tid == LLDB_INVALID_THREAD_ID)
728 tid = curr_tid;
729
730 // Set the pthread name if possible
731 if (pid == curr_pid && tid == curr_tid)
732 {
Michael Sartainc2052432013-08-01 18:51:08 +0000733 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000734 return true;
735 }
736 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000737#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000738 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
739 if (fn)
740 {
Matt Kopec62502c62013-05-13 19:33:58 +0000741 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
742 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000743 if (pid == LLDB_INVALID_PROCESS_ID)
744 pid = curr_pid;
745
746 if (tid == LLDB_INVALID_THREAD_ID)
747 tid = curr_tid;
748
Michael Sartainc2052432013-08-01 18:51:08 +0000749 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000750 {
Michael Sartainc2052432013-08-01 18:51:08 +0000751 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
752 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
753
754 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000755 return true;
756 }
757 }
758 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000759#else
760 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000761#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000762}
763
Ed Maste02983be2013-07-25 19:10:32 +0000764bool
765Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
766 const char *thread_name, size_t len)
767{
Enrico Granata67530b62014-02-12 03:37:33 +0000768 std::unique_ptr<char[]> namebuf(new char[len+1]);
769
Ed Maste02983be2013-07-25 19:10:32 +0000770 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
771 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
772 // off leads to a lot of similar named threads. Go through the thread name
773 // and search for the last dot and use that.
774 const char *lastdot = ::strrchr (thread_name, '.');
775
776 if (lastdot && lastdot != thread_name)
777 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000778 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000779 namebuf[len] = 0;
780
Enrico Granata67530b62014-02-12 03:37:33 +0000781 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000782 if (namebuflen > 0)
783 {
784 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
785 {
786 // Trim off trailing '(' and '>' characters for a bit more cleanup.
787 namebuflen--;
788 namebuf[namebuflen] = 0;
789 }
Enrico Granata67530b62014-02-12 03:37:33 +0000790 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000791 }
792 return false;
793}
794
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000795#endif
796
Greg Clayton2bddd342010-09-07 20:11:56 +0000797FileSpec
Zachary Turner9e757b72014-07-28 16:45:05 +0000798Host::GetUserProfileFileSpec ()
799{
800 static FileSpec g_profile_filespec;
801 if (!g_profile_filespec)
802 {
803 llvm::SmallString<64> path;
804 llvm::sys::path::home_directory(path);
805 return FileSpec(path.c_str(), false);
806 }
807 return g_profile_filespec;
808}
809
810FileSpec
Greg Clayton2bddd342010-09-07 20:11:56 +0000811Host::GetProgramFileSpec ()
812{
813 static FileSpec g_program_filespec;
814 if (!g_program_filespec)
815 {
816#if defined (__APPLE__)
817 char program_fullpath[PATH_MAX];
818 // If DST is NULL, then return the number of bytes needed.
819 uint32_t len = sizeof(program_fullpath);
820 int err = _NSGetExecutablePath (program_fullpath, &len);
821 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000822 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000823 else if (err == -1)
824 {
825 char *large_program_fullpath = (char *)::malloc (len + 1);
826
827 err = _NSGetExecutablePath (large_program_fullpath, &len);
828 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000829 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000830
831 ::free (large_program_fullpath);
832 }
833#elif defined (__linux__)
834 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000835 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
836 if (len > 0) {
837 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000838 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000839 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000840#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000841 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
842 size_t exe_path_size;
843 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
844 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000845 char *exe_path = new char[exe_path_size];
846 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
847 g_program_filespec.SetFile(exe_path, false);
848 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000849 }
Zachary Turner9e757b72014-07-28 16:45:05 +0000850#elif defined(_WIN32)
851 std::vector<char> buffer(PATH_MAX);
852 ::GetModuleFileName(NULL, &buffer[0], buffer.size());
Zachary Turnerd8a52732014-07-29 05:39:21 +0000853 g_program_filespec.SetFile(&buffer[0], false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000854#endif
855 }
856 return g_program_filespec;
857}
858
Greg Clayton2bddd342010-09-07 20:11:56 +0000859#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000860
861bool
862Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
863{
864 bundle.Clear();
865 return false;
866}
867
Greg Clayton2bddd342010-09-07 20:11:56 +0000868bool
Greg Claytondd36def2010-10-17 22:03:32 +0000869Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000870{
Greg Claytondd36def2010-10-17 22:03:32 +0000871 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000872}
873#endif
874
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000875#ifndef _WIN32
876
Greg Clayton45319462011-02-08 00:35:34 +0000877// Opaque info that tracks a dynamic library that was loaded
878struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000879{
Greg Clayton45319462011-02-08 00:35:34 +0000880 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
881 file_spec (fs),
882 open_options (o),
883 handle (h)
884 {
885 }
886
887 const FileSpec file_spec;
888 uint32_t open_options;
889 void * handle;
890};
891
892void *
893Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
894{
Greg Clayton4272cc72011-02-02 02:24:04 +0000895 char path[PATH_MAX];
896 if (file_spec.GetPath(path, sizeof(path)))
897 {
Greg Clayton45319462011-02-08 00:35:34 +0000898 int mode = 0;
899
900 if (options & eDynamicLibraryOpenOptionLazy)
901 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000902 else
903 mode |= RTLD_NOW;
904
Greg Clayton45319462011-02-08 00:35:34 +0000905
906 if (options & eDynamicLibraryOpenOptionLocal)
907 mode |= RTLD_LOCAL;
908 else
909 mode |= RTLD_GLOBAL;
910
911#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
912 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
913 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000914#endif
Greg Clayton45319462011-02-08 00:35:34 +0000915
916 void * opaque = ::dlopen (path, mode);
917
918 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000919 {
920 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000921 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000922 }
923 else
924 {
925 error.SetErrorString(::dlerror());
926 }
927 }
928 else
929 {
930 error.SetErrorString("failed to extract path");
931 }
Greg Clayton45319462011-02-08 00:35:34 +0000932 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000933}
934
935Error
Greg Clayton45319462011-02-08 00:35:34 +0000936Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000937{
938 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000939 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000940 {
941 error.SetErrorString ("invalid dynamic library handle");
942 }
Greg Clayton45319462011-02-08 00:35:34 +0000943 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000944 {
Greg Clayton45319462011-02-08 00:35:34 +0000945 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
946 if (::dlclose (dylib_info->handle) != 0)
947 {
948 error.SetErrorString(::dlerror());
949 }
950
951 dylib_info->open_options = 0;
952 dylib_info->handle = 0;
953 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000954 }
955 return error;
956}
957
958void *
Greg Clayton45319462011-02-08 00:35:34 +0000959Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000960{
Greg Clayton45319462011-02-08 00:35:34 +0000961 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000962 {
963 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000964 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000965 else
Greg Clayton45319462011-02-08 00:35:34 +0000966 {
967 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
968
969 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
970 if (symbol_addr)
971 {
972#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
973 // This host doesn't support limiting searches to this shared library
974 // so we need to verify that the match came from this shared library
975 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000976 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000977 {
978 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
979 if (match_dylib_spec != dylib_info->file_spec)
980 {
981 char dylib_path[PATH_MAX];
982 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
983 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
984 else
985 error.SetErrorString ("symbol not found");
986 return NULL;
987 }
988 }
989#endif
990 error.Clear();
991 return symbol_addr;
992 }
993 else
994 {
995 error.SetErrorString(::dlerror());
996 }
997 }
998 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000999}
Greg Claytondd36def2010-10-17 22:03:32 +00001000
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001001FileSpec
1002Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1003{
1004 FileSpec module_filespec;
1005 Dl_info info;
1006 if (::dladdr (host_addr, &info))
1007 {
1008 if (info.dli_fname)
1009 module_filespec.SetFile(info.dli_fname, true);
1010 }
1011 return module_filespec;
1012}
1013
1014#endif
1015
Greg Clayton23f8c952014-03-24 23:10:19 +00001016
1017static void CleanupProcessSpecificLLDBTempDir ()
1018{
1019 // Get the process specific LLDB temporary directory and delete it.
1020 FileSpec tmpdir_file_spec;
1021 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1022 {
1023 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1024 // true to all files that were created for the LLDB process can be cleaned up.
1025 const bool recurse = true;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001026 FileSystem::DeleteDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
Greg Clayton23f8c952014-03-24 23:10:19 +00001027 }
1028}
1029
Greg Claytondd36def2010-10-17 22:03:32 +00001030bool
1031Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1032{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001033 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001034 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1035 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001036 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001037 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001038 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001039
1040 switch (path_type)
1041 {
1042 case ePathTypeLLDBShlibDir:
1043 {
1044 static ConstString g_lldb_so_dir;
1045 if (!g_lldb_so_dir)
1046 {
David Majnemer8490da12014-07-22 22:00:42 +00001047 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1048 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +00001049 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001050 if (log)
1051 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001052 }
1053 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001054 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001055 }
1056 break;
1057
1058 case ePathTypeSupportExecutableDir:
1059 {
1060 static ConstString g_lldb_support_exe_dir;
1061 if (!g_lldb_support_exe_dir)
1062 {
1063 FileSpec lldb_file_spec;
1064 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1065 {
1066 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001067 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1068
1069#if defined (__APPLE__)
1070 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1071 if (framework_pos)
1072 {
1073 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +00001074#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001075 // Shallow bundle
1076 *framework_pos = '\0';
1077#else
1078 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001079 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001080#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001081 }
Todd Fiala015d8182014-07-22 23:41:36 +00001082#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1083 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1084 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
1085 // different trees.
1086 if (log)
1087 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1088 char *lib_pos = ::strstr (raw_path, "/lib");
1089 if (lib_pos != nullptr)
1090 {
1091 // First terminate the raw path at the start of lib.
1092 *lib_pos = '\0';
1093
1094 // Now write in bin in place of lib.
1095 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1096
1097 if (log)
1098 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1099 }
1100 else
1101 {
1102 if (log)
1103 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1104 }
Jason Molendaa3329782014-03-29 18:54:20 +00001105#endif // #if defined (__APPLE__)
Zachary Turner3f559742014-08-07 17:33:36 +00001106 llvm::SmallString<64> resolved_path(raw_path);
1107 FileSpec::Resolve (resolved_path);
1108 g_lldb_support_exe_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001109 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001110 if (log)
1111 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001112 }
1113 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001114 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001115 }
1116 break;
1117
1118 case ePathTypeHeaderDir:
1119 {
1120 static ConstString g_lldb_headers_dir;
1121 if (!g_lldb_headers_dir)
1122 {
1123#if defined (__APPLE__)
1124 FileSpec lldb_file_spec;
1125 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1126 {
1127 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001128 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1129
1130 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1131 if (framework_pos)
1132 {
1133 framework_pos += strlen("LLDB.framework");
1134 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1135 }
Jim Inghame1d263e2014-08-07 22:37:43 +00001136 llvm::SmallString<64> resolved_path(raw_path);
1137 FileSpec::Resolve (resolved_path);
1138 g_lldb_headers_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001139 }
1140#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001141 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001142 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1143#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001144 if (log)
1145 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001146 }
1147 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001148 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001149 }
1150 break;
1151
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001152#ifdef LLDB_DISABLE_PYTHON
1153 case ePathTypePythonDir:
1154 return false;
1155#else
1156 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001157 {
Greg Claytondd36def2010-10-17 22:03:32 +00001158 static ConstString g_lldb_python_dir;
1159 if (!g_lldb_python_dir)
1160 {
1161 FileSpec lldb_file_spec;
1162 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1163 {
1164 char raw_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001165#if defined(_WIN32)
1166 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1167 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1168#else
Greg Claytondd36def2010-10-17 22:03:32 +00001169 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1170
1171#if defined (__APPLE__)
1172 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1173 if (framework_pos)
1174 {
1175 framework_pos += strlen("LLDB.framework");
1176 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001177 }
1178 else
1179 {
1180#endif
1181 llvm::SmallString<256> python_version_dir;
1182 llvm::raw_svector_ostream os(python_version_dir);
1183 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1184 os.flush();
1185
1186 // We may get our string truncated. Should we protect
1187 // this with an assert?
1188
1189 ::strncat(raw_path, python_version_dir.c_str(),
1190 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001191#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001192#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001193 }
1194#endif
Zachary Turner3f559742014-08-07 17:33:36 +00001195 llvm::SmallString<64> resolved_path(raw_path);
1196 FileSpec::Resolve (resolved_path);
1197 g_lldb_python_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001198 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001199
1200 if (log)
1201 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1202
Greg Claytondd36def2010-10-17 22:03:32 +00001203 }
1204 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001205 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001206 }
1207 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001208#endif
1209
Greg Clayton4272cc72011-02-02 02:24:04 +00001210 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1211 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001212#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001213 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001214 static bool g_lldb_system_plugin_dir_located = false;
1215 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001216 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001217 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001218#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001219 FileSpec lldb_file_spec;
1220 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1221 {
1222 char raw_path[PATH_MAX];
Greg Clayton4272cc72011-02-02 02:24:04 +00001223 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1224
1225 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1226 if (framework_pos)
1227 {
1228 framework_pos += strlen("LLDB.framework");
1229 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Jim Inghame1d263e2014-08-07 22:37:43 +00001230 llvm::SmallString<64> resolved_path(raw_path);
1231 FileSpec::Resolve (resolved_path);
1232 g_lldb_system_plugin_dir.SetCString(resolved_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001233 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001234 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001235 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001236#elif defined (__linux__)
1237 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1238 if (lldb_file_spec.Exists())
1239 {
1240 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1241 }
1242#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001243
1244 if (log)
1245 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1246
Greg Clayton4272cc72011-02-02 02:24:04 +00001247 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001248
1249 if (g_lldb_system_plugin_dir)
1250 {
1251 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1252 return true;
1253 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001254#else
1255 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001256 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001257#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001258 }
1259 break;
1260
1261 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1262 {
1263#if defined (__APPLE__)
1264 static ConstString g_lldb_user_plugin_dir;
1265 if (!g_lldb_user_plugin_dir)
1266 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001267 llvm::SmallString<64> user_plugin_path("~/Library/Application Support/LLDB/PlugIns");
1268 FileSpec::Resolve (user_plugin_path);
1269 if (user_plugin_path.size())
Greg Clayton4272cc72011-02-02 02:24:04 +00001270 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001271 g_lldb_user_plugin_dir.SetCString(user_plugin_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001272 }
1273 }
1274 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001275 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001276#elif defined (__linux__)
1277 static ConstString g_lldb_user_plugin_dir;
1278 if (!g_lldb_user_plugin_dir)
1279 {
1280 // XDG Base Directory Specification
1281 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1282 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1283 FileSpec lldb_file_spec;
1284 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1285 if (xdg_data_home && xdg_data_home[0])
1286 {
1287 std::string user_plugin_dir (xdg_data_home);
1288 user_plugin_dir += "/lldb";
1289 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1290 }
1291 else
1292 {
1293 const char *home_dir = getenv("HOME");
1294 if (home_dir && home_dir[0])
1295 {
1296 std::string user_plugin_dir (home_dir);
1297 user_plugin_dir += "/.local/share/lldb";
1298 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1299 }
1300 }
1301
1302 if (lldb_file_spec.Exists())
1303 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001304 if (log)
1305 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001306 }
1307 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001308 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001309#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001310 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001311 return false;
1312 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001313
1314 case ePathTypeLLDBTempSystemDir:
1315 {
1316 static ConstString g_lldb_tmp_dir;
1317 if (!g_lldb_tmp_dir)
1318 {
1319 const char *tmpdir_cstr = getenv("TMPDIR");
1320 if (tmpdir_cstr == NULL)
1321 {
1322 tmpdir_cstr = getenv("TMP");
1323 if (tmpdir_cstr == NULL)
1324 tmpdir_cstr = getenv("TEMP");
1325 }
1326 if (tmpdir_cstr)
1327 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001328 StreamString pid_tmpdir;
1329 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001330 if (FileSystem::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault)
1331 .Success())
Greg Clayton23f8c952014-03-24 23:10:19 +00001332 {
1333 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001334 if (FileSystem::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault)
1335 .Success())
Greg Clayton23f8c952014-03-24 23:10:19 +00001336 {
1337 // Make an atexit handler to clean up the process specify LLDB temp dir
1338 // and all of its contents.
1339 ::atexit (CleanupProcessSpecificLLDBTempDir);
1340 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1341 if (log)
1342 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1343
1344 }
1345 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001346 }
1347 }
1348 file_spec.GetDirectory() = g_lldb_tmp_dir;
1349 return (bool)file_spec.GetDirectory();
1350 }
Greg Claytondd36def2010-10-17 22:03:32 +00001351 }
1352
1353 return false;
1354}
1355
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001356#ifndef _WIN32
1357
Greg Clayton32e0a752011-03-30 18:16:51 +00001358const char *
1359Host::GetUserName (uint32_t uid, std::string &user_name)
1360{
1361 struct passwd user_info;
1362 struct passwd *user_info_ptr = &user_info;
1363 char user_buffer[PATH_MAX];
1364 size_t user_buffer_size = sizeof(user_buffer);
1365 if (::getpwuid_r (uid,
1366 &user_info,
1367 user_buffer,
1368 user_buffer_size,
1369 &user_info_ptr) == 0)
1370 {
1371 if (user_info_ptr)
1372 {
1373 user_name.assign (user_info_ptr->pw_name);
1374 return user_name.c_str();
1375 }
1376 }
1377 user_name.clear();
1378 return NULL;
1379}
1380
1381const char *
1382Host::GetGroupName (uint32_t gid, std::string &group_name)
1383{
1384 char group_buffer[PATH_MAX];
1385 size_t group_buffer_size = sizeof(group_buffer);
1386 struct group group_info;
1387 struct group *group_info_ptr = &group_info;
1388 // Try the threadsafe version first
1389 if (::getgrgid_r (gid,
1390 &group_info,
1391 group_buffer,
1392 group_buffer_size,
1393 &group_info_ptr) == 0)
1394 {
1395 if (group_info_ptr)
1396 {
1397 group_name.assign (group_info_ptr->gr_name);
1398 return group_name.c_str();
1399 }
1400 }
1401 else
1402 {
1403 // The threadsafe version isn't currently working
1404 // for me on darwin, but the non-threadsafe version
1405 // is, so I am calling it below.
1406 group_info_ptr = ::getgrgid (gid);
1407 if (group_info_ptr)
1408 {
1409 group_name.assign (group_info_ptr->gr_name);
1410 return group_name.c_str();
1411 }
1412 }
1413 group_name.clear();
1414 return NULL;
1415}
1416
Han Ming Ong84647042012-02-25 01:07:38 +00001417uint32_t
1418Host::GetUserID ()
1419{
1420 return getuid();
1421}
1422
1423uint32_t
1424Host::GetGroupID ()
1425{
1426 return getgid();
1427}
1428
1429uint32_t
1430Host::GetEffectiveUserID ()
1431{
1432 return geteuid();
1433}
1434
1435uint32_t
1436Host::GetEffectiveGroupID ()
1437{
1438 return getegid();
1439}
1440
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001441#endif
1442
Zachary Turner310035a2014-07-08 04:52:15 +00001443#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1444 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001445uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001446Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001447{
1448 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001449 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001450}
1451
Greg Claytone996fd32011-03-08 22:40:15 +00001452bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001453Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001454{
Greg Claytone996fd32011-03-08 22:40:15 +00001455 process_info.Clear();
1456 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001457}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001458#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001459
Matt Kopec085d6ce2013-05-31 22:00:07 +00001460#if !defined(__linux__)
1461bool
1462Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1463{
1464 return false;
1465}
1466#endif
1467
Sean Callananc0a6e062011-10-27 21:22:25 +00001468lldb::TargetSP
1469Host::GetDummyTarget (lldb_private::Debugger &debugger)
1470{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001471 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001472
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001473 // FIXME: Maybe the dummy target should be per-Debugger
1474 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1475 {
1476 ArchSpec arch(Target::GetDefaultArchitecture());
1477 if (!arch.IsValid())
1478 arch = Host::GetArchitecture ();
1479 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001480 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001481 arch.GetTriple().getTriple().c_str(),
1482 false,
1483 NULL,
1484 g_dummy_target_sp);
1485 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001486
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001487 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001488}
1489
Greg Claytond1cf11a2012-04-14 01:42:46 +00001490struct ShellInfo
1491{
1492 ShellInfo () :
1493 process_reaped (false),
1494 can_delete (false),
1495 pid (LLDB_INVALID_PROCESS_ID),
1496 signo(-1),
1497 status(-1)
1498 {
1499 }
1500
1501 lldb_private::Predicate<bool> process_reaped;
1502 lldb_private::Predicate<bool> can_delete;
1503 lldb::pid_t pid;
1504 int signo;
1505 int status;
1506};
1507
1508static bool
1509MonitorShellCommand (void *callback_baton,
1510 lldb::pid_t pid,
1511 bool exited, // True if the process did exit
1512 int signo, // Zero for no signal
1513 int status) // Exit value of process if signal is zero
1514{
1515 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1516 shell_info->pid = pid;
1517 shell_info->signo = signo;
1518 shell_info->status = status;
1519 // Let the thread running Host::RunShellCommand() know that the process
1520 // exited and that ShellInfo has been filled in by broadcasting to it
1521 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1522 // Now wait for a handshake back from that thread running Host::RunShellCommand
1523 // so we know that we can delete shell_info_ptr
1524 shell_info->can_delete.WaitForValueEqualTo(true);
1525 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1526 usleep(1000);
1527 // Now delete the shell info that was passed into this function
1528 delete shell_info;
1529 return true;
1530}
1531
1532Error
1533Host::RunShellCommand (const char *command,
1534 const char *working_dir,
1535 int *status_ptr,
1536 int *signo_ptr,
1537 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001538 uint32_t timeout_sec,
1539 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001540{
1541 Error error;
1542 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001543 if (shell && shell[0])
1544 {
1545 // Run the command in a shell
1546 launch_info.SetShell(shell);
1547 launch_info.GetArguments().AppendArgument(command);
1548 const bool localhost = true;
1549 const bool will_debug = false;
1550 const bool first_arg_is_full_shell_command = true;
1551 launch_info.ConvertArgumentsForLaunchingInShell (error,
1552 localhost,
1553 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001554 first_arg_is_full_shell_command,
1555 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001556 }
1557 else
1558 {
1559 // No shell, just run it
1560 Args args (command);
1561 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001562 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001563 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001564
1565 if (working_dir)
1566 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001567 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001568 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001569
Greg Claytond1cf11a2012-04-14 01:42:46 +00001570 if (command_output_ptr)
1571 {
1572 // Create a temporary file to get the stdout/stderr and redirect the
1573 // output of the command into this file. We will later read this file
1574 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001575 FileSpec tmpdir_file_spec;
1576 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1577 {
1578 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1579 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1580 }
1581 else
1582 {
1583 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1584 }
1585
1586 output_file_path = ::mktemp(output_file_path_buffer);
1587 }
1588
1589 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1590 if (output_file_path)
1591 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001592 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001593 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001594 }
1595 else
1596 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001597 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1598 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1599 }
1600
1601 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001602 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001603
1604 const bool monitor_signals = false;
1605 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1606
1607 error = LaunchProcess (launch_info);
1608 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001609
1610 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1611 error.SetErrorString("failed to get process ID");
1612
1613 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001614 {
1615 // The process successfully launched, so we can defer ownership of
1616 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001617 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001618 // doesn't need to delete the ShellInfo anymore.
1619 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001620 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001621 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001622 if (timeout_sec > 0) {
1623 timeout_time.OffsetWithSeconds(timeout_sec);
1624 timeout_ptr = &timeout_time;
1625 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001626 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001627 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001628 if (timed_out)
1629 {
1630 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001631
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001632 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001633 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001634 // Wait for the monitor callback to get the message
1635 timeout_time = TimeValue::Now();
1636 timeout_time.OffsetWithSeconds(1);
1637 timed_out = false;
1638 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1639 }
1640 else
1641 {
1642 if (status_ptr)
1643 *status_ptr = shell_info->status;
1644
1645 if (signo_ptr)
1646 *signo_ptr = shell_info->signo;
1647
1648 if (command_output_ptr)
1649 {
1650 command_output_ptr->clear();
1651 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1652 uint64_t file_size = file_spec.GetByteSize();
1653 if (file_size > 0)
1654 {
1655 if (file_size > command_output_ptr->max_size())
1656 {
1657 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1658 }
1659 else
1660 {
1661 command_output_ptr->resize(file_size);
1662 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1663 }
1664 }
1665 }
1666 }
1667 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1668 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001669
1670 if (output_file_path)
1671 ::unlink (output_file_path);
1672 // Handshake with the monitor thread, or just let it know in advance that
1673 // it can delete "shell_info" in case we timed out and were not able to kill
1674 // the process...
1675 return error;
1676}
1677
Daniel Malea4244cbd2013-08-27 20:58:59 +00001678
Todd Fiala76747122014-01-23 00:52:28 +00001679// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1680// systems
1681
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001682#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001683
1684// this method needs to be visible to macosx/Host.cpp and
1685// common/Host.cpp.
1686
1687short
1688Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1689{
1690 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1691
1692#if defined (__APPLE__)
1693 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1694 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1695
1696 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1697 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1698
1699 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1700 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1701
1702 if (launch_info.GetLaunchInSeparateProcessGroup())
1703 flags |= POSIX_SPAWN_SETPGROUP;
1704
1705#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1706#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1707 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1708 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1709 {
1710 g_use_close_on_exec_flag = eLazyBoolNo;
1711
1712 uint32_t major, minor, update;
Zachary Turner97a14e62014-08-19 17:18:29 +00001713 if (HostInfo::GetOSVersion(major, minor, update))
Todd Fiala76747122014-01-23 00:52:28 +00001714 {
1715 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1716 if (major > 10 || (major == 10 && minor > 7))
1717 {
1718 // Only enable for 10.8 and later OS versions
1719 g_use_close_on_exec_flag = eLazyBoolYes;
1720 }
1721 }
1722 }
1723#else
1724 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1725#endif
1726 // Close all files exception those with file actions if this is supported.
1727 if (g_use_close_on_exec_flag == eLazyBoolYes)
1728 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1729#endif
1730#endif // #if defined (__APPLE__)
1731 return flags;
1732}
1733
1734Error
1735Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001736{
1737 Error error;
1738 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1739
Daniel Malea4244cbd2013-08-27 20:58:59 +00001740 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001741 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001742
1743 if (error.Fail() || log)
1744 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001745 if (error.Fail())
1746 return error;
1747
1748 // Make a quick class that will cleanup the posix spawn attributes in case
1749 // we return in the middle of this function.
1750 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1751
1752 sigset_t no_signals;
1753 sigset_t all_signals;
1754 sigemptyset (&no_signals);
1755 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001756 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001757#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001758 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001759#else
1760 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1761#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001762
Todd Fiala76747122014-01-23 00:52:28 +00001763 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001764
1765 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001766 if (error.Fail() || log)
1767 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001768 if (error.Fail())
1769 return error;
1770
Todd Fiala76747122014-01-23 00:52:28 +00001771 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1772 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1773#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001774
1775 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1776 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1777 // to do that job on OSX.
1778
1779 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001780 {
Jim Ingham90331d52014-02-21 01:25:21 +00001781 // We don't need to do this for ARM, and we really shouldn't now that we
1782 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1783 // to set which CPU subtype to launch...
1784 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1785 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1786 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1787 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001788 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1789 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001790 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1791 {
1792 size_t ocount = 0;
1793 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1794 if (error.Fail() || log)
1795 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu, (uint64_t)ocount);
Todd Fiala76747122014-01-23 00:52:28 +00001796
Jim Ingham90331d52014-02-21 01:25:21 +00001797 if (error.Fail() || ocount != 1)
1798 return error;
1799 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001800 }
1801
Todd Fiala76747122014-01-23 00:52:28 +00001802#endif
1803
1804 const char *tmp_argv[2];
1805 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1806 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1807 if (argv == NULL)
1808 {
1809 // posix_spawn gets very unhappy if it doesn't have at least the program
1810 // name in argv[0]. One of the side affects I have noticed is the environment
1811 // variables don't make it into the child process if "argv == NULL"!!!
1812 tmp_argv[0] = exe_path;
1813 tmp_argv[1] = NULL;
1814 argv = (char * const*)tmp_argv;
1815 }
1816
1817#if !defined (__APPLE__)
1818 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001819 char current_dir[PATH_MAX];
1820 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001821#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001822
1823 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001824 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001825 {
Todd Fiala76747122014-01-23 00:52:28 +00001826#if defined (__APPLE__)
1827 // Set the working directory on this thread only
1828 if (__pthread_chdir (working_dir) < 0) {
1829 if (errno == ENOENT) {
1830 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1831 } else if (errno == ENOTDIR) {
1832 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1833 } else {
1834 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1835 }
1836 return error;
1837 }
1838#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001839 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1840 {
1841 error.SetError(errno, eErrorTypePOSIX);
1842 error.LogIfError(log, "unable to save the current directory");
1843 return error;
1844 }
1845
1846 if (::chdir(working_dir) == -1)
1847 {
1848 error.SetError(errno, eErrorTypePOSIX);
1849 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1850 return error;
1851 }
Todd Fiala76747122014-01-23 00:52:28 +00001852#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001853 }
1854
Todd Fiala76747122014-01-23 00:52:28 +00001855 const size_t num_file_actions = launch_info.GetNumFileActions ();
1856 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001857 {
Todd Fiala76747122014-01-23 00:52:28 +00001858 posix_spawn_file_actions_t file_actions;
1859 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1860 if (error.Fail() || log)
1861 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1862 if (error.Fail())
1863 return error;
1864
1865 // Make a quick class that will cleanup the posix spawn attributes in case
1866 // we return in the middle of this function.
1867 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1868
1869 for (size_t i=0; i<num_file_actions; ++i)
1870 {
Zachary Turner696b5282014-08-14 16:01:25 +00001871 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +00001872 if (launch_file_action)
1873 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001874 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
Todd Fiala76747122014-01-23 00:52:28 +00001875 return error;
1876 }
1877 }
1878
1879 error.SetError (::posix_spawnp (&pid,
1880 exe_path,
1881 &file_actions,
1882 &attr,
1883 argv,
1884 envp),
1885 eErrorTypePOSIX);
1886
1887 if (error.Fail() || log)
1888 {
1889 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 +00001890 pid, exe_path, static_cast<void*>(&file_actions),
1891 static_cast<void*>(&attr),
1892 reinterpret_cast<const void*>(argv),
1893 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001894 if (log)
1895 {
1896 for (int ii=0; argv[ii]; ++ii)
1897 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1898 }
1899 }
1900
1901 }
1902 else
1903 {
1904 error.SetError (::posix_spawnp (&pid,
1905 exe_path,
1906 NULL,
1907 &attr,
1908 argv,
1909 envp),
1910 eErrorTypePOSIX);
1911
1912 if (error.Fail() || log)
1913 {
1914 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 +00001915 pid, exe_path, static_cast<void*>(&attr),
1916 reinterpret_cast<const void*>(argv),
1917 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001918 if (log)
1919 {
1920 for (int ii=0; argv[ii]; ++ii)
1921 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1922 }
1923 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001924 }
1925
Todd Fiala76747122014-01-23 00:52:28 +00001926 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001927 {
Todd Fiala76747122014-01-23 00:52:28 +00001928#if defined (__APPLE__)
1929 // No more thread specific current working directory
1930 __pthread_fchdir (-1);
1931#else
1932 if (::chdir(current_dir) == -1 && error.Success())
1933 {
1934 error.SetError(errno, eErrorTypePOSIX);
1935 error.LogIfError(log, "unable to change current directory back to %s",
1936 current_dir);
1937 }
1938#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001939 }
1940
1941 return error;
1942}
1943
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001944bool
1945Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
Zachary Turner696b5282014-08-14 16:01:25 +00001946{
1947 if (info == NULL)
1948 return false;
1949
1950 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
1951
1952 switch (info->GetAction())
1953 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001954 case FileAction::eFileActionNone:
1955 error.Clear();
1956 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001957
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001958 case FileAction::eFileActionClose:
1959 if (info->GetFD() == -1)
1960 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
1961 else
1962 {
1963 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
1964 if (log && (error.Fail() || log))
1965 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
1966 static_cast<void *>(file_actions), info->GetFD());
1967 }
1968 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001969
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001970 case FileAction::eFileActionDuplicate:
1971 if (info->GetFD() == -1)
1972 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
1973 else if (info->GetActionArgument() == -1)
1974 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
1975 else
1976 {
1977 error.SetError(
1978 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
1979 eErrorTypePOSIX);
1980 if (log && (error.Fail() || log))
1981 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
1982 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
1983 }
1984 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001985
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001986 case FileAction::eFileActionOpen:
1987 if (info->GetFD() == -1)
1988 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
1989 else
1990 {
1991 int oflag = info->GetActionArgument();
Zachary Turner696b5282014-08-14 16:01:25 +00001992
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001993 mode_t mode = 0;
Zachary Turner696b5282014-08-14 16:01:25 +00001994
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001995 if (oflag & O_CREAT)
1996 mode = 0640;
Zachary Turner696b5282014-08-14 16:01:25 +00001997
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001998 error.SetError(
1999 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
2000 eErrorTypePOSIX);
2001 if (error.Fail() || log)
2002 error.PutToLog(log,
2003 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
2004 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
2005 }
2006 break;
Zachary Turner696b5282014-08-14 16:01:25 +00002007 }
2008 return error.Success();
2009}
2010
Todd Fiala76747122014-01-23 00:52:28 +00002011#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2012
2013
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002014#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2015// The functions below implement process launching via posix_spawn() for Linux,
2016// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00002017
2018Error
2019Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2020{
2021 Error error;
2022 char exe_path[PATH_MAX];
2023
2024 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2025
2026 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2027
2028 FileSpec exe_spec(launch_info.GetExecutableFile());
2029
2030 FileSpec::FileType file_type = exe_spec.GetFileType();
2031 if (file_type != FileSpec::eFileTypeRegular)
2032 {
2033 lldb::ModuleSP exe_module_sp;
2034 error = host_platform_sp->ResolveExecutable (exe_spec,
2035 arch_spec,
2036 exe_module_sp,
2037 NULL);
2038
2039 if (error.Fail())
2040 return error;
2041
2042 if (exe_module_sp)
2043 exe_spec = exe_module_sp->GetFileSpec();
2044 }
2045
2046 if (exe_spec.Exists())
2047 {
2048 exe_spec.GetPath (exe_path, sizeof(exe_path));
2049 }
2050 else
2051 {
2052 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2053 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2054 return error;
2055 }
2056
2057 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2058
2059 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2060
2061 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2062
2063 if (pid != LLDB_INVALID_PROCESS_ID)
2064 {
2065 // If all went well, then set the process ID into the launch info
2066 launch_info.SetProcessID(pid);
2067
Todd Fiala76747122014-01-23 00:52:28 +00002068 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2069
Daniel Malea4244cbd2013-08-27 20:58:59 +00002070 // Make sure we reap any processes we spawn or we will have zombies.
2071 if (!launch_info.MonitorProcess())
2072 {
2073 const bool monitor_signals = false;
2074 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2075 NULL,
2076 pid,
2077 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002078 if (log)
2079 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2080 }
2081 else
2082 {
2083 if (log)
2084 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002085 }
2086 }
2087 else
2088 {
2089 // Invalid process ID, something didn't go well
2090 if (error.Success())
2091 error.SetErrorString ("process launch failed for unknown reasons");
2092 }
2093 return error;
2094}
2095
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002096#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002097
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002098#ifndef _WIN32
2099
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002100void
2101Host::Kill(lldb::pid_t pid, int signo)
2102{
2103 ::kill(pid, signo);
2104}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002105
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002106#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002107
Johnny Chen8f3d8382011-08-02 20:52:42 +00002108#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002109bool
Greg Clayton3b147632010-12-18 01:54:34 +00002110Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002111{
2112 return false;
2113}
Greg Claytondd36def2010-10-17 22:03:32 +00002114
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002115void
2116Host::SetCrashDescriptionWithFormat (const char *format, ...)
2117{
2118}
2119
2120void
2121Host::SetCrashDescription (const char *description)
2122{
2123}
Greg Claytondd36def2010-10-17 22:03:32 +00002124
2125lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002126Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002127{
2128 return LLDB_INVALID_PROCESS_ID;
2129}
2130
Greg Claytonfbb76342013-11-20 21:07:01 +00002131#endif