blob: df1c78726b6777ad0ad4300960fdd847c0524b05 [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"
Greg Clayton2bddd342010-09-07 20:11:56 +000070#include "lldb/Host/Mutex.h"
Greg Claytone996fd32011-03-08 22:40:15 +000071#include "lldb/Target/Process.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000072#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000073#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000074
Saleem Abdulrasool28606952014-06-27 05:17:41 +000075#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000076#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000077#include "llvm/Support/Host.h"
Zachary Turner9e757b72014-07-28 16:45:05 +000078#include "llvm/Support/Path.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000079#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000080
Todd Fiala76747122014-01-23 00:52:28 +000081#if defined (__APPLE__)
82#ifndef _POSIX_SPAWN_DISABLE_ASLR
83#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
84#endif
85
86extern "C"
87{
88 int __pthread_chdir(const char *path);
89 int __pthread_fchdir (int fildes);
90}
91
92#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000093
Greg Clayton2bddd342010-09-07 20:11:56 +000094using namespace lldb;
95using namespace lldb_private;
96
Todd Fiala17096d72014-07-16 19:03:16 +000097// Define maximum thread name length
98#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
99uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
100#else
101uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
102#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000103
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000104#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000105struct MonitorInfo
106{
107 lldb::pid_t pid; // The process ID to monitor
108 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
109 void *callback_baton; // The callback baton for the callback function
110 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
111};
112
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000113static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000114MonitorChildProcessThreadFunction (void *arg);
115
116lldb::thread_t
117Host::StartMonitoringChildProcess
118(
119 Host::MonitorChildProcessCallback callback,
120 void *callback_baton,
121 lldb::pid_t pid,
122 bool monitor_signals
123)
124{
125 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000126 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000127
Greg Claytone4e45922011-11-16 05:37:56 +0000128 info_ptr->pid = pid;
129 info_ptr->callback = callback;
130 info_ptr->callback_baton = callback_baton;
131 info_ptr->monitor_signals = monitor_signals;
132
133 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000134 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000135 thread = ThreadCreate (thread_name,
136 MonitorChildProcessThreadFunction,
137 info_ptr,
138 NULL);
139
Greg Clayton2bddd342010-09-07 20:11:56 +0000140 return thread;
141}
142
143//------------------------------------------------------------------
144// Scoped class that will disable thread canceling when it is
145// constructed, and exception safely restore the previous value it
146// when it goes out of scope.
147//------------------------------------------------------------------
148class ScopedPThreadCancelDisabler
149{
150public:
151 ScopedPThreadCancelDisabler()
152 {
153 // Disable the ability for this thread to be cancelled
154 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
155 if (err != 0)
156 m_old_state = -1;
157
158 }
159
160 ~ScopedPThreadCancelDisabler()
161 {
162 // Restore the ability for this thread to be cancelled to what it
163 // previously was.
164 if (m_old_state != -1)
165 ::pthread_setcancelstate (m_old_state, 0);
166 }
167private:
168 int m_old_state; // Save the old cancelability state.
169};
170
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000171static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000172MonitorChildProcessThreadFunction (void *arg)
173{
Greg Clayton5160ce52013-03-27 23:08:40 +0000174 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000175 const char *function = __FUNCTION__;
176 if (log)
177 log->Printf ("%s (arg = %p) thread starting...", function, arg);
178
179 MonitorInfo *info = (MonitorInfo *)arg;
180
181 const Host::MonitorChildProcessCallback callback = info->callback;
182 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000183 const bool monitor_signals = info->monitor_signals;
184
Daniel Malea4244cbd2013-08-27 20:58:59 +0000185 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000186 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000187
Greg Clayton2bddd342010-09-07 20:11:56 +0000188 delete info;
189
190 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000191#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000192 #define __WALL 0
193#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000194 const int options = __WALL;
195
Greg Clayton2bddd342010-09-07 20:11:56 +0000196 while (1)
197 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000198 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000199 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000200 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000201
202 // Wait for all child processes
203 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000204 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000205 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000206 ::pthread_testcancel ();
207
208 if (wait_pid == -1)
209 {
210 if (errno == EINTR)
211 continue;
212 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000213 {
214 if (log)
215 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000216 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000217 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000218 }
Matt Kopec650648f2013-01-08 16:30:18 +0000219 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000220 {
221 bool exited = false;
222 int signal = 0;
223 int exit_status = 0;
224 const char *status_cstr = NULL;
225 if (WIFSTOPPED(status))
226 {
227 signal = WSTOPSIG(status);
228 status_cstr = "STOPPED";
229 }
230 else if (WIFEXITED(status))
231 {
232 exit_status = WEXITSTATUS(status);
233 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000234 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000235 }
236 else if (WIFSIGNALED(status))
237 {
238 signal = WTERMSIG(status);
239 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000240 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000241 exited = true;
242 exit_status = -1;
243 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000244 }
245 else
246 {
Johnny Chen44805302011-07-19 19:48:13 +0000247 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000248 }
249
250 // Scope for pthread_cancel_disabler
251 {
252 ScopedPThreadCancelDisabler pthread_cancel_disabler;
253
Caroline Tice20ad3c42010-10-29 21:48:37 +0000254 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000255 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000256 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 +0000257 function,
258 wait_pid,
259 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000260 pid,
261 status,
262 status_cstr,
263 signal,
264 exit_status);
265
266 if (exited || (signal != 0 && monitor_signals))
267 {
Greg Claytone4e45922011-11-16 05:37:56 +0000268 bool callback_return = false;
269 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000270 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000271
272 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000273 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000274 {
275 if (log)
276 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000277 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000278 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000279 // If the callback returns true, it means this process should
280 // exit
281 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000282 {
283 if (log)
284 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000285 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000286 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000287 }
288 }
289 }
290 }
291
Caroline Tice20ad3c42010-10-29 21:48:37 +0000292 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000293 if (log)
294 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
295
296 return NULL;
297}
298
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000299#endif // #if !defined (__APPLE__) && !defined (_WIN32)
300
301#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000302
303void
304Host::SystemLog (SystemLogType type, const char *format, va_list args)
305{
306 vfprintf (stderr, format, args);
307}
308
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000309#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000310
Greg Claytone38a5ed2012-01-05 03:57:59 +0000311void
312Host::SystemLog (SystemLogType type, const char *format, ...)
313{
314 va_list args;
315 va_start (args, format);
316 SystemLog (type, format, args);
317 va_end (args);
318}
319
Greg Clayton2bddd342010-09-07 20:11:56 +0000320const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000321Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000322{
Greg Clayton514487e2011-02-15 21:59:32 +0000323 static bool g_supports_32 = false;
324 static bool g_supports_64 = false;
325 static ArchSpec g_host_arch_32;
326 static ArchSpec g_host_arch_64;
327
Greg Clayton2bddd342010-09-07 20:11:56 +0000328#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000329
330 // Apple is different in that it can support both 32 and 64 bit executables
331 // in the same operating system running concurrently. Here we detect the
332 // correct host architectures for both 32 and 64 bit including if 64 bit
333 // executables are supported on the system.
334
335 if (g_supports_32 == false && g_supports_64 == false)
336 {
337 // All apple systems support 32 bit execution.
338 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000339 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000340 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000341 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000342 ArchSpec host_arch;
343 // These will tell us about the kernel architecture, which even on a 64
344 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000345 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
346 {
Greg Clayton514487e2011-02-15 21:59:32 +0000347 len = sizeof (cpusubtype);
348 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
349 cpusubtype = CPU_TYPE_ANY;
350
Greg Clayton2bddd342010-09-07 20:11:56 +0000351 len = sizeof (is_64_bit_capable);
352 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
353 {
354 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000355 g_supports_64 = true;
356 }
357
358 if (is_64_bit_capable)
359 {
360 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000361 {
Greg Clayton514487e2011-02-15 21:59:32 +0000362 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000363 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000364 }
365 else
366 {
Greg Clayton52edb362014-07-14 22:53:02 +0000367 // We have a 64 bit kernel that is returning a 32 bit cputype, the
368 // cpusubtype will be correct as if it were for a 64 bit architecture
369 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype | CPU_ARCH_ABI64, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000370 }
Greg Clayton52edb362014-07-14 22:53:02 +0000371
372 // Now we need modify the cpusubtype for the 32 bit slices.
373 uint32_t cpusubtype32 = cpusubtype;
374#if defined (__i386__) || defined (__x86_64__)
375 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
376 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
377#elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
378 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
379 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
380#endif
381 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype & ~(CPU_ARCH_MASK), cpusubtype32);
Greg Claytonc76fa8a2014-07-29 21:27:21 +0000382
383 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
384 {
385 g_host_arch_32.GetTriple().setOS(llvm::Triple::IOS);
386 g_host_arch_64.GetTriple().setOS(llvm::Triple::IOS);
387 }
388 else
389 {
390 g_host_arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
391 g_host_arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
392 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000393 }
Greg Clayton514487e2011-02-15 21:59:32 +0000394 else
395 {
Greg Clayton52edb362014-07-14 22:53:02 +0000396 // We have a 32 bit kernel on a 32 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000397 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000398 g_host_arch_64.Clear();
399 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000400 }
Greg Clayton514487e2011-02-15 21:59:32 +0000401 }
402
403#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000404
Greg Clayton514487e2011-02-15 21:59:32 +0000405 if (g_supports_32 == false && g_supports_64 == false)
406 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000407 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000408
Stephen Wilsonbd588712011-02-24 19:15:09 +0000409 g_host_arch_32.Clear();
410 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000411
Greg Claytonb29e6c62012-10-11 17:38:58 +0000412 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
413 // for the default triple. It's probably an artifact of config.guess.
414 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000415 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000416
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000417 const char* distribution_id = GetDistributionId ().AsCString();
418
Stephen Wilsonbd588712011-02-24 19:15:09 +0000419 switch (triple.getArch())
420 {
421 default:
422 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000423 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000424 g_supports_32 = true;
425 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000426
Stephen Wilsonbd588712011-02-24 19:15:09 +0000427 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000428 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000429 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000430 g_supports_64 = true;
431 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000432 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000433 g_supports_32 = true;
434 break;
435
Ed Mastea8375762014-04-01 18:06:45 +0000436 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000437 case llvm::Triple::sparcv9:
438 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000439 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000440 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000441 g_supports_64 = true;
442 break;
443 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000444
445 g_supports_32 = g_host_arch_32.IsValid();
446 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000447 }
Greg Clayton514487e2011-02-15 21:59:32 +0000448
449#endif // #else for #if defined (__APPLE__)
450
451 if (arch_kind == eSystemDefaultArchitecture32)
452 return g_host_arch_32;
453 else if (arch_kind == eSystemDefaultArchitecture64)
454 return g_host_arch_64;
455
456 if (g_supports_64)
457 return g_host_arch_64;
458
459 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000460}
461
462const ConstString &
463Host::GetVendorString()
464{
465 static ConstString g_vendor;
466 if (!g_vendor)
467 {
Greg Clayton950971f2012-05-12 00:01:21 +0000468 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
469 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
470 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000471 }
472 return g_vendor;
473}
474
475const ConstString &
476Host::GetOSString()
477{
478 static ConstString g_os_string;
479 if (!g_os_string)
480 {
Greg Clayton950971f2012-05-12 00:01:21 +0000481 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
482 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
483 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000484 }
485 return g_os_string;
486}
487
488const ConstString &
489Host::GetTargetTriple()
490{
491 static ConstString g_host_triple;
492 if (!(g_host_triple))
493 {
Greg Clayton950971f2012-05-12 00:01:21 +0000494 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
495 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000496 }
497 return g_host_triple;
498}
499
Todd Fialaf3d61de2014-01-17 20:18:59 +0000500// See linux/Host.cpp for Linux-based implementations of this.
501// Add your platform-specific implementation to the appropriate host file.
502#if !defined(__linux__)
503
504const ConstString &
505 Host::GetDistributionId ()
506{
507 static ConstString s_distribution_id;
508 return s_distribution_id;
509}
510
511#endif // #if !defined(__linux__)
512
Greg Clayton2bddd342010-09-07 20:11:56 +0000513lldb::pid_t
514Host::GetCurrentProcessID()
515{
516 return ::getpid();
517}
518
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000519#ifndef _WIN32
520
Greg Clayton2bddd342010-09-07 20:11:56 +0000521lldb::tid_t
522Host::GetCurrentThreadID()
523{
524#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000525 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000526 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
527 // count.
528 thread_port_t thread_self = mach_thread_self();
529 mach_port_deallocate(mach_task_self(), thread_self);
530 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000531#elif defined(__FreeBSD__)
532 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000533#elif defined(__linux__)
534 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000535#else
536 return lldb::tid_t(pthread_self());
537#endif
538}
539
Jim Ingham372787f2012-04-07 00:00:41 +0000540lldb::thread_t
541Host::GetCurrentThread ()
542{
543 return lldb::thread_t(pthread_self());
544}
545
Greg Clayton2bddd342010-09-07 20:11:56 +0000546const char *
547Host::GetSignalAsCString (int signo)
548{
549 switch (signo)
550 {
551 case SIGHUP: return "SIGHUP"; // 1 hangup
552 case SIGINT: return "SIGINT"; // 2 interrupt
553 case SIGQUIT: return "SIGQUIT"; // 3 quit
554 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
555 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
556 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000557#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000558#if !defined(SIGIO) || (SIGPOLL != SIGIO)
559// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
560// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000561 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000562#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000563#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000564#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000565 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000566#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000567 case SIGFPE: return "SIGFPE"; // 8 floating point exception
568 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
569 case SIGBUS: return "SIGBUS"; // 10 bus error
570 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
571 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
572 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
573 case SIGALRM: return "SIGALRM"; // 14 alarm clock
574 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
575 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
576 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
577 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
578 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
579 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
580 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
581 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000582#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000583 case SIGIO: return "SIGIO"; // 23 input/output possible signal
584#endif
585 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
586 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
587 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
588 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000589#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000590 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000591#endif
592#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000593 case SIGINFO: return "SIGINFO"; // 29 information request
594#endif
595 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
596 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
597 default:
598 break;
599 }
600 return NULL;
601}
602
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000603#endif
604
Greg Clayton2bddd342010-09-07 20:11:56 +0000605void
606Host::WillTerminate ()
607{
608}
609
Sylvestre Ledru59405832013-07-01 08:21:36 +0000610#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000611
Greg Clayton2bddd342010-09-07 20:11:56 +0000612void
613Host::ThreadCreated (const char *thread_name)
614{
615}
Greg Claytone5219662010-12-03 06:02:24 +0000616
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000617void
Greg Claytone5219662010-12-03 06:02:24 +0000618Host::Backtrace (Stream &strm, uint32_t max_frames)
619{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000620 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000621}
622
Greg Clayton85851dd2010-12-04 00:10:17 +0000623size_t
624Host::GetEnvironment (StringList &env)
625{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000626 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000627 return 0;
628}
629
Sylvestre Ledru59405832013-07-01 08:21:36 +0000630#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000631
632struct HostThreadCreateInfo
633{
634 std::string thread_name;
635 thread_func_t thread_fptr;
636 thread_arg_t thread_arg;
637
638 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
639 thread_name (name ? name : ""),
640 thread_fptr (fptr),
641 thread_arg (arg)
642 {
643 }
644};
645
646static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000647#ifdef _WIN32
648__stdcall
649#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000650ThreadCreateTrampoline (thread_arg_t arg)
651{
652 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
653 Host::ThreadCreated (info->thread_name.c_str());
654 thread_func_t thread_fptr = info->thread_fptr;
655 thread_arg_t thread_arg = info->thread_arg;
656
Greg Clayton5160ce52013-03-27 23:08:40 +0000657 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000658 if (log)
659 log->Printf("thread created");
660
661 delete info;
662 return thread_fptr (thread_arg);
663}
664
665lldb::thread_t
666Host::ThreadCreate
667(
668 const char *thread_name,
669 thread_func_t thread_fptr,
670 thread_arg_t thread_arg,
671 Error *error
672)
673{
674 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
675
676 // Host::ThreadCreateTrampoline will delete this pointer for us.
677 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
678
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000679#ifdef _WIN32
680 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
681 int err = thread <= 0 ? GetLastError() : 0;
682#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000683 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000684#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000685 if (err == 0)
686 {
687 if (error)
688 error->Clear();
689 return thread;
690 }
691
692 if (error)
693 error->SetError (err, eErrorTypePOSIX);
694
695 return LLDB_INVALID_HOST_THREAD;
696}
697
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000698#ifndef _WIN32
699
Greg Clayton2bddd342010-09-07 20:11:56 +0000700bool
701Host::ThreadCancel (lldb::thread_t thread, Error *error)
702{
703 int err = ::pthread_cancel (thread);
704 if (error)
705 error->SetError(err, eErrorTypePOSIX);
706 return err == 0;
707}
708
709bool
710Host::ThreadDetach (lldb::thread_t thread, Error *error)
711{
712 int err = ::pthread_detach (thread);
713 if (error)
714 error->SetError(err, eErrorTypePOSIX);
715 return err == 0;
716}
717
718bool
719Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
720{
721 int err = ::pthread_join (thread, thread_result_ptr);
722 if (error)
723 error->SetError(err, eErrorTypePOSIX);
724 return err == 0;
725}
726
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000727lldb::thread_key_t
728Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
729{
730 pthread_key_t key;
731 ::pthread_key_create (&key, callback);
732 return key;
733}
734
735void*
736Host::ThreadLocalStorageGet(lldb::thread_key_t key)
737{
738 return ::pthread_getspecific (key);
739}
740
741void
742Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
743{
744 ::pthread_setspecific (key, value);
745}
746
Matt Kopec62502c62013-05-13 19:33:58 +0000747bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000748Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
749{
Greg Clayton85719632013-02-27 22:51:58 +0000750#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000751 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
752 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
753 if (pid == LLDB_INVALID_PROCESS_ID)
754 pid = curr_pid;
755
756 if (tid == LLDB_INVALID_THREAD_ID)
757 tid = curr_tid;
758
Greg Clayton2bddd342010-09-07 20:11:56 +0000759 // Set the pthread name if possible
760 if (pid == curr_pid && tid == curr_tid)
761 {
Matt Kopec62502c62013-05-13 19:33:58 +0000762 if (::pthread_setname_np (name) == 0)
763 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000764 }
Matt Kopec62502c62013-05-13 19:33:58 +0000765 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000766#elif defined (__FreeBSD__)
767 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
768 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
769 if (pid == LLDB_INVALID_PROCESS_ID)
770 pid = curr_pid;
771
772 if (tid == LLDB_INVALID_THREAD_ID)
773 tid = curr_tid;
774
775 // Set the pthread name if possible
776 if (pid == curr_pid && tid == curr_tid)
777 {
Michael Sartainc2052432013-08-01 18:51:08 +0000778 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000779 return true;
780 }
781 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000782#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000783 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
784 if (fn)
785 {
Matt Kopec62502c62013-05-13 19:33:58 +0000786 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
787 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000788 if (pid == LLDB_INVALID_PROCESS_ID)
789 pid = curr_pid;
790
791 if (tid == LLDB_INVALID_THREAD_ID)
792 tid = curr_tid;
793
Michael Sartainc2052432013-08-01 18:51:08 +0000794 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000795 {
Michael Sartainc2052432013-08-01 18:51:08 +0000796 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
797 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
798
799 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000800 return true;
801 }
802 }
803 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000804#else
805 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000806#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000807}
808
Ed Maste02983be2013-07-25 19:10:32 +0000809bool
810Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
811 const char *thread_name, size_t len)
812{
Enrico Granata67530b62014-02-12 03:37:33 +0000813 std::unique_ptr<char[]> namebuf(new char[len+1]);
814
Ed Maste02983be2013-07-25 19:10:32 +0000815 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
816 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
817 // off leads to a lot of similar named threads. Go through the thread name
818 // and search for the last dot and use that.
819 const char *lastdot = ::strrchr (thread_name, '.');
820
821 if (lastdot && lastdot != thread_name)
822 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000823 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000824 namebuf[len] = 0;
825
Enrico Granata67530b62014-02-12 03:37:33 +0000826 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000827 if (namebuflen > 0)
828 {
829 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
830 {
831 // Trim off trailing '(' and '>' characters for a bit more cleanup.
832 namebuflen--;
833 namebuf[namebuflen] = 0;
834 }
Enrico Granata67530b62014-02-12 03:37:33 +0000835 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000836 }
837 return false;
838}
839
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000840#endif
841
Greg Clayton2bddd342010-09-07 20:11:56 +0000842FileSpec
Zachary Turner9e757b72014-07-28 16:45:05 +0000843Host::GetUserProfileFileSpec ()
844{
845 static FileSpec g_profile_filespec;
846 if (!g_profile_filespec)
847 {
848 llvm::SmallString<64> path;
849 llvm::sys::path::home_directory(path);
850 return FileSpec(path.c_str(), false);
851 }
852 return g_profile_filespec;
853}
854
855FileSpec
Greg Clayton2bddd342010-09-07 20:11:56 +0000856Host::GetProgramFileSpec ()
857{
858 static FileSpec g_program_filespec;
859 if (!g_program_filespec)
860 {
861#if defined (__APPLE__)
862 char program_fullpath[PATH_MAX];
863 // If DST is NULL, then return the number of bytes needed.
864 uint32_t len = sizeof(program_fullpath);
865 int err = _NSGetExecutablePath (program_fullpath, &len);
866 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000867 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000868 else if (err == -1)
869 {
870 char *large_program_fullpath = (char *)::malloc (len + 1);
871
872 err = _NSGetExecutablePath (large_program_fullpath, &len);
873 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000874 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000875
876 ::free (large_program_fullpath);
877 }
878#elif defined (__linux__)
879 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000880 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
881 if (len > 0) {
882 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000883 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000884 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000885#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000886 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
887 size_t exe_path_size;
888 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
889 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000890 char *exe_path = new char[exe_path_size];
891 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
892 g_program_filespec.SetFile(exe_path, false);
893 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000894 }
Zachary Turner9e757b72014-07-28 16:45:05 +0000895#elif defined(_WIN32)
896 std::vector<char> buffer(PATH_MAX);
897 ::GetModuleFileName(NULL, &buffer[0], buffer.size());
Zachary Turnerd8a52732014-07-29 05:39:21 +0000898 g_program_filespec.SetFile(&buffer[0], false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000899#endif
900 }
901 return g_program_filespec;
902}
903
Greg Clayton2bddd342010-09-07 20:11:56 +0000904#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000905
906bool
907Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
908{
909 bundle.Clear();
910 return false;
911}
912
Greg Clayton2bddd342010-09-07 20:11:56 +0000913bool
Greg Claytondd36def2010-10-17 22:03:32 +0000914Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000915{
Greg Claytondd36def2010-10-17 22:03:32 +0000916 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000917}
918#endif
919
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000920#ifndef _WIN32
921
Greg Clayton45319462011-02-08 00:35:34 +0000922// Opaque info that tracks a dynamic library that was loaded
923struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000924{
Greg Clayton45319462011-02-08 00:35:34 +0000925 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
926 file_spec (fs),
927 open_options (o),
928 handle (h)
929 {
930 }
931
932 const FileSpec file_spec;
933 uint32_t open_options;
934 void * handle;
935};
936
937void *
938Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
939{
Greg Clayton4272cc72011-02-02 02:24:04 +0000940 char path[PATH_MAX];
941 if (file_spec.GetPath(path, sizeof(path)))
942 {
Greg Clayton45319462011-02-08 00:35:34 +0000943 int mode = 0;
944
945 if (options & eDynamicLibraryOpenOptionLazy)
946 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000947 else
948 mode |= RTLD_NOW;
949
Greg Clayton45319462011-02-08 00:35:34 +0000950
951 if (options & eDynamicLibraryOpenOptionLocal)
952 mode |= RTLD_LOCAL;
953 else
954 mode |= RTLD_GLOBAL;
955
956#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
957 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
958 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000959#endif
Greg Clayton45319462011-02-08 00:35:34 +0000960
961 void * opaque = ::dlopen (path, mode);
962
963 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000964 {
965 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000966 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000967 }
968 else
969 {
970 error.SetErrorString(::dlerror());
971 }
972 }
973 else
974 {
975 error.SetErrorString("failed to extract path");
976 }
Greg Clayton45319462011-02-08 00:35:34 +0000977 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000978}
979
980Error
Greg Clayton45319462011-02-08 00:35:34 +0000981Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000982{
983 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000984 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000985 {
986 error.SetErrorString ("invalid dynamic library handle");
987 }
Greg Clayton45319462011-02-08 00:35:34 +0000988 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000989 {
Greg Clayton45319462011-02-08 00:35:34 +0000990 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
991 if (::dlclose (dylib_info->handle) != 0)
992 {
993 error.SetErrorString(::dlerror());
994 }
995
996 dylib_info->open_options = 0;
997 dylib_info->handle = 0;
998 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000999 }
1000 return error;
1001}
1002
1003void *
Greg Clayton45319462011-02-08 00:35:34 +00001004Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +00001005{
Greg Clayton45319462011-02-08 00:35:34 +00001006 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +00001007 {
1008 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +00001009 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001010 else
Greg Clayton45319462011-02-08 00:35:34 +00001011 {
1012 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1013
1014 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
1015 if (symbol_addr)
1016 {
1017#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
1018 // This host doesn't support limiting searches to this shared library
1019 // so we need to verify that the match came from this shared library
1020 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +00001021 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +00001022 {
1023 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
1024 if (match_dylib_spec != dylib_info->file_spec)
1025 {
1026 char dylib_path[PATH_MAX];
1027 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
1028 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
1029 else
1030 error.SetErrorString ("symbol not found");
1031 return NULL;
1032 }
1033 }
1034#endif
1035 error.Clear();
1036 return symbol_addr;
1037 }
1038 else
1039 {
1040 error.SetErrorString(::dlerror());
1041 }
1042 }
1043 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +00001044}
Greg Claytondd36def2010-10-17 22:03:32 +00001045
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001046FileSpec
1047Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1048{
1049 FileSpec module_filespec;
1050 Dl_info info;
1051 if (::dladdr (host_addr, &info))
1052 {
1053 if (info.dli_fname)
1054 module_filespec.SetFile(info.dli_fname, true);
1055 }
1056 return module_filespec;
1057}
1058
1059#endif
1060
Greg Clayton23f8c952014-03-24 23:10:19 +00001061
1062static void CleanupProcessSpecificLLDBTempDir ()
1063{
1064 // Get the process specific LLDB temporary directory and delete it.
1065 FileSpec tmpdir_file_spec;
1066 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1067 {
1068 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1069 // true to all files that were created for the LLDB process can be cleaned up.
1070 const bool recurse = true;
1071 Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1072 }
1073}
1074
Greg Claytondd36def2010-10-17 22:03:32 +00001075bool
1076Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1077{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001078 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001079 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1080 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001081 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001082 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001083 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001084
1085 switch (path_type)
1086 {
1087 case ePathTypeLLDBShlibDir:
1088 {
1089 static ConstString g_lldb_so_dir;
1090 if (!g_lldb_so_dir)
1091 {
David Majnemer8490da12014-07-22 22:00:42 +00001092 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1093 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +00001094 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001095 if (log)
1096 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001097 }
1098 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001099 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001100 }
1101 break;
1102
1103 case ePathTypeSupportExecutableDir:
1104 {
1105 static ConstString g_lldb_support_exe_dir;
1106 if (!g_lldb_support_exe_dir)
1107 {
1108 FileSpec lldb_file_spec;
1109 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1110 {
1111 char raw_path[PATH_MAX];
1112 char resolved_path[PATH_MAX];
1113 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1114
1115#if defined (__APPLE__)
1116 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1117 if (framework_pos)
1118 {
1119 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +00001120#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001121 // Shallow bundle
1122 *framework_pos = '\0';
1123#else
1124 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001125 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001126#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001127 }
Todd Fiala015d8182014-07-22 23:41:36 +00001128#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1129 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1130 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
1131 // different trees.
1132 if (log)
1133 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1134 char *lib_pos = ::strstr (raw_path, "/lib");
1135 if (lib_pos != nullptr)
1136 {
1137 // First terminate the raw path at the start of lib.
1138 *lib_pos = '\0';
1139
1140 // Now write in bin in place of lib.
1141 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1142
1143 if (log)
1144 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1145 }
1146 else
1147 {
1148 if (log)
1149 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1150 }
Jason Molendaa3329782014-03-29 18:54:20 +00001151#endif // #if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001152 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1153 g_lldb_support_exe_dir.SetCString(resolved_path);
1154 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001155 if (log)
1156 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001157 }
1158 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001159 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001160 }
1161 break;
1162
1163 case ePathTypeHeaderDir:
1164 {
1165 static ConstString g_lldb_headers_dir;
1166 if (!g_lldb_headers_dir)
1167 {
1168#if defined (__APPLE__)
1169 FileSpec lldb_file_spec;
1170 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1171 {
1172 char raw_path[PATH_MAX];
1173 char resolved_path[PATH_MAX];
1174 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1175
1176 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1177 if (framework_pos)
1178 {
1179 framework_pos += strlen("LLDB.framework");
1180 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1181 }
1182 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1183 g_lldb_headers_dir.SetCString(resolved_path);
1184 }
1185#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001186 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001187 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1188#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001189 if (log)
1190 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001191 }
1192 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001193 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001194 }
1195 break;
1196
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001197#ifdef LLDB_DISABLE_PYTHON
1198 case ePathTypePythonDir:
1199 return false;
1200#else
1201 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001202 {
Greg Claytondd36def2010-10-17 22:03:32 +00001203 static ConstString g_lldb_python_dir;
1204 if (!g_lldb_python_dir)
1205 {
1206 FileSpec lldb_file_spec;
1207 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1208 {
1209 char raw_path[PATH_MAX];
1210 char resolved_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001211#if defined(_WIN32)
1212 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1213 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1214#else
Greg Claytondd36def2010-10-17 22:03:32 +00001215 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1216
1217#if defined (__APPLE__)
1218 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1219 if (framework_pos)
1220 {
1221 framework_pos += strlen("LLDB.framework");
1222 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001223 }
1224 else
1225 {
1226#endif
1227 llvm::SmallString<256> python_version_dir;
1228 llvm::raw_svector_ostream os(python_version_dir);
1229 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1230 os.flush();
1231
1232 // We may get our string truncated. Should we protect
1233 // this with an assert?
1234
1235 ::strncat(raw_path, python_version_dir.c_str(),
1236 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001237#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001238#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001239 }
1240#endif
1241 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1242 g_lldb_python_dir.SetCString(resolved_path);
1243 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001244
1245 if (log)
1246 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1247
Greg Claytondd36def2010-10-17 22:03:32 +00001248 }
1249 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001250 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001251 }
1252 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001253#endif
1254
Greg Clayton4272cc72011-02-02 02:24:04 +00001255 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1256 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001257#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001258 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001259 static bool g_lldb_system_plugin_dir_located = false;
1260 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001261 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001262 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001263#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001264 FileSpec lldb_file_spec;
1265 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1266 {
1267 char raw_path[PATH_MAX];
1268 char resolved_path[PATH_MAX];
1269 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1270
1271 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1272 if (framework_pos)
1273 {
1274 framework_pos += strlen("LLDB.framework");
1275 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Greg Clayton1cb64962011-03-24 04:28:38 +00001276 FileSpec::Resolve (raw_path, resolved_path, sizeof(resolved_path));
1277 g_lldb_system_plugin_dir.SetCString(resolved_path);
Greg Clayton4272cc72011-02-02 02:24:04 +00001278 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001279 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001280 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001281#elif defined (__linux__)
1282 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1283 if (lldb_file_spec.Exists())
1284 {
1285 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1286 }
1287#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001288
1289 if (log)
1290 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1291
Greg Clayton4272cc72011-02-02 02:24:04 +00001292 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001293
1294 if (g_lldb_system_plugin_dir)
1295 {
1296 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1297 return true;
1298 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001299#else
1300 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001301 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001302#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001303 }
1304 break;
1305
1306 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1307 {
1308#if defined (__APPLE__)
1309 static ConstString g_lldb_user_plugin_dir;
1310 if (!g_lldb_user_plugin_dir)
1311 {
1312 char user_plugin_path[PATH_MAX];
1313 if (FileSpec::Resolve ("~/Library/Application Support/LLDB/PlugIns",
1314 user_plugin_path,
1315 sizeof(user_plugin_path)))
1316 {
1317 g_lldb_user_plugin_dir.SetCString(user_plugin_path);
1318 }
1319 }
1320 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001321 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001322#elif defined (__linux__)
1323 static ConstString g_lldb_user_plugin_dir;
1324 if (!g_lldb_user_plugin_dir)
1325 {
1326 // XDG Base Directory Specification
1327 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1328 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1329 FileSpec lldb_file_spec;
1330 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1331 if (xdg_data_home && xdg_data_home[0])
1332 {
1333 std::string user_plugin_dir (xdg_data_home);
1334 user_plugin_dir += "/lldb";
1335 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1336 }
1337 else
1338 {
1339 const char *home_dir = getenv("HOME");
1340 if (home_dir && home_dir[0])
1341 {
1342 std::string user_plugin_dir (home_dir);
1343 user_plugin_dir += "/.local/share/lldb";
1344 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1345 }
1346 }
1347
1348 if (lldb_file_spec.Exists())
1349 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001350 if (log)
1351 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001352 }
1353 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001354 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001355#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001356 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001357 return false;
1358 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001359
1360 case ePathTypeLLDBTempSystemDir:
1361 {
1362 static ConstString g_lldb_tmp_dir;
1363 if (!g_lldb_tmp_dir)
1364 {
1365 const char *tmpdir_cstr = getenv("TMPDIR");
1366 if (tmpdir_cstr == NULL)
1367 {
1368 tmpdir_cstr = getenv("TMP");
1369 if (tmpdir_cstr == NULL)
1370 tmpdir_cstr = getenv("TEMP");
1371 }
1372 if (tmpdir_cstr)
1373 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001374 StreamString pid_tmpdir;
1375 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1376 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1377 {
1378 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1379 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1380 {
1381 // Make an atexit handler to clean up the process specify LLDB temp dir
1382 // and all of its contents.
1383 ::atexit (CleanupProcessSpecificLLDBTempDir);
1384 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1385 if (log)
1386 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1387
1388 }
1389 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001390 }
1391 }
1392 file_spec.GetDirectory() = g_lldb_tmp_dir;
1393 return (bool)file_spec.GetDirectory();
1394 }
Greg Claytondd36def2010-10-17 22:03:32 +00001395 }
1396
1397 return false;
1398}
1399
Greg Clayton1cb64962011-03-24 04:28:38 +00001400
1401bool
1402Host::GetHostname (std::string &s)
1403{
1404 char hostname[PATH_MAX];
1405 hostname[sizeof(hostname) - 1] = '\0';
1406 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1407 {
1408 struct hostent* h = ::gethostbyname (hostname);
1409 if (h)
1410 s.assign (h->h_name);
1411 else
1412 s.assign (hostname);
1413 return true;
1414 }
1415 return false;
1416}
1417
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001418#ifndef _WIN32
1419
Greg Clayton32e0a752011-03-30 18:16:51 +00001420const char *
1421Host::GetUserName (uint32_t uid, std::string &user_name)
1422{
1423 struct passwd user_info;
1424 struct passwd *user_info_ptr = &user_info;
1425 char user_buffer[PATH_MAX];
1426 size_t user_buffer_size = sizeof(user_buffer);
1427 if (::getpwuid_r (uid,
1428 &user_info,
1429 user_buffer,
1430 user_buffer_size,
1431 &user_info_ptr) == 0)
1432 {
1433 if (user_info_ptr)
1434 {
1435 user_name.assign (user_info_ptr->pw_name);
1436 return user_name.c_str();
1437 }
1438 }
1439 user_name.clear();
1440 return NULL;
1441}
1442
1443const char *
1444Host::GetGroupName (uint32_t gid, std::string &group_name)
1445{
1446 char group_buffer[PATH_MAX];
1447 size_t group_buffer_size = sizeof(group_buffer);
1448 struct group group_info;
1449 struct group *group_info_ptr = &group_info;
1450 // Try the threadsafe version first
1451 if (::getgrgid_r (gid,
1452 &group_info,
1453 group_buffer,
1454 group_buffer_size,
1455 &group_info_ptr) == 0)
1456 {
1457 if (group_info_ptr)
1458 {
1459 group_name.assign (group_info_ptr->gr_name);
1460 return group_name.c_str();
1461 }
1462 }
1463 else
1464 {
1465 // The threadsafe version isn't currently working
1466 // for me on darwin, but the non-threadsafe version
1467 // is, so I am calling it below.
1468 group_info_ptr = ::getgrgid (gid);
1469 if (group_info_ptr)
1470 {
1471 group_name.assign (group_info_ptr->gr_name);
1472 return group_name.c_str();
1473 }
1474 }
1475 group_name.clear();
1476 return NULL;
1477}
1478
Han Ming Ong84647042012-02-25 01:07:38 +00001479uint32_t
1480Host::GetUserID ()
1481{
1482 return getuid();
1483}
1484
1485uint32_t
1486Host::GetGroupID ()
1487{
1488 return getgid();
1489}
1490
1491uint32_t
1492Host::GetEffectiveUserID ()
1493{
1494 return geteuid();
1495}
1496
1497uint32_t
1498Host::GetEffectiveGroupID ()
1499{
1500 return getegid();
1501}
1502
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001503#endif
1504
1505#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1506bool
1507Host::GetOSBuildString (std::string &s)
1508{
1509 s.clear();
1510 return false;
1511}
1512
1513bool
1514Host::GetOSKernelDescription (std::string &s)
1515{
1516 s.clear();
1517 return false;
1518}
1519#endif
1520
Zachary Turner310035a2014-07-08 04:52:15 +00001521#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1522 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001523uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001524Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001525{
1526 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001527 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001528}
1529
Greg Claytone996fd32011-03-08 22:40:15 +00001530bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001531Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001532{
Greg Claytone996fd32011-03-08 22:40:15 +00001533 process_info.Clear();
1534 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001535}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001536#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001537
Matt Kopec085d6ce2013-05-31 22:00:07 +00001538#if !defined(__linux__)
1539bool
1540Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1541{
1542 return false;
1543}
1544#endif
1545
Sean Callananc0a6e062011-10-27 21:22:25 +00001546lldb::TargetSP
1547Host::GetDummyTarget (lldb_private::Debugger &debugger)
1548{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001549 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001550
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001551 // FIXME: Maybe the dummy target should be per-Debugger
1552 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1553 {
1554 ArchSpec arch(Target::GetDefaultArchitecture());
1555 if (!arch.IsValid())
1556 arch = Host::GetArchitecture ();
1557 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001558 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001559 arch.GetTriple().getTriple().c_str(),
1560 false,
1561 NULL,
1562 g_dummy_target_sp);
1563 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001564
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001565 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001566}
1567
Greg Claytond1cf11a2012-04-14 01:42:46 +00001568struct ShellInfo
1569{
1570 ShellInfo () :
1571 process_reaped (false),
1572 can_delete (false),
1573 pid (LLDB_INVALID_PROCESS_ID),
1574 signo(-1),
1575 status(-1)
1576 {
1577 }
1578
1579 lldb_private::Predicate<bool> process_reaped;
1580 lldb_private::Predicate<bool> can_delete;
1581 lldb::pid_t pid;
1582 int signo;
1583 int status;
1584};
1585
1586static bool
1587MonitorShellCommand (void *callback_baton,
1588 lldb::pid_t pid,
1589 bool exited, // True if the process did exit
1590 int signo, // Zero for no signal
1591 int status) // Exit value of process if signal is zero
1592{
1593 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1594 shell_info->pid = pid;
1595 shell_info->signo = signo;
1596 shell_info->status = status;
1597 // Let the thread running Host::RunShellCommand() know that the process
1598 // exited and that ShellInfo has been filled in by broadcasting to it
1599 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1600 // Now wait for a handshake back from that thread running Host::RunShellCommand
1601 // so we know that we can delete shell_info_ptr
1602 shell_info->can_delete.WaitForValueEqualTo(true);
1603 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1604 usleep(1000);
1605 // Now delete the shell info that was passed into this function
1606 delete shell_info;
1607 return true;
1608}
1609
1610Error
1611Host::RunShellCommand (const char *command,
1612 const char *working_dir,
1613 int *status_ptr,
1614 int *signo_ptr,
1615 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001616 uint32_t timeout_sec,
1617 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001618{
1619 Error error;
1620 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001621 if (shell && shell[0])
1622 {
1623 // Run the command in a shell
1624 launch_info.SetShell(shell);
1625 launch_info.GetArguments().AppendArgument(command);
1626 const bool localhost = true;
1627 const bool will_debug = false;
1628 const bool first_arg_is_full_shell_command = true;
1629 launch_info.ConvertArgumentsForLaunchingInShell (error,
1630 localhost,
1631 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001632 first_arg_is_full_shell_command,
1633 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001634 }
1635 else
1636 {
1637 // No shell, just run it
1638 Args args (command);
1639 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001640 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001641 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001642
1643 if (working_dir)
1644 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001645 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001646 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001647
Greg Claytond1cf11a2012-04-14 01:42:46 +00001648 if (command_output_ptr)
1649 {
1650 // Create a temporary file to get the stdout/stderr and redirect the
1651 // output of the command into this file. We will later read this file
1652 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001653 FileSpec tmpdir_file_spec;
1654 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1655 {
1656 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1657 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1658 }
1659 else
1660 {
1661 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1662 }
1663
1664 output_file_path = ::mktemp(output_file_path_buffer);
1665 }
1666
1667 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1668 if (output_file_path)
1669 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001670 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001671 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001672 }
1673 else
1674 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001675 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1676 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1677 }
1678
1679 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001680 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001681
1682 const bool monitor_signals = false;
1683 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1684
1685 error = LaunchProcess (launch_info);
1686 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001687
1688 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1689 error.SetErrorString("failed to get process ID");
1690
1691 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001692 {
1693 // The process successfully launched, so we can defer ownership of
1694 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001695 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001696 // doesn't need to delete the ShellInfo anymore.
1697 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001698 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001699 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001700 if (timeout_sec > 0) {
1701 timeout_time.OffsetWithSeconds(timeout_sec);
1702 timeout_ptr = &timeout_time;
1703 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001704 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001705 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001706 if (timed_out)
1707 {
1708 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001709
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001710 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001711 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001712 // Wait for the monitor callback to get the message
1713 timeout_time = TimeValue::Now();
1714 timeout_time.OffsetWithSeconds(1);
1715 timed_out = false;
1716 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1717 }
1718 else
1719 {
1720 if (status_ptr)
1721 *status_ptr = shell_info->status;
1722
1723 if (signo_ptr)
1724 *signo_ptr = shell_info->signo;
1725
1726 if (command_output_ptr)
1727 {
1728 command_output_ptr->clear();
1729 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1730 uint64_t file_size = file_spec.GetByteSize();
1731 if (file_size > 0)
1732 {
1733 if (file_size > command_output_ptr->max_size())
1734 {
1735 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1736 }
1737 else
1738 {
1739 command_output_ptr->resize(file_size);
1740 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1741 }
1742 }
1743 }
1744 }
1745 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1746 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001747
1748 if (output_file_path)
1749 ::unlink (output_file_path);
1750 // Handshake with the monitor thread, or just let it know in advance that
1751 // it can delete "shell_info" in case we timed out and were not able to kill
1752 // the process...
1753 return error;
1754}
1755
Daniel Malea4244cbd2013-08-27 20:58:59 +00001756
Todd Fiala76747122014-01-23 00:52:28 +00001757// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1758// systems
1759
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001760#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001761
1762// this method needs to be visible to macosx/Host.cpp and
1763// common/Host.cpp.
1764
1765short
1766Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1767{
1768 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1769
1770#if defined (__APPLE__)
1771 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1772 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1773
1774 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1775 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1776
1777 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1778 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1779
1780 if (launch_info.GetLaunchInSeparateProcessGroup())
1781 flags |= POSIX_SPAWN_SETPGROUP;
1782
1783#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1784#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1785 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1786 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1787 {
1788 g_use_close_on_exec_flag = eLazyBoolNo;
1789
1790 uint32_t major, minor, update;
1791 if (Host::GetOSVersion(major, minor, update))
1792 {
1793 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1794 if (major > 10 || (major == 10 && minor > 7))
1795 {
1796 // Only enable for 10.8 and later OS versions
1797 g_use_close_on_exec_flag = eLazyBoolYes;
1798 }
1799 }
1800 }
1801#else
1802 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1803#endif
1804 // Close all files exception those with file actions if this is supported.
1805 if (g_use_close_on_exec_flag == eLazyBoolYes)
1806 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1807#endif
1808#endif // #if defined (__APPLE__)
1809 return flags;
1810}
1811
1812Error
1813Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001814{
1815 Error error;
1816 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1817
Daniel Malea4244cbd2013-08-27 20:58:59 +00001818 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001819 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001820
1821 if (error.Fail() || log)
1822 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001823 if (error.Fail())
1824 return error;
1825
1826 // Make a quick class that will cleanup the posix spawn attributes in case
1827 // we return in the middle of this function.
1828 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1829
1830 sigset_t no_signals;
1831 sigset_t all_signals;
1832 sigemptyset (&no_signals);
1833 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001834 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001835#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001836 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001837#else
1838 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1839#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001840
Todd Fiala76747122014-01-23 00:52:28 +00001841 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001842
1843 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001844 if (error.Fail() || log)
1845 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001846 if (error.Fail())
1847 return error;
1848
Todd Fiala76747122014-01-23 00:52:28 +00001849 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1850 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1851#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001852
1853 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1854 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1855 // to do that job on OSX.
1856
1857 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001858 {
Jim Ingham90331d52014-02-21 01:25:21 +00001859 // We don't need to do this for ARM, and we really shouldn't now that we
1860 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1861 // to set which CPU subtype to launch...
1862 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1863 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1864 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1865 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001866 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1867 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001868 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1869 {
1870 size_t ocount = 0;
1871 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1872 if (error.Fail() || log)
1873 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 +00001874
Jim Ingham90331d52014-02-21 01:25:21 +00001875 if (error.Fail() || ocount != 1)
1876 return error;
1877 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001878 }
1879
Todd Fiala76747122014-01-23 00:52:28 +00001880#endif
1881
1882 const char *tmp_argv[2];
1883 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1884 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1885 if (argv == NULL)
1886 {
1887 // posix_spawn gets very unhappy if it doesn't have at least the program
1888 // name in argv[0]. One of the side affects I have noticed is the environment
1889 // variables don't make it into the child process if "argv == NULL"!!!
1890 tmp_argv[0] = exe_path;
1891 tmp_argv[1] = NULL;
1892 argv = (char * const*)tmp_argv;
1893 }
1894
1895#if !defined (__APPLE__)
1896 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001897 char current_dir[PATH_MAX];
1898 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001899#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001900
1901 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001902 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001903 {
Todd Fiala76747122014-01-23 00:52:28 +00001904#if defined (__APPLE__)
1905 // Set the working directory on this thread only
1906 if (__pthread_chdir (working_dir) < 0) {
1907 if (errno == ENOENT) {
1908 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1909 } else if (errno == ENOTDIR) {
1910 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1911 } else {
1912 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1913 }
1914 return error;
1915 }
1916#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001917 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1918 {
1919 error.SetError(errno, eErrorTypePOSIX);
1920 error.LogIfError(log, "unable to save the current directory");
1921 return error;
1922 }
1923
1924 if (::chdir(working_dir) == -1)
1925 {
1926 error.SetError(errno, eErrorTypePOSIX);
1927 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1928 return error;
1929 }
Todd Fiala76747122014-01-23 00:52:28 +00001930#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001931 }
1932
Todd Fiala76747122014-01-23 00:52:28 +00001933 const size_t num_file_actions = launch_info.GetNumFileActions ();
1934 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001935 {
Todd Fiala76747122014-01-23 00:52:28 +00001936 posix_spawn_file_actions_t file_actions;
1937 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1938 if (error.Fail() || log)
1939 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1940 if (error.Fail())
1941 return error;
1942
1943 // Make a quick class that will cleanup the posix spawn attributes in case
1944 // we return in the middle of this function.
1945 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1946
1947 for (size_t i=0; i<num_file_actions; ++i)
1948 {
1949 const ProcessLaunchInfo::FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1950 if (launch_file_action)
1951 {
1952 if (!ProcessLaunchInfo::FileAction::AddPosixSpawnFileAction (&file_actions,
1953 launch_file_action,
1954 log,
1955 error))
1956 return error;
1957 }
1958 }
1959
1960 error.SetError (::posix_spawnp (&pid,
1961 exe_path,
1962 &file_actions,
1963 &attr,
1964 argv,
1965 envp),
1966 eErrorTypePOSIX);
1967
1968 if (error.Fail() || log)
1969 {
1970 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 +00001971 pid, exe_path, static_cast<void*>(&file_actions),
1972 static_cast<void*>(&attr),
1973 reinterpret_cast<const void*>(argv),
1974 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001975 if (log)
1976 {
1977 for (int ii=0; argv[ii]; ++ii)
1978 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1979 }
1980 }
1981
1982 }
1983 else
1984 {
1985 error.SetError (::posix_spawnp (&pid,
1986 exe_path,
1987 NULL,
1988 &attr,
1989 argv,
1990 envp),
1991 eErrorTypePOSIX);
1992
1993 if (error.Fail() || log)
1994 {
1995 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 +00001996 pid, exe_path, static_cast<void*>(&attr),
1997 reinterpret_cast<const void*>(argv),
1998 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001999 if (log)
2000 {
2001 for (int ii=0; argv[ii]; ++ii)
2002 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
2003 }
2004 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00002005 }
2006
Todd Fiala76747122014-01-23 00:52:28 +00002007 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002008 {
Todd Fiala76747122014-01-23 00:52:28 +00002009#if defined (__APPLE__)
2010 // No more thread specific current working directory
2011 __pthread_fchdir (-1);
2012#else
2013 if (::chdir(current_dir) == -1 && error.Success())
2014 {
2015 error.SetError(errno, eErrorTypePOSIX);
2016 error.LogIfError(log, "unable to change current directory back to %s",
2017 current_dir);
2018 }
2019#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00002020 }
2021
2022 return error;
2023}
2024
Todd Fiala76747122014-01-23 00:52:28 +00002025#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2026
2027
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002028#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2029// The functions below implement process launching via posix_spawn() for Linux,
2030// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00002031
2032Error
2033Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2034{
2035 Error error;
2036 char exe_path[PATH_MAX];
2037
2038 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2039
2040 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2041
2042 FileSpec exe_spec(launch_info.GetExecutableFile());
2043
2044 FileSpec::FileType file_type = exe_spec.GetFileType();
2045 if (file_type != FileSpec::eFileTypeRegular)
2046 {
2047 lldb::ModuleSP exe_module_sp;
2048 error = host_platform_sp->ResolveExecutable (exe_spec,
2049 arch_spec,
2050 exe_module_sp,
2051 NULL);
2052
2053 if (error.Fail())
2054 return error;
2055
2056 if (exe_module_sp)
2057 exe_spec = exe_module_sp->GetFileSpec();
2058 }
2059
2060 if (exe_spec.Exists())
2061 {
2062 exe_spec.GetPath (exe_path, sizeof(exe_path));
2063 }
2064 else
2065 {
2066 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2067 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2068 return error;
2069 }
2070
2071 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2072
2073 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2074
2075 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2076
2077 if (pid != LLDB_INVALID_PROCESS_ID)
2078 {
2079 // If all went well, then set the process ID into the launch info
2080 launch_info.SetProcessID(pid);
2081
Todd Fiala76747122014-01-23 00:52:28 +00002082 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2083
Daniel Malea4244cbd2013-08-27 20:58:59 +00002084 // Make sure we reap any processes we spawn or we will have zombies.
2085 if (!launch_info.MonitorProcess())
2086 {
2087 const bool monitor_signals = false;
2088 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2089 NULL,
2090 pid,
2091 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002092 if (log)
2093 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2094 }
2095 else
2096 {
2097 if (log)
2098 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002099 }
2100 }
2101 else
2102 {
2103 // Invalid process ID, something didn't go well
2104 if (error.Success())
2105 error.SetErrorString ("process launch failed for unknown reasons");
2106 }
2107 return error;
2108}
2109
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002110#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002111
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002112#ifndef _WIN32
2113
2114size_t
2115Host::GetPageSize()
2116{
2117 return ::getpagesize();
2118}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002119
Greg Claytone3e3fee2013-02-17 20:46:30 +00002120uint32_t
2121Host::GetNumberCPUS ()
2122{
2123 static uint32_t g_num_cores = UINT32_MAX;
2124 if (g_num_cores == UINT32_MAX)
2125 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002126#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002127
2128 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002129
Greg Claytone3e3fee2013-02-17 20:46:30 +00002130#else
2131
2132 // Assume POSIX support if a host specific case has not been supplied above
2133 g_num_cores = 0;
2134 int num_cores = 0;
2135 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002136#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002137 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002138#else
2139 int mib[] = { CTL_HW, HW_NCPU };
2140#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002141
2142 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002143 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 +00002144 {
2145 g_num_cores = num_cores;
2146 }
2147 else
2148 {
2149 mib[1] = HW_NCPU;
2150 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002151 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 +00002152 {
2153 if (num_cores > 0)
2154 g_num_cores = num_cores;
2155 }
2156 }
2157#endif
2158 }
2159 return g_num_cores;
2160}
2161
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002162void
2163Host::Kill(lldb::pid_t pid, int signo)
2164{
2165 ::kill(pid, signo);
2166}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002167
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002168#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002169
Johnny Chen8f3d8382011-08-02 20:52:42 +00002170#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002171bool
Greg Clayton3b147632010-12-18 01:54:34 +00002172Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002173{
2174 return false;
2175}
Greg Claytondd36def2010-10-17 22:03:32 +00002176
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002177void
2178Host::SetCrashDescriptionWithFormat (const char *format, ...)
2179{
2180}
2181
2182void
2183Host::SetCrashDescription (const char *description)
2184{
2185}
Greg Claytondd36def2010-10-17 22:03:32 +00002186
2187lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002188Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002189{
2190 return LLDB_INVALID_PROCESS_ID;
2191}
2192
Greg Claytonfbb76342013-11-20 21:07:01 +00002193#endif
2194
2195
2196#ifdef LLDB_DISABLE_POSIX
2197
2198Error
2199Host::MakeDirectory (const char* path, uint32_t mode)
Daniel Maleae0f8f572013-08-26 23:57:52 +00002200{
Greg Claytonfbb76342013-11-20 21:07:01 +00002201 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002202 error.SetErrorStringWithFormat("%s in not implemented on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002203 return error;
Daniel Maleae0f8f572013-08-26 23:57:52 +00002204}
Greg Claytonfbb76342013-11-20 21:07:01 +00002205
2206Error
2207Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2208{
2209 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002210 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002211 return error;
2212}
2213
2214Error
2215Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2216{
2217 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002218 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002219 return error;
2220}
2221
2222Error
2223Host::Symlink (const char *src, const char *dst)
2224{
2225 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002226 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002227 return error;
2228}
2229
2230Error
2231Host::Readlink (const char *path, char *buf, size_t buf_len)
2232{
2233 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002234 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002235 return error;
2236}
2237
2238Error
2239Host::Unlink (const char *path)
2240{
2241 Error error;
Colin Riley909bb7a2013-11-26 15:10:46 +00002242 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
Greg Claytonfbb76342013-11-20 21:07:01 +00002243 return error;
2244}
2245
Greg Clayton23f8c952014-03-24 23:10:19 +00002246Error
2247Host::RemoveDirectory (const char* path, bool recurse)
2248{
2249 Error error;
2250 error.SetErrorStringWithFormat("%s is not supported on this host", __PRETTY_FUNCTION__);
2251 return error;
2252}
2253
Greg Claytonfbb76342013-11-20 21:07:01 +00002254#else
2255
2256Error
2257Host::MakeDirectory (const char* path, uint32_t file_permissions)
2258{
2259 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002260 if (path && path[0])
2261 {
Greg Claytonfb909312013-11-23 01:58:15 +00002262 if (::mkdir(path, file_permissions) != 0)
2263 {
2264 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002265 switch (error.GetError())
2266 {
2267 case ENOENT:
2268 {
2269 // Parent directory doesn't exist, so lets make it if we can
2270 FileSpec spec(path, false);
2271 if (spec.GetDirectory() && spec.GetFilename())
2272 {
2273 // Make the parent directory and try again
2274 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2275 if (error2.Success())
2276 {
2277 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002278 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002279 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002280 else
Greg Claytonfb909312013-11-23 01:58:15 +00002281 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002282 }
2283 }
2284 }
2285 break;
2286 case EEXIST:
2287 {
2288 FileSpec path_spec(path, false);
2289 if (path_spec.IsDirectory())
2290 error.Clear(); // It is a directory and it already exists
2291 }
2292 break;
2293 }
2294 }
Greg Claytonfb909312013-11-23 01:58:15 +00002295 }
2296 else
2297 {
2298 error.SetErrorString("empty path");
2299 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002300 return error;
2301}
Greg Clayton23f8c952014-03-24 23:10:19 +00002302
2303Error
2304Host::RemoveDirectory (const char* path, bool recurse)
2305{
2306 Error error;
2307 if (path && path[0])
2308 {
2309 if (recurse)
2310 {
2311 StreamString command;
2312 command.Printf("rm -rf \"%s\"", path);
2313 int status = ::system(command.GetString().c_str());
2314 if (status != 0)
2315 error.SetError(status, eErrorTypeGeneric);
2316 }
2317 else
2318 {
2319 if (::rmdir(path) != 0)
2320 error.SetErrorToErrno();
2321 }
2322 }
2323 else
2324 {
2325 error.SetErrorString("empty path");
2326 }
2327 return error;
2328}
Greg Claytonfbb76342013-11-20 21:07:01 +00002329
2330Error
2331Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2332{
2333 Error error;
2334 struct stat file_stats;
2335 if (::stat (path, &file_stats) == 0)
2336 {
2337 // The bits in "st_mode" currently match the definitions
2338 // for the file mode bits in unix.
2339 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2340 }
2341 else
2342 {
2343 error.SetErrorToErrno();
2344 }
2345 return error;
2346}
2347
2348Error
2349Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2350{
2351 Error error;
2352 if (::chmod(path, file_permissions) != 0)
2353 error.SetErrorToErrno();
2354 return error;
2355}
2356
2357Error
2358Host::Symlink (const char *src, const char *dst)
2359{
2360 Error error;
2361 if (::symlink(dst, src) == -1)
2362 error.SetErrorToErrno();
2363 return error;
2364}
2365
2366Error
2367Host::Unlink (const char *path)
2368{
2369 Error error;
2370 if (::unlink(path) == -1)
2371 error.SetErrorToErrno();
2372 return error;
2373}
2374
2375Error
2376Host::Readlink (const char *path, char *buf, size_t buf_len)
2377{
2378 Error error;
2379 ssize_t count = ::readlink(path, buf, buf_len);
2380 if (count < 0)
2381 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002382 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002383 buf[count] = '\0'; // Success
2384 else
2385 error.SetErrorString("'buf' buffer is too small to contain link contents");
2386 return error;
2387}
2388
2389
Greg Clayton2bddd342010-09-07 20:11:56 +00002390#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002391
2392typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2393FDToFileMap& GetFDToFileMap()
2394{
2395 static FDToFileMap g_fd2filemap;
2396 return g_fd2filemap;
2397}
2398
2399lldb::user_id_t
2400Host::OpenFile (const FileSpec& file_spec,
2401 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002402 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002403 Error &error)
2404{
2405 std::string path (file_spec.GetPath());
2406 if (path.empty())
2407 {
2408 error.SetErrorString("empty path");
2409 return UINT64_MAX;
2410 }
2411 FileSP file_sp(new File());
2412 error = file_sp->Open(path.c_str(),flags,mode);
2413 if (file_sp->IsValid() == false)
2414 return UINT64_MAX;
2415 lldb::user_id_t fd = file_sp->GetDescriptor();
2416 GetFDToFileMap()[fd] = file_sp;
2417 return fd;
2418}
2419
2420bool
2421Host::CloseFile (lldb::user_id_t fd, Error &error)
2422{
2423 if (fd == UINT64_MAX)
2424 {
2425 error.SetErrorString ("invalid file descriptor");
2426 return false;
2427 }
2428 FDToFileMap& file_map = GetFDToFileMap();
2429 FDToFileMap::iterator pos = file_map.find(fd);
2430 if (pos == file_map.end())
2431 {
2432 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2433 return false;
2434 }
2435 FileSP file_sp = pos->second;
2436 if (!file_sp)
2437 {
2438 error.SetErrorString ("invalid host backing file");
2439 return false;
2440 }
2441 error = file_sp->Close();
2442 file_map.erase(pos);
2443 return error.Success();
2444}
2445
2446uint64_t
2447Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2448{
2449 if (fd == UINT64_MAX)
2450 {
2451 error.SetErrorString ("invalid file descriptor");
2452 return UINT64_MAX;
2453 }
2454 FDToFileMap& file_map = GetFDToFileMap();
2455 FDToFileMap::iterator pos = file_map.find(fd);
2456 if (pos == file_map.end())
2457 {
2458 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2459 return false;
2460 }
2461 FileSP file_sp = pos->second;
2462 if (!file_sp)
2463 {
2464 error.SetErrorString ("invalid host backing file");
2465 return UINT64_MAX;
2466 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002467 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2468 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002469 return UINT64_MAX;
2470 size_t bytes_written = src_len;
2471 error = file_sp->Write(src, bytes_written);
2472 if (error.Fail())
2473 return UINT64_MAX;
2474 return bytes_written;
2475}
2476
2477uint64_t
2478Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2479{
2480 if (fd == UINT64_MAX)
2481 {
2482 error.SetErrorString ("invalid file descriptor");
2483 return UINT64_MAX;
2484 }
2485 FDToFileMap& file_map = GetFDToFileMap();
2486 FDToFileMap::iterator pos = file_map.find(fd);
2487 if (pos == file_map.end())
2488 {
2489 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2490 return false;
2491 }
2492 FileSP file_sp = pos->second;
2493 if (!file_sp)
2494 {
2495 error.SetErrorString ("invalid host backing file");
2496 return UINT64_MAX;
2497 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002498 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2499 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002500 return UINT64_MAX;
2501 size_t bytes_read = dst_len;
2502 error = file_sp->Read(dst ,bytes_read);
2503 if (error.Fail())
2504 return UINT64_MAX;
2505 return bytes_read;
2506}
2507
2508lldb::user_id_t
2509Host::GetFileSize (const FileSpec& file_spec)
2510{
2511 return file_spec.GetByteSize();
2512}
2513
2514bool
2515Host::GetFileExists (const FileSpec& file_spec)
2516{
2517 return file_spec.Exists();
2518}
2519
2520bool
2521Host::CalculateMD5 (const FileSpec& file_spec,
2522 uint64_t &low,
2523 uint64_t &high)
2524{
2525#if defined (__APPLE__)
2526 StreamString md5_cmd_line;
2527 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2528 std::string hash_string;
2529 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2530 if (err.Fail())
2531 return false;
2532 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2533 // if the output is any other length it is probably wrong
2534 if (hash_string.size() != 32)
2535 return false;
2536 std::string part1(hash_string,0,16);
2537 std::string part2(hash_string,16);
2538 const char* part1_cstr = part1.c_str();
2539 const char* part2_cstr = part2.c_str();
2540 high = ::strtoull(part1_cstr, NULL, 16);
2541 low = ::strtoull(part2_cstr, NULL, 16);
2542 return true;
2543#else
2544 // your own MD5 implementation here
2545 return false;
2546#endif
2547}