blob: 33df16f665bb15a48670739a905ddf306cb88238 [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"
Zachary Turner696b5282014-08-14 16:01:25 +000071#include "lldb/Target/FileAction.h"
Greg Claytone996fd32011-03-08 22:40:15 +000072#include "lldb/Target/Process.h"
Zachary Turner696b5282014-08-14 16:01:25 +000073#include "lldb/Target/ProcessLaunchInfo.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000074#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000075#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000076
Saleem Abdulrasool28606952014-06-27 05:17:41 +000077#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000078#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000079#include "llvm/Support/Host.h"
Zachary Turner9e757b72014-07-28 16:45:05 +000080#include "llvm/Support/Path.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000081#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000082
Todd Fiala76747122014-01-23 00:52:28 +000083#if defined (__APPLE__)
84#ifndef _POSIX_SPAWN_DISABLE_ASLR
85#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
86#endif
87
88extern "C"
89{
90 int __pthread_chdir(const char *path);
91 int __pthread_fchdir (int fildes);
92}
93
94#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000095
Greg Clayton2bddd342010-09-07 20:11:56 +000096using namespace lldb;
97using namespace lldb_private;
98
Todd Fiala17096d72014-07-16 19:03:16 +000099// Define maximum thread name length
100#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
101uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
102#else
103uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
104#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000105
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000106#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000107struct MonitorInfo
108{
109 lldb::pid_t pid; // The process ID to monitor
110 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
111 void *callback_baton; // The callback baton for the callback function
112 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
113};
114
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000115static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000116MonitorChildProcessThreadFunction (void *arg);
117
118lldb::thread_t
119Host::StartMonitoringChildProcess
120(
121 Host::MonitorChildProcessCallback callback,
122 void *callback_baton,
123 lldb::pid_t pid,
124 bool monitor_signals
125)
126{
127 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000128 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000129
Greg Claytone4e45922011-11-16 05:37:56 +0000130 info_ptr->pid = pid;
131 info_ptr->callback = callback;
132 info_ptr->callback_baton = callback_baton;
133 info_ptr->monitor_signals = monitor_signals;
134
135 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000136 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000137 thread = ThreadCreate (thread_name,
138 MonitorChildProcessThreadFunction,
139 info_ptr,
140 NULL);
141
Greg Clayton2bddd342010-09-07 20:11:56 +0000142 return thread;
143}
144
145//------------------------------------------------------------------
146// Scoped class that will disable thread canceling when it is
147// constructed, and exception safely restore the previous value it
148// when it goes out of scope.
149//------------------------------------------------------------------
150class ScopedPThreadCancelDisabler
151{
152public:
153 ScopedPThreadCancelDisabler()
154 {
155 // Disable the ability for this thread to be cancelled
156 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
157 if (err != 0)
158 m_old_state = -1;
159
160 }
161
162 ~ScopedPThreadCancelDisabler()
163 {
164 // Restore the ability for this thread to be cancelled to what it
165 // previously was.
166 if (m_old_state != -1)
167 ::pthread_setcancelstate (m_old_state, 0);
168 }
169private:
170 int m_old_state; // Save the old cancelability state.
171};
172
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000173static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000174MonitorChildProcessThreadFunction (void *arg)
175{
Greg Clayton5160ce52013-03-27 23:08:40 +0000176 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000177 const char *function = __FUNCTION__;
178 if (log)
179 log->Printf ("%s (arg = %p) thread starting...", function, arg);
180
181 MonitorInfo *info = (MonitorInfo *)arg;
182
183 const Host::MonitorChildProcessCallback callback = info->callback;
184 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000185 const bool monitor_signals = info->monitor_signals;
186
Daniel Malea4244cbd2013-08-27 20:58:59 +0000187 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000188 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000189
Greg Clayton2bddd342010-09-07 20:11:56 +0000190 delete info;
191
192 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000193#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000194 #define __WALL 0
195#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000196 const int options = __WALL;
197
Greg Clayton2bddd342010-09-07 20:11:56 +0000198 while (1)
199 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000200 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000201 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000202 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000203
204 // Wait for all child processes
205 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000206 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000207 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000208 ::pthread_testcancel ();
209
210 if (wait_pid == -1)
211 {
212 if (errno == EINTR)
213 continue;
214 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000215 {
216 if (log)
217 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000218 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000219 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000220 }
Matt Kopec650648f2013-01-08 16:30:18 +0000221 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000222 {
223 bool exited = false;
224 int signal = 0;
225 int exit_status = 0;
226 const char *status_cstr = NULL;
227 if (WIFSTOPPED(status))
228 {
229 signal = WSTOPSIG(status);
230 status_cstr = "STOPPED";
231 }
232 else if (WIFEXITED(status))
233 {
234 exit_status = WEXITSTATUS(status);
235 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000236 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000237 }
238 else if (WIFSIGNALED(status))
239 {
240 signal = WTERMSIG(status);
241 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000242 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000243 exited = true;
244 exit_status = -1;
245 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000246 }
247 else
248 {
Johnny Chen44805302011-07-19 19:48:13 +0000249 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000250 }
251
252 // Scope for pthread_cancel_disabler
253 {
254 ScopedPThreadCancelDisabler pthread_cancel_disabler;
255
Caroline Tice20ad3c42010-10-29 21:48:37 +0000256 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000257 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000258 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 +0000259 function,
260 wait_pid,
261 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000262 pid,
263 status,
264 status_cstr,
265 signal,
266 exit_status);
267
268 if (exited || (signal != 0 && monitor_signals))
269 {
Greg Claytone4e45922011-11-16 05:37:56 +0000270 bool callback_return = false;
271 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000272 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000273
274 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000275 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000276 {
277 if (log)
278 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000279 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000280 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000281 // If the callback returns true, it means this process should
282 // exit
283 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000284 {
285 if (log)
286 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000287 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000288 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000289 }
290 }
291 }
292 }
293
Caroline Tice20ad3c42010-10-29 21:48:37 +0000294 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000295 if (log)
296 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
297
298 return NULL;
299}
300
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000301#endif // #if !defined (__APPLE__) && !defined (_WIN32)
302
303#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000304
305void
306Host::SystemLog (SystemLogType type, const char *format, va_list args)
307{
308 vfprintf (stderr, format, args);
309}
310
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000311#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000312
Greg Claytone38a5ed2012-01-05 03:57:59 +0000313void
314Host::SystemLog (SystemLogType type, const char *format, ...)
315{
316 va_list args;
317 va_start (args, format);
318 SystemLog (type, format, args);
319 va_end (args);
320}
321
Greg Clayton2bddd342010-09-07 20:11:56 +0000322const ArchSpec &
Greg Clayton514487e2011-02-15 21:59:32 +0000323Host::GetArchitecture (SystemDefaultArchitecture arch_kind)
Greg Clayton2bddd342010-09-07 20:11:56 +0000324{
Greg Clayton514487e2011-02-15 21:59:32 +0000325 static bool g_supports_32 = false;
326 static bool g_supports_64 = false;
327 static ArchSpec g_host_arch_32;
328 static ArchSpec g_host_arch_64;
329
Greg Clayton2bddd342010-09-07 20:11:56 +0000330#if defined (__APPLE__)
Greg Clayton514487e2011-02-15 21:59:32 +0000331
332 // Apple is different in that it can support both 32 and 64 bit executables
333 // in the same operating system running concurrently. Here we detect the
334 // correct host architectures for both 32 and 64 bit including if 64 bit
335 // executables are supported on the system.
336
337 if (g_supports_32 == false && g_supports_64 == false)
338 {
339 // All apple systems support 32 bit execution.
340 g_supports_32 = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000341 uint32_t cputype, cpusubtype;
Greg Clayton514487e2011-02-15 21:59:32 +0000342 uint32_t is_64_bit_capable = false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000343 size_t len = sizeof(cputype);
Greg Clayton514487e2011-02-15 21:59:32 +0000344 ArchSpec host_arch;
345 // These will tell us about the kernel architecture, which even on a 64
346 // bit machine can be 32 bit...
Greg Clayton2bddd342010-09-07 20:11:56 +0000347 if (::sysctlbyname("hw.cputype", &cputype, &len, NULL, 0) == 0)
348 {
Greg Clayton514487e2011-02-15 21:59:32 +0000349 len = sizeof (cpusubtype);
350 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) != 0)
351 cpusubtype = CPU_TYPE_ANY;
352
Greg Clayton2bddd342010-09-07 20:11:56 +0000353 len = sizeof (is_64_bit_capable);
354 if (::sysctlbyname("hw.cpu64bit_capable", &is_64_bit_capable, &len, NULL, 0) == 0)
355 {
356 if (is_64_bit_capable)
Greg Clayton514487e2011-02-15 21:59:32 +0000357 g_supports_64 = true;
358 }
359
360 if (is_64_bit_capable)
361 {
362 if (cputype & CPU_ARCH_ABI64)
Greg Clayton2bddd342010-09-07 20:11:56 +0000363 {
Greg Clayton514487e2011-02-15 21:59:32 +0000364 // We have a 64 bit kernel on a 64 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000365 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000366 }
367 else
368 {
Greg Clayton52edb362014-07-14 22:53:02 +0000369 // We have a 64 bit kernel that is returning a 32 bit cputype, the
370 // cpusubtype will be correct as if it were for a 64 bit architecture
371 g_host_arch_64.SetArchitecture (eArchTypeMachO, cputype | CPU_ARCH_ABI64, cpusubtype);
Greg Clayton2bddd342010-09-07 20:11:56 +0000372 }
Greg Clayton52edb362014-07-14 22:53:02 +0000373
374 // Now we need modify the cpusubtype for the 32 bit slices.
375 uint32_t cpusubtype32 = cpusubtype;
376#if defined (__i386__) || defined (__x86_64__)
377 if (cpusubtype == CPU_SUBTYPE_486 || cpusubtype == CPU_SUBTYPE_X86_64_H)
378 cpusubtype32 = CPU_SUBTYPE_I386_ALL;
379#elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
380 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
381 cpusubtype32 = CPU_SUBTYPE_ARM_V7S;
382#endif
383 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype & ~(CPU_ARCH_MASK), cpusubtype32);
Greg Claytonc76fa8a2014-07-29 21:27:21 +0000384
385 if (cputype == CPU_TYPE_ARM || cputype == CPU_TYPE_ARM64)
386 {
387 g_host_arch_32.GetTriple().setOS(llvm::Triple::IOS);
388 g_host_arch_64.GetTriple().setOS(llvm::Triple::IOS);
389 }
390 else
391 {
392 g_host_arch_32.GetTriple().setOS(llvm::Triple::MacOSX);
393 g_host_arch_64.GetTriple().setOS(llvm::Triple::MacOSX);
394 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000395 }
Greg Clayton514487e2011-02-15 21:59:32 +0000396 else
397 {
Greg Clayton52edb362014-07-14 22:53:02 +0000398 // We have a 32 bit kernel on a 32 bit system
Greg Claytone0d378b2011-03-24 21:19:54 +0000399 g_host_arch_32.SetArchitecture (eArchTypeMachO, cputype, cpusubtype);
Greg Clayton514487e2011-02-15 21:59:32 +0000400 g_host_arch_64.Clear();
401 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000402 }
Greg Clayton514487e2011-02-15 21:59:32 +0000403 }
404
405#else // #if defined (__APPLE__)
Stephen Wilsonbd588712011-02-24 19:15:09 +0000406
Greg Clayton514487e2011-02-15 21:59:32 +0000407 if (g_supports_32 == false && g_supports_64 == false)
408 {
Peter Collingbourne1f6198d2011-11-05 01:35:31 +0000409 llvm::Triple triple(llvm::sys::getDefaultTargetTriple());
Greg Clayton514487e2011-02-15 21:59:32 +0000410
Stephen Wilsonbd588712011-02-24 19:15:09 +0000411 g_host_arch_32.Clear();
412 g_host_arch_64.Clear();
Greg Clayton514487e2011-02-15 21:59:32 +0000413
Greg Claytonb29e6c62012-10-11 17:38:58 +0000414 // If the OS is Linux, "unknown" in the vendor slot isn't what we want
415 // for the default triple. It's probably an artifact of config.guess.
416 if (triple.getOS() == llvm::Triple::Linux && triple.getVendor() == llvm::Triple::UnknownVendor)
Todd Fialae28f1d72014-01-17 22:21:22 +0000417 triple.setVendorName ("");
Greg Claytonb29e6c62012-10-11 17:38:58 +0000418
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000419 const char* distribution_id = GetDistributionId ().AsCString();
420
Stephen Wilsonbd588712011-02-24 19:15:09 +0000421 switch (triple.getArch())
422 {
423 default:
424 g_host_arch_32.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000425 g_host_arch_32.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000426 g_supports_32 = true;
427 break;
Greg Clayton514487e2011-02-15 21:59:32 +0000428
Stephen Wilsonbd588712011-02-24 19:15:09 +0000429 case llvm::Triple::x86_64:
Greg Clayton542e4072012-09-07 17:49:29 +0000430 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000431 g_host_arch_64.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000432 g_supports_64 = true;
433 g_host_arch_32.SetTriple(triple.get32BitArchVariant());
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000434 g_host_arch_32.SetDistributionId (distribution_id);
Greg Clayton542e4072012-09-07 17:49:29 +0000435 g_supports_32 = true;
436 break;
437
Ed Mastea8375762014-04-01 18:06:45 +0000438 case llvm::Triple::mips64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000439 case llvm::Triple::sparcv9:
440 case llvm::Triple::ppc64:
Stephen Wilsonbd588712011-02-24 19:15:09 +0000441 g_host_arch_64.SetTriple(triple);
Todd Fialaa9ddb0e2014-01-18 03:02:39 +0000442 g_host_arch_64.SetDistributionId (distribution_id);
Stephen Wilsonbd588712011-02-24 19:15:09 +0000443 g_supports_64 = true;
444 break;
445 }
Greg Clayton4796c4f2011-02-17 02:05:38 +0000446
447 g_supports_32 = g_host_arch_32.IsValid();
448 g_supports_64 = g_host_arch_64.IsValid();
Greg Clayton2bddd342010-09-07 20:11:56 +0000449 }
Greg Clayton514487e2011-02-15 21:59:32 +0000450
451#endif // #else for #if defined (__APPLE__)
452
453 if (arch_kind == eSystemDefaultArchitecture32)
454 return g_host_arch_32;
455 else if (arch_kind == eSystemDefaultArchitecture64)
456 return g_host_arch_64;
457
458 if (g_supports_64)
459 return g_host_arch_64;
460
461 return g_host_arch_32;
Greg Clayton2bddd342010-09-07 20:11:56 +0000462}
463
464const ConstString &
465Host::GetVendorString()
466{
467 static ConstString g_vendor;
468 if (!g_vendor)
469 {
Greg Clayton950971f2012-05-12 00:01:21 +0000470 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
471 const llvm::StringRef &str_ref = host_arch.GetTriple().getVendorName();
472 g_vendor.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000473 }
474 return g_vendor;
475}
476
477const ConstString &
478Host::GetOSString()
479{
480 static ConstString g_os_string;
481 if (!g_os_string)
482 {
Greg Clayton950971f2012-05-12 00:01:21 +0000483 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
484 const llvm::StringRef &str_ref = host_arch.GetTriple().getOSName();
485 g_os_string.SetCStringWithLength(str_ref.data(), str_ref.size());
Greg Clayton2bddd342010-09-07 20:11:56 +0000486 }
487 return g_os_string;
488}
489
490const ConstString &
491Host::GetTargetTriple()
492{
493 static ConstString g_host_triple;
494 if (!(g_host_triple))
495 {
Greg Clayton950971f2012-05-12 00:01:21 +0000496 const ArchSpec &host_arch = GetArchitecture (eSystemDefaultArchitecture);
497 g_host_triple.SetCString(host_arch.GetTriple().getTriple().c_str());
Greg Clayton2bddd342010-09-07 20:11:56 +0000498 }
499 return g_host_triple;
500}
501
Todd Fialaf3d61de2014-01-17 20:18:59 +0000502// See linux/Host.cpp for Linux-based implementations of this.
503// Add your platform-specific implementation to the appropriate host file.
504#if !defined(__linux__)
505
506const ConstString &
507 Host::GetDistributionId ()
508{
509 static ConstString s_distribution_id;
510 return s_distribution_id;
511}
512
513#endif // #if !defined(__linux__)
514
Greg Clayton2bddd342010-09-07 20:11:56 +0000515lldb::pid_t
516Host::GetCurrentProcessID()
517{
518 return ::getpid();
519}
520
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000521#ifndef _WIN32
522
Greg Clayton2bddd342010-09-07 20:11:56 +0000523lldb::tid_t
524Host::GetCurrentThreadID()
525{
526#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000527 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000528 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
529 // count.
530 thread_port_t thread_self = mach_thread_self();
531 mach_port_deallocate(mach_task_self(), thread_self);
532 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000533#elif defined(__FreeBSD__)
534 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000535#elif defined(__linux__)
536 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000537#else
538 return lldb::tid_t(pthread_self());
539#endif
540}
541
Jim Ingham372787f2012-04-07 00:00:41 +0000542lldb::thread_t
543Host::GetCurrentThread ()
544{
545 return lldb::thread_t(pthread_self());
546}
547
Greg Clayton2bddd342010-09-07 20:11:56 +0000548const char *
549Host::GetSignalAsCString (int signo)
550{
551 switch (signo)
552 {
553 case SIGHUP: return "SIGHUP"; // 1 hangup
554 case SIGINT: return "SIGINT"; // 2 interrupt
555 case SIGQUIT: return "SIGQUIT"; // 3 quit
556 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
557 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
558 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000559#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000560#if !defined(SIGIO) || (SIGPOLL != SIGIO)
561// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
562// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000563 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000564#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000565#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000566#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000567 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000568#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000569 case SIGFPE: return "SIGFPE"; // 8 floating point exception
570 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
571 case SIGBUS: return "SIGBUS"; // 10 bus error
572 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
573 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
574 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
575 case SIGALRM: return "SIGALRM"; // 14 alarm clock
576 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
577 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
578 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
579 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
580 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
581 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
582 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
583 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000584#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000585 case SIGIO: return "SIGIO"; // 23 input/output possible signal
586#endif
587 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
588 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
589 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
590 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000591#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000592 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000593#endif
594#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000595 case SIGINFO: return "SIGINFO"; // 29 information request
596#endif
597 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
598 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
599 default:
600 break;
601 }
602 return NULL;
603}
604
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000605#endif
606
Greg Clayton2bddd342010-09-07 20:11:56 +0000607void
608Host::WillTerminate ()
609{
610}
611
Sylvestre Ledru59405832013-07-01 08:21:36 +0000612#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000613
Greg Clayton2bddd342010-09-07 20:11:56 +0000614void
615Host::ThreadCreated (const char *thread_name)
616{
617}
Greg Claytone5219662010-12-03 06:02:24 +0000618
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000619void
Greg Claytone5219662010-12-03 06:02:24 +0000620Host::Backtrace (Stream &strm, uint32_t max_frames)
621{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000622 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000623}
624
Greg Clayton85851dd2010-12-04 00:10:17 +0000625size_t
626Host::GetEnvironment (StringList &env)
627{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000628 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000629 return 0;
630}
631
Sylvestre Ledru59405832013-07-01 08:21:36 +0000632#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000633
634struct HostThreadCreateInfo
635{
636 std::string thread_name;
637 thread_func_t thread_fptr;
638 thread_arg_t thread_arg;
639
640 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
641 thread_name (name ? name : ""),
642 thread_fptr (fptr),
643 thread_arg (arg)
644 {
645 }
646};
647
648static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000649#ifdef _WIN32
650__stdcall
651#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000652ThreadCreateTrampoline (thread_arg_t arg)
653{
654 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
655 Host::ThreadCreated (info->thread_name.c_str());
656 thread_func_t thread_fptr = info->thread_fptr;
657 thread_arg_t thread_arg = info->thread_arg;
658
Greg Clayton5160ce52013-03-27 23:08:40 +0000659 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000660 if (log)
661 log->Printf("thread created");
662
663 delete info;
664 return thread_fptr (thread_arg);
665}
666
667lldb::thread_t
668Host::ThreadCreate
669(
670 const char *thread_name,
671 thread_func_t thread_fptr,
672 thread_arg_t thread_arg,
673 Error *error
674)
675{
676 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
677
678 // Host::ThreadCreateTrampoline will delete this pointer for us.
679 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
680
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000681#ifdef _WIN32
682 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
683 int err = thread <= 0 ? GetLastError() : 0;
684#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000685 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000686#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000687 if (err == 0)
688 {
689 if (error)
690 error->Clear();
691 return thread;
692 }
693
694 if (error)
695 error->SetError (err, eErrorTypePOSIX);
696
697 return LLDB_INVALID_HOST_THREAD;
698}
699
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000700#ifndef _WIN32
701
Greg Clayton2bddd342010-09-07 20:11:56 +0000702bool
703Host::ThreadCancel (lldb::thread_t thread, Error *error)
704{
705 int err = ::pthread_cancel (thread);
706 if (error)
707 error->SetError(err, eErrorTypePOSIX);
708 return err == 0;
709}
710
711bool
712Host::ThreadDetach (lldb::thread_t thread, Error *error)
713{
714 int err = ::pthread_detach (thread);
715 if (error)
716 error->SetError(err, eErrorTypePOSIX);
717 return err == 0;
718}
719
720bool
721Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
722{
723 int err = ::pthread_join (thread, thread_result_ptr);
724 if (error)
725 error->SetError(err, eErrorTypePOSIX);
726 return err == 0;
727}
728
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000729lldb::thread_key_t
730Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
731{
732 pthread_key_t key;
733 ::pthread_key_create (&key, callback);
734 return key;
735}
736
737void*
738Host::ThreadLocalStorageGet(lldb::thread_key_t key)
739{
740 return ::pthread_getspecific (key);
741}
742
743void
744Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
745{
746 ::pthread_setspecific (key, value);
747}
748
Matt Kopec62502c62013-05-13 19:33:58 +0000749bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000750Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
751{
Greg Clayton85719632013-02-27 22:51:58 +0000752#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000753 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
754 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
755 if (pid == LLDB_INVALID_PROCESS_ID)
756 pid = curr_pid;
757
758 if (tid == LLDB_INVALID_THREAD_ID)
759 tid = curr_tid;
760
Greg Clayton2bddd342010-09-07 20:11:56 +0000761 // Set the pthread name if possible
762 if (pid == curr_pid && tid == curr_tid)
763 {
Matt Kopec62502c62013-05-13 19:33:58 +0000764 if (::pthread_setname_np (name) == 0)
765 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000766 }
Matt Kopec62502c62013-05-13 19:33:58 +0000767 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000768#elif defined (__FreeBSD__)
769 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
770 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
771 if (pid == LLDB_INVALID_PROCESS_ID)
772 pid = curr_pid;
773
774 if (tid == LLDB_INVALID_THREAD_ID)
775 tid = curr_tid;
776
777 // Set the pthread name if possible
778 if (pid == curr_pid && tid == curr_tid)
779 {
Michael Sartainc2052432013-08-01 18:51:08 +0000780 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000781 return true;
782 }
783 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000784#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000785 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
786 if (fn)
787 {
Matt Kopec62502c62013-05-13 19:33:58 +0000788 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
789 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000790 if (pid == LLDB_INVALID_PROCESS_ID)
791 pid = curr_pid;
792
793 if (tid == LLDB_INVALID_THREAD_ID)
794 tid = curr_tid;
795
Michael Sartainc2052432013-08-01 18:51:08 +0000796 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000797 {
Michael Sartainc2052432013-08-01 18:51:08 +0000798 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
799 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
800
801 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000802 return true;
803 }
804 }
805 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000806#else
807 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000808#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000809}
810
Ed Maste02983be2013-07-25 19:10:32 +0000811bool
812Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
813 const char *thread_name, size_t len)
814{
Enrico Granata67530b62014-02-12 03:37:33 +0000815 std::unique_ptr<char[]> namebuf(new char[len+1]);
816
Ed Maste02983be2013-07-25 19:10:32 +0000817 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
818 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
819 // off leads to a lot of similar named threads. Go through the thread name
820 // and search for the last dot and use that.
821 const char *lastdot = ::strrchr (thread_name, '.');
822
823 if (lastdot && lastdot != thread_name)
824 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000825 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000826 namebuf[len] = 0;
827
Enrico Granata67530b62014-02-12 03:37:33 +0000828 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000829 if (namebuflen > 0)
830 {
831 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
832 {
833 // Trim off trailing '(' and '>' characters for a bit more cleanup.
834 namebuflen--;
835 namebuf[namebuflen] = 0;
836 }
Enrico Granata67530b62014-02-12 03:37:33 +0000837 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000838 }
839 return false;
840}
841
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000842#endif
843
Zachary Turnerdf62f202014-08-07 17:33:07 +0000844FileSpec::PathSyntax
845Host::GetHostPathSyntax()
846{
847#if defined(_WIN32)
848 return FileSpec::ePathSyntaxWindows;
849#else
850 return FileSpec::ePathSyntaxPosix;
851#endif
852}
853
Greg Clayton2bddd342010-09-07 20:11:56 +0000854FileSpec
Zachary Turner9e757b72014-07-28 16:45:05 +0000855Host::GetUserProfileFileSpec ()
856{
857 static FileSpec g_profile_filespec;
858 if (!g_profile_filespec)
859 {
860 llvm::SmallString<64> path;
861 llvm::sys::path::home_directory(path);
862 return FileSpec(path.c_str(), false);
863 }
864 return g_profile_filespec;
865}
866
867FileSpec
Greg Clayton2bddd342010-09-07 20:11:56 +0000868Host::GetProgramFileSpec ()
869{
870 static FileSpec g_program_filespec;
871 if (!g_program_filespec)
872 {
873#if defined (__APPLE__)
874 char program_fullpath[PATH_MAX];
875 // If DST is NULL, then return the number of bytes needed.
876 uint32_t len = sizeof(program_fullpath);
877 int err = _NSGetExecutablePath (program_fullpath, &len);
878 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000879 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000880 else if (err == -1)
881 {
882 char *large_program_fullpath = (char *)::malloc (len + 1);
883
884 err = _NSGetExecutablePath (large_program_fullpath, &len);
885 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000886 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000887
888 ::free (large_program_fullpath);
889 }
890#elif defined (__linux__)
891 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000892 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
893 if (len > 0) {
894 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000895 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000896 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000897#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000898 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
899 size_t exe_path_size;
900 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
901 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000902 char *exe_path = new char[exe_path_size];
903 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
904 g_program_filespec.SetFile(exe_path, false);
905 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000906 }
Zachary Turner9e757b72014-07-28 16:45:05 +0000907#elif defined(_WIN32)
908 std::vector<char> buffer(PATH_MAX);
909 ::GetModuleFileName(NULL, &buffer[0], buffer.size());
Zachary Turnerd8a52732014-07-29 05:39:21 +0000910 g_program_filespec.SetFile(&buffer[0], false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000911#endif
912 }
913 return g_program_filespec;
914}
915
Greg Clayton2bddd342010-09-07 20:11:56 +0000916#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000917
918bool
919Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
920{
921 bundle.Clear();
922 return false;
923}
924
Greg Clayton2bddd342010-09-07 20:11:56 +0000925bool
Greg Claytondd36def2010-10-17 22:03:32 +0000926Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000927{
Greg Claytondd36def2010-10-17 22:03:32 +0000928 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000929}
930#endif
931
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000932#ifndef _WIN32
933
Greg Clayton45319462011-02-08 00:35:34 +0000934// Opaque info that tracks a dynamic library that was loaded
935struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000936{
Greg Clayton45319462011-02-08 00:35:34 +0000937 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
938 file_spec (fs),
939 open_options (o),
940 handle (h)
941 {
942 }
943
944 const FileSpec file_spec;
945 uint32_t open_options;
946 void * handle;
947};
948
949void *
950Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
951{
Greg Clayton4272cc72011-02-02 02:24:04 +0000952 char path[PATH_MAX];
953 if (file_spec.GetPath(path, sizeof(path)))
954 {
Greg Clayton45319462011-02-08 00:35:34 +0000955 int mode = 0;
956
957 if (options & eDynamicLibraryOpenOptionLazy)
958 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000959 else
960 mode |= RTLD_NOW;
961
Greg Clayton45319462011-02-08 00:35:34 +0000962
963 if (options & eDynamicLibraryOpenOptionLocal)
964 mode |= RTLD_LOCAL;
965 else
966 mode |= RTLD_GLOBAL;
967
968#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
969 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
970 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000971#endif
Greg Clayton45319462011-02-08 00:35:34 +0000972
973 void * opaque = ::dlopen (path, mode);
974
975 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000976 {
977 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000978 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000979 }
980 else
981 {
982 error.SetErrorString(::dlerror());
983 }
984 }
985 else
986 {
987 error.SetErrorString("failed to extract path");
988 }
Greg Clayton45319462011-02-08 00:35:34 +0000989 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000990}
991
992Error
Greg Clayton45319462011-02-08 00:35:34 +0000993Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000994{
995 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000996 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000997 {
998 error.SetErrorString ("invalid dynamic library handle");
999 }
Greg Clayton45319462011-02-08 00:35:34 +00001000 else
Greg Clayton4272cc72011-02-02 02:24:04 +00001001 {
Greg Clayton45319462011-02-08 00:35:34 +00001002 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1003 if (::dlclose (dylib_info->handle) != 0)
1004 {
1005 error.SetErrorString(::dlerror());
1006 }
1007
1008 dylib_info->open_options = 0;
1009 dylib_info->handle = 0;
1010 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +00001011 }
1012 return error;
1013}
1014
1015void *
Greg Clayton45319462011-02-08 00:35:34 +00001016Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +00001017{
Greg Clayton45319462011-02-08 00:35:34 +00001018 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +00001019 {
1020 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +00001021 }
Greg Clayton4272cc72011-02-02 02:24:04 +00001022 else
Greg Clayton45319462011-02-08 00:35:34 +00001023 {
1024 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
1025
1026 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
1027 if (symbol_addr)
1028 {
1029#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
1030 // This host doesn't support limiting searches to this shared library
1031 // so we need to verify that the match came from this shared library
1032 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +00001033 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +00001034 {
1035 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
1036 if (match_dylib_spec != dylib_info->file_spec)
1037 {
1038 char dylib_path[PATH_MAX];
1039 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
1040 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
1041 else
1042 error.SetErrorString ("symbol not found");
1043 return NULL;
1044 }
1045 }
1046#endif
1047 error.Clear();
1048 return symbol_addr;
1049 }
1050 else
1051 {
1052 error.SetErrorString(::dlerror());
1053 }
1054 }
1055 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +00001056}
Greg Claytondd36def2010-10-17 22:03:32 +00001057
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001058FileSpec
1059Host::GetModuleFileSpecForHostAddress (const void *host_addr)
1060{
1061 FileSpec module_filespec;
1062 Dl_info info;
1063 if (::dladdr (host_addr, &info))
1064 {
1065 if (info.dli_fname)
1066 module_filespec.SetFile(info.dli_fname, true);
1067 }
1068 return module_filespec;
1069}
1070
1071#endif
1072
Greg Clayton23f8c952014-03-24 23:10:19 +00001073
1074static void CleanupProcessSpecificLLDBTempDir ()
1075{
1076 // Get the process specific LLDB temporary directory and delete it.
1077 FileSpec tmpdir_file_spec;
1078 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1079 {
1080 // Remove the LLDB temporary directory if we have one. Set "recurse" to
1081 // true to all files that were created for the LLDB process can be cleaned up.
1082 const bool recurse = true;
1083 Host::RemoveDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
1084 }
1085}
1086
Greg Claytondd36def2010-10-17 22:03:32 +00001087bool
1088Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
1089{
Greg Clayton710dd5a2011-01-08 20:28:42 +00001090 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +00001091 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
1092 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +00001093 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +00001094 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001095 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +00001096
1097 switch (path_type)
1098 {
1099 case ePathTypeLLDBShlibDir:
1100 {
1101 static ConstString g_lldb_so_dir;
1102 if (!g_lldb_so_dir)
1103 {
David Majnemer8490da12014-07-22 22:00:42 +00001104 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
1105 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +00001106 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001107 if (log)
1108 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001109 }
1110 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001111 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001112 }
1113 break;
1114
1115 case ePathTypeSupportExecutableDir:
1116 {
1117 static ConstString g_lldb_support_exe_dir;
1118 if (!g_lldb_support_exe_dir)
1119 {
1120 FileSpec lldb_file_spec;
1121 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1122 {
1123 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001124 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1125
1126#if defined (__APPLE__)
1127 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1128 if (framework_pos)
1129 {
1130 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +00001131#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001132 // Shallow bundle
1133 *framework_pos = '\0';
1134#else
1135 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +00001136 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +00001137#endif
Greg Claytondd36def2010-10-17 22:03:32 +00001138 }
Todd Fiala015d8182014-07-22 23:41:36 +00001139#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
1140 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
1141 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
1142 // different trees.
1143 if (log)
1144 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
1145 char *lib_pos = ::strstr (raw_path, "/lib");
1146 if (lib_pos != nullptr)
1147 {
1148 // First terminate the raw path at the start of lib.
1149 *lib_pos = '\0';
1150
1151 // Now write in bin in place of lib.
1152 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
1153
1154 if (log)
1155 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
1156 }
1157 else
1158 {
1159 if (log)
1160 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
1161 }
Jason Molendaa3329782014-03-29 18:54:20 +00001162#endif // #if defined (__APPLE__)
Zachary Turner3f559742014-08-07 17:33:36 +00001163 llvm::SmallString<64> resolved_path(raw_path);
1164 FileSpec::Resolve (resolved_path);
1165 g_lldb_support_exe_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001166 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001167 if (log)
1168 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001169 }
1170 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001171 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001172 }
1173 break;
1174
1175 case ePathTypeHeaderDir:
1176 {
1177 static ConstString g_lldb_headers_dir;
1178 if (!g_lldb_headers_dir)
1179 {
1180#if defined (__APPLE__)
1181 FileSpec lldb_file_spec;
1182 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1183 {
1184 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +00001185 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1186
1187 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1188 if (framework_pos)
1189 {
1190 framework_pos += strlen("LLDB.framework");
1191 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
1192 }
Jim Inghame1d263e2014-08-07 22:37:43 +00001193 llvm::SmallString<64> resolved_path(raw_path);
1194 FileSpec::Resolve (resolved_path);
1195 g_lldb_headers_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001196 }
1197#else
Greg Clayton4272cc72011-02-02 02:24:04 +00001198 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +00001199 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
1200#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001201 if (log)
1202 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +00001203 }
1204 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001205 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001206 }
1207 break;
1208
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001209#ifdef LLDB_DISABLE_PYTHON
1210 case ePathTypePythonDir:
1211 return false;
1212#else
1213 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001214 {
Greg Claytondd36def2010-10-17 22:03:32 +00001215 static ConstString g_lldb_python_dir;
1216 if (!g_lldb_python_dir)
1217 {
1218 FileSpec lldb_file_spec;
1219 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1220 {
1221 char raw_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001222#if defined(_WIN32)
1223 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1224 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1225#else
Greg Claytondd36def2010-10-17 22:03:32 +00001226 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1227
1228#if defined (__APPLE__)
1229 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1230 if (framework_pos)
1231 {
1232 framework_pos += strlen("LLDB.framework");
1233 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001234 }
1235 else
1236 {
1237#endif
1238 llvm::SmallString<256> python_version_dir;
1239 llvm::raw_svector_ostream os(python_version_dir);
1240 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1241 os.flush();
1242
1243 // We may get our string truncated. Should we protect
1244 // this with an assert?
1245
1246 ::strncat(raw_path, python_version_dir.c_str(),
1247 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001248#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001249#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001250 }
1251#endif
Zachary Turner3f559742014-08-07 17:33:36 +00001252 llvm::SmallString<64> resolved_path(raw_path);
1253 FileSpec::Resolve (resolved_path);
1254 g_lldb_python_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001255 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001256
1257 if (log)
1258 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1259
Greg Claytondd36def2010-10-17 22:03:32 +00001260 }
1261 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001262 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001263 }
1264 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001265#endif
1266
Greg Clayton4272cc72011-02-02 02:24:04 +00001267 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1268 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001269#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001270 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001271 static bool g_lldb_system_plugin_dir_located = false;
1272 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001273 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001274 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001275#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001276 FileSpec lldb_file_spec;
1277 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1278 {
1279 char raw_path[PATH_MAX];
Greg Clayton4272cc72011-02-02 02:24:04 +00001280 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1281
1282 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1283 if (framework_pos)
1284 {
1285 framework_pos += strlen("LLDB.framework");
1286 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Jim Inghame1d263e2014-08-07 22:37:43 +00001287 llvm::SmallString<64> resolved_path(raw_path);
1288 FileSpec::Resolve (resolved_path);
1289 g_lldb_system_plugin_dir.SetCString(resolved_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001290 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001291 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001292 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001293#elif defined (__linux__)
1294 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1295 if (lldb_file_spec.Exists())
1296 {
1297 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1298 }
1299#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001300
1301 if (log)
1302 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1303
Greg Clayton4272cc72011-02-02 02:24:04 +00001304 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001305
1306 if (g_lldb_system_plugin_dir)
1307 {
1308 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1309 return true;
1310 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001311#else
1312 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001313 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001314#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001315 }
1316 break;
1317
1318 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1319 {
1320#if defined (__APPLE__)
1321 static ConstString g_lldb_user_plugin_dir;
1322 if (!g_lldb_user_plugin_dir)
1323 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001324 llvm::SmallString<64> user_plugin_path("~/Library/Application Support/LLDB/PlugIns");
1325 FileSpec::Resolve (user_plugin_path);
1326 if (user_plugin_path.size())
Greg Clayton4272cc72011-02-02 02:24:04 +00001327 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001328 g_lldb_user_plugin_dir.SetCString(user_plugin_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001329 }
1330 }
1331 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001332 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001333#elif defined (__linux__)
1334 static ConstString g_lldb_user_plugin_dir;
1335 if (!g_lldb_user_plugin_dir)
1336 {
1337 // XDG Base Directory Specification
1338 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1339 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1340 FileSpec lldb_file_spec;
1341 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1342 if (xdg_data_home && xdg_data_home[0])
1343 {
1344 std::string user_plugin_dir (xdg_data_home);
1345 user_plugin_dir += "/lldb";
1346 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1347 }
1348 else
1349 {
1350 const char *home_dir = getenv("HOME");
1351 if (home_dir && home_dir[0])
1352 {
1353 std::string user_plugin_dir (home_dir);
1354 user_plugin_dir += "/.local/share/lldb";
1355 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1356 }
1357 }
1358
1359 if (lldb_file_spec.Exists())
1360 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001361 if (log)
1362 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001363 }
1364 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001365 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001366#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001367 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001368 return false;
1369 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001370
1371 case ePathTypeLLDBTempSystemDir:
1372 {
1373 static ConstString g_lldb_tmp_dir;
1374 if (!g_lldb_tmp_dir)
1375 {
1376 const char *tmpdir_cstr = getenv("TMPDIR");
1377 if (tmpdir_cstr == NULL)
1378 {
1379 tmpdir_cstr = getenv("TMP");
1380 if (tmpdir_cstr == NULL)
1381 tmpdir_cstr = getenv("TEMP");
1382 }
1383 if (tmpdir_cstr)
1384 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001385 StreamString pid_tmpdir;
1386 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
1387 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1388 {
1389 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
1390 if (Host::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault).Success())
1391 {
1392 // Make an atexit handler to clean up the process specify LLDB temp dir
1393 // and all of its contents.
1394 ::atexit (CleanupProcessSpecificLLDBTempDir);
1395 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1396 if (log)
1397 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1398
1399 }
1400 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001401 }
1402 }
1403 file_spec.GetDirectory() = g_lldb_tmp_dir;
1404 return (bool)file_spec.GetDirectory();
1405 }
Greg Claytondd36def2010-10-17 22:03:32 +00001406 }
1407
1408 return false;
1409}
1410
Greg Clayton1cb64962011-03-24 04:28:38 +00001411
1412bool
1413Host::GetHostname (std::string &s)
1414{
1415 char hostname[PATH_MAX];
1416 hostname[sizeof(hostname) - 1] = '\0';
1417 if (::gethostname (hostname, sizeof(hostname) - 1) == 0)
1418 {
1419 struct hostent* h = ::gethostbyname (hostname);
1420 if (h)
1421 s.assign (h->h_name);
1422 else
1423 s.assign (hostname);
1424 return true;
1425 }
1426 return false;
1427}
1428
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001429#ifndef _WIN32
1430
Greg Clayton32e0a752011-03-30 18:16:51 +00001431const char *
1432Host::GetUserName (uint32_t uid, std::string &user_name)
1433{
1434 struct passwd user_info;
1435 struct passwd *user_info_ptr = &user_info;
1436 char user_buffer[PATH_MAX];
1437 size_t user_buffer_size = sizeof(user_buffer);
1438 if (::getpwuid_r (uid,
1439 &user_info,
1440 user_buffer,
1441 user_buffer_size,
1442 &user_info_ptr) == 0)
1443 {
1444 if (user_info_ptr)
1445 {
1446 user_name.assign (user_info_ptr->pw_name);
1447 return user_name.c_str();
1448 }
1449 }
1450 user_name.clear();
1451 return NULL;
1452}
1453
1454const char *
1455Host::GetGroupName (uint32_t gid, std::string &group_name)
1456{
1457 char group_buffer[PATH_MAX];
1458 size_t group_buffer_size = sizeof(group_buffer);
1459 struct group group_info;
1460 struct group *group_info_ptr = &group_info;
1461 // Try the threadsafe version first
1462 if (::getgrgid_r (gid,
1463 &group_info,
1464 group_buffer,
1465 group_buffer_size,
1466 &group_info_ptr) == 0)
1467 {
1468 if (group_info_ptr)
1469 {
1470 group_name.assign (group_info_ptr->gr_name);
1471 return group_name.c_str();
1472 }
1473 }
1474 else
1475 {
1476 // The threadsafe version isn't currently working
1477 // for me on darwin, but the non-threadsafe version
1478 // is, so I am calling it below.
1479 group_info_ptr = ::getgrgid (gid);
1480 if (group_info_ptr)
1481 {
1482 group_name.assign (group_info_ptr->gr_name);
1483 return group_name.c_str();
1484 }
1485 }
1486 group_name.clear();
1487 return NULL;
1488}
1489
Han Ming Ong84647042012-02-25 01:07:38 +00001490uint32_t
1491Host::GetUserID ()
1492{
1493 return getuid();
1494}
1495
1496uint32_t
1497Host::GetGroupID ()
1498{
1499 return getgid();
1500}
1501
1502uint32_t
1503Host::GetEffectiveUserID ()
1504{
1505 return geteuid();
1506}
1507
1508uint32_t
1509Host::GetEffectiveGroupID ()
1510{
1511 return getegid();
1512}
1513
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001514#endif
1515
1516#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) // see macosx/Host.mm
1517bool
1518Host::GetOSBuildString (std::string &s)
1519{
1520 s.clear();
1521 return false;
1522}
1523
1524bool
1525Host::GetOSKernelDescription (std::string &s)
1526{
1527 s.clear();
1528 return false;
1529}
1530#endif
1531
Zachary Turner310035a2014-07-08 04:52:15 +00001532#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1533 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001534uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001535Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001536{
1537 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001538 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001539}
1540
Greg Claytone996fd32011-03-08 22:40:15 +00001541bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001542Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001543{
Greg Claytone996fd32011-03-08 22:40:15 +00001544 process_info.Clear();
1545 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001546}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001547#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001548
Matt Kopec085d6ce2013-05-31 22:00:07 +00001549#if !defined(__linux__)
1550bool
1551Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1552{
1553 return false;
1554}
1555#endif
1556
Sean Callananc0a6e062011-10-27 21:22:25 +00001557lldb::TargetSP
1558Host::GetDummyTarget (lldb_private::Debugger &debugger)
1559{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001560 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001561
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001562 // FIXME: Maybe the dummy target should be per-Debugger
1563 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1564 {
1565 ArchSpec arch(Target::GetDefaultArchitecture());
1566 if (!arch.IsValid())
1567 arch = Host::GetArchitecture ();
1568 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001569 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001570 arch.GetTriple().getTriple().c_str(),
1571 false,
1572 NULL,
1573 g_dummy_target_sp);
1574 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001575
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001576 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001577}
1578
Greg Claytond1cf11a2012-04-14 01:42:46 +00001579struct ShellInfo
1580{
1581 ShellInfo () :
1582 process_reaped (false),
1583 can_delete (false),
1584 pid (LLDB_INVALID_PROCESS_ID),
1585 signo(-1),
1586 status(-1)
1587 {
1588 }
1589
1590 lldb_private::Predicate<bool> process_reaped;
1591 lldb_private::Predicate<bool> can_delete;
1592 lldb::pid_t pid;
1593 int signo;
1594 int status;
1595};
1596
1597static bool
1598MonitorShellCommand (void *callback_baton,
1599 lldb::pid_t pid,
1600 bool exited, // True if the process did exit
1601 int signo, // Zero for no signal
1602 int status) // Exit value of process if signal is zero
1603{
1604 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1605 shell_info->pid = pid;
1606 shell_info->signo = signo;
1607 shell_info->status = status;
1608 // Let the thread running Host::RunShellCommand() know that the process
1609 // exited and that ShellInfo has been filled in by broadcasting to it
1610 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1611 // Now wait for a handshake back from that thread running Host::RunShellCommand
1612 // so we know that we can delete shell_info_ptr
1613 shell_info->can_delete.WaitForValueEqualTo(true);
1614 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1615 usleep(1000);
1616 // Now delete the shell info that was passed into this function
1617 delete shell_info;
1618 return true;
1619}
1620
1621Error
1622Host::RunShellCommand (const char *command,
1623 const char *working_dir,
1624 int *status_ptr,
1625 int *signo_ptr,
1626 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001627 uint32_t timeout_sec,
1628 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001629{
1630 Error error;
1631 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001632 if (shell && shell[0])
1633 {
1634 // Run the command in a shell
1635 launch_info.SetShell(shell);
1636 launch_info.GetArguments().AppendArgument(command);
1637 const bool localhost = true;
1638 const bool will_debug = false;
1639 const bool first_arg_is_full_shell_command = true;
1640 launch_info.ConvertArgumentsForLaunchingInShell (error,
1641 localhost,
1642 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001643 first_arg_is_full_shell_command,
1644 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001645 }
1646 else
1647 {
1648 // No shell, just run it
1649 Args args (command);
1650 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001651 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001652 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001653
1654 if (working_dir)
1655 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001656 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001657 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001658
Greg Claytond1cf11a2012-04-14 01:42:46 +00001659 if (command_output_ptr)
1660 {
1661 // Create a temporary file to get the stdout/stderr and redirect the
1662 // output of the command into this file. We will later read this file
1663 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001664 FileSpec tmpdir_file_spec;
1665 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1666 {
1667 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1668 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1669 }
1670 else
1671 {
1672 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1673 }
1674
1675 output_file_path = ::mktemp(output_file_path_buffer);
1676 }
1677
1678 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1679 if (output_file_path)
1680 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001681 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001682 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001683 }
1684 else
1685 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001686 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1687 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1688 }
1689
1690 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001691 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001692
1693 const bool monitor_signals = false;
1694 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1695
1696 error = LaunchProcess (launch_info);
1697 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001698
1699 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1700 error.SetErrorString("failed to get process ID");
1701
1702 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001703 {
1704 // The process successfully launched, so we can defer ownership of
1705 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001706 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001707 // doesn't need to delete the ShellInfo anymore.
1708 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001709 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001710 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001711 if (timeout_sec > 0) {
1712 timeout_time.OffsetWithSeconds(timeout_sec);
1713 timeout_ptr = &timeout_time;
1714 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001715 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001716 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001717 if (timed_out)
1718 {
1719 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001720
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001721 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001722 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001723 // Wait for the monitor callback to get the message
1724 timeout_time = TimeValue::Now();
1725 timeout_time.OffsetWithSeconds(1);
1726 timed_out = false;
1727 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1728 }
1729 else
1730 {
1731 if (status_ptr)
1732 *status_ptr = shell_info->status;
1733
1734 if (signo_ptr)
1735 *signo_ptr = shell_info->signo;
1736
1737 if (command_output_ptr)
1738 {
1739 command_output_ptr->clear();
1740 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1741 uint64_t file_size = file_spec.GetByteSize();
1742 if (file_size > 0)
1743 {
1744 if (file_size > command_output_ptr->max_size())
1745 {
1746 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1747 }
1748 else
1749 {
1750 command_output_ptr->resize(file_size);
1751 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1752 }
1753 }
1754 }
1755 }
1756 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1757 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001758
1759 if (output_file_path)
1760 ::unlink (output_file_path);
1761 // Handshake with the monitor thread, or just let it know in advance that
1762 // it can delete "shell_info" in case we timed out and were not able to kill
1763 // the process...
1764 return error;
1765}
1766
Daniel Malea4244cbd2013-08-27 20:58:59 +00001767
Todd Fiala76747122014-01-23 00:52:28 +00001768// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1769// systems
1770
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001771#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001772
1773// this method needs to be visible to macosx/Host.cpp and
1774// common/Host.cpp.
1775
1776short
1777Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1778{
1779 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1780
1781#if defined (__APPLE__)
1782 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1783 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1784
1785 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1786 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1787
1788 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1789 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1790
1791 if (launch_info.GetLaunchInSeparateProcessGroup())
1792 flags |= POSIX_SPAWN_SETPGROUP;
1793
1794#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1795#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1796 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1797 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1798 {
1799 g_use_close_on_exec_flag = eLazyBoolNo;
1800
1801 uint32_t major, minor, update;
1802 if (Host::GetOSVersion(major, minor, update))
1803 {
1804 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1805 if (major > 10 || (major == 10 && minor > 7))
1806 {
1807 // Only enable for 10.8 and later OS versions
1808 g_use_close_on_exec_flag = eLazyBoolYes;
1809 }
1810 }
1811 }
1812#else
1813 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1814#endif
1815 // Close all files exception those with file actions if this is supported.
1816 if (g_use_close_on_exec_flag == eLazyBoolYes)
1817 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1818#endif
1819#endif // #if defined (__APPLE__)
1820 return flags;
1821}
1822
1823Error
1824Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001825{
1826 Error error;
1827 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1828
Daniel Malea4244cbd2013-08-27 20:58:59 +00001829 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001830 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001831
1832 if (error.Fail() || log)
1833 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001834 if (error.Fail())
1835 return error;
1836
1837 // Make a quick class that will cleanup the posix spawn attributes in case
1838 // we return in the middle of this function.
1839 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1840
1841 sigset_t no_signals;
1842 sigset_t all_signals;
1843 sigemptyset (&no_signals);
1844 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001845 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001846#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001847 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001848#else
1849 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1850#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001851
Todd Fiala76747122014-01-23 00:52:28 +00001852 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001853
1854 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001855 if (error.Fail() || log)
1856 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001857 if (error.Fail())
1858 return error;
1859
Todd Fiala76747122014-01-23 00:52:28 +00001860 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1861 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1862#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001863
1864 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1865 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1866 // to do that job on OSX.
1867
1868 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001869 {
Jim Ingham90331d52014-02-21 01:25:21 +00001870 // We don't need to do this for ARM, and we really shouldn't now that we
1871 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1872 // to set which CPU subtype to launch...
1873 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1874 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1875 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1876 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001877 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1878 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001879 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1880 {
1881 size_t ocount = 0;
1882 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1883 if (error.Fail() || log)
1884 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 +00001885
Jim Ingham90331d52014-02-21 01:25:21 +00001886 if (error.Fail() || ocount != 1)
1887 return error;
1888 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001889 }
1890
Todd Fiala76747122014-01-23 00:52:28 +00001891#endif
1892
1893 const char *tmp_argv[2];
1894 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1895 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1896 if (argv == NULL)
1897 {
1898 // posix_spawn gets very unhappy if it doesn't have at least the program
1899 // name in argv[0]. One of the side affects I have noticed is the environment
1900 // variables don't make it into the child process if "argv == NULL"!!!
1901 tmp_argv[0] = exe_path;
1902 tmp_argv[1] = NULL;
1903 argv = (char * const*)tmp_argv;
1904 }
1905
1906#if !defined (__APPLE__)
1907 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001908 char current_dir[PATH_MAX];
1909 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001910#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001911
1912 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001913 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001914 {
Todd Fiala76747122014-01-23 00:52:28 +00001915#if defined (__APPLE__)
1916 // Set the working directory on this thread only
1917 if (__pthread_chdir (working_dir) < 0) {
1918 if (errno == ENOENT) {
1919 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1920 } else if (errno == ENOTDIR) {
1921 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1922 } else {
1923 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1924 }
1925 return error;
1926 }
1927#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001928 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1929 {
1930 error.SetError(errno, eErrorTypePOSIX);
1931 error.LogIfError(log, "unable to save the current directory");
1932 return error;
1933 }
1934
1935 if (::chdir(working_dir) == -1)
1936 {
1937 error.SetError(errno, eErrorTypePOSIX);
1938 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1939 return error;
1940 }
Todd Fiala76747122014-01-23 00:52:28 +00001941#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001942 }
1943
Todd Fiala76747122014-01-23 00:52:28 +00001944 const size_t num_file_actions = launch_info.GetNumFileActions ();
1945 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001946 {
Todd Fiala76747122014-01-23 00:52:28 +00001947 posix_spawn_file_actions_t file_actions;
1948 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1949 if (error.Fail() || log)
1950 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1951 if (error.Fail())
1952 return error;
1953
1954 // Make a quick class that will cleanup the posix spawn attributes in case
1955 // we return in the middle of this function.
1956 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1957
1958 for (size_t i=0; i<num_file_actions; ++i)
1959 {
Zachary Turner696b5282014-08-14 16:01:25 +00001960 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +00001961 if (launch_file_action)
1962 {
Zachary Turner696b5282014-08-14 16:01:25 +00001963 if (!AddPosixSpawnFileAction (&file_actions,
Todd Fiala76747122014-01-23 00:52:28 +00001964 launch_file_action,
1965 log,
1966 error))
1967 return error;
1968 }
1969 }
1970
1971 error.SetError (::posix_spawnp (&pid,
1972 exe_path,
1973 &file_actions,
1974 &attr,
1975 argv,
1976 envp),
1977 eErrorTypePOSIX);
1978
1979 if (error.Fail() || log)
1980 {
1981 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 +00001982 pid, exe_path, static_cast<void*>(&file_actions),
1983 static_cast<void*>(&attr),
1984 reinterpret_cast<const void*>(argv),
1985 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001986 if (log)
1987 {
1988 for (int ii=0; argv[ii]; ++ii)
1989 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1990 }
1991 }
1992
1993 }
1994 else
1995 {
1996 error.SetError (::posix_spawnp (&pid,
1997 exe_path,
1998 NULL,
1999 &attr,
2000 argv,
2001 envp),
2002 eErrorTypePOSIX);
2003
2004 if (error.Fail() || log)
2005 {
2006 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 +00002007 pid, exe_path, static_cast<void*>(&attr),
2008 reinterpret_cast<const void*>(argv),
2009 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00002010 if (log)
2011 {
2012 for (int ii=0; argv[ii]; ++ii)
2013 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
2014 }
2015 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00002016 }
2017
Todd Fiala76747122014-01-23 00:52:28 +00002018 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002019 {
Todd Fiala76747122014-01-23 00:52:28 +00002020#if defined (__APPLE__)
2021 // No more thread specific current working directory
2022 __pthread_fchdir (-1);
2023#else
2024 if (::chdir(current_dir) == -1 && error.Success())
2025 {
2026 error.SetError(errno, eErrorTypePOSIX);
2027 error.LogIfError(log, "unable to change current directory back to %s",
2028 current_dir);
2029 }
2030#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00002031 }
2032
2033 return error;
2034}
2035
Zachary Turner696b5282014-08-14 16:01:25 +00002036bool Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
2037{
2038 if (info == NULL)
2039 return false;
2040
2041 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
2042
2043 switch (info->GetAction())
2044 {
2045 case FileAction::eFileActionNone:
2046 error.Clear();
2047 break;
2048
2049 case FileAction::eFileActionClose:
2050 if (info->GetFD() == -1)
2051 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
2052 else
2053 {
2054 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
2055 if (log && (error.Fail() || log))
2056 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
2057 static_cast<void *>(file_actions), info->GetFD());
2058 }
2059 break;
2060
2061 case FileAction::eFileActionDuplicate:
2062 if (info->GetFD() == -1)
2063 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
2064 else if (info->GetActionArgument() == -1)
2065 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
2066 else
2067 {
2068 error.SetError(::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
2069 eErrorTypePOSIX);
2070 if (log && (error.Fail() || log))
2071 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
2072 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
2073 }
2074 break;
2075
2076 case FileAction::eFileActionOpen:
2077 if (info->GetFD() == -1)
2078 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
2079 else
2080 {
2081 int oflag = info->GetActionArgument();
2082
2083 mode_t mode = 0;
2084
2085 if (oflag & O_CREAT)
2086 mode = 0640;
2087
2088 error.SetError(
2089 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
2090 eErrorTypePOSIX);
2091 if (error.Fail() || log)
2092 error.PutToLog(log, "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
2093 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
2094 }
2095 break;
2096 }
2097 return error.Success();
2098}
2099
Todd Fiala76747122014-01-23 00:52:28 +00002100#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
2101
2102
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002103#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
2104// The functions below implement process launching via posix_spawn() for Linux,
2105// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00002106
2107Error
2108Host::LaunchProcess (ProcessLaunchInfo &launch_info)
2109{
2110 Error error;
2111 char exe_path[PATH_MAX];
2112
2113 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
2114
2115 const ArchSpec &arch_spec = launch_info.GetArchitecture();
2116
2117 FileSpec exe_spec(launch_info.GetExecutableFile());
2118
2119 FileSpec::FileType file_type = exe_spec.GetFileType();
2120 if (file_type != FileSpec::eFileTypeRegular)
2121 {
2122 lldb::ModuleSP exe_module_sp;
2123 error = host_platform_sp->ResolveExecutable (exe_spec,
2124 arch_spec,
2125 exe_module_sp,
2126 NULL);
2127
2128 if (error.Fail())
2129 return error;
2130
2131 if (exe_module_sp)
2132 exe_spec = exe_module_sp->GetFileSpec();
2133 }
2134
2135 if (exe_spec.Exists())
2136 {
2137 exe_spec.GetPath (exe_path, sizeof(exe_path));
2138 }
2139 else
2140 {
2141 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
2142 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
2143 return error;
2144 }
2145
2146 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
2147
2148 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
2149
2150 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
2151
2152 if (pid != LLDB_INVALID_PROCESS_ID)
2153 {
2154 // If all went well, then set the process ID into the launch info
2155 launch_info.SetProcessID(pid);
2156
Todd Fiala76747122014-01-23 00:52:28 +00002157 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
2158
Daniel Malea4244cbd2013-08-27 20:58:59 +00002159 // Make sure we reap any processes we spawn or we will have zombies.
2160 if (!launch_info.MonitorProcess())
2161 {
2162 const bool monitor_signals = false;
2163 StartMonitoringChildProcess (Process::SetProcessExitStatus,
2164 NULL,
2165 pid,
2166 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00002167 if (log)
2168 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
2169 }
2170 else
2171 {
2172 if (log)
2173 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00002174 }
2175 }
2176 else
2177 {
2178 // Invalid process ID, something didn't go well
2179 if (error.Success())
2180 error.SetErrorString ("process launch failed for unknown reasons");
2181 }
2182 return error;
2183}
2184
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00002185#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00002186
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002187#ifndef _WIN32
2188
2189size_t
2190Host::GetPageSize()
2191{
2192 return ::getpagesize();
2193}
Greg Claytond1cf11a2012-04-14 01:42:46 +00002194
Greg Claytone3e3fee2013-02-17 20:46:30 +00002195uint32_t
2196Host::GetNumberCPUS ()
2197{
2198 static uint32_t g_num_cores = UINT32_MAX;
2199 if (g_num_cores == UINT32_MAX)
2200 {
Sylvestre Ledru59405832013-07-01 08:21:36 +00002201#if defined(__APPLE__) or defined (__linux__) or defined (__FreeBSD__) or defined (__FreeBSD_kernel__)
Greg Claytone3e3fee2013-02-17 20:46:30 +00002202
2203 g_num_cores = ::sysconf(_SC_NPROCESSORS_ONLN);
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002204
Greg Claytone3e3fee2013-02-17 20:46:30 +00002205#else
2206
2207 // Assume POSIX support if a host specific case has not been supplied above
2208 g_num_cores = 0;
2209 int num_cores = 0;
2210 size_t num_cores_len = sizeof(num_cores);
Sylvestre Ledru59405832013-07-01 08:21:36 +00002211#ifdef HW_AVAILCPU
Greg Claytone3e3fee2013-02-17 20:46:30 +00002212 int mib[] = { CTL_HW, HW_AVAILCPU };
Sylvestre Ledru59405832013-07-01 08:21:36 +00002213#else
2214 int mib[] = { CTL_HW, HW_NCPU };
2215#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +00002216
2217 /* get the number of CPUs from the system */
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002218 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 +00002219 {
2220 g_num_cores = num_cores;
2221 }
2222 else
2223 {
2224 mib[1] = HW_NCPU;
2225 num_cores_len = sizeof(num_cores);
Saleem Abdulrasool28606952014-06-27 05:17:41 +00002226 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 +00002227 {
2228 if (num_cores > 0)
2229 g_num_cores = num_cores;
2230 }
2231 }
2232#endif
2233 }
2234 return g_num_cores;
2235}
2236
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002237void
2238Host::Kill(lldb::pid_t pid, int signo)
2239{
2240 ::kill(pid, signo);
2241}
Greg Claytone3e3fee2013-02-17 20:46:30 +00002242
Virgile Bellob2f1fb22013-08-23 12:44:05 +00002243#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00002244
Johnny Chen8f3d8382011-08-02 20:52:42 +00002245#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00002246bool
Greg Clayton3b147632010-12-18 01:54:34 +00002247Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00002248{
2249 return false;
2250}
Greg Claytondd36def2010-10-17 22:03:32 +00002251
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00002252void
2253Host::SetCrashDescriptionWithFormat (const char *format, ...)
2254{
2255}
2256
2257void
2258Host::SetCrashDescription (const char *description)
2259{
2260}
Greg Claytondd36def2010-10-17 22:03:32 +00002261
2262lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00002263Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00002264{
2265 return LLDB_INVALID_PROCESS_ID;
2266}
2267
Greg Claytonfbb76342013-11-20 21:07:01 +00002268#endif
2269
2270
Zachary Turnere88be262014-08-09 01:29:07 +00002271#if !defined(_WIN32)
Greg Claytonfbb76342013-11-20 21:07:01 +00002272Error
2273Host::MakeDirectory (const char* path, uint32_t file_permissions)
2274{
2275 Error error;
Greg Claytonfb909312013-11-23 01:58:15 +00002276 if (path && path[0])
2277 {
Greg Claytonfb909312013-11-23 01:58:15 +00002278 if (::mkdir(path, file_permissions) != 0)
2279 {
2280 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002281 switch (error.GetError())
2282 {
2283 case ENOENT:
2284 {
2285 // Parent directory doesn't exist, so lets make it if we can
2286 FileSpec spec(path, false);
2287 if (spec.GetDirectory() && spec.GetFilename())
2288 {
2289 // Make the parent directory and try again
2290 Error error2 = Host::MakeDirectory(spec.GetDirectory().GetCString(), file_permissions);
2291 if (error2.Success())
2292 {
2293 // Try and make the directory again now that the parent directory was made successfully
Greg Claytonfb909312013-11-23 01:58:15 +00002294 if (::mkdir(path, file_permissions) == 0)
Greg Claytonfb909312013-11-23 01:58:15 +00002295 error.Clear();
Greg Claytonfb909312013-11-23 01:58:15 +00002296 else
Greg Claytonfb909312013-11-23 01:58:15 +00002297 error.SetErrorToErrno();
Greg Claytonfb909312013-11-23 01:58:15 +00002298 }
2299 }
2300 }
2301 break;
2302 case EEXIST:
2303 {
2304 FileSpec path_spec(path, false);
2305 if (path_spec.IsDirectory())
2306 error.Clear(); // It is a directory and it already exists
2307 }
2308 break;
2309 }
2310 }
Greg Claytonfb909312013-11-23 01:58:15 +00002311 }
2312 else
2313 {
2314 error.SetErrorString("empty path");
2315 }
Greg Claytonfbb76342013-11-20 21:07:01 +00002316 return error;
2317}
Greg Clayton23f8c952014-03-24 23:10:19 +00002318
2319Error
2320Host::RemoveDirectory (const char* path, bool recurse)
2321{
2322 Error error;
2323 if (path && path[0])
2324 {
2325 if (recurse)
2326 {
2327 StreamString command;
2328 command.Printf("rm -rf \"%s\"", path);
2329 int status = ::system(command.GetString().c_str());
2330 if (status != 0)
2331 error.SetError(status, eErrorTypeGeneric);
2332 }
2333 else
2334 {
2335 if (::rmdir(path) != 0)
2336 error.SetErrorToErrno();
2337 }
2338 }
2339 else
2340 {
2341 error.SetErrorString("empty path");
2342 }
2343 return error;
2344}
Greg Claytonfbb76342013-11-20 21:07:01 +00002345
2346Error
2347Host::GetFilePermissions (const char* path, uint32_t &file_permissions)
2348{
2349 Error error;
2350 struct stat file_stats;
2351 if (::stat (path, &file_stats) == 0)
2352 {
2353 // The bits in "st_mode" currently match the definitions
2354 // for the file mode bits in unix.
2355 file_permissions = file_stats.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
2356 }
2357 else
2358 {
2359 error.SetErrorToErrno();
2360 }
2361 return error;
2362}
2363
2364Error
2365Host::SetFilePermissions (const char* path, uint32_t file_permissions)
2366{
2367 Error error;
2368 if (::chmod(path, file_permissions) != 0)
2369 error.SetErrorToErrno();
2370 return error;
2371}
2372
2373Error
2374Host::Symlink (const char *src, const char *dst)
2375{
2376 Error error;
2377 if (::symlink(dst, src) == -1)
2378 error.SetErrorToErrno();
2379 return error;
2380}
2381
2382Error
2383Host::Unlink (const char *path)
2384{
2385 Error error;
2386 if (::unlink(path) == -1)
2387 error.SetErrorToErrno();
2388 return error;
2389}
2390
2391Error
2392Host::Readlink (const char *path, char *buf, size_t buf_len)
2393{
2394 Error error;
2395 ssize_t count = ::readlink(path, buf, buf_len);
2396 if (count < 0)
2397 error.SetErrorToErrno();
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002398 else if (static_cast<size_t>(count) < (buf_len-1))
Greg Claytonfbb76342013-11-20 21:07:01 +00002399 buf[count] = '\0'; // Success
2400 else
2401 error.SetErrorString("'buf' buffer is too small to contain link contents");
2402 return error;
2403}
2404
2405
Greg Clayton2bddd342010-09-07 20:11:56 +00002406#endif
Daniel Maleae0f8f572013-08-26 23:57:52 +00002407
2408typedef std::map<lldb::user_id_t, lldb::FileSP> FDToFileMap;
2409FDToFileMap& GetFDToFileMap()
2410{
2411 static FDToFileMap g_fd2filemap;
2412 return g_fd2filemap;
2413}
2414
2415lldb::user_id_t
2416Host::OpenFile (const FileSpec& file_spec,
2417 uint32_t flags,
Greg Claytonfbb76342013-11-20 21:07:01 +00002418 uint32_t mode,
Daniel Maleae0f8f572013-08-26 23:57:52 +00002419 Error &error)
2420{
2421 std::string path (file_spec.GetPath());
2422 if (path.empty())
2423 {
2424 error.SetErrorString("empty path");
2425 return UINT64_MAX;
2426 }
2427 FileSP file_sp(new File());
2428 error = file_sp->Open(path.c_str(),flags,mode);
2429 if (file_sp->IsValid() == false)
2430 return UINT64_MAX;
2431 lldb::user_id_t fd = file_sp->GetDescriptor();
2432 GetFDToFileMap()[fd] = file_sp;
2433 return fd;
2434}
2435
2436bool
2437Host::CloseFile (lldb::user_id_t fd, Error &error)
2438{
2439 if (fd == UINT64_MAX)
2440 {
2441 error.SetErrorString ("invalid file descriptor");
2442 return false;
2443 }
2444 FDToFileMap& file_map = GetFDToFileMap();
2445 FDToFileMap::iterator pos = file_map.find(fd);
2446 if (pos == file_map.end())
2447 {
2448 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2449 return false;
2450 }
2451 FileSP file_sp = pos->second;
2452 if (!file_sp)
2453 {
2454 error.SetErrorString ("invalid host backing file");
2455 return false;
2456 }
2457 error = file_sp->Close();
2458 file_map.erase(pos);
2459 return error.Success();
2460}
2461
2462uint64_t
2463Host::WriteFile (lldb::user_id_t fd, uint64_t offset, const void* src, uint64_t src_len, Error &error)
2464{
2465 if (fd == UINT64_MAX)
2466 {
2467 error.SetErrorString ("invalid file descriptor");
2468 return UINT64_MAX;
2469 }
2470 FDToFileMap& file_map = GetFDToFileMap();
2471 FDToFileMap::iterator pos = file_map.find(fd);
2472 if (pos == file_map.end())
2473 {
2474 error.SetErrorStringWithFormat("invalid host file descriptor %" PRIu64 , fd);
2475 return false;
2476 }
2477 FileSP file_sp = pos->second;
2478 if (!file_sp)
2479 {
2480 error.SetErrorString ("invalid host backing file");
2481 return UINT64_MAX;
2482 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002483 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2484 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002485 return UINT64_MAX;
2486 size_t bytes_written = src_len;
2487 error = file_sp->Write(src, bytes_written);
2488 if (error.Fail())
2489 return UINT64_MAX;
2490 return bytes_written;
2491}
2492
2493uint64_t
2494Host::ReadFile (lldb::user_id_t fd, uint64_t offset, void* dst, uint64_t dst_len, Error &error)
2495{
2496 if (fd == UINT64_MAX)
2497 {
2498 error.SetErrorString ("invalid file descriptor");
2499 return UINT64_MAX;
2500 }
2501 FDToFileMap& file_map = GetFDToFileMap();
2502 FDToFileMap::iterator pos = file_map.find(fd);
2503 if (pos == file_map.end())
2504 {
2505 error.SetErrorStringWithFormat ("invalid host file descriptor %" PRIu64, fd);
2506 return false;
2507 }
2508 FileSP file_sp = pos->second;
2509 if (!file_sp)
2510 {
2511 error.SetErrorString ("invalid host backing file");
2512 return UINT64_MAX;
2513 }
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00002514 if (static_cast<uint64_t>(file_sp->SeekFromStart(offset, &error)) != offset ||
2515 error.Fail())
Daniel Maleae0f8f572013-08-26 23:57:52 +00002516 return UINT64_MAX;
2517 size_t bytes_read = dst_len;
2518 error = file_sp->Read(dst ,bytes_read);
2519 if (error.Fail())
2520 return UINT64_MAX;
2521 return bytes_read;
2522}
2523
2524lldb::user_id_t
2525Host::GetFileSize (const FileSpec& file_spec)
2526{
2527 return file_spec.GetByteSize();
2528}
2529
2530bool
2531Host::GetFileExists (const FileSpec& file_spec)
2532{
2533 return file_spec.Exists();
2534}
2535
2536bool
2537Host::CalculateMD5 (const FileSpec& file_spec,
2538 uint64_t &low,
2539 uint64_t &high)
2540{
2541#if defined (__APPLE__)
2542 StreamString md5_cmd_line;
2543 md5_cmd_line.Printf("md5 -q '%s'", file_spec.GetPath().c_str());
2544 std::string hash_string;
2545 Error err = Host::RunShellCommand(md5_cmd_line.GetData(), NULL, NULL, NULL, &hash_string, 60);
2546 if (err.Fail())
2547 return false;
2548 // a correctly formed MD5 is 16-bytes, that is 32 hex digits
2549 // if the output is any other length it is probably wrong
2550 if (hash_string.size() != 32)
2551 return false;
2552 std::string part1(hash_string,0,16);
2553 std::string part2(hash_string,16);
2554 const char* part1_cstr = part1.c_str();
2555 const char* part2_cstr = part2.c_str();
2556 high = ::strtoull(part1_cstr, NULL, 16);
2557 low = ::strtoull(part2_cstr, NULL, 16);
2558 return true;
2559#else
2560 // your own MD5 implementation here
2561 return false;
2562#endif
2563}