blob: f7c1ac66b76d0a814cfabf9b7eba60283c41310f [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
Greg Claytone3e3fee2013-02-17 20:46:30 +000010// C includes
Greg Claytone3e3fee2013-02-17 20:46:30 +000011#include <errno.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000012#include <limits.h>
Greg Clayton23f8c952014-03-24 23:10:19 +000013#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000014#include <sys/types.h>
Zachary Turnercb37ddd2014-10-15 17:27:11 +000015#ifndef _WIN32
Deepak Panickalb36da432014-01-13 14:55:15 +000016#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000017#include <dlfcn.h>
18#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000019#include <netdb.h>
20#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000021#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000022#endif
23
Greg Claytone3e3fee2013-02-17 20:46:30 +000024#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000025#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000026#include <mach/mach_init.h>
27#include <mach-o/dyld.h>
Ed Maste8b006c62013-06-25 18:58:11 +000028#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000029
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +000030#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
Shawn Best8da0bf32014-11-08 01:41:49 +000031#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000032#include <spawn.h>
Todd Fialacacde7d2014-09-27 16:54:22 +000033#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000034#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000035#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000036#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000037
Ed Maste8b006c62013-06-25 18:58:11 +000038#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000039#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000040#endif
41
Todd Fiala17096d72014-07-16 19:03:16 +000042// C++ includes
43#include <limits>
44
Zachary Turner270e99a2014-12-08 21:36:42 +000045#include "lldb/Host/FileSystem.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000046#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000047#include "lldb/Host/HostInfo.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000048#include "lldb/Core/ArchSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000049#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000050#include "lldb/Core/Log.h"
Greg Claytone996fd32011-03-08 22:40:15 +000051#include "lldb/Host/FileSpec.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000052#include "lldb/Host/HostProcess.h"
53#include "lldb/Host/MonitoringProcessLauncher.h"
Vince Harron76861ea2015-01-16 06:47:43 +000054#include "lldb/Host/Predicate.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000055#include "lldb/Host/ProcessLauncher.h"
Zachary Turner39de3112014-09-09 20:54:56 +000056#include "lldb/Host/ThreadLauncher.h"
Todd Fiala4ceced32014-08-29 17:35:57 +000057#include "lldb/lldb-private-forward.h"
Vince Harron76861ea2015-01-16 06:47:43 +000058#include "llvm/Support/FileSystem.h"
Zachary Turner696b5282014-08-14 16:01:25 +000059#include "lldb/Target/FileAction.h"
Zachary Turner696b5282014-08-14 16:01:25 +000060#include "lldb/Target/ProcessLaunchInfo.h"
Vince Harron76861ea2015-01-16 06:47:43 +000061#include "lldb/Target/UnixSignals.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000062#include "lldb/Utility/CleanUp.h"
Vince Harron76861ea2015-01-16 06:47:43 +000063#include "llvm/ADT/SmallString.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000064
Zachary Turner172d37d2014-10-14 21:55:08 +000065#if defined(_WIN32)
66#include "lldb/Host/windows/ProcessLauncherWindows.h"
Tamas Berghammer00e305d2015-02-12 18:13:44 +000067#elif defined(__ANDROID__) || defined(__ANDROID_NDK__)
68#include "lldb/Host/android/ProcessLauncherAndroid.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000069#else
70#include "lldb/Host/posix/ProcessLauncherPosix.h"
71#endif
72
Todd Fiala76747122014-01-23 00:52:28 +000073#if defined (__APPLE__)
74#ifndef _POSIX_SPAWN_DISABLE_ASLR
75#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
76#endif
77
78extern "C"
79{
80 int __pthread_chdir(const char *path);
81 int __pthread_fchdir (int fildes);
82}
83
84#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000085
Greg Clayton2bddd342010-09-07 20:11:56 +000086using namespace lldb;
87using namespace lldb_private;
88
Virgile Bellob2f1fb22013-08-23 12:44:05 +000089#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000090struct MonitorInfo
91{
92 lldb::pid_t pid; // The process ID to monitor
93 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
94 void *callback_baton; // The callback baton for the callback function
95 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
96};
97
Virgile Bellob2f1fb22013-08-23 12:44:05 +000098static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +000099MonitorChildProcessThreadFunction (void *arg);
100
Zachary Turner39de3112014-09-09 20:54:56 +0000101HostThread
102Host::StartMonitoringChildProcess(Host::MonitorChildProcessCallback callback, void *callback_baton, lldb::pid_t pid, bool monitor_signals)
Greg Clayton2bddd342010-09-07 20:11:56 +0000103{
Greg Claytone4e45922011-11-16 05:37:56 +0000104 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000105
Greg Claytone4e45922011-11-16 05:37:56 +0000106 info_ptr->pid = pid;
107 info_ptr->callback = callback;
108 info_ptr->callback_baton = callback_baton;
109 info_ptr->monitor_signals = monitor_signals;
110
111 char thread_name[256];
Zachary Turner39de3112014-09-09 20:54:56 +0000112 ::snprintf(thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
113 return ThreadLauncher::LaunchThread(thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL);
Greg Clayton2bddd342010-09-07 20:11:56 +0000114}
115
Shawn Best8da0bf32014-11-08 01:41:49 +0000116#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000117//------------------------------------------------------------------
118// Scoped class that will disable thread canceling when it is
119// constructed, and exception safely restore the previous value it
120// when it goes out of scope.
121//------------------------------------------------------------------
122class ScopedPThreadCancelDisabler
123{
124public:
125 ScopedPThreadCancelDisabler()
126 {
127 // Disable the ability for this thread to be cancelled
128 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
129 if (err != 0)
130 m_old_state = -1;
Greg Clayton2bddd342010-09-07 20:11:56 +0000131 }
132
133 ~ScopedPThreadCancelDisabler()
134 {
135 // Restore the ability for this thread to be cancelled to what it
136 // previously was.
137 if (m_old_state != -1)
138 ::pthread_setcancelstate (m_old_state, 0);
139 }
140private:
141 int m_old_state; // Save the old cancelability state.
142};
Shawn Best8da0bf32014-11-08 01:41:49 +0000143#endif // __ANDROID_NDK__
Greg Clayton2bddd342010-09-07 20:11:56 +0000144
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000145static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000146MonitorChildProcessThreadFunction (void *arg)
147{
Greg Clayton5160ce52013-03-27 23:08:40 +0000148 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000149 const char *function = __FUNCTION__;
150 if (log)
151 log->Printf ("%s (arg = %p) thread starting...", function, arg);
152
153 MonitorInfo *info = (MonitorInfo *)arg;
154
155 const Host::MonitorChildProcessCallback callback = info->callback;
156 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000157 const bool monitor_signals = info->monitor_signals;
158
Daniel Malea4244cbd2013-08-27 20:58:59 +0000159 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000160 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000161
Greg Clayton2bddd342010-09-07 20:11:56 +0000162 delete info;
163
164 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000165#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000166 #define __WALL 0
167#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000168 const int options = __WALL;
169
Greg Clayton2bddd342010-09-07 20:11:56 +0000170 while (1)
171 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000172 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000173 if (log)
Vince Harronb956a812015-01-23 22:48:28 +0000174 log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000175
176 // Wait for all child processes
Shawn Best8da0bf32014-11-08 01:41:49 +0000177#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000178 ::pthread_testcancel ();
Todd Fialacacde7d2014-09-27 16:54:22 +0000179#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000180 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000181 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Shawn Best8da0bf32014-11-08 01:41:49 +0000182#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000183 ::pthread_testcancel ();
Todd Fialacacde7d2014-09-27 16:54:22 +0000184#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000185 if (wait_pid == -1)
186 {
187 if (errno == EINTR)
188 continue;
189 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000190 {
191 if (log)
192 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000193 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000194 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000195 }
Matt Kopec650648f2013-01-08 16:30:18 +0000196 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000197 {
198 bool exited = false;
199 int signal = 0;
200 int exit_status = 0;
201 const char *status_cstr = NULL;
202 if (WIFSTOPPED(status))
203 {
204 signal = WSTOPSIG(status);
205 status_cstr = "STOPPED";
206 }
207 else if (WIFEXITED(status))
208 {
209 exit_status = WEXITSTATUS(status);
210 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000211 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000212 }
213 else if (WIFSIGNALED(status))
214 {
215 signal = WTERMSIG(status);
216 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000217 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000218 exited = true;
219 exit_status = -1;
220 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000221 }
222 else
223 {
Johnny Chen44805302011-07-19 19:48:13 +0000224 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000225 }
226
227 // Scope for pthread_cancel_disabler
228 {
Shawn Best8da0bf32014-11-08 01:41:49 +0000229#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000230 ScopedPThreadCancelDisabler pthread_cancel_disabler;
Todd Fialacacde7d2014-09-27 16:54:22 +0000231#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000232
Caroline Tice20ad3c42010-10-29 21:48:37 +0000233 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000234 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000235 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 +0000236 function,
Greg Clayton2bddd342010-09-07 20:11:56 +0000237 pid,
Vince Harronb956a812015-01-23 22:48:28 +0000238 options,
239 wait_pid,
Greg Clayton2bddd342010-09-07 20:11:56 +0000240 status,
241 status_cstr,
242 signal,
243 exit_status);
244
245 if (exited || (signal != 0 && monitor_signals))
246 {
Greg Claytone4e45922011-11-16 05:37:56 +0000247 bool callback_return = false;
248 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000249 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000250
251 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000252 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000253 {
254 if (log)
255 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000256 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000257 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 // If the callback returns true, it means this process should
259 // exit
260 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000261 {
262 if (log)
263 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000264 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000265 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000266 }
267 }
268 }
269 }
270
Caroline Tice20ad3c42010-10-29 21:48:37 +0000271 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000272 if (log)
273 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
274
275 return NULL;
276}
277
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000278#endif // #if !defined (__APPLE__) && !defined (_WIN32)
279
280#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000281
282void
283Host::SystemLog (SystemLogType type, const char *format, va_list args)
284{
285 vfprintf (stderr, format, args);
286}
287
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000288#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000289
Greg Claytone38a5ed2012-01-05 03:57:59 +0000290void
291Host::SystemLog (SystemLogType type, const char *format, ...)
292{
293 va_list args;
294 va_start (args, format);
295 SystemLog (type, format, args);
296 va_end (args);
297}
298
Greg Clayton2bddd342010-09-07 20:11:56 +0000299lldb::pid_t
300Host::GetCurrentProcessID()
301{
302 return ::getpid();
303}
304
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000305#ifndef _WIN32
306
Greg Clayton2bddd342010-09-07 20:11:56 +0000307lldb::tid_t
308Host::GetCurrentThreadID()
309{
310#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000311 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000312 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
313 // count.
314 thread_port_t thread_self = mach_thread_self();
315 mach_port_deallocate(mach_task_self(), thread_self);
316 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000317#elif defined(__FreeBSD__)
318 return lldb::tid_t(pthread_getthreadid_np());
Shawn Best8da0bf32014-11-08 01:41:49 +0000319#elif defined(__ANDROID_NDK__)
320 return lldb::tid_t(gettid());
Michael Sartainc2052432013-08-01 18:51:08 +0000321#elif defined(__linux__)
322 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000323#else
324 return lldb::tid_t(pthread_self());
325#endif
326}
327
Jim Ingham372787f2012-04-07 00:00:41 +0000328lldb::thread_t
329Host::GetCurrentThread ()
330{
331 return lldb::thread_t(pthread_self());
332}
333
Greg Clayton2bddd342010-09-07 20:11:56 +0000334const char *
335Host::GetSignalAsCString (int signo)
336{
337 switch (signo)
338 {
339 case SIGHUP: return "SIGHUP"; // 1 hangup
340 case SIGINT: return "SIGINT"; // 2 interrupt
341 case SIGQUIT: return "SIGQUIT"; // 3 quit
342 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
343 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
344 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000345#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000346#if !defined(SIGIO) || (SIGPOLL != SIGIO)
347// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
348// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000349 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000350#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000351#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000352#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000353 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000354#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000355 case SIGFPE: return "SIGFPE"; // 8 floating point exception
356 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
357 case SIGBUS: return "SIGBUS"; // 10 bus error
358 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
359 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
360 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
361 case SIGALRM: return "SIGALRM"; // 14 alarm clock
362 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
363 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
364 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
365 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
366 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
367 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
368 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
369 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000370#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000371 case SIGIO: return "SIGIO"; // 23 input/output possible signal
372#endif
373 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
374 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
375 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
376 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000377#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000378 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000379#endif
380#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000381 case SIGINFO: return "SIGINFO"; // 29 information request
382#endif
383 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
384 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
385 default:
386 break;
387 }
388 return NULL;
389}
390
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000391#endif
392
Greg Clayton2bddd342010-09-07 20:11:56 +0000393void
394Host::WillTerminate ()
395{
396}
397
Sylvestre Ledru59405832013-07-01 08:21:36 +0000398#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000399
Greg Clayton2bddd342010-09-07 20:11:56 +0000400void
Greg Claytone5219662010-12-03 06:02:24 +0000401Host::Backtrace (Stream &strm, uint32_t max_frames)
402{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000403 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000404}
405
Greg Clayton85851dd2010-12-04 00:10:17 +0000406size_t
407Host::GetEnvironment (StringList &env)
408{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000409 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000410 return 0;
411}
412
Sylvestre Ledru59405832013-07-01 08:21:36 +0000413#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000414
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000415#ifndef _WIN32
416
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000417lldb::thread_key_t
418Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
419{
420 pthread_key_t key;
421 ::pthread_key_create (&key, callback);
422 return key;
423}
424
425void*
426Host::ThreadLocalStorageGet(lldb::thread_key_t key)
427{
428 return ::pthread_getspecific (key);
429}
430
431void
432Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
433{
434 ::pthread_setspecific (key, value);
435}
436
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000437#endif
438
Greg Clayton2bddd342010-09-07 20:11:56 +0000439#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000440
441bool
442Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
443{
444 bundle.Clear();
445 return false;
446}
447
Greg Clayton2bddd342010-09-07 20:11:56 +0000448bool
Greg Claytondd36def2010-10-17 22:03:32 +0000449Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000450{
Greg Claytondd36def2010-10-17 22:03:32 +0000451 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000452}
453#endif
454
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000455#ifndef _WIN32
456
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000457FileSpec
458Host::GetModuleFileSpecForHostAddress (const void *host_addr)
459{
460 FileSpec module_filespec;
Shawn Best8da0bf32014-11-08 01:41:49 +0000461#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000462 Dl_info info;
463 if (::dladdr (host_addr, &info))
464 {
465 if (info.dli_fname)
466 module_filespec.SetFile(info.dli_fname, true);
467 }
Todd Fialacacde7d2014-09-27 16:54:22 +0000468#else
469 assert(false && "dladdr() not supported on Android");
470#endif
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000471 return module_filespec;
472}
473
474#endif
475
Matt Kopec085d6ce2013-05-31 22:00:07 +0000476#if !defined(__linux__)
477bool
478Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
479{
480 return false;
481}
482#endif
483
Greg Claytond1cf11a2012-04-14 01:42:46 +0000484struct ShellInfo
485{
486 ShellInfo () :
487 process_reaped (false),
488 can_delete (false),
489 pid (LLDB_INVALID_PROCESS_ID),
490 signo(-1),
491 status(-1)
492 {
493 }
494
495 lldb_private::Predicate<bool> process_reaped;
496 lldb_private::Predicate<bool> can_delete;
497 lldb::pid_t pid;
498 int signo;
499 int status;
500};
501
502static bool
503MonitorShellCommand (void *callback_baton,
504 lldb::pid_t pid,
505 bool exited, // True if the process did exit
506 int signo, // Zero for no signal
507 int status) // Exit value of process if signal is zero
508{
509 ShellInfo *shell_info = (ShellInfo *)callback_baton;
510 shell_info->pid = pid;
511 shell_info->signo = signo;
512 shell_info->status = status;
513 // Let the thread running Host::RunShellCommand() know that the process
514 // exited and that ShellInfo has been filled in by broadcasting to it
515 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
516 // Now wait for a handshake back from that thread running Host::RunShellCommand
517 // so we know that we can delete shell_info_ptr
518 shell_info->can_delete.WaitForValueEqualTo(true);
519 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
520 usleep(1000);
521 // Now delete the shell info that was passed into this function
522 delete shell_info;
523 return true;
524}
525
526Error
527Host::RunShellCommand (const char *command,
528 const char *working_dir,
529 int *status_ptr,
530 int *signo_ptr,
531 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +0000532 uint32_t timeout_sec,
Zachary Turner10687b02014-10-20 17:46:43 +0000533 bool run_in_default_shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +0000534{
535 Error error;
536 ProcessLaunchInfo launch_info;
Zachary Turner270e99a2014-12-08 21:36:42 +0000537 launch_info.SetArchitecture(HostInfo::GetArchitecture());
Zachary Turner10687b02014-10-20 17:46:43 +0000538 if (run_in_default_shell)
Greg Claytonc8f814d2012-09-27 03:13:55 +0000539 {
540 // Run the command in a shell
Zachary Turner10687b02014-10-20 17:46:43 +0000541 launch_info.SetShell(HostInfo::GetDefaultShell());
Greg Claytonc8f814d2012-09-27 03:13:55 +0000542 launch_info.GetArguments().AppendArgument(command);
543 const bool localhost = true;
544 const bool will_debug = false;
545 const bool first_arg_is_full_shell_command = true;
546 launch_info.ConvertArgumentsForLaunchingInShell (error,
547 localhost,
548 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000549 first_arg_is_full_shell_command,
550 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000551 }
552 else
553 {
554 // No shell, just run it
555 Args args (command);
556 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +0000557 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000558 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000559
560 if (working_dir)
561 launch_info.SetWorkingDirectory(working_dir);
Zachary Turner270e99a2014-12-08 21:36:42 +0000562 llvm::SmallString<PATH_MAX> output_file_path;
563
Greg Claytond1cf11a2012-04-14 01:42:46 +0000564 if (command_output_ptr)
565 {
566 // Create a temporary file to get the stdout/stderr and redirect the
567 // output of the command into this file. We will later read this file
568 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +0000569 FileSpec tmpdir_file_spec;
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000570 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
Greg Claytonc6931fc2013-12-04 18:53:50 +0000571 {
Zachary Turner270e99a2014-12-08 21:36:42 +0000572 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
573 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), output_file_path);
Greg Claytonc6931fc2013-12-04 18:53:50 +0000574 }
575 else
576 {
Zachary Turner270e99a2014-12-08 21:36:42 +0000577 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "", output_file_path);
Greg Claytonc6931fc2013-12-04 18:53:50 +0000578 }
Greg Claytonc6931fc2013-12-04 18:53:50 +0000579 }
580
581 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
Zachary Turner270e99a2014-12-08 21:36:42 +0000582 if (!output_file_path.empty())
Greg Claytonc6931fc2013-12-04 18:53:50 +0000583 {
Zachary Turner270e99a2014-12-08 21:36:42 +0000584 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path.c_str(), false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000585 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000586 }
587 else
588 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000589 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
590 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
591 }
592
593 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000594 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +0000595
596 const bool monitor_signals = false;
597 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
598
599 error = LaunchProcess (launch_info);
600 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +0000601
602 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
603 error.SetErrorString("failed to get process ID");
604
605 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +0000606 {
607 // The process successfully launched, so we can defer ownership of
608 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +0000609 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +0000610 // doesn't need to delete the ShellInfo anymore.
611 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000612 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +0000613 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +0000614 if (timeout_sec > 0) {
615 timeout_time.OffsetWithSeconds(timeout_sec);
616 timeout_ptr = &timeout_time;
617 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000618 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000619 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000620 if (timed_out)
621 {
622 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +0000623
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000624 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000625 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000626 // Wait for the monitor callback to get the message
627 timeout_time = TimeValue::Now();
628 timeout_time.OffsetWithSeconds(1);
629 timed_out = false;
630 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
631 }
632 else
633 {
634 if (status_ptr)
635 *status_ptr = shell_info->status;
636
637 if (signo_ptr)
638 *signo_ptr = shell_info->signo;
639
640 if (command_output_ptr)
641 {
642 command_output_ptr->clear();
Zachary Turner270e99a2014-12-08 21:36:42 +0000643 FileSpec file_spec(output_file_path.c_str(), File::eOpenOptionRead);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000644 uint64_t file_size = file_spec.GetByteSize();
645 if (file_size > 0)
646 {
647 if (file_size > command_output_ptr->max_size())
648 {
649 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
650 }
651 else
652 {
653 command_output_ptr->resize(file_size);
654 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
655 }
656 }
657 }
658 }
659 shell_info->can_delete.SetValue(true, eBroadcastAlways);
660 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000661
Zachary Turner270e99a2014-12-08 21:36:42 +0000662 FileSpec output_file_spec(output_file_path.c_str(), false);
663 if (FileSystem::GetFileExists(output_file_spec))
664 FileSystem::Unlink(output_file_path.c_str());
Greg Claytond1cf11a2012-04-14 01:42:46 +0000665 // Handshake with the monitor thread, or just let it know in advance that
666 // it can delete "shell_info" in case we timed out and were not able to kill
667 // the process...
668 return error;
669}
670
Daniel Malea4244cbd2013-08-27 20:58:59 +0000671
Todd Fiala76747122014-01-23 00:52:28 +0000672// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
673// systems
674
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000675#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Tamas Berghammer00e305d2015-02-12 18:13:44 +0000676#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Todd Fiala76747122014-01-23 00:52:28 +0000677// this method needs to be visible to macosx/Host.cpp and
678// common/Host.cpp.
679
680short
Zachary Turner172d37d2014-10-14 21:55:08 +0000681Host::GetPosixspawnFlags(const ProcessLaunchInfo &launch_info)
Todd Fiala76747122014-01-23 00:52:28 +0000682{
683 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
684
685#if defined (__APPLE__)
686 if (launch_info.GetFlags().Test (eLaunchFlagExec))
687 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
688
689 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
690 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
691
692 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
693 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
694
695 if (launch_info.GetLaunchInSeparateProcessGroup())
696 flags |= POSIX_SPAWN_SETPGROUP;
697
698#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
699#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
700 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
701 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
702 {
703 g_use_close_on_exec_flag = eLazyBoolNo;
704
705 uint32_t major, minor, update;
Zachary Turner97a14e62014-08-19 17:18:29 +0000706 if (HostInfo::GetOSVersion(major, minor, update))
Todd Fiala76747122014-01-23 00:52:28 +0000707 {
708 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
709 if (major > 10 || (major == 10 && minor > 7))
710 {
711 // Only enable for 10.8 and later OS versions
712 g_use_close_on_exec_flag = eLazyBoolYes;
713 }
714 }
715 }
716#else
717 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
718#endif
719 // Close all files exception those with file actions if this is supported.
720 if (g_use_close_on_exec_flag == eLazyBoolYes)
721 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
722#endif
723#endif // #if defined (__APPLE__)
724 return flags;
725}
726
727Error
Zachary Turner172d37d2014-10-14 21:55:08 +0000728Host::LaunchProcessPosixSpawn(const char *exe_path, const ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000729{
730 Error error;
731 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
732
Daniel Malea4244cbd2013-08-27 20:58:59 +0000733 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000734 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000735
736 if (error.Fail() || log)
737 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +0000738 if (error.Fail())
739 return error;
740
741 // Make a quick class that will cleanup the posix spawn attributes in case
742 // we return in the middle of this function.
743 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
744
745 sigset_t no_signals;
746 sigset_t all_signals;
747 sigemptyset (&no_signals);
748 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000749 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +0000750#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000751 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000752#else
753 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
754#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000755
Todd Fiala76747122014-01-23 00:52:28 +0000756 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000757
758 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000759 if (error.Fail() || log)
760 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000761 if (error.Fail())
762 return error;
763
Todd Fiala76747122014-01-23 00:52:28 +0000764 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
765 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
766#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +0000767
768 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
769 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
770 // to do that job on OSX.
771
772 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000773 {
Jim Ingham90331d52014-02-21 01:25:21 +0000774 // We don't need to do this for ARM, and we really shouldn't now that we
775 // have multiple CPU subtypes and no posix_spawnattr call that allows us
776 // to set which CPU subtype to launch...
777 const ArchSpec &arch_spec = launch_info.GetArchitecture();
778 cpu_type_t cpu = arch_spec.GetMachOCPUType();
779 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
780 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +0000781 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
782 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +0000783 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
784 {
785 size_t ocount = 0;
786 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
787 if (error.Fail() || log)
788 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 +0000789
Jim Ingham90331d52014-02-21 01:25:21 +0000790 if (error.Fail() || ocount != 1)
791 return error;
792 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000793 }
794
Todd Fiala76747122014-01-23 00:52:28 +0000795#endif
796
797 const char *tmp_argv[2];
798 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
799 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
800 if (argv == NULL)
801 {
802 // posix_spawn gets very unhappy if it doesn't have at least the program
803 // name in argv[0]. One of the side affects I have noticed is the environment
804 // variables don't make it into the child process if "argv == NULL"!!!
805 tmp_argv[0] = exe_path;
806 tmp_argv[1] = NULL;
807 argv = (char * const*)tmp_argv;
808 }
809
810#if !defined (__APPLE__)
811 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +0000812 char current_dir[PATH_MAX];
813 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +0000814#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000815
816 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +0000817 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000818 {
Todd Fiala76747122014-01-23 00:52:28 +0000819#if defined (__APPLE__)
820 // Set the working directory on this thread only
821 if (__pthread_chdir (working_dir) < 0) {
822 if (errno == ENOENT) {
823 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
824 } else if (errno == ENOTDIR) {
825 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
826 } else {
827 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
828 }
829 return error;
830 }
831#else
Daniel Malea4244cbd2013-08-27 20:58:59 +0000832 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
833 {
834 error.SetError(errno, eErrorTypePOSIX);
835 error.LogIfError(log, "unable to save the current directory");
836 return error;
837 }
838
839 if (::chdir(working_dir) == -1)
840 {
841 error.SetError(errno, eErrorTypePOSIX);
842 error.LogIfError(log, "unable to change working directory to %s", working_dir);
843 return error;
844 }
Todd Fiala76747122014-01-23 00:52:28 +0000845#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000846 }
847
Zachary Turner172d37d2014-10-14 21:55:08 +0000848 ::pid_t result_pid = LLDB_INVALID_PROCESS_ID;
Todd Fiala76747122014-01-23 00:52:28 +0000849 const size_t num_file_actions = launch_info.GetNumFileActions ();
850 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000851 {
Todd Fiala76747122014-01-23 00:52:28 +0000852 posix_spawn_file_actions_t file_actions;
853 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
854 if (error.Fail() || log)
855 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
856 if (error.Fail())
857 return error;
858
859 // Make a quick class that will cleanup the posix spawn attributes in case
860 // we return in the middle of this function.
861 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
862
863 for (size_t i=0; i<num_file_actions; ++i)
864 {
Zachary Turner696b5282014-08-14 16:01:25 +0000865 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +0000866 if (launch_file_action)
867 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000868 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
Todd Fiala76747122014-01-23 00:52:28 +0000869 return error;
870 }
871 }
872
Zachary Turner172d37d2014-10-14 21:55:08 +0000873 error.SetError(::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000874
875 if (error.Fail() || log)
876 {
Zachary Turner172d37d2014-10-14 21:55:08 +0000877 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", result_pid,
878 exe_path, static_cast<void *>(&file_actions), static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
879 reinterpret_cast<const void *>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000880 if (log)
881 {
882 for (int ii=0; argv[ii]; ++ii)
883 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
884 }
885 }
886
887 }
888 else
889 {
Zachary Turner172d37d2014-10-14 21:55:08 +0000890 error.SetError(::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000891
892 if (error.Fail() || log)
893 {
894 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
Zachary Turner172d37d2014-10-14 21:55:08 +0000895 result_pid, exe_path, static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
896 reinterpret_cast<const void *>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000897 if (log)
898 {
899 for (int ii=0; argv[ii]; ++ii)
900 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
901 }
902 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000903 }
Zachary Turner172d37d2014-10-14 21:55:08 +0000904 pid = result_pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000905
Todd Fiala76747122014-01-23 00:52:28 +0000906 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000907 {
Todd Fiala76747122014-01-23 00:52:28 +0000908#if defined (__APPLE__)
909 // No more thread specific current working directory
910 __pthread_fchdir (-1);
911#else
912 if (::chdir(current_dir) == -1 && error.Success())
913 {
914 error.SetError(errno, eErrorTypePOSIX);
915 error.LogIfError(log, "unable to change current directory back to %s",
916 current_dir);
917 }
918#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000919 }
920
921 return error;
922}
923
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000924bool
925Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
Zachary Turner696b5282014-08-14 16:01:25 +0000926{
927 if (info == NULL)
928 return false;
929
930 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
931
932 switch (info->GetAction())
933 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000934 case FileAction::eFileActionNone:
935 error.Clear();
936 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000937
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000938 case FileAction::eFileActionClose:
939 if (info->GetFD() == -1)
940 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
941 else
942 {
943 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
944 if (log && (error.Fail() || log))
945 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
946 static_cast<void *>(file_actions), info->GetFD());
947 }
948 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000949
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000950 case FileAction::eFileActionDuplicate:
951 if (info->GetFD() == -1)
952 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
953 else if (info->GetActionArgument() == -1)
954 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
955 else
956 {
957 error.SetError(
958 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
959 eErrorTypePOSIX);
960 if (log && (error.Fail() || log))
961 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
962 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
963 }
964 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000965
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000966 case FileAction::eFileActionOpen:
967 if (info->GetFD() == -1)
968 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
969 else
970 {
971 int oflag = info->GetActionArgument();
Zachary Turner696b5282014-08-14 16:01:25 +0000972
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000973 mode_t mode = 0;
Zachary Turner696b5282014-08-14 16:01:25 +0000974
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000975 if (oflag & O_CREAT)
976 mode = 0640;
Zachary Turner696b5282014-08-14 16:01:25 +0000977
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000978 error.SetError(
979 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
980 eErrorTypePOSIX);
981 if (error.Fail() || log)
982 error.PutToLog(log,
983 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
984 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
985 }
986 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000987 }
988 return error.Success();
989}
Tamas Berghammer00e305d2015-02-12 18:13:44 +0000990#endif // !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
991#endif // defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +0000992
Zachary Turner172d37d2014-10-14 21:55:08 +0000993#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__) || defined(_WIN32)
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000994// The functions below implement process launching via posix_spawn() for Linux,
995// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +0000996
997Error
998Host::LaunchProcess (ProcessLaunchInfo &launch_info)
999{
Zachary Turner172d37d2014-10-14 21:55:08 +00001000 std::unique_ptr<ProcessLauncher> delegate_launcher;
1001#if defined(_WIN32)
1002 delegate_launcher.reset(new ProcessLauncherWindows());
Tamas Berghammer00e305d2015-02-12 18:13:44 +00001003#elif defined(__ANDROID__) || defined(__ANDROID_NDK__)
1004 delegate_launcher.reset(new ProcessLauncherAndroid());
Zachary Turner172d37d2014-10-14 21:55:08 +00001005#else
1006 delegate_launcher.reset(new ProcessLauncherPosix());
1007#endif
1008 MonitoringProcessLauncher launcher(std::move(delegate_launcher));
1009
Daniel Malea4244cbd2013-08-27 20:58:59 +00001010 Error error;
Zachary Turner172d37d2014-10-14 21:55:08 +00001011 HostProcess process = launcher.LaunchProcess(launch_info, error);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001012
Zachary Turner172d37d2014-10-14 21:55:08 +00001013 // TODO(zturner): It would be better if the entire HostProcess were returned instead of writing
1014 // it into this structure.
1015 launch_info.SetProcessID(process.GetProcessId());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001016
Daniel Malea4244cbd2013-08-27 20:58:59 +00001017 return error;
1018}
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001019#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001020
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001021#ifndef _WIN32
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001022void
1023Host::Kill(lldb::pid_t pid, int signo)
1024{
1025 ::kill(pid, signo);
1026}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001027
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001028#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001029
Johnny Chen8f3d8382011-08-02 20:52:42 +00001030#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001031bool
Greg Clayton3b147632010-12-18 01:54:34 +00001032Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001033{
1034 return false;
1035}
Greg Claytondd36def2010-10-17 22:03:32 +00001036
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001037void
1038Host::SetCrashDescriptionWithFormat (const char *format, ...)
1039{
1040}
1041
1042void
1043Host::SetCrashDescription (const char *description)
1044{
1045}
Greg Claytondd36def2010-10-17 22:03:32 +00001046
Greg Claytonfbb76342013-11-20 21:07:01 +00001047#endif
Todd Fiala4ceced32014-08-29 17:35:57 +00001048
Sylvestre Ledru57958b52015-02-10 17:16:13 +00001049#if !defined (__linux__) && !defined (__FreeBSD__) && !defined(__FreeBSD_kernel__) && !defined (__NetBSD__)
Todd Fiala4ceced32014-08-29 17:35:57 +00001050
1051const lldb_private::UnixSignalsSP&
1052Host::GetUnixSignals ()
1053{
1054 static UnixSignalsSP s_unix_signals_sp (new UnixSignals ());
1055 return s_unix_signals_sp;
1056}
1057
1058#endif