blob: 3c2d098732f8c35bc40788e534ac780828b8f57a [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>
Ed Maste8b006c62013-06-25 18:58:11 +000039#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000040
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +000041#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000042#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000043#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000044#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000045#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000046
Ed Maste8b006c62013-06-25 18:58:11 +000047#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000048#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#endif
50
Todd Fiala17096d72014-07-16 19:03:16 +000051// C++ includes
52#include <limits>
53
Greg Clayton2bddd342010-09-07 20:11:56 +000054#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000055#include "lldb/Host/HostInfo.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000056#include "lldb/Core/ArchSpec.h"
57#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000058#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000059#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000060#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000061#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000062#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000063#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000064#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000065#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000066#include "lldb/Host/FileSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000067#include "lldb/Host/FileSystem.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000068#include "lldb/Host/Mutex.h"
Zachary Turner696b5282014-08-14 16:01:25 +000069#include "lldb/Target/FileAction.h"
Greg Claytone996fd32011-03-08 22:40:15 +000070#include "lldb/Target/Process.h"
Zachary Turner696b5282014-08-14 16:01:25 +000071#include "lldb/Target/ProcessLaunchInfo.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000072#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000073#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000074
Saleem Abdulrasool28606952014-06-27 05:17:41 +000075#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000076#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000077#include "llvm/Support/Host.h"
Zachary Turner9e757b72014-07-28 16:45:05 +000078#include "llvm/Support/Path.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000079#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000080
Todd Fiala76747122014-01-23 00:52:28 +000081#if defined (__APPLE__)
82#ifndef _POSIX_SPAWN_DISABLE_ASLR
83#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
84#endif
85
86extern "C"
87{
88 int __pthread_chdir(const char *path);
89 int __pthread_fchdir (int fildes);
90}
91
92#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000093
Greg Clayton2bddd342010-09-07 20:11:56 +000094using namespace lldb;
95using namespace lldb_private;
96
Todd Fiala17096d72014-07-16 19:03:16 +000097// Define maximum thread name length
98#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
99uint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
100#else
101uint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
102#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000103
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000104#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000105struct MonitorInfo
106{
107 lldb::pid_t pid; // The process ID to monitor
108 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
109 void *callback_baton; // The callback baton for the callback function
110 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
111};
112
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000113static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000114MonitorChildProcessThreadFunction (void *arg);
115
116lldb::thread_t
117Host::StartMonitoringChildProcess
118(
119 Host::MonitorChildProcessCallback callback,
120 void *callback_baton,
121 lldb::pid_t pid,
122 bool monitor_signals
123)
124{
125 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
Greg Claytone4e45922011-11-16 05:37:56 +0000126 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000127
Greg Claytone4e45922011-11-16 05:37:56 +0000128 info_ptr->pid = pid;
129 info_ptr->callback = callback;
130 info_ptr->callback_baton = callback_baton;
131 info_ptr->monitor_signals = monitor_signals;
132
133 char thread_name[256];
Daniel Malead01b2952012-11-29 21:49:15 +0000134 ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
Greg Claytone4e45922011-11-16 05:37:56 +0000135 thread = ThreadCreate (thread_name,
136 MonitorChildProcessThreadFunction,
137 info_ptr,
138 NULL);
139
Greg Clayton2bddd342010-09-07 20:11:56 +0000140 return thread;
141}
142
143//------------------------------------------------------------------
144// Scoped class that will disable thread canceling when it is
145// constructed, and exception safely restore the previous value it
146// when it goes out of scope.
147//------------------------------------------------------------------
148class ScopedPThreadCancelDisabler
149{
150public:
151 ScopedPThreadCancelDisabler()
152 {
153 // Disable the ability for this thread to be cancelled
154 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
155 if (err != 0)
156 m_old_state = -1;
157
158 }
159
160 ~ScopedPThreadCancelDisabler()
161 {
162 // Restore the ability for this thread to be cancelled to what it
163 // previously was.
164 if (m_old_state != -1)
165 ::pthread_setcancelstate (m_old_state, 0);
166 }
167private:
168 int m_old_state; // Save the old cancelability state.
169};
170
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000171static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000172MonitorChildProcessThreadFunction (void *arg)
173{
Greg Clayton5160ce52013-03-27 23:08:40 +0000174 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000175 const char *function = __FUNCTION__;
176 if (log)
177 log->Printf ("%s (arg = %p) thread starting...", function, arg);
178
179 MonitorInfo *info = (MonitorInfo *)arg;
180
181 const Host::MonitorChildProcessCallback callback = info->callback;
182 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000183 const bool monitor_signals = info->monitor_signals;
184
Daniel Malea4244cbd2013-08-27 20:58:59 +0000185 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000186 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000187
Greg Clayton2bddd342010-09-07 20:11:56 +0000188 delete info;
189
190 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000191#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000192 #define __WALL 0
193#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000194 const int options = __WALL;
195
Greg Clayton2bddd342010-09-07 20:11:56 +0000196 while (1)
197 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000198 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000199 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000200 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000201
202 // Wait for all child processes
203 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000204 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000205 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000206 ::pthread_testcancel ();
207
208 if (wait_pid == -1)
209 {
210 if (errno == EINTR)
211 continue;
212 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000213 {
214 if (log)
215 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000216 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000217 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000218 }
Matt Kopec650648f2013-01-08 16:30:18 +0000219 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000220 {
221 bool exited = false;
222 int signal = 0;
223 int exit_status = 0;
224 const char *status_cstr = NULL;
225 if (WIFSTOPPED(status))
226 {
227 signal = WSTOPSIG(status);
228 status_cstr = "STOPPED";
229 }
230 else if (WIFEXITED(status))
231 {
232 exit_status = WEXITSTATUS(status);
233 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000234 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000235 }
236 else if (WIFSIGNALED(status))
237 {
238 signal = WTERMSIG(status);
239 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000240 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000241 exited = true;
242 exit_status = -1;
243 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000244 }
245 else
246 {
Johnny Chen44805302011-07-19 19:48:13 +0000247 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000248 }
249
250 // Scope for pthread_cancel_disabler
251 {
252 ScopedPThreadCancelDisabler pthread_cancel_disabler;
253
Caroline Tice20ad3c42010-10-29 21:48:37 +0000254 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000255 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000256 log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
Greg Clayton2bddd342010-09-07 20:11:56 +0000257 function,
258 wait_pid,
259 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000260 pid,
261 status,
262 status_cstr,
263 signal,
264 exit_status);
265
266 if (exited || (signal != 0 && monitor_signals))
267 {
Greg Claytone4e45922011-11-16 05:37:56 +0000268 bool callback_return = false;
269 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000270 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000271
272 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000273 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000274 {
275 if (log)
276 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000277 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000278 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000279 // If the callback returns true, it means this process should
280 // exit
281 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000282 {
283 if (log)
284 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000285 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000286 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000287 }
288 }
289 }
290 }
291
Caroline Tice20ad3c42010-10-29 21:48:37 +0000292 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000293 if (log)
294 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
295
296 return NULL;
297}
298
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000299#endif // #if !defined (__APPLE__) && !defined (_WIN32)
300
301#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000302
303void
304Host::SystemLog (SystemLogType type, const char *format, va_list args)
305{
306 vfprintf (stderr, format, args);
307}
308
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000309#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000310
Greg Claytone38a5ed2012-01-05 03:57:59 +0000311void
312Host::SystemLog (SystemLogType type, const char *format, ...)
313{
314 va_list args;
315 va_start (args, format);
316 SystemLog (type, format, args);
317 va_end (args);
318}
319
Greg Clayton2bddd342010-09-07 20:11:56 +0000320lldb::pid_t
321Host::GetCurrentProcessID()
322{
323 return ::getpid();
324}
325
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000326#ifndef _WIN32
327
Greg Clayton2bddd342010-09-07 20:11:56 +0000328lldb::tid_t
329Host::GetCurrentThreadID()
330{
331#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000332 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000333 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
334 // count.
335 thread_port_t thread_self = mach_thread_self();
336 mach_port_deallocate(mach_task_self(), thread_self);
337 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000338#elif defined(__FreeBSD__)
339 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000340#elif defined(__linux__)
341 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000342#else
343 return lldb::tid_t(pthread_self());
344#endif
345}
346
Jim Ingham372787f2012-04-07 00:00:41 +0000347lldb::thread_t
348Host::GetCurrentThread ()
349{
350 return lldb::thread_t(pthread_self());
351}
352
Greg Clayton2bddd342010-09-07 20:11:56 +0000353const char *
354Host::GetSignalAsCString (int signo)
355{
356 switch (signo)
357 {
358 case SIGHUP: return "SIGHUP"; // 1 hangup
359 case SIGINT: return "SIGINT"; // 2 interrupt
360 case SIGQUIT: return "SIGQUIT"; // 3 quit
361 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
362 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
363 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000364#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000365#if !defined(SIGIO) || (SIGPOLL != SIGIO)
366// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
367// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000368 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000369#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000370#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000371#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000372 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000373#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000374 case SIGFPE: return "SIGFPE"; // 8 floating point exception
375 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
376 case SIGBUS: return "SIGBUS"; // 10 bus error
377 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
378 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
379 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
380 case SIGALRM: return "SIGALRM"; // 14 alarm clock
381 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
382 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
383 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
384 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
385 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
386 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
387 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
388 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000389#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000390 case SIGIO: return "SIGIO"; // 23 input/output possible signal
391#endif
392 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
393 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
394 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
395 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000396#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000397 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000398#endif
399#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000400 case SIGINFO: return "SIGINFO"; // 29 information request
401#endif
402 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
403 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
404 default:
405 break;
406 }
407 return NULL;
408}
409
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000410#endif
411
Greg Clayton2bddd342010-09-07 20:11:56 +0000412void
413Host::WillTerminate ()
414{
415}
416
Sylvestre Ledru59405832013-07-01 08:21:36 +0000417#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000418
Greg Clayton2bddd342010-09-07 20:11:56 +0000419void
420Host::ThreadCreated (const char *thread_name)
421{
422}
Greg Claytone5219662010-12-03 06:02:24 +0000423
Peter Collingbourne2ced9132011-08-05 00:35:43 +0000424void
Greg Claytone5219662010-12-03 06:02:24 +0000425Host::Backtrace (Stream &strm, uint32_t max_frames)
426{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000427 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000428}
429
Greg Clayton85851dd2010-12-04 00:10:17 +0000430size_t
431Host::GetEnvironment (StringList &env)
432{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000433 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000434 return 0;
435}
436
Sylvestre Ledru59405832013-07-01 08:21:36 +0000437#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000438
439struct HostThreadCreateInfo
440{
441 std::string thread_name;
442 thread_func_t thread_fptr;
443 thread_arg_t thread_arg;
444
445 HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
446 thread_name (name ? name : ""),
447 thread_fptr (fptr),
448 thread_arg (arg)
449 {
450 }
451};
452
453static thread_result_t
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000454#ifdef _WIN32
455__stdcall
456#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000457ThreadCreateTrampoline (thread_arg_t arg)
458{
459 HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
460 Host::ThreadCreated (info->thread_name.c_str());
461 thread_func_t thread_fptr = info->thread_fptr;
462 thread_arg_t thread_arg = info->thread_arg;
463
Greg Clayton5160ce52013-03-27 23:08:40 +0000464 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
Greg Clayton2bddd342010-09-07 20:11:56 +0000465 if (log)
466 log->Printf("thread created");
467
468 delete info;
469 return thread_fptr (thread_arg);
470}
471
472lldb::thread_t
473Host::ThreadCreate
474(
475 const char *thread_name,
476 thread_func_t thread_fptr,
477 thread_arg_t thread_arg,
478 Error *error
479)
480{
481 lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
482
483 // Host::ThreadCreateTrampoline will delete this pointer for us.
484 HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
485
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000486#ifdef _WIN32
487 thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
488 int err = thread <= 0 ? GetLastError() : 0;
489#else
Greg Clayton2bddd342010-09-07 20:11:56 +0000490 int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000491#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000492 if (err == 0)
493 {
494 if (error)
495 error->Clear();
496 return thread;
497 }
498
499 if (error)
500 error->SetError (err, eErrorTypePOSIX);
501
502 return LLDB_INVALID_HOST_THREAD;
503}
504
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000505#ifndef _WIN32
506
Greg Clayton2bddd342010-09-07 20:11:56 +0000507bool
508Host::ThreadCancel (lldb::thread_t thread, Error *error)
509{
510 int err = ::pthread_cancel (thread);
511 if (error)
512 error->SetError(err, eErrorTypePOSIX);
513 return err == 0;
514}
515
516bool
517Host::ThreadDetach (lldb::thread_t thread, Error *error)
518{
519 int err = ::pthread_detach (thread);
520 if (error)
521 error->SetError(err, eErrorTypePOSIX);
522 return err == 0;
523}
524
525bool
526Host::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
527{
528 int err = ::pthread_join (thread, thread_result_ptr);
529 if (error)
530 error->SetError(err, eErrorTypePOSIX);
531 return err == 0;
532}
533
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000534lldb::thread_key_t
535Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
536{
537 pthread_key_t key;
538 ::pthread_key_create (&key, callback);
539 return key;
540}
541
542void*
543Host::ThreadLocalStorageGet(lldb::thread_key_t key)
544{
545 return ::pthread_getspecific (key);
546}
547
548void
549Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
550{
551 ::pthread_setspecific (key, value);
552}
553
Matt Kopec62502c62013-05-13 19:33:58 +0000554bool
Greg Clayton2bddd342010-09-07 20:11:56 +0000555Host::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
556{
Greg Clayton85719632013-02-27 22:51:58 +0000557#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
Greg Clayton2bddd342010-09-07 20:11:56 +0000558 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
559 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
560 if (pid == LLDB_INVALID_PROCESS_ID)
561 pid = curr_pid;
562
563 if (tid == LLDB_INVALID_THREAD_ID)
564 tid = curr_tid;
565
Greg Clayton2bddd342010-09-07 20:11:56 +0000566 // Set the pthread name if possible
567 if (pid == curr_pid && tid == curr_tid)
568 {
Matt Kopec62502c62013-05-13 19:33:58 +0000569 if (::pthread_setname_np (name) == 0)
570 return true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000571 }
Matt Kopec62502c62013-05-13 19:33:58 +0000572 return false;
Ed Maste02983be2013-07-25 19:10:32 +0000573#elif defined (__FreeBSD__)
574 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
575 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
576 if (pid == LLDB_INVALID_PROCESS_ID)
577 pid = curr_pid;
578
579 if (tid == LLDB_INVALID_THREAD_ID)
580 tid = curr_tid;
581
582 // Set the pthread name if possible
583 if (pid == curr_pid && tid == curr_tid)
584 {
Michael Sartainc2052432013-08-01 18:51:08 +0000585 ::pthread_set_name_np (::pthread_self(), name);
Ed Maste02983be2013-07-25 19:10:32 +0000586 return true;
587 }
588 return false;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000589#elif defined (__linux__) || defined (__GLIBC__)
Matt Kopec62502c62013-05-13 19:33:58 +0000590 void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
591 if (fn)
592 {
Matt Kopec62502c62013-05-13 19:33:58 +0000593 lldb::pid_t curr_pid = Host::GetCurrentProcessID();
594 lldb::tid_t curr_tid = Host::GetCurrentThreadID();
Matt Kopec62502c62013-05-13 19:33:58 +0000595 if (pid == LLDB_INVALID_PROCESS_ID)
596 pid = curr_pid;
597
598 if (tid == LLDB_INVALID_THREAD_ID)
599 tid = curr_tid;
600
Michael Sartainc2052432013-08-01 18:51:08 +0000601 if (pid == curr_pid && tid == curr_tid)
Matt Kopec62502c62013-05-13 19:33:58 +0000602 {
Michael Sartainc2052432013-08-01 18:51:08 +0000603 int (*pthread_setname_np_func)(pthread_t thread, const char *name);
604 *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
605
606 if (pthread_setname_np_func (::pthread_self(), name) == 0)
Matt Kopec62502c62013-05-13 19:33:58 +0000607 return true;
608 }
609 }
610 return false;
Jim Ingham5c42d8a2013-05-15 18:27:08 +0000611#else
612 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000613#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000614}
615
Ed Maste02983be2013-07-25 19:10:32 +0000616bool
617Host::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
618 const char *thread_name, size_t len)
619{
Enrico Granata67530b62014-02-12 03:37:33 +0000620 std::unique_ptr<char[]> namebuf(new char[len+1]);
621
Ed Maste02983be2013-07-25 19:10:32 +0000622 // Thread names are coming in like '<lldb.comm.debugger.edit>' and
623 // '<lldb.comm.debugger.editline>'. So just chopping the end of the string
624 // off leads to a lot of similar named threads. Go through the thread name
625 // and search for the last dot and use that.
626 const char *lastdot = ::strrchr (thread_name, '.');
627
628 if (lastdot && lastdot != thread_name)
629 thread_name = lastdot + 1;
Enrico Granata67530b62014-02-12 03:37:33 +0000630 ::strncpy (namebuf.get(), thread_name, len);
Ed Maste02983be2013-07-25 19:10:32 +0000631 namebuf[len] = 0;
632
Enrico Granata67530b62014-02-12 03:37:33 +0000633 int namebuflen = strlen(namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000634 if (namebuflen > 0)
635 {
636 if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
637 {
638 // Trim off trailing '(' and '>' characters for a bit more cleanup.
639 namebuflen--;
640 namebuf[namebuflen] = 0;
641 }
Enrico Granata67530b62014-02-12 03:37:33 +0000642 return Host::SetThreadName (pid, tid, namebuf.get());
Ed Maste02983be2013-07-25 19:10:32 +0000643 }
644 return false;
645}
646
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000647#endif
648
Greg Clayton2bddd342010-09-07 20:11:56 +0000649FileSpec
Zachary Turner9e757b72014-07-28 16:45:05 +0000650Host::GetUserProfileFileSpec ()
651{
652 static FileSpec g_profile_filespec;
653 if (!g_profile_filespec)
654 {
655 llvm::SmallString<64> path;
656 llvm::sys::path::home_directory(path);
657 return FileSpec(path.c_str(), false);
658 }
659 return g_profile_filespec;
660}
661
662FileSpec
Greg Clayton2bddd342010-09-07 20:11:56 +0000663Host::GetProgramFileSpec ()
664{
665 static FileSpec g_program_filespec;
666 if (!g_program_filespec)
667 {
668#if defined (__APPLE__)
669 char program_fullpath[PATH_MAX];
670 // If DST is NULL, then return the number of bytes needed.
671 uint32_t len = sizeof(program_fullpath);
672 int err = _NSGetExecutablePath (program_fullpath, &len);
673 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000674 g_program_filespec.SetFile (program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000675 else if (err == -1)
676 {
677 char *large_program_fullpath = (char *)::malloc (len + 1);
678
679 err = _NSGetExecutablePath (large_program_fullpath, &len);
680 if (err == 0)
Greg Claytonb3326392011-01-13 01:23:43 +0000681 g_program_filespec.SetFile (large_program_fullpath, false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000682
683 ::free (large_program_fullpath);
684 }
685#elif defined (__linux__)
686 char exe_path[PATH_MAX];
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000687 ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
688 if (len > 0) {
689 exe_path[len] = 0;
Greg Claytonb3326392011-01-13 01:23:43 +0000690 g_program_filespec.SetFile(exe_path, false);
Stephen Wilsone5b94a92011-01-12 04:21:21 +0000691 }
Sylvestre Ledru59405832013-07-01 08:21:36 +0000692#elif defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000693 int exe_path_mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
694 size_t exe_path_size;
695 if (sysctl(exe_path_mib, 4, NULL, &exe_path_size, NULL, 0) == 0)
696 {
Greg Clayton87ff1ac2011-01-13 01:27:55 +0000697 char *exe_path = new char[exe_path_size];
698 if (sysctl(exe_path_mib, 4, exe_path, &exe_path_size, NULL, 0) == 0)
699 g_program_filespec.SetFile(exe_path, false);
700 delete[] exe_path;
Greg Clayton2bddd342010-09-07 20:11:56 +0000701 }
Zachary Turner9e757b72014-07-28 16:45:05 +0000702#elif defined(_WIN32)
703 std::vector<char> buffer(PATH_MAX);
704 ::GetModuleFileName(NULL, &buffer[0], buffer.size());
Zachary Turnerd8a52732014-07-29 05:39:21 +0000705 g_program_filespec.SetFile(&buffer[0], false);
Greg Clayton2bddd342010-09-07 20:11:56 +0000706#endif
707 }
708 return g_program_filespec;
709}
710
Greg Clayton2bddd342010-09-07 20:11:56 +0000711#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000712
713bool
714Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
715{
716 bundle.Clear();
717 return false;
718}
719
Greg Clayton2bddd342010-09-07 20:11:56 +0000720bool
Greg Claytondd36def2010-10-17 22:03:32 +0000721Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000722{
Greg Claytondd36def2010-10-17 22:03:32 +0000723 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000724}
725#endif
726
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000727#ifndef _WIN32
728
Greg Clayton45319462011-02-08 00:35:34 +0000729// Opaque info that tracks a dynamic library that was loaded
730struct DynamicLibraryInfo
Greg Clayton4272cc72011-02-02 02:24:04 +0000731{
Greg Clayton45319462011-02-08 00:35:34 +0000732 DynamicLibraryInfo (const FileSpec &fs, int o, void *h) :
733 file_spec (fs),
734 open_options (o),
735 handle (h)
736 {
737 }
738
739 const FileSpec file_spec;
740 uint32_t open_options;
741 void * handle;
742};
743
744void *
745Host::DynamicLibraryOpen (const FileSpec &file_spec, uint32_t options, Error &error)
746{
Greg Clayton4272cc72011-02-02 02:24:04 +0000747 char path[PATH_MAX];
748 if (file_spec.GetPath(path, sizeof(path)))
749 {
Greg Clayton45319462011-02-08 00:35:34 +0000750 int mode = 0;
751
752 if (options & eDynamicLibraryOpenOptionLazy)
753 mode |= RTLD_LAZY;
Greg Claytonf9399452011-02-08 05:24:57 +0000754 else
755 mode |= RTLD_NOW;
756
Greg Clayton45319462011-02-08 00:35:34 +0000757
758 if (options & eDynamicLibraryOpenOptionLocal)
759 mode |= RTLD_LOCAL;
760 else
761 mode |= RTLD_GLOBAL;
762
763#ifdef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
764 if (options & eDynamicLibraryOpenOptionLimitGetSymbol)
765 mode |= RTLD_FIRST;
Greg Clayton75852f52011-02-07 17:43:47 +0000766#endif
Greg Clayton45319462011-02-08 00:35:34 +0000767
768 void * opaque = ::dlopen (path, mode);
769
770 if (opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000771 {
772 error.Clear();
Greg Clayton45319462011-02-08 00:35:34 +0000773 return new DynamicLibraryInfo (file_spec, options, opaque);
Greg Clayton4272cc72011-02-02 02:24:04 +0000774 }
775 else
776 {
777 error.SetErrorString(::dlerror());
778 }
779 }
780 else
781 {
782 error.SetErrorString("failed to extract path");
783 }
Greg Clayton45319462011-02-08 00:35:34 +0000784 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000785}
786
787Error
Greg Clayton45319462011-02-08 00:35:34 +0000788Host::DynamicLibraryClose (void *opaque)
Greg Clayton4272cc72011-02-02 02:24:04 +0000789{
790 Error error;
Greg Clayton45319462011-02-08 00:35:34 +0000791 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000792 {
793 error.SetErrorString ("invalid dynamic library handle");
794 }
Greg Clayton45319462011-02-08 00:35:34 +0000795 else
Greg Clayton4272cc72011-02-02 02:24:04 +0000796 {
Greg Clayton45319462011-02-08 00:35:34 +0000797 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
798 if (::dlclose (dylib_info->handle) != 0)
799 {
800 error.SetErrorString(::dlerror());
801 }
802
803 dylib_info->open_options = 0;
804 dylib_info->handle = 0;
805 delete dylib_info;
Greg Clayton4272cc72011-02-02 02:24:04 +0000806 }
807 return error;
808}
809
810void *
Greg Clayton45319462011-02-08 00:35:34 +0000811Host::DynamicLibraryGetSymbol (void *opaque, const char *symbol_name, Error &error)
Greg Clayton4272cc72011-02-02 02:24:04 +0000812{
Greg Clayton45319462011-02-08 00:35:34 +0000813 if (opaque == NULL)
Greg Clayton4272cc72011-02-02 02:24:04 +0000814 {
815 error.SetErrorString ("invalid dynamic library handle");
Greg Clayton4272cc72011-02-02 02:24:04 +0000816 }
Greg Clayton4272cc72011-02-02 02:24:04 +0000817 else
Greg Clayton45319462011-02-08 00:35:34 +0000818 {
819 DynamicLibraryInfo *dylib_info = (DynamicLibraryInfo *) opaque;
820
821 void *symbol_addr = ::dlsym (dylib_info->handle, symbol_name);
822 if (symbol_addr)
823 {
824#ifndef LLDB_CONFIG_DLOPEN_RTLD_FIRST_SUPPORTED
825 // This host doesn't support limiting searches to this shared library
826 // so we need to verify that the match came from this shared library
827 // if it was requested in the Host::DynamicLibraryOpen() function.
Greg Claytonf9399452011-02-08 05:24:57 +0000828 if (dylib_info->open_options & eDynamicLibraryOpenOptionLimitGetSymbol)
Greg Clayton45319462011-02-08 00:35:34 +0000829 {
830 FileSpec match_dylib_spec (Host::GetModuleFileSpecForHostAddress (symbol_addr));
831 if (match_dylib_spec != dylib_info->file_spec)
832 {
833 char dylib_path[PATH_MAX];
834 if (dylib_info->file_spec.GetPath (dylib_path, sizeof(dylib_path)))
835 error.SetErrorStringWithFormat ("symbol not found in \"%s\"", dylib_path);
836 else
837 error.SetErrorString ("symbol not found");
838 return NULL;
839 }
840 }
841#endif
842 error.Clear();
843 return symbol_addr;
844 }
845 else
846 {
847 error.SetErrorString(::dlerror());
848 }
849 }
850 return NULL;
Greg Clayton4272cc72011-02-02 02:24:04 +0000851}
Greg Claytondd36def2010-10-17 22:03:32 +0000852
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000853FileSpec
854Host::GetModuleFileSpecForHostAddress (const void *host_addr)
855{
856 FileSpec module_filespec;
857 Dl_info info;
858 if (::dladdr (host_addr, &info))
859 {
860 if (info.dli_fname)
861 module_filespec.SetFile(info.dli_fname, true);
862 }
863 return module_filespec;
864}
865
866#endif
867
Greg Clayton23f8c952014-03-24 23:10:19 +0000868
869static void CleanupProcessSpecificLLDBTempDir ()
870{
871 // Get the process specific LLDB temporary directory and delete it.
872 FileSpec tmpdir_file_spec;
873 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
874 {
875 // Remove the LLDB temporary directory if we have one. Set "recurse" to
876 // true to all files that were created for the LLDB process can be cleaned up.
877 const bool recurse = true;
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000878 FileSystem::DeleteDirectory(tmpdir_file_spec.GetDirectory().GetCString(), recurse);
Greg Clayton23f8c952014-03-24 23:10:19 +0000879 }
880}
881
Greg Claytondd36def2010-10-17 22:03:32 +0000882bool
883Host::GetLLDBPath (PathType path_type, FileSpec &file_spec)
884{
Greg Clayton710dd5a2011-01-08 20:28:42 +0000885 // To get paths related to LLDB we get the path to the executable that
Greg Claytondd36def2010-10-17 22:03:32 +0000886 // contains this function. On MacOSX this will be "LLDB.framework/.../LLDB",
887 // on linux this is assumed to be the "lldb" main executable. If LLDB on
Michael Sartain3cf443d2013-07-17 00:26:30 +0000888 // linux is actually in a shared library (liblldb.so) then this function will
Greg Claytondd36def2010-10-17 22:03:32 +0000889 // need to be modified to "do the right thing".
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000890 Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST);
Greg Claytondd36def2010-10-17 22:03:32 +0000891
892 switch (path_type)
893 {
894 case ePathTypeLLDBShlibDir:
895 {
896 static ConstString g_lldb_so_dir;
897 if (!g_lldb_so_dir)
898 {
David Majnemer8490da12014-07-22 22:00:42 +0000899 FileSpec lldb_file_spec(Host::GetModuleFileSpecForHostAddress(
900 reinterpret_cast<void *>(reinterpret_cast<intptr_t>(Host::GetLLDBPath))));
Greg Claytondd36def2010-10-17 22:03:32 +0000901 g_lldb_so_dir = lldb_file_spec.GetDirectory();
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000902 if (log)
903 log->Printf("Host::GetLLDBPath(ePathTypeLLDBShlibDir) => '%s'", g_lldb_so_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +0000904 }
905 file_spec.GetDirectory() = g_lldb_so_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +0000906 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +0000907 }
908 break;
909
910 case ePathTypeSupportExecutableDir:
911 {
912 static ConstString g_lldb_support_exe_dir;
913 if (!g_lldb_support_exe_dir)
914 {
915 FileSpec lldb_file_spec;
916 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
917 {
918 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +0000919 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
920
921#if defined (__APPLE__)
922 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
923 if (framework_pos)
924 {
925 framework_pos += strlen("LLDB.framework");
Todd Fiala013434e2014-07-09 01:29:05 +0000926#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000927 // Shallow bundle
928 *framework_pos = '\0';
929#else
930 // Normal bundle
Greg Claytondd36def2010-10-17 22:03:32 +0000931 ::strncpy (framework_pos, "/Resources", PATH_MAX - (framework_pos - raw_path));
Greg Claytondce502e2011-11-04 03:34:56 +0000932#endif
Greg Claytondd36def2010-10-17 22:03:32 +0000933 }
Todd Fiala015d8182014-07-22 23:41:36 +0000934#elif defined (__linux__) || defined (__FreeBSD__) || defined (__NetBSD__)
935 // Linux/*BSD will attempt to replace a */lib with */bin as the base directory for
936 // helper exe programs. This will fail if the /lib and /bin directories are rooted in entirely
937 // different trees.
938 if (log)
939 log->Printf ("Host::%s() attempting to derive the bin path (ePathTypeSupportExecutableDir) from this path: %s", __FUNCTION__, raw_path);
940 char *lib_pos = ::strstr (raw_path, "/lib");
941 if (lib_pos != nullptr)
942 {
943 // First terminate the raw path at the start of lib.
944 *lib_pos = '\0';
945
946 // Now write in bin in place of lib.
947 ::strncpy (lib_pos, "/bin", PATH_MAX - (lib_pos - raw_path));
948
949 if (log)
950 log->Printf ("Host::%s() derived the bin path as: %s", __FUNCTION__, raw_path);
951 }
952 else
953 {
954 if (log)
955 log->Printf ("Host::%s() failed to find /lib/liblldb within the shared lib path, bailing on bin path construction", __FUNCTION__);
956 }
Jason Molendaa3329782014-03-29 18:54:20 +0000957#endif // #if defined (__APPLE__)
Zachary Turner3f559742014-08-07 17:33:36 +0000958 llvm::SmallString<64> resolved_path(raw_path);
959 FileSpec::Resolve (resolved_path);
960 g_lldb_support_exe_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +0000961 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000962 if (log)
963 log->Printf("Host::GetLLDBPath(ePathTypeSupportExecutableDir) => '%s'", g_lldb_support_exe_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +0000964 }
965 file_spec.GetDirectory() = g_lldb_support_exe_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +0000966 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +0000967 }
968 break;
969
970 case ePathTypeHeaderDir:
971 {
972 static ConstString g_lldb_headers_dir;
973 if (!g_lldb_headers_dir)
974 {
975#if defined (__APPLE__)
976 FileSpec lldb_file_spec;
977 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
978 {
979 char raw_path[PATH_MAX];
Greg Claytondd36def2010-10-17 22:03:32 +0000980 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
981
982 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
983 if (framework_pos)
984 {
985 framework_pos += strlen("LLDB.framework");
986 ::strncpy (framework_pos, "/Headers", PATH_MAX - (framework_pos - raw_path));
987 }
Jim Inghame1d263e2014-08-07 22:37:43 +0000988 llvm::SmallString<64> resolved_path(raw_path);
989 FileSpec::Resolve (resolved_path);
990 g_lldb_headers_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +0000991 }
992#else
Greg Clayton4272cc72011-02-02 02:24:04 +0000993 // TODO: Anyone know how we can determine this for linux? Other systems??
Greg Claytondd36def2010-10-17 22:03:32 +0000994 g_lldb_headers_dir.SetCString ("/opt/local/include/lldb");
995#endif
Greg Clayton3bd19fb2013-11-22 18:48:24 +0000996 if (log)
997 log->Printf("Host::GetLLDBPath(ePathTypeHeaderDir) => '%s'", g_lldb_headers_dir.GetCString());
Greg Claytondd36def2010-10-17 22:03:32 +0000998 }
999 file_spec.GetDirectory() = g_lldb_headers_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001000 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001001 }
1002 break;
1003
Joerg Sonnenbergerc7598762013-09-25 17:52:18 +00001004#ifdef LLDB_DISABLE_PYTHON
1005 case ePathTypePythonDir:
1006 return false;
1007#else
1008 case ePathTypePythonDir:
Greg Claytondd36def2010-10-17 22:03:32 +00001009 {
Greg Claytondd36def2010-10-17 22:03:32 +00001010 static ConstString g_lldb_python_dir;
1011 if (!g_lldb_python_dir)
1012 {
1013 FileSpec lldb_file_spec;
1014 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1015 {
1016 char raw_path[PATH_MAX];
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001017#if defined(_WIN32)
1018 lldb_file_spec.AppendPathComponent("../lib/site-packages");
1019 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1020#else
Greg Claytondd36def2010-10-17 22:03:32 +00001021 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1022
1023#if defined (__APPLE__)
1024 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1025 if (framework_pos)
1026 {
1027 framework_pos += strlen("LLDB.framework");
1028 ::strncpy (framework_pos, "/Resources/Python", PATH_MAX - (framework_pos - raw_path));
Todd Fiala5000e282014-01-18 08:05:32 +00001029 }
1030 else
1031 {
1032#endif
1033 llvm::SmallString<256> python_version_dir;
1034 llvm::raw_svector_ostream os(python_version_dir);
1035 os << "/python" << PY_MAJOR_VERSION << '.' << PY_MINOR_VERSION << "/site-packages";
1036 os.flush();
1037
1038 // We may get our string truncated. Should we protect
1039 // this with an assert?
1040
1041 ::strncat(raw_path, python_version_dir.c_str(),
1042 sizeof(raw_path) - strlen(raw_path) - 1);
Zachary Turnerc9bf0c72014-07-18 20:36:08 +00001043#endif
Todd Fiala5000e282014-01-18 08:05:32 +00001044#if defined (__APPLE__)
Greg Claytondd36def2010-10-17 22:03:32 +00001045 }
1046#endif
Zachary Turner3f559742014-08-07 17:33:36 +00001047 llvm::SmallString<64> resolved_path(raw_path);
1048 FileSpec::Resolve (resolved_path);
1049 g_lldb_python_dir.SetCString(resolved_path.c_str());
Greg Claytondd36def2010-10-17 22:03:32 +00001050 }
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001051
1052 if (log)
1053 log->Printf("Host::GetLLDBPath(ePathTypePythonDir) => '%s'", g_lldb_python_dir.GetCString());
1054
Greg Claytondd36def2010-10-17 22:03:32 +00001055 }
1056 file_spec.GetDirectory() = g_lldb_python_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001057 return (bool)file_spec.GetDirectory();
Greg Claytondd36def2010-10-17 22:03:32 +00001058 }
1059 break;
Ed Mastea85d3642013-07-02 19:30:52 +00001060#endif
1061
Greg Clayton4272cc72011-02-02 02:24:04 +00001062 case ePathTypeLLDBSystemPlugins: // System plug-ins directory
1063 {
Michael Sartain3cf443d2013-07-17 00:26:30 +00001064#if defined (__APPLE__) || defined(__linux__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001065 static ConstString g_lldb_system_plugin_dir;
Greg Clayton1cb64962011-03-24 04:28:38 +00001066 static bool g_lldb_system_plugin_dir_located = false;
1067 if (!g_lldb_system_plugin_dir_located)
Greg Clayton4272cc72011-02-02 02:24:04 +00001068 {
Greg Clayton1cb64962011-03-24 04:28:38 +00001069 g_lldb_system_plugin_dir_located = true;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001070#if defined (__APPLE__)
Greg Clayton4272cc72011-02-02 02:24:04 +00001071 FileSpec lldb_file_spec;
1072 if (GetLLDBPath (ePathTypeLLDBShlibDir, lldb_file_spec))
1073 {
1074 char raw_path[PATH_MAX];
Greg Clayton4272cc72011-02-02 02:24:04 +00001075 lldb_file_spec.GetPath(raw_path, sizeof(raw_path));
1076
1077 char *framework_pos = ::strstr (raw_path, "LLDB.framework");
1078 if (framework_pos)
1079 {
1080 framework_pos += strlen("LLDB.framework");
1081 ::strncpy (framework_pos, "/Resources/PlugIns", PATH_MAX - (framework_pos - raw_path));
Jim Inghame1d263e2014-08-07 22:37:43 +00001082 llvm::SmallString<64> resolved_path(raw_path);
1083 FileSpec::Resolve (resolved_path);
1084 g_lldb_system_plugin_dir.SetCString(resolved_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001085 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001086 return false;
Greg Clayton4272cc72011-02-02 02:24:04 +00001087 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001088#elif defined (__linux__)
1089 FileSpec lldb_file_spec("/usr/lib/lldb", true);
1090 if (lldb_file_spec.Exists())
1091 {
1092 g_lldb_system_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
1093 }
1094#endif // __APPLE__ || __linux__
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001095
1096 if (log)
1097 log->Printf("Host::GetLLDBPath(ePathTypeLLDBSystemPlugins) => '%s'", g_lldb_system_plugin_dir.GetCString());
1098
Greg Clayton4272cc72011-02-02 02:24:04 +00001099 }
Greg Clayton1cb64962011-03-24 04:28:38 +00001100
1101 if (g_lldb_system_plugin_dir)
1102 {
1103 file_spec.GetDirectory() = g_lldb_system_plugin_dir;
1104 return true;
1105 }
Michael Sartain3cf443d2013-07-17 00:26:30 +00001106#else
1107 // TODO: where would system LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001108 return false;
Michael Sartain3cf443d2013-07-17 00:26:30 +00001109#endif
Greg Clayton4272cc72011-02-02 02:24:04 +00001110 }
1111 break;
1112
1113 case ePathTypeLLDBUserPlugins: // User plug-ins directory
1114 {
1115#if defined (__APPLE__)
1116 static ConstString g_lldb_user_plugin_dir;
1117 if (!g_lldb_user_plugin_dir)
1118 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001119 llvm::SmallString<64> user_plugin_path("~/Library/Application Support/LLDB/PlugIns");
1120 FileSpec::Resolve (user_plugin_path);
1121 if (user_plugin_path.size())
Greg Clayton4272cc72011-02-02 02:24:04 +00001122 {
Jim Inghame1d263e2014-08-07 22:37:43 +00001123 g_lldb_user_plugin_dir.SetCString(user_plugin_path.c_str());
Greg Clayton4272cc72011-02-02 02:24:04 +00001124 }
1125 }
1126 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001127 return (bool)file_spec.GetDirectory();
Michael Sartain3cf443d2013-07-17 00:26:30 +00001128#elif defined (__linux__)
1129 static ConstString g_lldb_user_plugin_dir;
1130 if (!g_lldb_user_plugin_dir)
1131 {
1132 // XDG Base Directory Specification
1133 // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
1134 // If XDG_DATA_HOME exists, use that, otherwise use ~/.local/share/lldb.
1135 FileSpec lldb_file_spec;
1136 const char *xdg_data_home = getenv("XDG_DATA_HOME");
1137 if (xdg_data_home && xdg_data_home[0])
1138 {
1139 std::string user_plugin_dir (xdg_data_home);
1140 user_plugin_dir += "/lldb";
1141 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1142 }
1143 else
1144 {
1145 const char *home_dir = getenv("HOME");
1146 if (home_dir && home_dir[0])
1147 {
1148 std::string user_plugin_dir (home_dir);
1149 user_plugin_dir += "/.local/share/lldb";
1150 lldb_file_spec.SetFile (user_plugin_dir.c_str(), true);
1151 }
1152 }
1153
1154 if (lldb_file_spec.Exists())
1155 g_lldb_user_plugin_dir.SetCString(lldb_file_spec.GetPath().c_str());
Greg Clayton3bd19fb2013-11-22 18:48:24 +00001156 if (log)
1157 log->Printf("Host::GetLLDBPath(ePathTypeLLDBUserPlugins) => '%s'", g_lldb_user_plugin_dir.GetCString());
Michael Sartain3cf443d2013-07-17 00:26:30 +00001158 }
1159 file_spec.GetDirectory() = g_lldb_user_plugin_dir;
Sean Callananddd7a2a2013-10-03 22:27:29 +00001160 return (bool)file_spec.GetDirectory();
Greg Clayton4272cc72011-02-02 02:24:04 +00001161#endif
Michael Sartain3cf443d2013-07-17 00:26:30 +00001162 // TODO: where would user LLDB plug-ins be located on other systems?
Greg Clayton4272cc72011-02-02 02:24:04 +00001163 return false;
1164 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001165
1166 case ePathTypeLLDBTempSystemDir:
1167 {
1168 static ConstString g_lldb_tmp_dir;
1169 if (!g_lldb_tmp_dir)
1170 {
1171 const char *tmpdir_cstr = getenv("TMPDIR");
1172 if (tmpdir_cstr == NULL)
1173 {
1174 tmpdir_cstr = getenv("TMP");
1175 if (tmpdir_cstr == NULL)
1176 tmpdir_cstr = getenv("TEMP");
1177 }
1178 if (tmpdir_cstr)
1179 {
Greg Clayton23f8c952014-03-24 23:10:19 +00001180 StreamString pid_tmpdir;
1181 pid_tmpdir.Printf("%s/lldb", tmpdir_cstr);
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001182 if (FileSystem::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault)
1183 .Success())
Greg Clayton23f8c952014-03-24 23:10:19 +00001184 {
1185 pid_tmpdir.Printf("/%" PRIu64, Host::GetCurrentProcessID());
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001186 if (FileSystem::MakeDirectory(pid_tmpdir.GetString().c_str(), eFilePermissionsDirectoryDefault)
1187 .Success())
Greg Clayton23f8c952014-03-24 23:10:19 +00001188 {
1189 // Make an atexit handler to clean up the process specify LLDB temp dir
1190 // and all of its contents.
1191 ::atexit (CleanupProcessSpecificLLDBTempDir);
1192 g_lldb_tmp_dir.SetCString(pid_tmpdir.GetString().c_str());
1193 if (log)
1194 log->Printf("Host::GetLLDBPath(ePathTypeLLDBTempSystemDir) => '%s'", g_lldb_tmp_dir.GetCString());
1195
1196 }
1197 }
Greg Claytonc6931fc2013-12-04 18:53:50 +00001198 }
1199 }
1200 file_spec.GetDirectory() = g_lldb_tmp_dir;
1201 return (bool)file_spec.GetDirectory();
1202 }
Greg Claytondd36def2010-10-17 22:03:32 +00001203 }
1204
1205 return false;
1206}
1207
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001208#ifndef _WIN32
1209
Greg Clayton32e0a752011-03-30 18:16:51 +00001210const char *
1211Host::GetUserName (uint32_t uid, std::string &user_name)
1212{
1213 struct passwd user_info;
1214 struct passwd *user_info_ptr = &user_info;
1215 char user_buffer[PATH_MAX];
1216 size_t user_buffer_size = sizeof(user_buffer);
1217 if (::getpwuid_r (uid,
1218 &user_info,
1219 user_buffer,
1220 user_buffer_size,
1221 &user_info_ptr) == 0)
1222 {
1223 if (user_info_ptr)
1224 {
1225 user_name.assign (user_info_ptr->pw_name);
1226 return user_name.c_str();
1227 }
1228 }
1229 user_name.clear();
1230 return NULL;
1231}
1232
1233const char *
1234Host::GetGroupName (uint32_t gid, std::string &group_name)
1235{
1236 char group_buffer[PATH_MAX];
1237 size_t group_buffer_size = sizeof(group_buffer);
1238 struct group group_info;
1239 struct group *group_info_ptr = &group_info;
1240 // Try the threadsafe version first
1241 if (::getgrgid_r (gid,
1242 &group_info,
1243 group_buffer,
1244 group_buffer_size,
1245 &group_info_ptr) == 0)
1246 {
1247 if (group_info_ptr)
1248 {
1249 group_name.assign (group_info_ptr->gr_name);
1250 return group_name.c_str();
1251 }
1252 }
1253 else
1254 {
1255 // The threadsafe version isn't currently working
1256 // for me on darwin, but the non-threadsafe version
1257 // is, so I am calling it below.
1258 group_info_ptr = ::getgrgid (gid);
1259 if (group_info_ptr)
1260 {
1261 group_name.assign (group_info_ptr->gr_name);
1262 return group_name.c_str();
1263 }
1264 }
1265 group_name.clear();
1266 return NULL;
1267}
1268
Han Ming Ong84647042012-02-25 01:07:38 +00001269uint32_t
1270Host::GetUserID ()
1271{
1272 return getuid();
1273}
1274
1275uint32_t
1276Host::GetGroupID ()
1277{
1278 return getgid();
1279}
1280
1281uint32_t
1282Host::GetEffectiveUserID ()
1283{
1284 return geteuid();
1285}
1286
1287uint32_t
1288Host::GetEffectiveGroupID ()
1289{
1290 return getegid();
1291}
1292
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001293#endif
1294
Zachary Turner310035a2014-07-08 04:52:15 +00001295#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) \
1296 && !defined(__linux__) && !defined(_WIN32)
Greg Claytone996fd32011-03-08 22:40:15 +00001297uint32_t
Greg Clayton8b82f082011-04-12 05:54:46 +00001298Host::FindProcesses (const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos)
Greg Claytone996fd32011-03-08 22:40:15 +00001299{
1300 process_infos.Clear();
Greg Claytone996fd32011-03-08 22:40:15 +00001301 return process_infos.GetSize();
Greg Clayton2bddd342010-09-07 20:11:56 +00001302}
1303
Greg Claytone996fd32011-03-08 22:40:15 +00001304bool
Greg Clayton8b82f082011-04-12 05:54:46 +00001305Host::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
Greg Clayton2bddd342010-09-07 20:11:56 +00001306{
Greg Claytone996fd32011-03-08 22:40:15 +00001307 process_info.Clear();
1308 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001309}
Johnny Chen8f3d8382011-08-02 20:52:42 +00001310#endif
Greg Clayton2bddd342010-09-07 20:11:56 +00001311
Matt Kopec085d6ce2013-05-31 22:00:07 +00001312#if !defined(__linux__)
1313bool
1314Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
1315{
1316 return false;
1317}
1318#endif
1319
Sean Callananc0a6e062011-10-27 21:22:25 +00001320lldb::TargetSP
1321Host::GetDummyTarget (lldb_private::Debugger &debugger)
1322{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001323 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001324
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001325 // FIXME: Maybe the dummy target should be per-Debugger
1326 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
1327 {
1328 ArchSpec arch(Target::GetDefaultArchitecture());
1329 if (!arch.IsValid())
Zachary Turner13b18262014-08-20 16:42:51 +00001330 arch = HostInfo::GetArchitecture();
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001331 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +00001332 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001333 arch.GetTriple().getTriple().c_str(),
1334 false,
1335 NULL,
1336 g_dummy_target_sp);
1337 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +00001338
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +00001339 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +00001340}
1341
Greg Claytond1cf11a2012-04-14 01:42:46 +00001342struct ShellInfo
1343{
1344 ShellInfo () :
1345 process_reaped (false),
1346 can_delete (false),
1347 pid (LLDB_INVALID_PROCESS_ID),
1348 signo(-1),
1349 status(-1)
1350 {
1351 }
1352
1353 lldb_private::Predicate<bool> process_reaped;
1354 lldb_private::Predicate<bool> can_delete;
1355 lldb::pid_t pid;
1356 int signo;
1357 int status;
1358};
1359
1360static bool
1361MonitorShellCommand (void *callback_baton,
1362 lldb::pid_t pid,
1363 bool exited, // True if the process did exit
1364 int signo, // Zero for no signal
1365 int status) // Exit value of process if signal is zero
1366{
1367 ShellInfo *shell_info = (ShellInfo *)callback_baton;
1368 shell_info->pid = pid;
1369 shell_info->signo = signo;
1370 shell_info->status = status;
1371 // Let the thread running Host::RunShellCommand() know that the process
1372 // exited and that ShellInfo has been filled in by broadcasting to it
1373 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
1374 // Now wait for a handshake back from that thread running Host::RunShellCommand
1375 // so we know that we can delete shell_info_ptr
1376 shell_info->can_delete.WaitForValueEqualTo(true);
1377 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
1378 usleep(1000);
1379 // Now delete the shell info that was passed into this function
1380 delete shell_info;
1381 return true;
1382}
1383
1384Error
1385Host::RunShellCommand (const char *command,
1386 const char *working_dir,
1387 int *status_ptr,
1388 int *signo_ptr,
1389 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +00001390 uint32_t timeout_sec,
1391 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +00001392{
1393 Error error;
1394 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +00001395 if (shell && shell[0])
1396 {
1397 // Run the command in a shell
1398 launch_info.SetShell(shell);
1399 launch_info.GetArguments().AppendArgument(command);
1400 const bool localhost = true;
1401 const bool will_debug = false;
1402 const bool first_arg_is_full_shell_command = true;
1403 launch_info.ConvertArgumentsForLaunchingInShell (error,
1404 localhost,
1405 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +00001406 first_arg_is_full_shell_command,
1407 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001408 }
1409 else
1410 {
1411 // No shell, just run it
1412 Args args (command);
1413 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +00001414 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001415 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001416
1417 if (working_dir)
1418 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +00001419 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +00001420 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +00001421
Greg Claytond1cf11a2012-04-14 01:42:46 +00001422 if (command_output_ptr)
1423 {
1424 // Create a temporary file to get the stdout/stderr and redirect the
1425 // output of the command into this file. We will later read this file
1426 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +00001427 FileSpec tmpdir_file_spec;
1428 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
1429 {
1430 tmpdir_file_spec.GetFilename().SetCString("lldb-shell-output.XXXXXX");
1431 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
1432 }
1433 else
1434 {
1435 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
1436 }
1437
1438 output_file_path = ::mktemp(output_file_path_buffer);
1439 }
1440
1441 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1442 if (output_file_path)
1443 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001444 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +00001445 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001446 }
1447 else
1448 {
Greg Claytond1cf11a2012-04-14 01:42:46 +00001449 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1450 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
1451 }
1452
1453 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +00001454 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +00001455
1456 const bool monitor_signals = false;
1457 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
1458
1459 error = LaunchProcess (launch_info);
1460 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +00001461
1462 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
1463 error.SetErrorString("failed to get process ID");
1464
1465 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +00001466 {
1467 // The process successfully launched, so we can defer ownership of
1468 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +00001469 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +00001470 // doesn't need to delete the ShellInfo anymore.
1471 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +00001472 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +00001473 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001474 if (timeout_sec > 0) {
1475 timeout_time.OffsetWithSeconds(timeout_sec);
1476 timeout_ptr = &timeout_time;
1477 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001478 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001479 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001480 if (timed_out)
1481 {
1482 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001483
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +00001484 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001485 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +00001486 // Wait for the monitor callback to get the message
1487 timeout_time = TimeValue::Now();
1488 timeout_time.OffsetWithSeconds(1);
1489 timed_out = false;
1490 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
1491 }
1492 else
1493 {
1494 if (status_ptr)
1495 *status_ptr = shell_info->status;
1496
1497 if (signo_ptr)
1498 *signo_ptr = shell_info->signo;
1499
1500 if (command_output_ptr)
1501 {
1502 command_output_ptr->clear();
1503 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
1504 uint64_t file_size = file_spec.GetByteSize();
1505 if (file_size > 0)
1506 {
1507 if (file_size > command_output_ptr->max_size())
1508 {
1509 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
1510 }
1511 else
1512 {
1513 command_output_ptr->resize(file_size);
1514 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
1515 }
1516 }
1517 }
1518 }
1519 shell_info->can_delete.SetValue(true, eBroadcastAlways);
1520 }
Greg Claytond1cf11a2012-04-14 01:42:46 +00001521
1522 if (output_file_path)
1523 ::unlink (output_file_path);
1524 // Handshake with the monitor thread, or just let it know in advance that
1525 // it can delete "shell_info" in case we timed out and were not able to kill
1526 // the process...
1527 return error;
1528}
1529
Daniel Malea4244cbd2013-08-27 20:58:59 +00001530
Todd Fiala76747122014-01-23 00:52:28 +00001531// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
1532// systems
1533
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001534#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001535
1536// this method needs to be visible to macosx/Host.cpp and
1537// common/Host.cpp.
1538
1539short
1540Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
1541{
1542 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1543
1544#if defined (__APPLE__)
1545 if (launch_info.GetFlags().Test (eLaunchFlagExec))
1546 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
1547
1548 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
1549 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
1550
1551 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
1552 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
1553
1554 if (launch_info.GetLaunchInSeparateProcessGroup())
1555 flags |= POSIX_SPAWN_SETPGROUP;
1556
1557#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
1558#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
1559 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
1560 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
1561 {
1562 g_use_close_on_exec_flag = eLazyBoolNo;
1563
1564 uint32_t major, minor, update;
Zachary Turner97a14e62014-08-19 17:18:29 +00001565 if (HostInfo::GetOSVersion(major, minor, update))
Todd Fiala76747122014-01-23 00:52:28 +00001566 {
1567 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
1568 if (major > 10 || (major == 10 && minor > 7))
1569 {
1570 // Only enable for 10.8 and later OS versions
1571 g_use_close_on_exec_flag = eLazyBoolYes;
1572 }
1573 }
1574 }
1575#else
1576 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
1577#endif
1578 // Close all files exception those with file actions if this is supported.
1579 if (g_use_close_on_exec_flag == eLazyBoolYes)
1580 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
1581#endif
1582#endif // #if defined (__APPLE__)
1583 return flags;
1584}
1585
1586Error
1587Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001588{
1589 Error error;
1590 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
1591
Daniel Malea4244cbd2013-08-27 20:58:59 +00001592 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +00001593 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001594
1595 if (error.Fail() || log)
1596 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001597 if (error.Fail())
1598 return error;
1599
1600 // Make a quick class that will cleanup the posix spawn attributes in case
1601 // we return in the middle of this function.
1602 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
1603
1604 sigset_t no_signals;
1605 sigset_t all_signals;
1606 sigemptyset (&no_signals);
1607 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001608 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +00001609#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001610 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001611#else
1612 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1613#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001614
Todd Fiala76747122014-01-23 00:52:28 +00001615 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001616
1617 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +00001618 if (error.Fail() || log)
1619 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001620 if (error.Fail())
1621 return error;
1622
Todd Fiala76747122014-01-23 00:52:28 +00001623 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1624 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1625#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +00001626
1627 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
1628 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
1629 // to do that job on OSX.
1630
1631 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001632 {
Jim Ingham90331d52014-02-21 01:25:21 +00001633 // We don't need to do this for ARM, and we really shouldn't now that we
1634 // have multiple CPU subtypes and no posix_spawnattr call that allows us
1635 // to set which CPU subtype to launch...
1636 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1637 cpu_type_t cpu = arch_spec.GetMachOCPUType();
1638 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1639 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +00001640 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1641 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +00001642 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1643 {
1644 size_t ocount = 0;
1645 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1646 if (error.Fail() || log)
1647 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 +00001648
Jim Ingham90331d52014-02-21 01:25:21 +00001649 if (error.Fail() || ocount != 1)
1650 return error;
1651 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001652 }
1653
Todd Fiala76747122014-01-23 00:52:28 +00001654#endif
1655
1656 const char *tmp_argv[2];
1657 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1658 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1659 if (argv == NULL)
1660 {
1661 // posix_spawn gets very unhappy if it doesn't have at least the program
1662 // name in argv[0]. One of the side affects I have noticed is the environment
1663 // variables don't make it into the child process if "argv == NULL"!!!
1664 tmp_argv[0] = exe_path;
1665 tmp_argv[1] = NULL;
1666 argv = (char * const*)tmp_argv;
1667 }
1668
1669#if !defined (__APPLE__)
1670 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +00001671 char current_dir[PATH_MAX];
1672 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +00001673#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001674
1675 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +00001676 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001677 {
Todd Fiala76747122014-01-23 00:52:28 +00001678#if defined (__APPLE__)
1679 // Set the working directory on this thread only
1680 if (__pthread_chdir (working_dir) < 0) {
1681 if (errno == ENOENT) {
1682 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1683 } else if (errno == ENOTDIR) {
1684 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1685 } else {
1686 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1687 }
1688 return error;
1689 }
1690#else
Daniel Malea4244cbd2013-08-27 20:58:59 +00001691 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1692 {
1693 error.SetError(errno, eErrorTypePOSIX);
1694 error.LogIfError(log, "unable to save the current directory");
1695 return error;
1696 }
1697
1698 if (::chdir(working_dir) == -1)
1699 {
1700 error.SetError(errno, eErrorTypePOSIX);
1701 error.LogIfError(log, "unable to change working directory to %s", working_dir);
1702 return error;
1703 }
Todd Fiala76747122014-01-23 00:52:28 +00001704#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001705 }
1706
Todd Fiala76747122014-01-23 00:52:28 +00001707 const size_t num_file_actions = launch_info.GetNumFileActions ();
1708 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001709 {
Todd Fiala76747122014-01-23 00:52:28 +00001710 posix_spawn_file_actions_t file_actions;
1711 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1712 if (error.Fail() || log)
1713 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1714 if (error.Fail())
1715 return error;
1716
1717 // Make a quick class that will cleanup the posix spawn attributes in case
1718 // we return in the middle of this function.
1719 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1720
1721 for (size_t i=0; i<num_file_actions; ++i)
1722 {
Zachary Turner696b5282014-08-14 16:01:25 +00001723 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +00001724 if (launch_file_action)
1725 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001726 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
Todd Fiala76747122014-01-23 00:52:28 +00001727 return error;
1728 }
1729 }
1730
1731 error.SetError (::posix_spawnp (&pid,
1732 exe_path,
1733 &file_actions,
1734 &attr,
1735 argv,
1736 envp),
1737 eErrorTypePOSIX);
1738
1739 if (error.Fail() || log)
1740 {
1741 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 +00001742 pid, exe_path, static_cast<void*>(&file_actions),
1743 static_cast<void*>(&attr),
1744 reinterpret_cast<const void*>(argv),
1745 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001746 if (log)
1747 {
1748 for (int ii=0; argv[ii]; ++ii)
1749 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1750 }
1751 }
1752
1753 }
1754 else
1755 {
1756 error.SetError (::posix_spawnp (&pid,
1757 exe_path,
1758 NULL,
1759 &attr,
1760 argv,
1761 envp),
1762 eErrorTypePOSIX);
1763
1764 if (error.Fail() || log)
1765 {
1766 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 +00001767 pid, exe_path, static_cast<void*>(&attr),
1768 reinterpret_cast<const void*>(argv),
1769 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +00001770 if (log)
1771 {
1772 for (int ii=0; argv[ii]; ++ii)
1773 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1774 }
1775 }
Daniel Malea4244cbd2013-08-27 20:58:59 +00001776 }
1777
Todd Fiala76747122014-01-23 00:52:28 +00001778 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001779 {
Todd Fiala76747122014-01-23 00:52:28 +00001780#if defined (__APPLE__)
1781 // No more thread specific current working directory
1782 __pthread_fchdir (-1);
1783#else
1784 if (::chdir(current_dir) == -1 && error.Success())
1785 {
1786 error.SetError(errno, eErrorTypePOSIX);
1787 error.LogIfError(log, "unable to change current directory back to %s",
1788 current_dir);
1789 }
1790#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +00001791 }
1792
1793 return error;
1794}
1795
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001796bool
1797Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
Zachary Turner696b5282014-08-14 16:01:25 +00001798{
1799 if (info == NULL)
1800 return false;
1801
1802 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
1803
1804 switch (info->GetAction())
1805 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001806 case FileAction::eFileActionNone:
1807 error.Clear();
1808 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001809
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001810 case FileAction::eFileActionClose:
1811 if (info->GetFD() == -1)
1812 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
1813 else
1814 {
1815 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
1816 if (log && (error.Fail() || log))
1817 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
1818 static_cast<void *>(file_actions), info->GetFD());
1819 }
1820 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001821
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001822 case FileAction::eFileActionDuplicate:
1823 if (info->GetFD() == -1)
1824 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
1825 else if (info->GetActionArgument() == -1)
1826 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
1827 else
1828 {
1829 error.SetError(
1830 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
1831 eErrorTypePOSIX);
1832 if (log && (error.Fail() || log))
1833 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
1834 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
1835 }
1836 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001837
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001838 case FileAction::eFileActionOpen:
1839 if (info->GetFD() == -1)
1840 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
1841 else
1842 {
1843 int oflag = info->GetActionArgument();
Zachary Turner696b5282014-08-14 16:01:25 +00001844
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001845 mode_t mode = 0;
Zachary Turner696b5282014-08-14 16:01:25 +00001846
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001847 if (oflag & O_CREAT)
1848 mode = 0640;
Zachary Turner696b5282014-08-14 16:01:25 +00001849
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001850 error.SetError(
1851 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
1852 eErrorTypePOSIX);
1853 if (error.Fail() || log)
1854 error.PutToLog(log,
1855 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
1856 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
1857 }
1858 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001859 }
1860 return error.Success();
1861}
1862
Todd Fiala76747122014-01-23 00:52:28 +00001863#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1864
1865
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001866#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
1867// The functions below implement process launching via posix_spawn() for Linux,
1868// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001869
1870Error
1871Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1872{
1873 Error error;
1874 char exe_path[PATH_MAX];
1875
1876 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1877
1878 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1879
1880 FileSpec exe_spec(launch_info.GetExecutableFile());
1881
1882 FileSpec::FileType file_type = exe_spec.GetFileType();
1883 if (file_type != FileSpec::eFileTypeRegular)
1884 {
1885 lldb::ModuleSP exe_module_sp;
1886 error = host_platform_sp->ResolveExecutable (exe_spec,
1887 arch_spec,
1888 exe_module_sp,
1889 NULL);
1890
1891 if (error.Fail())
1892 return error;
1893
1894 if (exe_module_sp)
1895 exe_spec = exe_module_sp->GetFileSpec();
1896 }
1897
1898 if (exe_spec.Exists())
1899 {
1900 exe_spec.GetPath (exe_path, sizeof(exe_path));
1901 }
1902 else
1903 {
1904 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1905 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1906 return error;
1907 }
1908
1909 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1910
1911 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1912
1913 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1914
1915 if (pid != LLDB_INVALID_PROCESS_ID)
1916 {
1917 // If all went well, then set the process ID into the launch info
1918 launch_info.SetProcessID(pid);
1919
Todd Fiala76747122014-01-23 00:52:28 +00001920 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1921
Daniel Malea4244cbd2013-08-27 20:58:59 +00001922 // Make sure we reap any processes we spawn or we will have zombies.
1923 if (!launch_info.MonitorProcess())
1924 {
1925 const bool monitor_signals = false;
1926 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1927 NULL,
1928 pid,
1929 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001930 if (log)
1931 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
1932 }
1933 else
1934 {
1935 if (log)
1936 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001937 }
1938 }
1939 else
1940 {
1941 // Invalid process ID, something didn't go well
1942 if (error.Success())
1943 error.SetErrorString ("process launch failed for unknown reasons");
1944 }
1945 return error;
1946}
1947
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001948#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001949
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001950#ifndef _WIN32
1951
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001952void
1953Host::Kill(lldb::pid_t pid, int signo)
1954{
1955 ::kill(pid, signo);
1956}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001957
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001958#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001959
Johnny Chen8f3d8382011-08-02 20:52:42 +00001960#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001961bool
Greg Clayton3b147632010-12-18 01:54:34 +00001962Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001963{
1964 return false;
1965}
Greg Claytondd36def2010-10-17 22:03:32 +00001966
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001967void
1968Host::SetCrashDescriptionWithFormat (const char *format, ...)
1969{
1970}
1971
1972void
1973Host::SetCrashDescription (const char *description)
1974{
1975}
Greg Claytondd36def2010-10-17 22:03:32 +00001976
1977lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001978Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001979{
1980 return LLDB_INVALID_PROCESS_ID;
1981}
1982
Greg Claytonfbb76342013-11-20 21:07:01 +00001983#endif