blob: 6d0ad0175fd87ae25a7a42d85ab27631e23e67e7 [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
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#include <dlfcn.h>
17#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000018#include <netdb.h>
19#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000020#include <sys/stat.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000021#include <unistd.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000022#endif
23
Kate Stoneb9c1b512016-09-06 20:57:50 +000024#if defined(__APPLE__)
Charles Davis510938e2013-08-27 05:04:57 +000025#include <mach-o/dyld.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000026#include <mach/mach_init.h>
27#include <mach/mach_port.h>
Ed Maste8b006c62013-06-25 18:58:11 +000028#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000029
Kate Stoneb9c1b512016-09-06 20:57:50 +000030#if defined(__linux__) || defined(__FreeBSD__) || \
31 defined(__FreeBSD_kernel__) || defined(__APPLE__) || defined(__NetBSD__)
Pavel Labathe705c8b2016-12-02 11:15:15 +000032#if !defined(__ANDROID__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000033#include <spawn.h>
Todd Fialacacde7d2014-09-27 16:54:22 +000034#endif
Michael Sartainc2052432013-08-01 18:51:08 +000035#include <sys/syscall.h>
Kate Stoneb9c1b512016-09-06 20:57:50 +000036#include <sys/wait.h>
Ed Maste8b006c62013-06-25 18:58:11 +000037#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000038
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#if defined(__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000040#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000041#endif
42
Jim Ingham9d9b46b2016-03-15 21:11:02 +000043// C++ Includes
44
45// Other libraries and framework includes
46// Project includes
Todd Fiala17096d72014-07-16 19:03:16 +000047
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"
Kate Stoneb9c1b512016-09-06 20:57:50 +000052#include "lldb/Host/FileSystem.h"
53#include "lldb/Host/Host.h"
54#include "lldb/Host/HostInfo.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000055#include "lldb/Host/HostProcess.h"
56#include "lldb/Host/MonitoringProcessLauncher.h"
Vince Harron76861ea2015-01-16 06:47:43 +000057#include "lldb/Host/Predicate.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000058#include "lldb/Host/ProcessLauncher.h"
Zachary Turner39de3112014-09-09 20:54:56 +000059#include "lldb/Host/ThreadLauncher.h"
Zachary Turner696b5282014-08-14 16:01:25 +000060#include "lldb/Target/FileAction.h"
Zachary Turner696b5282014-08-14 16:01:25 +000061#include "lldb/Target/ProcessLaunchInfo.h"
Vince Harron76861ea2015-01-16 06:47:43 +000062#include "lldb/Target/UnixSignals.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000063#include "lldb/Utility/CleanUp.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000064#include "lldb/lldb-private-forward.h"
Vince Harron76861ea2015-01-16 06:47:43 +000065#include "llvm/ADT/SmallString.h"
Kate Stoneb9c1b512016-09-06 20:57:50 +000066#include "llvm/Support/FileSystem.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000067
Zachary Turner172d37d2014-10-14 21:55:08 +000068#if defined(_WIN32)
69#include "lldb/Host/windows/ProcessLauncherWindows.h"
Pavel Labath5ad891f2016-07-21 14:54:03 +000070#elif defined(__linux__)
71#include "lldb/Host/linux/ProcessLauncherLinux.h"
Zachary Turner172d37d2014-10-14 21:55:08 +000072#else
73#include "lldb/Host/posix/ProcessLauncherPosix.h"
74#endif
75
Kate Stoneb9c1b512016-09-06 20:57:50 +000076#if defined(__APPLE__)
Todd Fiala76747122014-01-23 00:52:28 +000077#ifndef _POSIX_SPAWN_DISABLE_ASLR
Kate Stoneb9c1b512016-09-06 20:57:50 +000078#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
Todd Fiala76747122014-01-23 00:52:28 +000079#endif
80
Kate Stoneb9c1b512016-09-06 20:57:50 +000081extern "C" {
82int __pthread_chdir(const char *path);
83int __pthread_fchdir(int fildes);
Todd Fiala76747122014-01-23 00:52:28 +000084}
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
Kate Stoneb9c1b512016-09-06 20:57:50 +000091#if !defined(__APPLE__) && !defined(_WIN32)
92struct MonitorInfo {
93 lldb::pid_t pid; // The process ID to monitor
94 Host::MonitorChildProcessCallback
95 callback; // The callback function to call when "pid" exits or signals
96 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
Greg Clayton2bddd342010-09-07 20:11:56 +000097};
98
Kate Stoneb9c1b512016-09-06 20:57:50 +000099static thread_result_t MonitorChildProcessThreadFunction(void *arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101HostThread Host::StartMonitoringChildProcess(
102 const Host::MonitorChildProcessCallback &callback, lldb::pid_t pid,
103 bool monitor_signals) {
104 MonitorInfo *info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000105
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 info_ptr->pid = pid;
107 info_ptr->callback = callback;
108 info_ptr->monitor_signals = monitor_signals;
109
110 char thread_name[256];
111 ::snprintf(thread_name, sizeof(thread_name),
112 "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
113 return ThreadLauncher::LaunchThread(
114 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//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123class ScopedPThreadCancelDisabler {
Greg Clayton2bddd342010-09-07 20:11:56 +0000124public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 ScopedPThreadCancelDisabler() {
126 // Disable the ability for this thread to be cancelled
127 int err = ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &m_old_state);
128 if (err != 0)
129 m_old_state = -1;
130 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000131
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132 ~ScopedPThreadCancelDisabler() {
133 // Restore the ability for this thread to be cancelled to what it
134 // previously was.
135 if (m_old_state != -1)
136 ::pthread_setcancelstate(m_old_state, 0);
137 }
138
Greg Clayton2bddd342010-09-07 20:11:56 +0000139private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 int m_old_state; // Save the old cancelability state.
Greg Clayton2bddd342010-09-07 20:11:56 +0000141};
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000142#endif // __linux__
143
144#ifdef __linux__
Omair Javaid20405482015-08-09 19:04:41 +0000145#if defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8))
146static __thread volatile sig_atomic_t g_usr1_called;
147#else
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000148static thread_local volatile sig_atomic_t g_usr1_called;
Omair Javaid20405482015-08-09 19:04:41 +0000149#endif
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151static void SigUsr1Handler(int) { g_usr1_called = 1; }
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000152#endif // __linux__
153
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154static bool CheckForMonitorCancellation() {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000155#ifdef __linux__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 if (g_usr1_called) {
157 g_usr1_called = 0;
158 return true;
159 }
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000160#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 ::pthread_testcancel();
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000162#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 return false;
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000164}
Greg Clayton2bddd342010-09-07 20:11:56 +0000165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166static thread_result_t MonitorChildProcessThreadFunction(void *arg) {
167 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
168 const char *function = __FUNCTION__;
169 if (log)
170 log->Printf("%s (arg = %p) thread starting...", function, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172 MonitorInfo *info = (MonitorInfo *)arg;
Greg Clayton2bddd342010-09-07 20:11:56 +0000173
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174 const Host::MonitorChildProcessCallback callback = info->callback;
175 const bool monitor_signals = info->monitor_signals;
Greg Clayton2bddd342010-09-07 20:11:56 +0000176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177 assert(info->pid <= UINT32_MAX);
178 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000179
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 delete info;
Greg Clayton2bddd342010-09-07 20:11:56 +0000181
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182 int status = -1;
183#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__)
184#define __WALL 0
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000185#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000186 const int options = __WALL;
Matt Kopec650648f2013-01-08 16:30:18 +0000187
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000188#ifdef __linux__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000189 // This signal is only used to interrupt the thread from waitpid
190 struct sigaction sigUsr1Action;
191 memset(&sigUsr1Action, 0, sizeof(sigUsr1Action));
192 sigUsr1Action.sa_handler = SigUsr1Handler;
193 ::sigaction(SIGUSR1, &sigUsr1Action, nullptr);
194#endif // __linux__
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000195
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 while (1) {
197 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
198 if (log)
199 log->Printf("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i)...",
200 function, pid, options);
201
202 if (CheckForMonitorCancellation())
203 break;
204
205 // Get signals from all children with same process group of pid
206 const ::pid_t wait_pid = ::waitpid(pid, &status, options);
207
208 if (CheckForMonitorCancellation())
209 break;
210
211 if (wait_pid == -1) {
212 if (errno == EINTR)
213 continue;
214 else {
Greg Clayton2bddd342010-09-07 20:11:56 +0000215 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216 log->Printf(
217 "%s (arg = %p) thread exiting because waitpid failed (%s)...",
218 __FUNCTION__, arg, strerror(errno));
219 break;
220 }
221 } else if (wait_pid > 0) {
222 bool exited = false;
223 int signal = 0;
224 int exit_status = 0;
225 const char *status_cstr = NULL;
226 if (WIFSTOPPED(status)) {
227 signal = WSTOPSIG(status);
228 status_cstr = "STOPPED";
229 } else if (WIFEXITED(status)) {
230 exit_status = WEXITSTATUS(status);
231 status_cstr = "EXITED";
232 exited = true;
233 } else if (WIFSIGNALED(status)) {
234 signal = WTERMSIG(status);
235 status_cstr = "SIGNALED";
236 if (wait_pid == abs(pid)) {
237 exited = true;
238 exit_status = -1;
Greg Clayton2bddd342010-09-07 20:11:56 +0000239 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 } else {
241 status_cstr = "(\?\?\?)";
242 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 // Scope for pthread_cancel_disabler
245 {
Tamas Berghammer0cbf0b12015-03-13 11:16:03 +0000246#ifndef __linux__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 ScopedPThreadCancelDisabler pthread_cancel_disabler;
Todd Fialacacde7d2014-09-27 16:54:22 +0000248#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000249
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
251 if (log)
252 log->Printf("%s ::waitpid (pid = %" PRIi32
253 ", &status, options = %i) => pid = %" PRIi32
254 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
255 function, pid, options, wait_pid, status, status_cstr,
256 signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000257
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 if (exited || (signal != 0 && monitor_signals)) {
259 bool callback_return = false;
260 if (callback)
261 callback_return = callback(wait_pid, exited, signal, exit_status);
Pavel Labath998bdc52016-05-11 16:59:04 +0000262
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263 // If our process exited, then this thread should exit
264 if (exited && wait_pid == abs(pid)) {
265 if (log)
266 log->Printf("%s (arg = %p) thread exiting because pid received "
267 "exit signal...",
268 __FUNCTION__, arg);
269 break;
270 }
271 // If the callback returns true, it means this process should
272 // exit
273 if (callback_return) {
274 if (log)
275 log->Printf("%s (arg = %p) thread exiting because callback "
276 "returned true...",
277 __FUNCTION__, arg);
278 break;
279 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000280 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000281 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000282 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000284
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285 log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
286 if (log)
287 log->Printf("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000288
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289 return NULL;
Greg Clayton2bddd342010-09-07 20:11:56 +0000290}
291
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000292#endif // #if !defined (__APPLE__) && !defined (_WIN32)
293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294#if !defined(__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000295
Kate Stoneb9c1b512016-09-06 20:57:50 +0000296void Host::SystemLog(SystemLogType type, const char *format, va_list args) {
297 vfprintf(stderr, format, args);
Greg Claytone38a5ed2012-01-05 03:57:59 +0000298}
299
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000300#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000301
Kate Stoneb9c1b512016-09-06 20:57:50 +0000302void Host::SystemLog(SystemLogType type, const char *format, ...) {
303 va_list args;
304 va_start(args, format);
305 SystemLog(type, format, args);
306 va_end(args);
Greg Claytone38a5ed2012-01-05 03:57:59 +0000307}
308
Kate Stoneb9c1b512016-09-06 20:57:50 +0000309lldb::pid_t Host::GetCurrentProcessID() { return ::getpid(); }
Greg Clayton2bddd342010-09-07 20:11:56 +0000310
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000311#ifndef _WIN32
312
Kate Stoneb9c1b512016-09-06 20:57:50 +0000313lldb::tid_t Host::GetCurrentThreadID() {
314#if defined(__APPLE__)
315 // Calling "mach_thread_self()" bumps the reference count on the thread
316 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
317 // count.
318 thread_port_t thread_self = mach_thread_self();
319 mach_port_deallocate(mach_task_self(), thread_self);
320 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000321#elif defined(__FreeBSD__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 return lldb::tid_t(pthread_getthreadid_np());
Pavel Labathe705c8b2016-12-02 11:15:15 +0000323#elif defined(__ANDROID__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 return lldb::tid_t(gettid());
Michael Sartainc2052432013-08-01 18:51:08 +0000325#elif defined(__linux__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000327#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 return lldb::tid_t(pthread_self());
Greg Clayton2bddd342010-09-07 20:11:56 +0000329#endif
330}
331
Kate Stoneb9c1b512016-09-06 20:57:50 +0000332lldb::thread_t Host::GetCurrentThread() {
333 return lldb::thread_t(pthread_self());
Jim Ingham372787f2012-04-07 00:00:41 +0000334}
335
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336const char *Host::GetSignalAsCString(int signo) {
337 switch (signo) {
338 case SIGHUP:
339 return "SIGHUP"; // 1 hangup
340 case SIGINT:
341 return "SIGINT"; // 2 interrupt
342 case SIGQUIT:
343 return "SIGQUIT"; // 3 quit
344 case SIGILL:
345 return "SIGILL"; // 4 illegal instruction (not reset when caught)
346 case SIGTRAP:
347 return "SIGTRAP"; // 5 trace trap (not reset when caught)
348 case SIGABRT:
349 return "SIGABRT"; // 6 abort()
350#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000351#if !defined(SIGIO) || (SIGPOLL != SIGIO)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 // Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
353 // fail with 'multiple define cases with same value'
354 case SIGPOLL:
355 return "SIGPOLL"; // 7 pollable event ([XSR] generated, not supported)
Benjamin Kramer44030f12011-11-04 16:06:40 +0000356#endif
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000357#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358#if defined(SIGEMT)
359 case SIGEMT:
360 return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000361#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 case SIGFPE:
363 return "SIGFPE"; // 8 floating point exception
364 case SIGKILL:
365 return "SIGKILL"; // 9 kill (cannot be caught or ignored)
366 case SIGBUS:
367 return "SIGBUS"; // 10 bus error
368 case SIGSEGV:
369 return "SIGSEGV"; // 11 segmentation violation
370 case SIGSYS:
371 return "SIGSYS"; // 12 bad argument to system call
372 case SIGPIPE:
373 return "SIGPIPE"; // 13 write on a pipe with no one to read it
374 case SIGALRM:
375 return "SIGALRM"; // 14 alarm clock
376 case SIGTERM:
377 return "SIGTERM"; // 15 software termination signal from kill
378 case SIGURG:
379 return "SIGURG"; // 16 urgent condition on IO channel
380 case SIGSTOP:
381 return "SIGSTOP"; // 17 sendable stop signal not from tty
382 case SIGTSTP:
383 return "SIGTSTP"; // 18 stop signal from tty
384 case SIGCONT:
385 return "SIGCONT"; // 19 continue a stopped process
386 case SIGCHLD:
387 return "SIGCHLD"; // 20 to parent on child stop or exit
388 case SIGTTIN:
389 return "SIGTTIN"; // 21 to readers pgrp upon background tty read
390 case SIGTTOU:
391 return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
392#if defined(SIGIO)
393 case SIGIO:
394 return "SIGIO"; // 23 input/output possible signal
Greg Clayton2bddd342010-09-07 20:11:56 +0000395#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 case SIGXCPU:
397 return "SIGXCPU"; // 24 exceeded CPU time limit
398 case SIGXFSZ:
399 return "SIGXFSZ"; // 25 exceeded file size limit
400 case SIGVTALRM:
401 return "SIGVTALRM"; // 26 virtual time alarm
402 case SIGPROF:
403 return "SIGPROF"; // 27 profiling time alarm
404#if defined(SIGWINCH)
405 case SIGWINCH:
406 return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000407#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408#if defined(SIGINFO)
409 case SIGINFO:
410 return "SIGINFO"; // 29 information request
Greg Clayton2bddd342010-09-07 20:11:56 +0000411#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 case SIGUSR1:
413 return "SIGUSR1"; // 30 user defined signal 1
414 case SIGUSR2:
415 return "SIGUSR2"; // 31 user defined signal 2
416 default:
417 break;
418 }
419 return NULL;
Greg Clayton2bddd342010-09-07 20:11:56 +0000420}
421
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000422#endif
423
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000424#ifndef _WIN32
425
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000426lldb::thread_key_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback) {
428 pthread_key_t key;
429 ::pthread_key_create(&key, callback);
430 return key;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000431}
432
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433void *Host::ThreadLocalStorageGet(lldb::thread_key_t key) {
434 return ::pthread_getspecific(key);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000435}
436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437void Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value) {
438 ::pthread_setspecific(key, value);
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000439}
440
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000441#endif
442
Kate Stoneb9c1b512016-09-06 20:57:50 +0000443#if !defined(__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445bool Host::GetBundleDirectory(const FileSpec &file, FileSpec &bundle) {
446 bundle.Clear();
447 return false;
Greg Claytonc859e2d2012-02-13 23:10:39 +0000448}
449
Kate Stoneb9c1b512016-09-06 20:57:50 +0000450bool Host::ResolveExecutableInBundle(FileSpec &file) { return false; }
Greg Clayton2bddd342010-09-07 20:11:56 +0000451#endif
452
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000453#ifndef _WIN32
454
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455FileSpec Host::GetModuleFileSpecForHostAddress(const void *host_addr) {
456 FileSpec module_filespec;
Pavel Labathe705c8b2016-12-02 11:15:15 +0000457#if !defined(__ANDROID__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 Dl_info info;
459 if (::dladdr(host_addr, &info)) {
460 if (info.dli_fname)
461 module_filespec.SetFile(info.dli_fname, true);
462 }
Todd Fialacacde7d2014-09-27 16:54:22 +0000463#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 return module_filespec;
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000465}
466
467#endif
468
Matt Kopec085d6ce2013-05-31 22:00:07 +0000469#if !defined(__linux__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470bool Host::FindProcessThreads(const lldb::pid_t pid, TidMap &tids_to_attach) {
471 return false;
Matt Kopec085d6ce2013-05-31 22:00:07 +0000472}
473#endif
474
Kate Stoneb9c1b512016-09-06 20:57:50 +0000475struct ShellInfo {
476 ShellInfo()
477 : process_reaped(false), pid(LLDB_INVALID_PROCESS_ID), signo(-1),
478 status(-1) {}
Greg Claytond1cf11a2012-04-14 01:42:46 +0000479
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480 lldb_private::Predicate<bool> process_reaped;
481 lldb::pid_t pid;
482 int signo;
483 int status;
Greg Claytond1cf11a2012-04-14 01:42:46 +0000484};
485
486static bool
Pavel Labath998bdc52016-05-11 16:59:04 +0000487MonitorShellCommand(std::shared_ptr<ShellInfo> shell_info, lldb::pid_t pid,
488 bool exited, // True if the process did exit
489 int signo, // Zero for no signal
490 int status) // Exit value of process if signal is zero
Greg Claytond1cf11a2012-04-14 01:42:46 +0000491{
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 shell_info->pid = pid;
493 shell_info->signo = signo;
494 shell_info->status = status;
495 // Let the thread running Host::RunShellCommand() know that the process
496 // exited and that ShellInfo has been filled in by broadcasting to it
497 shell_info->process_reaped.SetValue(true, eBroadcastAlways);
498 return true;
Greg Claytond1cf11a2012-04-14 01:42:46 +0000499}
500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501Error Host::RunShellCommand(const char *command, const FileSpec &working_dir,
502 int *status_ptr, int *signo_ptr,
503 std::string *command_output_ptr,
504 uint32_t timeout_sec, bool run_in_default_shell) {
505 return RunShellCommand(Args(command), working_dir, status_ptr, signo_ptr,
506 command_output_ptr, timeout_sec, run_in_default_shell);
Enrico Granata66eda732015-04-17 01:50:11 +0000507}
508
Kate Stoneb9c1b512016-09-06 20:57:50 +0000509Error Host::RunShellCommand(const Args &args, const FileSpec &working_dir,
510 int *status_ptr, int *signo_ptr,
511 std::string *command_output_ptr,
512 uint32_t timeout_sec, bool run_in_default_shell) {
513 Error error;
514 ProcessLaunchInfo launch_info;
515 launch_info.SetArchitecture(HostInfo::GetArchitecture());
516 if (run_in_default_shell) {
517 // Run the command in a shell
518 launch_info.SetShell(HostInfo::GetDefaultShell());
519 launch_info.GetArguments().AppendArguments(args);
520 const bool localhost = true;
521 const bool will_debug = false;
522 const bool first_arg_is_full_shell_command = false;
523 launch_info.ConvertArgumentsForLaunchingInShell(
524 error, localhost, will_debug, first_arg_is_full_shell_command, 0);
525 } else {
526 // No shell, just run it
527 const bool first_arg_is_executable = true;
528 launch_info.SetArguments(args, first_arg_is_executable);
529 }
530
531 if (working_dir)
532 launch_info.SetWorkingDirectory(working_dir);
533 llvm::SmallString<PATH_MAX> output_file_path;
534
535 if (command_output_ptr) {
536 // Create a temporary file to get the stdout/stderr and redirect the
537 // output of the command into this file. We will later read this file
538 // if all goes well and fill the data into "command_output_ptr"
539 FileSpec tmpdir_file_spec;
540 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec)) {
541 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.%%%%%%");
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000542 llvm::sys::fs::createUniqueFile(tmpdir_file_spec.GetPath(),
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 output_file_path);
544 } else {
545 llvm::sys::fs::createTemporaryFile("lldb-shell-output.%%%%%%", "",
546 output_file_path);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000547 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 }
549
550 FileSpec output_file_spec{output_file_path.c_str(), false};
551
552 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
553 if (output_file_spec) {
554 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_spec, false,
555 true);
556 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
557 } else {
558 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
559 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
560 }
561
562 std::shared_ptr<ShellInfo> shell_info_sp(new ShellInfo());
563 const bool monitor_signals = false;
564 launch_info.SetMonitorProcessCallback(
565 std::bind(MonitorShellCommand, shell_info_sp, std::placeholders::_1,
566 std::placeholders::_2, std::placeholders::_3,
567 std::placeholders::_4),
568 monitor_signals);
569
570 error = LaunchProcess(launch_info);
571 const lldb::pid_t pid = launch_info.GetProcessID();
572
573 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
574 error.SetErrorString("failed to get process ID");
575
576 if (error.Success()) {
577 bool timed_out = false;
578 shell_info_sp->process_reaped.WaitForValueEqualTo(
579 true, std::chrono::seconds(timeout_sec), &timed_out);
580 if (timed_out) {
581 error.SetErrorString("timed out waiting for shell command to complete");
582
583 // Kill the process since it didn't complete within the timeout specified
584 Kill(pid, SIGKILL);
585 // Wait for the monitor callback to get the message
586 timed_out = false;
587 shell_info_sp->process_reaped.WaitForValueEqualTo(
588 true, std::chrono::seconds(1), &timed_out);
589 } else {
590 if (status_ptr)
591 *status_ptr = shell_info_sp->status;
592
593 if (signo_ptr)
594 *signo_ptr = shell_info_sp->signo;
595
596 if (command_output_ptr) {
597 command_output_ptr->clear();
598 uint64_t file_size = output_file_spec.GetByteSize();
599 if (file_size > 0) {
600 if (file_size > command_output_ptr->max_size()) {
601 error.SetErrorStringWithFormat(
602 "shell command output is too large to fit into a std::string");
603 } else {
604 std::vector<char> command_output(file_size);
605 output_file_spec.ReadFileContents(0, command_output.data(),
606 file_size, &error);
607 if (error.Success())
608 command_output_ptr->assign(command_output.data(), file_size);
609 }
Greg Claytonc6931fc2013-12-04 18:53:50 +0000610 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000611 }
Greg Claytonc6931fc2013-12-04 18:53:50 +0000612 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 }
Chaoren Lind3173f32015-05-29 19:52:29 +0000614
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 if (FileSystem::GetFileExists(output_file_spec))
616 FileSystem::Unlink(output_file_spec);
617 return error;
Greg Claytond1cf11a2012-04-14 01:42:46 +0000618}
619
Todd Fiala76747122014-01-23 00:52:28 +0000620// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
621// systems
622
Kate Stoneb9c1b512016-09-06 20:57:50 +0000623#if defined(__APPLE__) || defined(__linux__) || defined(__FreeBSD__) || \
624 defined(__GLIBC__) || defined(__NetBSD__)
Pavel Labathe705c8b2016-12-02 11:15:15 +0000625#if !defined(__ANDROID__)
Todd Fiala76747122014-01-23 00:52:28 +0000626// this method needs to be visible to macosx/Host.cpp and
627// common/Host.cpp.
628
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629short Host::GetPosixspawnFlags(const ProcessLaunchInfo &launch_info) {
630 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
Todd Fiala76747122014-01-23 00:52:28 +0000631
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632#if defined(__APPLE__)
633 if (launch_info.GetFlags().Test(eLaunchFlagExec))
634 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
635
636 if (launch_info.GetFlags().Test(eLaunchFlagDebug))
637 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
638
639 if (launch_info.GetFlags().Test(eLaunchFlagDisableASLR))
640 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
641
642 if (launch_info.GetLaunchInSeparateProcessGroup())
643 flags |= POSIX_SPAWN_SETPGROUP;
644
Todd Fiala76747122014-01-23 00:52:28 +0000645#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646#if defined(__APPLE__) && (defined(__x86_64__) || defined(__i386__))
647 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
648 if (g_use_close_on_exec_flag == eLazyBoolCalculate) {
649 g_use_close_on_exec_flag = eLazyBoolNo;
650
651 uint32_t major, minor, update;
652 if (HostInfo::GetOSVersion(major, minor, update)) {
653 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or
654 // earlier
655 if (major > 10 || (major == 10 && minor > 7)) {
656 // Only enable for 10.8 and later OS versions
657 g_use_close_on_exec_flag = eLazyBoolYes;
658 }
Todd Fiala76747122014-01-23 00:52:28 +0000659 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 }
Todd Fiala76747122014-01-23 00:52:28 +0000661#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000662 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
Todd Fiala76747122014-01-23 00:52:28 +0000663#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 // Close all files exception those with file actions if this is supported.
665 if (g_use_close_on_exec_flag == eLazyBoolYes)
666 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
Todd Fiala76747122014-01-23 00:52:28 +0000667#endif
668#endif // #if defined (__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000669 return flags;
Todd Fiala76747122014-01-23 00:52:28 +0000670}
671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672Error Host::LaunchProcessPosixSpawn(const char *exe_path,
673 const ProcessLaunchInfo &launch_info,
674 lldb::pid_t &pid) {
675 Error error;
676 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST |
677 LIBLLDB_LOG_PROCESS));
Daniel Malea4244cbd2013-08-27 20:58:59 +0000678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 posix_spawnattr_t attr;
680 error.SetError(::posix_spawnattr_init(&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000681
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682 if (error.Fail() || log)
683 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
684 if (error.Fail())
685 return error;
686
687 // Make a quick class that will cleanup the posix spawn attributes in case
688 // we return in the middle of this function.
689 lldb_utility::CleanUp<posix_spawnattr_t *, int> posix_spawnattr_cleanup(
690 &attr, posix_spawnattr_destroy);
691
692 sigset_t no_signals;
693 sigset_t all_signals;
694 sigemptyset(&no_signals);
695 sigfillset(&all_signals);
696 ::posix_spawnattr_setsigmask(&attr, &no_signals);
697#if defined(__linux__) || defined(__FreeBSD__)
698 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
699#else
700 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
701#endif
702
703 short flags = GetPosixspawnFlags(launch_info);
704
705 error.SetError(::posix_spawnattr_setflags(&attr, flags), eErrorTypePOSIX);
706 if (error.Fail() || log)
707 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )",
708 flags);
709 if (error.Fail())
710 return error;
711
712// posix_spawnattr_setbinpref_np appears to be an Apple extension per:
713// http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
714#if defined(__APPLE__) && !defined(__arm__)
715
716 // Don't set the binpref if a shell was provided. After all, that's only
717 // going to affect what version of the shell
718 // is launched, not what fork of the binary is launched. We insert "arch
719 // --arch <ARCH> as part of the shell invocation
720 // to do that job on OSX.
721
722 if (launch_info.GetShell() == nullptr) {
723 // We don't need to do this for ARM, and we really shouldn't now that we
724 // have multiple CPU subtypes and no posix_spawnattr call that allows us
725 // to set which CPU subtype to launch...
726 const ArchSpec &arch_spec = launch_info.GetArchitecture();
727 cpu_type_t cpu = arch_spec.GetMachOCPUType();
728 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
729 if (cpu != 0 && cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
730 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
731 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try
732 // to set the CPU type or we will fail
733 {
734 size_t ocount = 0;
735 error.SetError(::posix_spawnattr_setbinpref_np(&attr, 1, &cpu, &ocount),
736 eErrorTypePOSIX);
737 if (error.Fail() || log)
738 error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, "
739 "cpu_type = 0x%8.8x, count => %llu )",
740 cpu, (uint64_t)ocount);
741
742 if (error.Fail() || ocount != 1)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000743 return error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000744 }
745 }
746
747#endif
748
749 const char *tmp_argv[2];
750 char *const *argv = const_cast<char *const *>(
751 launch_info.GetArguments().GetConstArgumentVector());
752 char *const *envp = const_cast<char *const *>(
753 launch_info.GetEnvironmentEntries().GetConstArgumentVector());
754 if (argv == NULL) {
755 // posix_spawn gets very unhappy if it doesn't have at least the program
756 // name in argv[0]. One of the side affects I have noticed is the
757 // environment
758 // variables don't make it into the child process if "argv == NULL"!!!
759 tmp_argv[0] = exe_path;
760 tmp_argv[1] = NULL;
761 argv = const_cast<char *const *>(tmp_argv);
762 }
763
764#if !defined(__APPLE__)
765 // manage the working directory
766 char current_dir[PATH_MAX];
767 current_dir[0] = '\0';
768#endif
769
770 FileSpec working_dir{launch_info.GetWorkingDirectory()};
771 if (working_dir) {
772#if defined(__APPLE__)
773 // Set the working directory on this thread only
774 if (__pthread_chdir(working_dir.GetCString()) < 0) {
775 if (errno == ENOENT) {
776 error.SetErrorStringWithFormat("No such file or directory: %s",
777 working_dir.GetCString());
778 } else if (errno == ENOTDIR) {
779 error.SetErrorStringWithFormat("Path doesn't name a directory: %s",
780 working_dir.GetCString());
781 } else {
782 error.SetErrorStringWithFormat("An unknown error occurred when "
783 "changing directory for process "
784 "execution.");
785 }
786 return error;
787 }
788#else
789 if (::getcwd(current_dir, sizeof(current_dir)) == NULL) {
790 error.SetError(errno, eErrorTypePOSIX);
791 error.LogIfError(log, "unable to save the current directory");
792 return error;
793 }
794
795 if (::chdir(working_dir.GetCString()) == -1) {
796 error.SetError(errno, eErrorTypePOSIX);
797 error.LogIfError(log, "unable to change working directory to %s",
798 working_dir.GetCString());
799 return error;
800 }
801#endif
802 }
803
804 ::pid_t result_pid = LLDB_INVALID_PROCESS_ID;
805 const size_t num_file_actions = launch_info.GetNumFileActions();
806 if (num_file_actions > 0) {
807 posix_spawn_file_actions_t file_actions;
808 error.SetError(::posix_spawn_file_actions_init(&file_actions),
809 eErrorTypePOSIX);
810 if (error.Fail() || log)
811 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
812 if (error.Fail())
813 return error;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000814
815 // Make a quick class that will cleanup the posix spawn attributes in case
816 // we return in the middle of this function.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 lldb_utility::CleanUp<posix_spawn_file_actions_t *, int>
818 posix_spawn_file_actions_cleanup(&file_actions,
819 posix_spawn_file_actions_destroy);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000820
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 for (size_t i = 0; i < num_file_actions; ++i) {
822 const FileAction *launch_file_action =
823 launch_info.GetFileActionAtIndex(i);
824 if (launch_file_action) {
825 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log,
826 error))
827 return error;
828 }
829 }
830
831 error.SetError(
832 ::posix_spawnp(&result_pid, exe_path, &file_actions, &attr, argv, envp),
833 eErrorTypePOSIX);
834
835 if (error.Fail() || log) {
836 error.PutToLog(
837 log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, "
838 "attr = %p, argv = %p, envp = %p )",
839 result_pid, exe_path, static_cast<void *>(&file_actions),
840 static_cast<void *>(&attr), reinterpret_cast<const void *>(argv),
841 reinterpret_cast<const void *>(envp));
842 if (log) {
843 for (int ii = 0; argv[ii]; ++ii)
844 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
845 }
846 }
847
848 } else {
849 error.SetError(
850 ::posix_spawnp(&result_pid, exe_path, NULL, &attr, argv, envp),
851 eErrorTypePOSIX);
852
853 if (error.Fail() || log) {
854 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', "
855 "file_actions = NULL, attr = %p, argv = %p, envp = "
856 "%p )",
857 result_pid, exe_path, static_cast<void *>(&attr),
858 reinterpret_cast<const void *>(argv),
859 reinterpret_cast<const void *>(envp));
860 if (log) {
861 for (int ii = 0; argv[ii]; ++ii)
862 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
863 }
864 }
865 }
866 pid = result_pid;
867
868 if (working_dir) {
869#if defined(__APPLE__)
870 // No more thread specific current working directory
871 __pthread_fchdir(-1);
Todd Fiala76747122014-01-23 00:52:28 +0000872#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 if (::chdir(current_dir) == -1 && error.Success()) {
874 error.SetError(errno, eErrorTypePOSIX);
875 error.LogIfError(log, "unable to change current directory back to %s",
876 current_dir);
877 }
Todd Fiala76747122014-01-23 00:52:28 +0000878#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000880
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 return error;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000882}
883
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884bool Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info,
885 Log *log, Error &error) {
886 if (info == NULL)
887 return false;
Zachary Turner696b5282014-08-14 16:01:25 +0000888
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889 posix_spawn_file_actions_t *file_actions =
890 reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
Zachary Turner696b5282014-08-14 16:01:25 +0000891
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 switch (info->GetAction()) {
893 case FileAction::eFileActionNone:
894 error.Clear();
895 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000896
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 case FileAction::eFileActionClose:
898 if (info->GetFD() == -1)
899 error.SetErrorString(
900 "invalid fd for posix_spawn_file_actions_addclose(...)");
901 else {
902 error.SetError(
903 ::posix_spawn_file_actions_addclose(file_actions, info->GetFD()),
904 eErrorTypePOSIX);
905 if (log && (error.Fail() || log))
906 error.PutToLog(log,
907 "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
908 static_cast<void *>(file_actions), info->GetFD());
Zachary Turner696b5282014-08-14 16:01:25 +0000909 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 break;
911
912 case FileAction::eFileActionDuplicate:
913 if (info->GetFD() == -1)
914 error.SetErrorString(
915 "invalid fd for posix_spawn_file_actions_adddup2(...)");
916 else if (info->GetActionArgument() == -1)
917 error.SetErrorString(
918 "invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
919 else {
920 error.SetError(
921 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(),
922 info->GetActionArgument()),
923 eErrorTypePOSIX);
924 if (log && (error.Fail() || log))
925 error.PutToLog(
926 log,
927 "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
928 static_cast<void *>(file_actions), info->GetFD(),
929 info->GetActionArgument());
930 }
931 break;
932
933 case FileAction::eFileActionOpen:
934 if (info->GetFD() == -1)
935 error.SetErrorString(
936 "invalid fd in posix_spawn_file_actions_addopen(...)");
937 else {
938 int oflag = info->GetActionArgument();
939
940 mode_t mode = 0;
941
942 if (oflag & O_CREAT)
943 mode = 0640;
944
Zachary Turnerd4c6dae2016-09-23 22:27:03 +0000945 error.SetError(::posix_spawn_file_actions_addopen(
946 file_actions, info->GetFD(),
947 info->GetPath().str().c_str(), oflag, mode),
948 eErrorTypePOSIX);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 if (error.Fail() || log)
950 error.PutToLog(log, "posix_spawn_file_actions_addopen (action=%p, "
951 "fd=%i, path='%s', oflag=%i, mode=%i)",
952 static_cast<void *>(file_actions), info->GetFD(),
Zachary Turnerd4c6dae2016-09-23 22:27:03 +0000953 info->GetPath().str().c_str(), oflag, mode);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 }
955 break;
956 }
957 return error.Success();
Zachary Turner696b5282014-08-14 16:01:25 +0000958}
Pavel Labathe705c8b2016-12-02 11:15:15 +0000959#endif // !defined(__ANDROID__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960#endif // defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) ||
961 // defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +0000962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || \
964 defined(__NetBSD__) || defined(_WIN32)
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000965// The functions below implement process launching via posix_spawn() for Linux,
966// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +0000967
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968Error Host::LaunchProcess(ProcessLaunchInfo &launch_info) {
969 std::unique_ptr<ProcessLauncher> delegate_launcher;
Zachary Turner172d37d2014-10-14 21:55:08 +0000970#if defined(_WIN32)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 delegate_launcher.reset(new ProcessLauncherWindows());
Pavel Labath5ad891f2016-07-21 14:54:03 +0000972#elif defined(__linux__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 delegate_launcher.reset(new ProcessLauncherLinux());
Zachary Turner172d37d2014-10-14 21:55:08 +0000974#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 delegate_launcher.reset(new ProcessLauncherPosix());
Zachary Turner172d37d2014-10-14 21:55:08 +0000976#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 MonitoringProcessLauncher launcher(std::move(delegate_launcher));
Zachary Turner172d37d2014-10-14 21:55:08 +0000978
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 Error error;
980 HostProcess process = launcher.LaunchProcess(launch_info, error);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000981
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 // TODO(zturner): It would be better if the entire HostProcess were returned
983 // instead of writing
984 // it into this structure.
985 launch_info.SetProcessID(process.GetProcessId());
Daniel Malea4244cbd2013-08-27 20:58:59 +0000986
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 return error;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000988}
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000989#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000990
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000991#ifndef _WIN32
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992void Host::Kill(lldb::pid_t pid, int signo) { ::kill(pid, signo); }
Greg Claytone3e3fee2013-02-17 20:46:30 +0000993
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000994#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +0000995
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996#if !defined(__APPLE__)
997bool Host::OpenFileInExternalEditor(const FileSpec &file_spec,
998 uint32_t line_no) {
999 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +00001000}
Greg Claytondd36def2010-10-17 22:03:32 +00001001
Greg Claytonfbb76342013-11-20 21:07:01 +00001002#endif
Todd Fiala4ceced32014-08-29 17:35:57 +00001003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004const UnixSignalsSP &Host::GetUnixSignals() {
1005 static const auto s_unix_signals_sp =
1006 UnixSignals::Create(HostInfo::GetArchitecture());
1007 return s_unix_signals_sp;
Todd Fiala4ceced32014-08-29 17:35:57 +00001008}