blob: 20d6355e6195238da4fffb9eb92ee72dda3a9c8d [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
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000116#ifndef __linux__
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};
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000143#endif // __linux__
144
145#ifdef __linux__
146static thread_local volatile sig_atomic_t g_usr1_called;
147
148static void
149SigUsr1Handler (int)
150{
151 g_usr1_called = 1;
152}
153#endif // __linux__
154
155static bool
156CheckForMonitorCancellation()
157{
158#ifdef __linux__
159 if (g_usr1_called)
160 {
161 g_usr1_called = 0;
162 return true;
163 }
164#else
165 ::pthread_testcancel ();
166#endif
167 return false;
168}
Greg Clayton2bddd342010-09-07 20:11:56 +0000169
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000170static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000171MonitorChildProcessThreadFunction (void *arg)
172{
Greg Clayton5160ce52013-03-27 23:08:40 +0000173 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000174 const char *function = __FUNCTION__;
175 if (log)
176 log->Printf ("%s (arg = %p) thread starting...", function, arg);
177
178 MonitorInfo *info = (MonitorInfo *)arg;
179
180 const Host::MonitorChildProcessCallback callback = info->callback;
181 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000182 const bool monitor_signals = info->monitor_signals;
183
Daniel Malea4244cbd2013-08-27 20:58:59 +0000184 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000185 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000186
Greg Clayton2bddd342010-09-07 20:11:56 +0000187 delete info;
188
189 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000190#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000191 #define __WALL 0
192#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000193 const int options = __WALL;
194
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000195#ifdef __linux__
196 // This signal is only used to interrupt the thread from waitpid
197 struct sigaction sigUsr1Action;
198 memset(&sigUsr1Action, 0, sizeof(sigUsr1Action));
199 sigUsr1Action.sa_handler = SigUsr1Handler;
200 ::sigaction(SIGUSR1, &sigUsr1Action, nullptr);
201#endif // __linux__
202
Greg Clayton2bddd342010-09-07 20:11:56 +0000203 while (1)
204 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000205 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000206 if (log)
Vince Harronb956a812015-01-23 22:48:28 +0000207 log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000208
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000209 if (CheckForMonitorCancellation ())
210 break;
211
Matt Kopec650648f2013-01-08 16:30:18 +0000212 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000213 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000214
215 if (CheckForMonitorCancellation ())
216 break;
217
Greg Clayton2bddd342010-09-07 20:11:56 +0000218 if (wait_pid == -1)
219 {
220 if (errno == EINTR)
221 continue;
222 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000223 {
224 if (log)
225 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000226 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000227 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000228 }
Matt Kopec650648f2013-01-08 16:30:18 +0000229 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000230 {
231 bool exited = false;
232 int signal = 0;
233 int exit_status = 0;
234 const char *status_cstr = NULL;
235 if (WIFSTOPPED(status))
236 {
237 signal = WSTOPSIG(status);
238 status_cstr = "STOPPED";
239 }
240 else if (WIFEXITED(status))
241 {
242 exit_status = WEXITSTATUS(status);
243 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000244 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000245 }
246 else if (WIFSIGNALED(status))
247 {
248 signal = WTERMSIG(status);
249 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000250 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000251 exited = true;
252 exit_status = -1;
253 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000254 }
255 else
256 {
Johnny Chen44805302011-07-19 19:48:13 +0000257 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 }
259
260 // Scope for pthread_cancel_disabler
261 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000262#ifndef __linux__
Greg Clayton2bddd342010-09-07 20:11:56 +0000263 ScopedPThreadCancelDisabler pthread_cancel_disabler;
Todd Fialacacde7d2014-09-27 16:54:22 +0000264#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000265
Caroline Tice20ad3c42010-10-29 21:48:37 +0000266 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000267 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000268 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 +0000269 function,
Greg Clayton2bddd342010-09-07 20:11:56 +0000270 pid,
Vince Harronb956a812015-01-23 22:48:28 +0000271 options,
272 wait_pid,
Greg Clayton2bddd342010-09-07 20:11:56 +0000273 status,
274 status_cstr,
275 signal,
276 exit_status);
277
278 if (exited || (signal != 0 && monitor_signals))
279 {
Greg Claytone4e45922011-11-16 05:37:56 +0000280 bool callback_return = false;
281 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000282 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000283
284 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000285 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000286 {
287 if (log)
288 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000289 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000290 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000291 // If the callback returns true, it means this process should
292 // exit
293 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000294 {
295 if (log)
296 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000297 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000298 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000299 }
300 }
301 }
302 }
303
Caroline Tice20ad3c42010-10-29 21:48:37 +0000304 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000305 if (log)
306 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
307
308 return NULL;
309}
310
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000311#endif // #if !defined (__APPLE__) && !defined (_WIN32)
312
313#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000314
315void
316Host::SystemLog (SystemLogType type, const char *format, va_list args)
317{
318 vfprintf (stderr, format, args);
319}
320
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000321#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000322
Greg Claytone38a5ed2012-01-05 03:57:59 +0000323void
324Host::SystemLog (SystemLogType type, const char *format, ...)
325{
326 va_list args;
327 va_start (args, format);
328 SystemLog (type, format, args);
329 va_end (args);
330}
331
Greg Clayton2bddd342010-09-07 20:11:56 +0000332lldb::pid_t
333Host::GetCurrentProcessID()
334{
335 return ::getpid();
336}
337
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000338#ifndef _WIN32
339
Greg Clayton2bddd342010-09-07 20:11:56 +0000340lldb::tid_t
341Host::GetCurrentThreadID()
342{
343#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000344 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000345 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
346 // count.
347 thread_port_t thread_self = mach_thread_self();
348 mach_port_deallocate(mach_task_self(), thread_self);
349 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000350#elif defined(__FreeBSD__)
351 return lldb::tid_t(pthread_getthreadid_np());
Shawn Best8da0bf32014-11-08 01:41:49 +0000352#elif defined(__ANDROID_NDK__)
353 return lldb::tid_t(gettid());
Michael Sartainc2052432013-08-01 18:51:08 +0000354#elif defined(__linux__)
355 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000356#else
357 return lldb::tid_t(pthread_self());
358#endif
359}
360
Jim Ingham372787f2012-04-07 00:00:41 +0000361lldb::thread_t
362Host::GetCurrentThread ()
363{
364 return lldb::thread_t(pthread_self());
365}
366
Greg Clayton2bddd342010-09-07 20:11:56 +0000367const char *
368Host::GetSignalAsCString (int signo)
369{
370 switch (signo)
371 {
372 case SIGHUP: return "SIGHUP"; // 1 hangup
373 case SIGINT: return "SIGINT"; // 2 interrupt
374 case SIGQUIT: return "SIGQUIT"; // 3 quit
375 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
376 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
377 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000378#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000379#if !defined(SIGIO) || (SIGPOLL != SIGIO)
380// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
381// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000382 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000383#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000384#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000385#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000386 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000387#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000388 case SIGFPE: return "SIGFPE"; // 8 floating point exception
389 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
390 case SIGBUS: return "SIGBUS"; // 10 bus error
391 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
392 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
393 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
394 case SIGALRM: return "SIGALRM"; // 14 alarm clock
395 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
396 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
397 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
398 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
399 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
400 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
401 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
402 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000403#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000404 case SIGIO: return "SIGIO"; // 23 input/output possible signal
405#endif
406 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
407 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
408 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
409 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000410#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000411 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000412#endif
413#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000414 case SIGINFO: return "SIGINFO"; // 29 information request
415#endif
416 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
417 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
418 default:
419 break;
420 }
421 return NULL;
422}
423
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000424#endif
425
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000426#ifndef _WIN32
427
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000428lldb::thread_key_t
429Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
430{
431 pthread_key_t key;
432 ::pthread_key_create (&key, callback);
433 return key;
434}
435
436void*
437Host::ThreadLocalStorageGet(lldb::thread_key_t key)
438{
439 return ::pthread_getspecific (key);
440}
441
442void
443Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
444{
445 ::pthread_setspecific (key, value);
446}
447
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000448#endif
449
Greg Clayton2bddd342010-09-07 20:11:56 +0000450#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000451
452bool
453Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
454{
455 bundle.Clear();
456 return false;
457}
458
Greg Clayton2bddd342010-09-07 20:11:56 +0000459bool
Greg Claytondd36def2010-10-17 22:03:32 +0000460Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000461{
Greg Claytondd36def2010-10-17 22:03:32 +0000462 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000463}
464#endif
465
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000466#ifndef _WIN32
467
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000468FileSpec
469Host::GetModuleFileSpecForHostAddress (const void *host_addr)
470{
471 FileSpec module_filespec;
Shawn Best8da0bf32014-11-08 01:41:49 +0000472#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000473 Dl_info info;
474 if (::dladdr (host_addr, &info))
475 {
476 if (info.dli_fname)
477 module_filespec.SetFile(info.dli_fname, true);
478 }
Todd Fialacacde7d2014-09-27 16:54:22 +0000479#endif
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000480 return module_filespec;
481}
482
483#endif
484
Matt Kopec085d6ce2013-05-31 22:00:07 +0000485#if !defined(__linux__)
486bool
487Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
488{
489 return false;
490}
491#endif
492
Greg Claytond1cf11a2012-04-14 01:42:46 +0000493struct ShellInfo
494{
495 ShellInfo () :
496 process_reaped (false),
497 can_delete (false),
498 pid (LLDB_INVALID_PROCESS_ID),
499 signo(-1),
500 status(-1)
501 {
502 }
503
504 lldb_private::Predicate<bool> process_reaped;
505 lldb_private::Predicate<bool> can_delete;
506 lldb::pid_t pid;
507 int signo;
508 int status;
509};
510
511static bool
512MonitorShellCommand (void *callback_baton,
513 lldb::pid_t pid,
514 bool exited, // True if the process did exit
515 int signo, // Zero for no signal
516 int status) // Exit value of process if signal is zero
517{
518 ShellInfo *shell_info = (ShellInfo *)callback_baton;
519 shell_info->pid = pid;
520 shell_info->signo = signo;
521 shell_info->status = status;
522 // Let the thread running Host::RunShellCommand() know that the process
523 // exited and that ShellInfo has been filled in by broadcasting to it
524 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
525 // Now wait for a handshake back from that thread running Host::RunShellCommand
526 // so we know that we can delete shell_info_ptr
527 shell_info->can_delete.WaitForValueEqualTo(true);
528 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
529 usleep(1000);
530 // Now delete the shell info that was passed into this function
531 delete shell_info;
532 return true;
533}
534
535Error
Chaoren Lind3173f32015-05-29 19:52:29 +0000536Host::RunShellCommand(const char *command,
537 const FileSpec &working_dir,
538 int *status_ptr,
539 int *signo_ptr,
540 std::string *command_output_ptr,
541 uint32_t timeout_sec,
542 bool run_in_default_shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +0000543{
Enrico Granata66eda732015-04-17 01:50:11 +0000544 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, command_output_ptr, timeout_sec, run_in_default_shell);
545}
546
547Error
Chaoren Lind3173f32015-05-29 19:52:29 +0000548Host::RunShellCommand(const Args &args,
549 const FileSpec &working_dir,
550 int *status_ptr,
551 int *signo_ptr,
552 std::string *command_output_ptr,
553 uint32_t timeout_sec,
554 bool run_in_default_shell)
Enrico Granata66eda732015-04-17 01:50:11 +0000555{
Greg Claytond1cf11a2012-04-14 01:42:46 +0000556 Error error;
557 ProcessLaunchInfo launch_info;
Zachary Turner270e99a2014-12-08 21:36:42 +0000558 launch_info.SetArchitecture(HostInfo::GetArchitecture());
Zachary Turner10687b02014-10-20 17:46:43 +0000559 if (run_in_default_shell)
Greg Claytonc8f814d2012-09-27 03:13:55 +0000560 {
561 // Run the command in a shell
Zachary Turner10687b02014-10-20 17:46:43 +0000562 launch_info.SetShell(HostInfo::GetDefaultShell());
Enrico Granata66eda732015-04-17 01:50:11 +0000563 launch_info.GetArguments().AppendArguments(args);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000564 const bool localhost = true;
565 const bool will_debug = false;
Enrico Granata66eda732015-04-17 01:50:11 +0000566 const bool first_arg_is_full_shell_command = false;
Greg Claytonc8f814d2012-09-27 03:13:55 +0000567 launch_info.ConvertArgumentsForLaunchingInShell (error,
568 localhost,
569 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000570 first_arg_is_full_shell_command,
571 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000572 }
573 else
574 {
575 // No shell, just run it
Greg Claytonc8f814d2012-09-27 03:13:55 +0000576 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +0000577 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000578 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000579
580 if (working_dir)
581 launch_info.SetWorkingDirectory(working_dir);
Zachary Turner270e99a2014-12-08 21:36:42 +0000582 llvm::SmallString<PATH_MAX> output_file_path;
Enrico Granata66eda732015-04-17 01:50:11 +0000583
Greg Claytond1cf11a2012-04-14 01:42:46 +0000584 if (command_output_ptr)
585 {
586 // Create a temporary file to get the stdout/stderr and redirect the
587 // output of the command into this file. We will later read this file
588 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +0000589 FileSpec tmpdir_file_spec;
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000590 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
Greg Claytonc6931fc2013-12-04 18:53:50 +0000591 {
Zachary Turner270e99a2014-12-08 21:36:42 +0000592 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
593 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), output_file_path);
Greg Claytonc6931fc2013-12-04 18:53:50 +0000594 }
595 else
596 {
Zachary Turner270e99a2014-12-08 21:36:42 +0000597 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "", output_file_path);
Greg Claytonc6931fc2013-12-04 18:53:50 +0000598 }
Greg Claytonc6931fc2013-12-04 18:53:50 +0000599 }
Chaoren Lind3173f32015-05-29 19:52:29 +0000600
601 FileSpec output_file_spec{output_file_path.c_str(), false};
602
Greg Claytonc6931fc2013-12-04 18:53:50 +0000603 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000604 if (output_file_spec)
Greg Claytonc6931fc2013-12-04 18:53:50 +0000605 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000606 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000607 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000608 }
609 else
610 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000611 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
612 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
613 }
614
615 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000616 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +0000617
618 const bool monitor_signals = false;
619 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
620
621 error = LaunchProcess (launch_info);
622 const lldb::pid_t pid = launch_info.GetProcessID();
Enrico Granata66eda732015-04-17 01:50:11 +0000623
Daniel Maleae0f8f572013-08-26 23:57:52 +0000624 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
625 error.SetErrorString("failed to get process ID");
Enrico Granata66eda732015-04-17 01:50:11 +0000626
Daniel Maleae0f8f572013-08-26 23:57:52 +0000627 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +0000628 {
629 // The process successfully launched, so we can defer ownership of
630 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +0000631 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +0000632 // doesn't need to delete the ShellInfo anymore.
633 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000634 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +0000635 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +0000636 if (timeout_sec > 0) {
637 timeout_time.OffsetWithSeconds(timeout_sec);
638 timeout_ptr = &timeout_time;
639 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000640 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000641 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000642 if (timed_out)
643 {
644 error.SetErrorString("timed out waiting for shell command to complete");
Enrico Granata66eda732015-04-17 01:50:11 +0000645
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000646 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000647 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000648 // Wait for the monitor callback to get the message
649 timeout_time = TimeValue::Now();
650 timeout_time.OffsetWithSeconds(1);
651 timed_out = false;
652 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
653 }
654 else
655 {
656 if (status_ptr)
657 *status_ptr = shell_info->status;
Enrico Granata66eda732015-04-17 01:50:11 +0000658
Greg Claytond1cf11a2012-04-14 01:42:46 +0000659 if (signo_ptr)
660 *signo_ptr = shell_info->signo;
Enrico Granata66eda732015-04-17 01:50:11 +0000661
Greg Claytond1cf11a2012-04-14 01:42:46 +0000662 if (command_output_ptr)
663 {
664 command_output_ptr->clear();
Chaoren Lind3173f32015-05-29 19:52:29 +0000665 uint64_t file_size = output_file_spec.GetByteSize();
Greg Claytond1cf11a2012-04-14 01:42:46 +0000666 if (file_size > 0)
667 {
668 if (file_size > command_output_ptr->max_size())
669 {
670 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
671 }
672 else
673 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000674 std::vector<char> command_output(file_size);
675 output_file_spec.ReadFileContents(0, command_output.data(), file_size, &error);
676 if (error.Success())
677 command_output_ptr->assign(command_output.data(), file_size);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000678 }
679 }
680 }
681 }
682 shell_info->can_delete.SetValue(true, eBroadcastAlways);
683 }
Chaoren Lind3173f32015-05-29 19:52:29 +0000684
Zachary Turner270e99a2014-12-08 21:36:42 +0000685 if (FileSystem::GetFileExists(output_file_spec))
Chaoren Lind3173f32015-05-29 19:52:29 +0000686 FileSystem::Unlink(output_file_spec);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000687 // Handshake with the monitor thread, or just let it know in advance that
688 // it can delete "shell_info" in case we timed out and were not able to kill
689 // the process...
690 return error;
691}
692
Todd Fiala76747122014-01-23 00:52:28 +0000693// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
694// systems
695
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000696#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Tamas Berghammer00e305d2015-02-12 18:13:44 +0000697#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Todd Fiala76747122014-01-23 00:52:28 +0000698// this method needs to be visible to macosx/Host.cpp and
699// common/Host.cpp.
700
701short
Zachary Turner172d37d2014-10-14 21:55:08 +0000702Host::GetPosixspawnFlags(const ProcessLaunchInfo &launch_info)
Todd Fiala76747122014-01-23 00:52:28 +0000703{
704 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
705
706#if defined (__APPLE__)
707 if (launch_info.GetFlags().Test (eLaunchFlagExec))
708 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
709
710 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
711 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
712
713 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
714 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
715
716 if (launch_info.GetLaunchInSeparateProcessGroup())
717 flags |= POSIX_SPAWN_SETPGROUP;
718
719#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
720#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
721 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
722 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
723 {
724 g_use_close_on_exec_flag = eLazyBoolNo;
725
726 uint32_t major, minor, update;
Zachary Turner97a14e62014-08-19 17:18:29 +0000727 if (HostInfo::GetOSVersion(major, minor, update))
Todd Fiala76747122014-01-23 00:52:28 +0000728 {
729 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
730 if (major > 10 || (major == 10 && minor > 7))
731 {
732 // Only enable for 10.8 and later OS versions
733 g_use_close_on_exec_flag = eLazyBoolYes;
734 }
735 }
736 }
737#else
738 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
739#endif
740 // Close all files exception those with file actions if this is supported.
741 if (g_use_close_on_exec_flag == eLazyBoolYes)
742 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
743#endif
744#endif // #if defined (__APPLE__)
745 return flags;
746}
747
748Error
Zachary Turner172d37d2014-10-14 21:55:08 +0000749Host::LaunchProcessPosixSpawn(const char *exe_path, const ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000750{
751 Error error;
752 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
753
Daniel Malea4244cbd2013-08-27 20:58:59 +0000754 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000755 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000756
757 if (error.Fail() || log)
758 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +0000759 if (error.Fail())
760 return error;
761
762 // Make a quick class that will cleanup the posix spawn attributes in case
763 // we return in the middle of this function.
764 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
765
766 sigset_t no_signals;
767 sigset_t all_signals;
768 sigemptyset (&no_signals);
769 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000770 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +0000771#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000772 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000773#else
774 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
775#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000776
Todd Fiala76747122014-01-23 00:52:28 +0000777 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000778
779 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000780 if (error.Fail() || log)
781 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000782 if (error.Fail())
783 return error;
784
Todd Fiala76747122014-01-23 00:52:28 +0000785 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
786 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
787#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +0000788
789 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
790 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
791 // to do that job on OSX.
792
793 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000794 {
Jim Ingham90331d52014-02-21 01:25:21 +0000795 // We don't need to do this for ARM, and we really shouldn't now that we
796 // have multiple CPU subtypes and no posix_spawnattr call that allows us
797 // to set which CPU subtype to launch...
798 const ArchSpec &arch_spec = launch_info.GetArchitecture();
799 cpu_type_t cpu = arch_spec.GetMachOCPUType();
800 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
801 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +0000802 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
803 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +0000804 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
805 {
806 size_t ocount = 0;
807 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
808 if (error.Fail() || log)
809 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 +0000810
Jim Ingham90331d52014-02-21 01:25:21 +0000811 if (error.Fail() || ocount != 1)
812 return error;
813 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000814 }
815
Todd Fiala76747122014-01-23 00:52:28 +0000816#endif
817
818 const char *tmp_argv[2];
819 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
820 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
821 if (argv == NULL)
822 {
823 // posix_spawn gets very unhappy if it doesn't have at least the program
824 // name in argv[0]. One of the side affects I have noticed is the environment
825 // variables don't make it into the child process if "argv == NULL"!!!
826 tmp_argv[0] = exe_path;
827 tmp_argv[1] = NULL;
828 argv = (char * const*)tmp_argv;
829 }
830
831#if !defined (__APPLE__)
832 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +0000833 char current_dir[PATH_MAX];
834 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +0000835#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000836
Chaoren Lind3173f32015-05-29 19:52:29 +0000837 FileSpec working_dir{launch_info.GetWorkingDirectory()};
Todd Fiala76747122014-01-23 00:52:28 +0000838 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000839 {
Todd Fiala76747122014-01-23 00:52:28 +0000840#if defined (__APPLE__)
841 // Set the working directory on this thread only
Chaoren Lind3173f32015-05-29 19:52:29 +0000842 if (__pthread_chdir(working_dir.GetCString()) < 0) {
Todd Fiala76747122014-01-23 00:52:28 +0000843 if (errno == ENOENT) {
Chaoren Lind3173f32015-05-29 19:52:29 +0000844 error.SetErrorStringWithFormat("No such file or directory: %s",
845 working_dir.GetCString());
Todd Fiala76747122014-01-23 00:52:28 +0000846 } else if (errno == ENOTDIR) {
Chaoren Lind3173f32015-05-29 19:52:29 +0000847 error.SetErrorStringWithFormat("Path doesn't name a directory: %s",
848 working_dir.GetCString());
Todd Fiala76747122014-01-23 00:52:28 +0000849 } else {
850 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
851 }
852 return error;
853 }
854#else
Daniel Malea4244cbd2013-08-27 20:58:59 +0000855 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
856 {
857 error.SetError(errno, eErrorTypePOSIX);
858 error.LogIfError(log, "unable to save the current directory");
859 return error;
860 }
861
Chaoren Lind3173f32015-05-29 19:52:29 +0000862 if (::chdir(working_dir.GetCString()) == -1)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000863 {
864 error.SetError(errno, eErrorTypePOSIX);
Chaoren Lind3173f32015-05-29 19:52:29 +0000865 error.LogIfError(log, "unable to change working directory to %s",
866 working_dir.GetCString());
Daniel Malea4244cbd2013-08-27 20:58:59 +0000867 return error;
868 }
Todd Fiala76747122014-01-23 00:52:28 +0000869#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000870 }
871
Zachary Turner172d37d2014-10-14 21:55:08 +0000872 ::pid_t result_pid = LLDB_INVALID_PROCESS_ID;
Todd Fiala76747122014-01-23 00:52:28 +0000873 const size_t num_file_actions = launch_info.GetNumFileActions ();
874 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000875 {
Todd Fiala76747122014-01-23 00:52:28 +0000876 posix_spawn_file_actions_t file_actions;
877 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
878 if (error.Fail() || log)
879 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
880 if (error.Fail())
881 return error;
882
883 // Make a quick class that will cleanup the posix spawn attributes in case
884 // we return in the middle of this function.
885 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
886
887 for (size_t i=0; i<num_file_actions; ++i)
888 {
Zachary Turner696b5282014-08-14 16:01:25 +0000889 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +0000890 if (launch_file_action)
891 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000892 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
Todd Fiala76747122014-01-23 00:52:28 +0000893 return error;
894 }
895 }
896
Zachary Turner172d37d2014-10-14 21:55:08 +0000897 error.SetError(::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000898
899 if (error.Fail() || log)
900 {
Zachary Turner172d37d2014-10-14 21:55:08 +0000901 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", result_pid,
902 exe_path, static_cast<void *>(&file_actions), static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
903 reinterpret_cast<const void *>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000904 if (log)
905 {
906 for (int ii=0; argv[ii]; ++ii)
907 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
908 }
909 }
910
911 }
912 else
913 {
Zachary Turner172d37d2014-10-14 21:55:08 +0000914 error.SetError(::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000915
916 if (error.Fail() || log)
917 {
918 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 +0000919 result_pid, exe_path, static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
920 reinterpret_cast<const void *>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000921 if (log)
922 {
923 for (int ii=0; argv[ii]; ++ii)
924 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
925 }
926 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000927 }
Zachary Turner172d37d2014-10-14 21:55:08 +0000928 pid = result_pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000929
Todd Fiala76747122014-01-23 00:52:28 +0000930 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000931 {
Todd Fiala76747122014-01-23 00:52:28 +0000932#if defined (__APPLE__)
933 // No more thread specific current working directory
934 __pthread_fchdir (-1);
935#else
936 if (::chdir(current_dir) == -1 && error.Success())
937 {
938 error.SetError(errno, eErrorTypePOSIX);
939 error.LogIfError(log, "unable to change current directory back to %s",
940 current_dir);
941 }
942#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000943 }
944
945 return error;
946}
947
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000948bool
949Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
Zachary Turner696b5282014-08-14 16:01:25 +0000950{
951 if (info == NULL)
952 return false;
953
954 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
955
956 switch (info->GetAction())
957 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000958 case FileAction::eFileActionNone:
959 error.Clear();
960 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000961
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000962 case FileAction::eFileActionClose:
963 if (info->GetFD() == -1)
964 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
965 else
966 {
967 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
968 if (log && (error.Fail() || log))
969 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
970 static_cast<void *>(file_actions), info->GetFD());
971 }
972 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000973
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000974 case FileAction::eFileActionDuplicate:
975 if (info->GetFD() == -1)
976 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
977 else if (info->GetActionArgument() == -1)
978 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
979 else
980 {
981 error.SetError(
982 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
983 eErrorTypePOSIX);
984 if (log && (error.Fail() || log))
985 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
986 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
987 }
988 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000989
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000990 case FileAction::eFileActionOpen:
991 if (info->GetFD() == -1)
992 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
993 else
994 {
995 int oflag = info->GetActionArgument();
Zachary Turner696b5282014-08-14 16:01:25 +0000996
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000997 mode_t mode = 0;
Zachary Turner696b5282014-08-14 16:01:25 +0000998
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000999 if (oflag & O_CREAT)
1000 mode = 0640;
Zachary Turner696b5282014-08-14 16:01:25 +00001001
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001002 error.SetError(
1003 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
1004 eErrorTypePOSIX);
1005 if (error.Fail() || log)
1006 error.PutToLog(log,
1007 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
1008 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
1009 }
1010 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001011 }
1012 return error.Success();
1013}
Tamas Berghammer00e305d2015-02-12 18:13:44 +00001014#endif // !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
1015#endif // defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +00001016
Zachary Turner172d37d2014-10-14 21:55:08 +00001017#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__) || defined(_WIN32)
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001018// The functions below implement process launching via posix_spawn() for Linux,
1019// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001020
1021Error
1022Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1023{
Zachary Turner172d37d2014-10-14 21:55:08 +00001024 std::unique_ptr<ProcessLauncher> delegate_launcher;
1025#if defined(_WIN32)
1026 delegate_launcher.reset(new ProcessLauncherWindows());
Tamas Berghammer00e305d2015-02-12 18:13:44 +00001027#elif defined(__ANDROID__) || defined(__ANDROID_NDK__)
1028 delegate_launcher.reset(new ProcessLauncherAndroid());
Zachary Turner172d37d2014-10-14 21:55:08 +00001029#else
1030 delegate_launcher.reset(new ProcessLauncherPosix());
1031#endif
1032 MonitoringProcessLauncher launcher(std::move(delegate_launcher));
1033
Daniel Malea4244cbd2013-08-27 20:58:59 +00001034 Error error;
Zachary Turner172d37d2014-10-14 21:55:08 +00001035 HostProcess process = launcher.LaunchProcess(launch_info, error);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001036
Zachary Turner172d37d2014-10-14 21:55:08 +00001037 // TODO(zturner): It would be better if the entire HostProcess were returned instead of writing
1038 // it into this structure.
1039 launch_info.SetProcessID(process.GetProcessId());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001040
Daniel Malea4244cbd2013-08-27 20:58:59 +00001041 return error;
1042}
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001043#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001044
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001045#ifndef _WIN32
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001046void
1047Host::Kill(lldb::pid_t pid, int signo)
1048{
1049 ::kill(pid, signo);
1050}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001051
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001052#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001053
Johnny Chen8f3d8382011-08-02 20:52:42 +00001054#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001055bool
Greg Clayton3b147632010-12-18 01:54:34 +00001056Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001057{
1058 return false;
1059}
Greg Claytondd36def2010-10-17 22:03:32 +00001060
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001061void
1062Host::SetCrashDescriptionWithFormat (const char *format, ...)
1063{
1064}
1065
1066void
1067Host::SetCrashDescription (const char *description)
1068{
1069}
Greg Claytondd36def2010-10-17 22:03:32 +00001070
Greg Claytonfbb76342013-11-20 21:07:01 +00001071#endif
Todd Fiala4ceced32014-08-29 17:35:57 +00001072
Sylvestre Ledru57958b52015-02-10 17:16:13 +00001073#if !defined (__linux__) && !defined (__FreeBSD__) && !defined(__FreeBSD_kernel__) && !defined (__NetBSD__)
Todd Fiala4ceced32014-08-29 17:35:57 +00001074
1075const lldb_private::UnixSignalsSP&
1076Host::GetUnixSignals ()
1077{
1078 static UnixSignalsSP s_unix_signals_sp (new UnixSignals ());
1079 return s_unix_signals_sp;
1080}
1081
1082#endif