blob: c5dd105a59bec3578966d29cbfbbbecd3cd055cb [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
Jim Ingham9d9b46b2016-03-15 21:11:02 +000042// C++ Includes
43
44// Other libraries and framework includes
45// Project includes
Todd Fiala17096d72014-07-16 19:03:16 +000046
Zachary Turner270e99a2014-12-08 21:36:42 +000047#include "lldb/Host/FileSystem.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000048#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000049#include "lldb/Host/HostInfo.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000050#include "lldb/Core/ArchSpec.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000051#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000052#include "lldb/Core/Log.h"
Greg Claytone996fd32011-03-08 22:40:15 +000053#include "lldb/Host/FileSpec.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000054#include "lldb/Host/HostProcess.h"
55#include "lldb/Host/MonitoringProcessLauncher.h"
Vince Harron76861ea2015-01-16 06:47:43 +000056#include "lldb/Host/Predicate.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000057#include "lldb/Host/ProcessLauncher.h"
Zachary Turner39de3112014-09-09 20:54:56 +000058#include "lldb/Host/ThreadLauncher.h"
Todd Fiala4ceced32014-08-29 17:35:57 +000059#include "lldb/lldb-private-forward.h"
Vince Harron76861ea2015-01-16 06:47:43 +000060#include "llvm/Support/FileSystem.h"
Zachary Turner696b5282014-08-14 16:01:25 +000061#include "lldb/Target/FileAction.h"
Zachary Turner696b5282014-08-14 16:01:25 +000062#include "lldb/Target/ProcessLaunchInfo.h"
Vince Harron76861ea2015-01-16 06:47:43 +000063#include "lldb/Target/UnixSignals.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000064#include "lldb/Utility/CleanUp.h"
Vince Harron76861ea2015-01-16 06:47:43 +000065#include "llvm/ADT/SmallString.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000066
Zachary Turner172d37d2014-10-14 21:55:08 +000067#if defined(_WIN32)
68#include "lldb/Host/windows/ProcessLauncherWindows.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000069#elif defined(__linux__)
70#include "lldb/Host/linux/ProcessLauncherLinux.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000071#else
72#include "lldb/Host/posix/ProcessLauncherPosix.h"
73#endif
74
Todd Fiala76747122014-01-23 00:52:28 +000075#if defined (__APPLE__)
76#ifndef _POSIX_SPAWN_DISABLE_ASLR
77#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
78#endif
79
80extern "C"
81{
82 int __pthread_chdir(const char *path);
83 int __pthread_fchdir (int fildes);
84}
85
86#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000087
Greg Clayton2bddd342010-09-07 20:11:56 +000088using namespace lldb;
89using namespace lldb_private;
90
Virgile Bellob2f1fb22013-08-23 12:44:05 +000091#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +000092struct MonitorInfo
93{
94 lldb::pid_t pid; // The process ID to monitor
95 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
Greg Clayton2bddd342010-09-07 20:11:56 +000096 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
97};
98
Virgile Bellob2f1fb22013-08-23 12:44:05 +000099static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000100MonitorChildProcessThreadFunction (void *arg);
101
Zachary Turner39de3112014-09-09 20:54:56 +0000102HostThread
Pavel Labath998bdc52016-05-11 16:59:04 +0000103Host::StartMonitoringChildProcess(const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid,
104 bool monitor_signals)
Greg Clayton2bddd342010-09-07 20:11:56 +0000105{
Greg Claytone4e45922011-11-16 05:37:56 +0000106 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000107
Greg Claytone4e45922011-11-16 05:37:56 +0000108 info_ptr->pid = pid;
109 info_ptr->callback = callback;
Greg Claytone4e45922011-11-16 05:37:56 +0000110 info_ptr->monitor_signals = monitor_signals;
111
112 char thread_name[256];
Zachary Turner39de3112014-09-09 20:54:56 +0000113 ::snprintf(thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
114 return ThreadLauncher::LaunchThread(thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL);
Greg Clayton2bddd342010-09-07 20:11:56 +0000115}
116
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000117#ifndef __linux__
Greg Clayton2bddd342010-09-07 20:11:56 +0000118//------------------------------------------------------------------
119// Scoped class that will disable thread canceling when it is
120// constructed, and exception safely restore the previous value it
121// when it goes out of scope.
122//------------------------------------------------------------------
123class ScopedPThreadCancelDisabler
124{
125public:
126 ScopedPThreadCancelDisabler()
127 {
128 // Disable the ability for this thread to be cancelled
129 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
130 if (err != 0)
131 m_old_state = -1;
Greg Clayton2bddd342010-09-07 20:11:56 +0000132 }
133
134 ~ScopedPThreadCancelDisabler()
135 {
136 // Restore the ability for this thread to be cancelled to what it
137 // previously was.
138 if (m_old_state != -1)
139 ::pthread_setcancelstate (m_old_state, 0);
140 }
141private:
142 int m_old_state; // Save the old cancelability state.
143};
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000144#endif // __linux__
145
146#ifdef __linux__
Omair Javaid20405482015-08-09 19:04:41 +0000147#if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
148static __thread volatile sig_atomic_t g_usr1_called;
149#else
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000150static thread_local volatile sig_atomic_t g_usr1_called;
Omair Javaid20405482015-08-09 19:04:41 +0000151#endif
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000152
153static void
154SigUsr1Handler (int)
155{
156 g_usr1_called = 1;
157}
158#endif // __linux__
159
160static bool
161CheckForMonitorCancellation()
162{
163#ifdef __linux__
164 if (g_usr1_called)
165 {
166 g_usr1_called = 0;
167 return true;
168 }
169#else
170 ::pthread_testcancel ();
171#endif
172 return false;
173}
Greg Clayton2bddd342010-09-07 20:11:56 +0000174
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000175static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000176MonitorChildProcessThreadFunction (void *arg)
177{
Greg Clayton5160ce52013-03-27 23:08:40 +0000178 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000179 const char *function = __FUNCTION__;
180 if (log)
181 log->Printf ("%s (arg = %p) thread starting...", function, arg);
182
183 MonitorInfo *info = (MonitorInfo *)arg;
184
185 const Host::MonitorChildProcessCallback callback = info->callback;
Greg Clayton2bddd342010-09-07 20:11:56 +0000186 const bool monitor_signals = info->monitor_signals;
187
Daniel Malea4244cbd2013-08-27 20:58:59 +0000188 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000189 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000190
Greg Clayton2bddd342010-09-07 20:11:56 +0000191 delete info;
192
193 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000194#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000195 #define __WALL 0
196#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000197 const int options = __WALL;
198
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000199#ifdef __linux__
200 // This signal is only used to interrupt the thread from waitpid
201 struct sigaction sigUsr1Action;
202 memset(&sigUsr1Action, 0, sizeof(sigUsr1Action));
203 sigUsr1Action.sa_handler = SigUsr1Handler;
204 ::sigaction(SIGUSR1, &sigUsr1Action, nullptr);
205#endif // __linux__
206
Greg Clayton2bddd342010-09-07 20:11:56 +0000207 while (1)
208 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000209 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000210 if (log)
Vince Harronb956a812015-01-23 22:48:28 +0000211 log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000212
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000213 if (CheckForMonitorCancellation ())
214 break;
215
Matt Kopec650648f2013-01-08 16:30:18 +0000216 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000217 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000218
219 if (CheckForMonitorCancellation ())
220 break;
221
Greg Clayton2bddd342010-09-07 20:11:56 +0000222 if (wait_pid == -1)
223 {
224 if (errno == EINTR)
225 continue;
226 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000227 {
228 if (log)
229 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000230 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000231 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000232 }
Matt Kopec650648f2013-01-08 16:30:18 +0000233 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000234 {
235 bool exited = false;
236 int signal = 0;
237 int exit_status = 0;
238 const char *status_cstr = NULL;
239 if (WIFSTOPPED(status))
240 {
241 signal = WSTOPSIG(status);
242 status_cstr = "STOPPED";
243 }
244 else if (WIFEXITED(status))
245 {
246 exit_status = WEXITSTATUS(status);
247 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000248 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000249 }
250 else if (WIFSIGNALED(status))
251 {
252 signal = WTERMSIG(status);
253 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000254 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000255 exited = true;
256 exit_status = -1;
257 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000258 }
259 else
260 {
Johnny Chen44805302011-07-19 19:48:13 +0000261 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000262 }
263
264 // Scope for pthread_cancel_disabler
265 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000266#ifndef __linux__
Greg Clayton2bddd342010-09-07 20:11:56 +0000267 ScopedPThreadCancelDisabler pthread_cancel_disabler;
Todd Fialacacde7d2014-09-27 16:54:22 +0000268#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000269
Caroline Tice20ad3c42010-10-29 21:48:37 +0000270 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000271 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000272 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 +0000273 function,
Greg Clayton2bddd342010-09-07 20:11:56 +0000274 pid,
Vince Harronb956a812015-01-23 22:48:28 +0000275 options,
276 wait_pid,
Greg Clayton2bddd342010-09-07 20:11:56 +0000277 status,
278 status_cstr,
279 signal,
280 exit_status);
281
282 if (exited || (signal != 0 && monitor_signals))
283 {
Greg Claytone4e45922011-11-16 05:37:56 +0000284 bool callback_return = false;
285 if (callback)
Pavel Labath998bdc52016-05-11 16:59:04 +0000286 callback_return = callback(wait_pid, exited, signal, exit_status);
287
Greg Clayton2bddd342010-09-07 20:11:56 +0000288 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000289 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000290 {
291 if (log)
292 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000293 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000294 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000295 // If the callback returns true, it means this process should
296 // exit
297 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000298 {
299 if (log)
300 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000301 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000302 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000303 }
304 }
305 }
306 }
307
Caroline Tice20ad3c42010-10-29 21:48:37 +0000308 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000309 if (log)
310 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
311
312 return NULL;
313}
314
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000315#endif // #if !defined (__APPLE__) && !defined (_WIN32)
316
317#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000318
319void
320Host::SystemLog (SystemLogType type, const char *format, va_list args)
321{
322 vfprintf (stderr, format, args);
323}
324
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000325#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000326
Greg Claytone38a5ed2012-01-05 03:57:59 +0000327void
328Host::SystemLog (SystemLogType type, const char *format, ...)
329{
330 va_list args;
331 va_start (args, format);
332 SystemLog (type, format, args);
333 va_end (args);
334}
335
Greg Clayton2bddd342010-09-07 20:11:56 +0000336lldb::pid_t
337Host::GetCurrentProcessID()
338{
339 return ::getpid();
340}
341
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000342#ifndef _WIN32
343
Greg Clayton2bddd342010-09-07 20:11:56 +0000344lldb::tid_t
345Host::GetCurrentThreadID()
346{
347#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000348 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000349 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
350 // count.
351 thread_port_t thread_self = mach_thread_self();
352 mach_port_deallocate(mach_task_self(), thread_self);
353 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000354#elif defined(__FreeBSD__)
355 return lldb::tid_t(pthread_getthreadid_np());
Shawn Best8da0bf32014-11-08 01:41:49 +0000356#elif defined(__ANDROID_NDK__)
357 return lldb::tid_t(gettid());
Michael Sartainc2052432013-08-01 18:51:08 +0000358#elif defined(__linux__)
359 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000360#else
361 return lldb::tid_t(pthread_self());
362#endif
363}
364
Jim Ingham372787f2012-04-07 00:00:41 +0000365lldb::thread_t
366Host::GetCurrentThread ()
367{
368 return lldb::thread_t(pthread_self());
369}
370
Greg Clayton2bddd342010-09-07 20:11:56 +0000371const char *
372Host::GetSignalAsCString (int signo)
373{
374 switch (signo)
375 {
376 case SIGHUP: return "SIGHUP"; // 1 hangup
377 case SIGINT: return "SIGINT"; // 2 interrupt
378 case SIGQUIT: return "SIGQUIT"; // 3 quit
379 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
380 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
381 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000382#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000383#if !defined(SIGIO) || (SIGPOLL != SIGIO)
384// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
385// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000386 case SIGPOLL: return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000387#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000388#endif
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000389#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000390 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000391#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000392 case SIGFPE: return "SIGFPE"; // 8 floating point exception
393 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
394 case SIGBUS: return "SIGBUS"; // 10 bus error
395 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
396 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
397 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
398 case SIGALRM: return "SIGALRM"; // 14 alarm clock
399 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
400 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
401 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
402 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
403 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
404 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
405 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
406 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000407#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000408 case SIGIO: return "SIGIO"; // 23 input/output possible signal
409#endif
410 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
411 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
412 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
413 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000414#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000415 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000416#endif
417#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000418 case SIGINFO: return "SIGINFO"; // 29 information request
419#endif
420 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
421 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
422 default:
423 break;
424 }
425 return NULL;
426}
427
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000428#endif
429
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000430#ifndef _WIN32
431
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000432lldb::thread_key_t
433Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
434{
435 pthread_key_t key;
436 ::pthread_key_create (&key, callback);
437 return key;
438}
439
440void*
441Host::ThreadLocalStorageGet(lldb::thread_key_t key)
442{
443 return ::pthread_getspecific (key);
444}
445
446void
447Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
448{
449 ::pthread_setspecific (key, value);
450}
451
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000452#endif
453
Greg Clayton2bddd342010-09-07 20:11:56 +0000454#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000455
456bool
457Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
458{
459 bundle.Clear();
460 return false;
461}
462
Greg Clayton2bddd342010-09-07 20:11:56 +0000463bool
Greg Claytondd36def2010-10-17 22:03:32 +0000464Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000465{
Greg Claytondd36def2010-10-17 22:03:32 +0000466 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000467}
468#endif
469
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000470#ifndef _WIN32
471
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000472FileSpec
473Host::GetModuleFileSpecForHostAddress (const void *host_addr)
474{
475 FileSpec module_filespec;
Shawn Best8da0bf32014-11-08 01:41:49 +0000476#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000477 Dl_info info;
478 if (::dladdr (host_addr, &info))
479 {
480 if (info.dli_fname)
481 module_filespec.SetFile(info.dli_fname, true);
482 }
Todd Fialacacde7d2014-09-27 16:54:22 +0000483#endif
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000484 return module_filespec;
485}
486
487#endif
488
Matt Kopec085d6ce2013-05-31 22:00:07 +0000489#if !defined(__linux__)
490bool
491Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
492{
493 return false;
494}
495#endif
496
Greg Claytond1cf11a2012-04-14 01:42:46 +0000497struct ShellInfo
498{
499 ShellInfo () :
500 process_reaped (false),
Greg Claytond1cf11a2012-04-14 01:42:46 +0000501 pid (LLDB_INVALID_PROCESS_ID),
502 signo(-1),
503 status(-1)
504 {
505 }
506
507 lldb_private::Predicate<bool> process_reaped;
Greg Claytond1cf11a2012-04-14 01:42:46 +0000508 lldb::pid_t pid;
509 int signo;
510 int status;
511};
512
513static bool
Pavel Labath998bdc52016-05-11 16:59:04 +0000514MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid,
515 bool exited, // True if the process did exit
516 int signo, // Zero for no signal
517 int status) // Exit value of process if signal is zero
Greg Claytond1cf11a2012-04-14 01:42:46 +0000518{
Greg Claytond1cf11a2012-04-14 01:42:46 +0000519 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
Pavel Labath998bdc52016-05-11 16:59:04 +0000524 shell_info->process_reaped.SetValue(true, eBroadcastAlways);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000525 return true;
526}
527
528Error
Chaoren Lind3173f32015-05-29 19:52:29 +0000529Host::RunShellCommand(const char *command,
530 const FileSpec &working_dir,
531 int *status_ptr,
532 int *signo_ptr,
533 std::string *command_output_ptr,
534 uint32_t timeout_sec,
535 bool run_in_default_shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +0000536{
Enrico Granata66eda732015-04-17 01:50:11 +0000537 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr, command_output_ptr, timeout_sec, run_in_default_shell);
538}
539
540Error
Chaoren Lind3173f32015-05-29 19:52:29 +0000541Host::RunShellCommand(const Args &args,
542 const FileSpec &working_dir,
543 int *status_ptr,
544 int *signo_ptr,
545 std::string *command_output_ptr,
546 uint32_t timeout_sec,
547 bool run_in_default_shell)
Enrico Granata66eda732015-04-17 01:50:11 +0000548{
Greg Claytond1cf11a2012-04-14 01:42:46 +0000549 Error error;
550 ProcessLaunchInfo launch_info;
Zachary Turner270e99a2014-12-08 21:36:42 +0000551 launch_info.SetArchitecture(HostInfo::GetArchitecture());
Zachary Turner10687b02014-10-20 17:46:43 +0000552 if (run_in_default_shell)
Greg Claytonc8f814d2012-09-27 03:13:55 +0000553 {
554 // Run the command in a shell
Zachary Turner10687b02014-10-20 17:46:43 +0000555 launch_info.SetShell(HostInfo::GetDefaultShell());
Enrico Granata66eda732015-04-17 01:50:11 +0000556 launch_info.GetArguments().AppendArguments(args);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000557 const bool localhost = true;
558 const bool will_debug = false;
Enrico Granata66eda732015-04-17 01:50:11 +0000559 const bool first_arg_is_full_shell_command = false;
Greg Claytonc8f814d2012-09-27 03:13:55 +0000560 launch_info.ConvertArgumentsForLaunchingInShell (error,
561 localhost,
562 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000563 first_arg_is_full_shell_command,
564 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000565 }
566 else
567 {
568 // No shell, just run it
Greg Claytonc8f814d2012-09-27 03:13:55 +0000569 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +0000570 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000571 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000572
573 if (working_dir)
574 launch_info.SetWorkingDirectory(working_dir);
Zachary Turner270e99a2014-12-08 21:36:42 +0000575 llvm::SmallString<PATH_MAX> output_file_path;
Enrico Granata66eda732015-04-17 01:50:11 +0000576
Greg Claytond1cf11a2012-04-14 01:42:46 +0000577 if (command_output_ptr)
578 {
579 // Create a temporary file to get the stdout/stderr and redirect the
580 // output of the command into this file. We will later read this file
581 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +0000582 FileSpec tmpdir_file_spec;
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000583 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
Greg Claytonc6931fc2013-12-04 18:53:50 +0000584 {
Zachary Turner270e99a2014-12-08 21:36:42 +0000585 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
586 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath().c_str(), output_file_path);
Greg Claytonc6931fc2013-12-04 18:53:50 +0000587 }
588 else
589 {
Zachary Turner270e99a2014-12-08 21:36:42 +0000590 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "", output_file_path);
Greg Claytonc6931fc2013-12-04 18:53:50 +0000591 }
Greg Claytonc6931fc2013-12-04 18:53:50 +0000592 }
Chaoren Lind3173f32015-05-29 19:52:29 +0000593
594 FileSpec output_file_spec{output_file_path.c_str(), false};
595
Greg Claytonc6931fc2013-12-04 18:53:50 +0000596 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
Chaoren Lind3173f32015-05-29 19:52:29 +0000597 if (output_file_spec)
Greg Claytonc6931fc2013-12-04 18:53:50 +0000598 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000599 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000600 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000601 }
602 else
603 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000604 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
605 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
606 }
Pavel Labath998bdc52016-05-11 16:59:04 +0000607
608 std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +0000609 const bool monitor_signals = false;
Pavel Labath998bdc52016-05-11 16:59:04 +0000610 launch_info.SetMonitorProcessCallback(std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1,
611 std::placeholders::_2, std::placeholders::_3,
612 std::placeholders::_4),
613 monitor_signals);
614
Greg Claytond1cf11a2012-04-14 01:42:46 +0000615 error = LaunchProcess (launch_info);
616 const lldb::pid_t pid = launch_info.GetProcessID();
Enrico Granata66eda732015-04-17 01:50:11 +0000617
Daniel Maleae0f8f572013-08-26 23:57:52 +0000618 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
619 error.SetErrorString("failed to get process ID");
Enrico Granata66eda732015-04-17 01:50:11 +0000620
Daniel Maleae0f8f572013-08-26 23:57:52 +0000621 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +0000622 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000623 bool timed_out = false;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000624 shell_info_sp->process_reaped.WaitForValueEqualTo(true, std::chrono::seconds(timeout_sec), &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000625 if (timed_out)
626 {
627 error.SetErrorString("timed out waiting for shell command to complete");
Enrico Granata66eda732015-04-17 01:50:11 +0000628
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000629 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000630 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000631 // Wait for the monitor callback to get the message
Greg Claytond1cf11a2012-04-14 01:42:46 +0000632 timed_out = false;
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000633 shell_info_sp->process_reaped.WaitForValueEqualTo(true, std::chrono::seconds(1), &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000634 }
635 else
636 {
637 if (status_ptr)
Pavel Labath998bdc52016-05-11 16:59:04 +0000638 *status_ptr = shell_info_sp->status;
639
Greg Claytond1cf11a2012-04-14 01:42:46 +0000640 if (signo_ptr)
Pavel Labath998bdc52016-05-11 16:59:04 +0000641 *signo_ptr = shell_info_sp->signo;
642
Greg Claytond1cf11a2012-04-14 01:42:46 +0000643 if (command_output_ptr)
644 {
645 command_output_ptr->clear();
Chaoren Lind3173f32015-05-29 19:52:29 +0000646 uint64_t file_size = output_file_spec.GetByteSize();
Greg Claytond1cf11a2012-04-14 01:42:46 +0000647 if (file_size > 0)
648 {
649 if (file_size > command_output_ptr->max_size())
650 {
651 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
652 }
653 else
654 {
Chaoren Lind3173f32015-05-29 19:52:29 +0000655 std::vector<char> command_output(file_size);
656 output_file_spec.ReadFileContents(0, command_output.data(), file_size, &error);
657 if (error.Success())
658 command_output_ptr->assign(command_output.data(), file_size);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000659 }
660 }
661 }
662 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000663 }
Chaoren Lind3173f32015-05-29 19:52:29 +0000664
Zachary Turner270e99a2014-12-08 21:36:42 +0000665 if (FileSystem::GetFileExists(output_file_spec))
Chaoren Lind3173f32015-05-29 19:52:29 +0000666 FileSystem::Unlink(output_file_spec);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000667 return error;
668}
669
Todd Fiala76747122014-01-23 00:52:28 +0000670// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
671// systems
672
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000673#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Tamas Berghammer00e305d2015-02-12 18:13:44 +0000674#if !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
Todd Fiala76747122014-01-23 00:52:28 +0000675// this method needs to be visible to macosx/Host.cpp and
676// common/Host.cpp.
677
678short
Zachary Turner172d37d2014-10-14 21:55:08 +0000679Host::GetPosixspawnFlags(const ProcessLaunchInfo &launch_info)
Todd Fiala76747122014-01-23 00:52:28 +0000680{
681 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
682
683#if defined (__APPLE__)
684 if (launch_info.GetFlags().Test (eLaunchFlagExec))
685 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
686
687 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
688 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
689
690 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
691 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
692
693 if (launch_info.GetLaunchInSeparateProcessGroup())
694 flags |= POSIX_SPAWN_SETPGROUP;
695
696#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
697#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
698 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
699 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
700 {
701 g_use_close_on_exec_flag = eLazyBoolNo;
702
703 uint32_t major, minor, update;
Zachary Turner97a14e62014-08-19 17:18:29 +0000704 if (HostInfo::GetOSVersion(major, minor, update))
Todd Fiala76747122014-01-23 00:52:28 +0000705 {
706 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
707 if (major > 10 || (major == 10 && minor > 7))
708 {
709 // Only enable for 10.8 and later OS versions
710 g_use_close_on_exec_flag = eLazyBoolYes;
711 }
712 }
713 }
714#else
715 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
716#endif
717 // Close all files exception those with file actions if this is supported.
718 if (g_use_close_on_exec_flag == eLazyBoolYes)
719 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
720#endif
721#endif // #if defined (__APPLE__)
722 return flags;
723}
724
725Error
Zachary Turner172d37d2014-10-14 21:55:08 +0000726Host::LaunchProcessPosixSpawn(const char *exe_path, const ProcessLaunchInfo &launch_info, lldb::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000727{
728 Error error;
729 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
730
Daniel Malea4244cbd2013-08-27 20:58:59 +0000731 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000732 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000733
734 if (error.Fail() || log)
735 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +0000736 if (error.Fail())
737 return error;
738
739 // Make a quick class that will cleanup the posix spawn attributes in case
740 // we return in the middle of this function.
741 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
742
743 sigset_t no_signals;
744 sigset_t all_signals;
745 sigemptyset (&no_signals);
746 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000747 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +0000748#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000749 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000750#else
751 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
752#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000753
Todd Fiala76747122014-01-23 00:52:28 +0000754 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000755
756 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000757 if (error.Fail() || log)
758 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000759 if (error.Fail())
760 return error;
761
Todd Fiala76747122014-01-23 00:52:28 +0000762 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
763 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
764#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +0000765
766 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
767 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
768 // to do that job on OSX.
769
770 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000771 {
Jim Ingham90331d52014-02-21 01:25:21 +0000772 // We don't need to do this for ARM, and we really shouldn't now that we
773 // have multiple CPU subtypes and no posix_spawnattr call that allows us
774 // to set which CPU subtype to launch...
775 const ArchSpec &arch_spec = launch_info.GetArchitecture();
776 cpu_type_t cpu = arch_spec.GetMachOCPUType();
777 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
778 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +0000779 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
780 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +0000781 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
782 {
783 size_t ocount = 0;
784 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
785 if (error.Fail() || log)
786 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 +0000787
Jim Ingham90331d52014-02-21 01:25:21 +0000788 if (error.Fail() || ocount != 1)
789 return error;
790 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000791 }
792
Todd Fiala76747122014-01-23 00:52:28 +0000793#endif
794
795 const char *tmp_argv[2];
Saleem Abdulrasoolba507b02015-10-18 19:34:38 +0000796 char * const *argv = const_cast<char * const*>(launch_info.GetArguments().GetConstArgumentVector());
797 char * const *envp = const_cast<char * const*>(launch_info.GetEnvironmentEntries().GetConstArgumentVector());
Todd Fiala76747122014-01-23 00:52:28 +0000798 if (argv == NULL)
799 {
800 // posix_spawn gets very unhappy if it doesn't have at least the program
801 // name in argv[0]. One of the side affects I have noticed is the environment
802 // variables don't make it into the child process if "argv == NULL"!!!
803 tmp_argv[0] = exe_path;
804 tmp_argv[1] = NULL;
Saleem Abdulrasoolba507b02015-10-18 19:34:38 +0000805 argv = const_cast<char * const*>(tmp_argv);
Todd Fiala76747122014-01-23 00:52:28 +0000806 }
807
808#if !defined (__APPLE__)
809 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +0000810 char current_dir[PATH_MAX];
811 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +0000812#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000813
Chaoren Lind3173f32015-05-29 19:52:29 +0000814 FileSpec working_dir{launch_info.GetWorkingDirectory()};
Todd Fiala76747122014-01-23 00:52:28 +0000815 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000816 {
Todd Fiala76747122014-01-23 00:52:28 +0000817#if defined (__APPLE__)
818 // Set the working directory on this thread only
Chaoren Lind3173f32015-05-29 19:52:29 +0000819 if (__pthread_chdir(working_dir.GetCString()) < 0) {
Todd Fiala76747122014-01-23 00:52:28 +0000820 if (errno == ENOENT) {
Chaoren Lind3173f32015-05-29 19:52:29 +0000821 error.SetErrorStringWithFormat("No such file or directory: %s",
822 working_dir.GetCString());
Todd Fiala76747122014-01-23 00:52:28 +0000823 } else if (errno == ENOTDIR) {
Chaoren Lind3173f32015-05-29 19:52:29 +0000824 error.SetErrorStringWithFormat("Path doesn't name a directory: %s",
825 working_dir.GetCString());
Todd Fiala76747122014-01-23 00:52:28 +0000826 } 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
Chaoren Lind3173f32015-05-29 19:52:29 +0000839 if (::chdir(working_dir.GetCString()) == -1)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000840 {
841 error.SetError(errno, eErrorTypePOSIX);
Chaoren Lind3173f32015-05-29 19:52:29 +0000842 error.LogIfError(log, "unable to change working directory to %s",
843 working_dir.GetCString());
Daniel Malea4244cbd2013-08-27 20:58:59 +0000844 return error;
845 }
Todd Fiala76747122014-01-23 00:52:28 +0000846#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000847 }
848
Zachary Turner172d37d2014-10-14 21:55:08 +0000849 ::pid_t result_pid = LLDB_INVALID_PROCESS_ID;
Todd Fiala76747122014-01-23 00:52:28 +0000850 const size_t num_file_actions = launch_info.GetNumFileActions ();
851 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000852 {
Todd Fiala76747122014-01-23 00:52:28 +0000853 posix_spawn_file_actions_t file_actions;
854 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
855 if (error.Fail() || log)
856 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
857 if (error.Fail())
858 return error;
859
860 // Make a quick class that will cleanup the posix spawn attributes in case
861 // we return in the middle of this function.
862 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
863
864 for (size_t i=0; i<num_file_actions; ++i)
865 {
Zachary Turner696b5282014-08-14 16:01:25 +0000866 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +0000867 if (launch_file_action)
868 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000869 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
Todd Fiala76747122014-01-23 00:52:28 +0000870 return error;
871 }
872 }
873
Zachary Turner172d37d2014-10-14 21:55:08 +0000874 error.SetError(::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000875
876 if (error.Fail() || log)
877 {
Zachary Turner172d37d2014-10-14 21:55:08 +0000878 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", result_pid,
879 exe_path, static_cast<void *>(&file_actions), static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
880 reinterpret_cast<const void *>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000881 if (log)
882 {
883 for (int ii=0; argv[ii]; ++ii)
884 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
885 }
886 }
887
888 }
889 else
890 {
Zachary Turner172d37d2014-10-14 21:55:08 +0000891 error.SetError(::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000892
893 if (error.Fail() || log)
894 {
895 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 +0000896 result_pid, exe_path, static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
897 reinterpret_cast<const void *>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000898 if (log)
899 {
900 for (int ii=0; argv[ii]; ++ii)
901 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
902 }
903 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000904 }
Zachary Turner172d37d2014-10-14 21:55:08 +0000905 pid = result_pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000906
Todd Fiala76747122014-01-23 00:52:28 +0000907 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000908 {
Todd Fiala76747122014-01-23 00:52:28 +0000909#if defined (__APPLE__)
910 // No more thread specific current working directory
911 __pthread_fchdir (-1);
912#else
913 if (::chdir(current_dir) == -1 && error.Success())
914 {
915 error.SetError(errno, eErrorTypePOSIX);
916 error.LogIfError(log, "unable to change current directory back to %s",
917 current_dir);
918 }
919#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000920 }
921
922 return error;
923}
924
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000925bool
926Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
Zachary Turner696b5282014-08-14 16:01:25 +0000927{
928 if (info == NULL)
929 return false;
930
931 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
932
933 switch (info->GetAction())
934 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000935 case FileAction::eFileActionNone:
936 error.Clear();
937 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000938
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000939 case FileAction::eFileActionClose:
940 if (info->GetFD() == -1)
941 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
942 else
943 {
944 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
945 if (log && (error.Fail() || log))
946 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
947 static_cast<void *>(file_actions), info->GetFD());
948 }
949 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000950
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000951 case FileAction::eFileActionDuplicate:
952 if (info->GetFD() == -1)
953 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
954 else if (info->GetActionArgument() == -1)
955 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
956 else
957 {
958 error.SetError(
959 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
960 eErrorTypePOSIX);
961 if (log && (error.Fail() || log))
962 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
963 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
964 }
965 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000966
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000967 case FileAction::eFileActionOpen:
968 if (info->GetFD() == -1)
969 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
970 else
971 {
972 int oflag = info->GetActionArgument();
Zachary Turner696b5282014-08-14 16:01:25 +0000973
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000974 mode_t mode = 0;
Zachary Turner696b5282014-08-14 16:01:25 +0000975
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000976 if (oflag & O_CREAT)
977 mode = 0640;
Zachary Turner696b5282014-08-14 16:01:25 +0000978
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000979 error.SetError(
980 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
981 eErrorTypePOSIX);
982 if (error.Fail() || log)
983 error.PutToLog(log,
984 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
985 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
986 }
987 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000988 }
989 return error.Success();
990}
Tamas Berghammer00e305d2015-02-12 18:13:44 +0000991#endif // !defined(__ANDROID__) && !defined(__ANDROID_NDK__)
992#endif // defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +0000993
Zachary Turner172d37d2014-10-14 21:55:08 +0000994#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__) || defined(_WIN32)
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000995// The functions below implement process launching via posix_spawn() for Linux,
996// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +0000997
998Error
999Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1000{
Zachary Turner172d37d2014-10-14 21:55:08 +00001001 std::unique_ptr<ProcessLauncher> delegate_launcher;
1002#if defined(_WIN32)
1003 delegate_launcher.reset(new ProcessLauncherWindows());
Pavel Labath5ad891f2016-07-21 14:54:03 +00001004#elif defined(__linux__)
1005 delegate_launcher.reset(new ProcessLauncherLinux());
Zachary Turner172d37d2014-10-14 21:55:08 +00001006#else
1007 delegate_launcher.reset(new ProcessLauncherPosix());
1008#endif
1009 MonitoringProcessLauncher launcher(std::move(delegate_launcher));
1010
Daniel Malea4244cbd2013-08-27 20:58:59 +00001011 Error error;
Zachary Turner172d37d2014-10-14 21:55:08 +00001012 HostProcess process = launcher.LaunchProcess(launch_info, error);
Daniel Malea4244cbd2013-08-27 20:58:59 +00001013
Zachary Turner172d37d2014-10-14 21:55:08 +00001014 // TODO(zturner): It would be better if the entire HostProcess were returned instead of writing
1015 // it into this structure.
1016 launch_info.SetProcessID(process.GetProcessId());
Daniel Malea4244cbd2013-08-27 20:58:59 +00001017
Daniel Malea4244cbd2013-08-27 20:58:59 +00001018 return error;
1019}
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001020#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001021
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001022#ifndef _WIN32
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001023void
1024Host::Kill(lldb::pid_t pid, int signo)
1025{
1026 ::kill(pid, signo);
1027}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001028
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001029#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001030
Johnny Chen8f3d8382011-08-02 20:52:42 +00001031#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001032bool
Greg Clayton3b147632010-12-18 01:54:34 +00001033Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001034{
1035 return false;
1036}
Greg Claytondd36def2010-10-17 22:03:32 +00001037
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001038void
1039Host::SetCrashDescriptionWithFormat (const char *format, ...)
1040{
1041}
1042
1043void
1044Host::SetCrashDescription (const char *description)
1045{
1046}
Greg Claytondd36def2010-10-17 22:03:32 +00001047
Greg Claytonfbb76342013-11-20 21:07:01 +00001048#endif
Todd Fiala4ceced32014-08-29 17:35:57 +00001049
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001050const UnixSignalsSP &
1051Host::GetUnixSignals()
Todd Fiala4ceced32014-08-29 17:35:57 +00001052{
Chaoren Lin98d0a4b2015-07-14 01:09:28 +00001053 static const auto s_unix_signals_sp = UnixSignals::Create(HostInfo::GetArchitecture());
Todd Fiala4ceced32014-08-29 17:35:57 +00001054 return s_unix_signals_sp;
1055}