blob: ce1af3288fcde8b1949ad6dadcd07765860c650a [file] [log] [blame]
Greg Clayton2bddd342010-09-07 20:11:56 +00001//===-- Host.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Greg Claytone3e3fee2013-02-17 20:46:30 +000012// C includes
Greg Claytone3e3fee2013-02-17 20:46:30 +000013#include <errno.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000014#include <limits.h>
Greg Clayton23f8c952014-03-24 23:10:19 +000015#include <stdlib.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000016#include <sys/types.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000017#ifdef _WIN32
18#include "lldb/Host/windows/windows.h"
19#include <winsock2.h>
Hafiz Abid Qadeera6678752014-03-10 22:31:39 +000020#include <ws2tcpip.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000021#else
Deepak Panickalb36da432014-01-13 14:55:15 +000022#include <unistd.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000023#include <dlfcn.h>
24#include <grp.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000025#include <netdb.h>
26#include <pwd.h>
Jason Molenda4a4b5dc2013-11-21 02:45:55 +000027#include <sys/stat.h>
Sylvestre Ledru785ee472013-09-05 15:39:09 +000028#endif
29
30#if !defined (__GNU__) && !defined (_WIN32)
31// Does not exist under GNU/HURD or Windows
Ed Mastef2b01622013-06-28 12:35:08 +000032#include <sys/sysctl.h>
Virgile Bellob2f1fb22013-08-23 12:44:05 +000033#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000034
35#if defined (__APPLE__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000036#include <mach/mach_port.h>
Charles Davis510938e2013-08-27 05:04:57 +000037#include <mach/mach_init.h>
38#include <mach-o/dyld.h>
Ed Maste8b006c62013-06-25 18:58:11 +000039#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000040
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +000041#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +000042#include <spawn.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000043#include <sys/wait.h>
Michael Sartainc2052432013-08-01 18:51:08 +000044#include <sys/syscall.h>
Ed Maste8b006c62013-06-25 18:58:11 +000045#endif
Greg Claytone3e3fee2013-02-17 20:46:30 +000046
Ed Maste8b006c62013-06-25 18:58:11 +000047#if defined (__FreeBSD__)
Greg Claytone3e3fee2013-02-17 20:46:30 +000048#include <pthread_np.h>
Greg Claytone3e3fee2013-02-17 20:46:30 +000049#endif
50
Zachary Turner39de3112014-09-09 20:54:56 +000051#if defined(__linux__)
52#include "Plugins/Process/Linux/ProcFileReader.h"
53#endif
54
Todd Fiala17096d72014-07-16 19:03:16 +000055// C++ includes
56#include <limits>
57
Greg Clayton2bddd342010-09-07 20:11:56 +000058#include "lldb/Host/Host.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000059#include "lldb/Host/HostInfo.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000060#include "lldb/Core/ArchSpec.h"
61#include "lldb/Core/ConstString.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000062#include "lldb/Core/Debugger.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000063#include "lldb/Core/Error.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000064#include "lldb/Core/Log.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000065#include "lldb/Core/Module.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000066#include "lldb/Core/StreamString.h"
Jim Inghamc075ecd2012-05-04 19:24:49 +000067#include "lldb/Core/ThreadSafeSTLMap.h"
Greg Clayton45319462011-02-08 00:35:34 +000068#include "lldb/Host/Config.h"
Greg Clayton7fb56d02011-02-01 01:31:41 +000069#include "lldb/Host/Endian.h"
Greg Claytone996fd32011-03-08 22:40:15 +000070#include "lldb/Host/FileSpec.h"
Zachary Turnerc00cf4a2014-08-15 22:04:21 +000071#include "lldb/Host/FileSystem.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000072#include "lldb/Host/Mutex.h"
Zachary Turner39de3112014-09-09 20:54:56 +000073#include "lldb/Host/ThreadLauncher.h"
Todd Fiala4ceced32014-08-29 17:35:57 +000074#include "lldb/lldb-private-forward.h"
Zachary Turner696b5282014-08-14 16:01:25 +000075#include "lldb/Target/FileAction.h"
Greg Claytone996fd32011-03-08 22:40:15 +000076#include "lldb/Target/Process.h"
Zachary Turner696b5282014-08-14 16:01:25 +000077#include "lldb/Target/ProcessLaunchInfo.h"
Sean Callananc0a6e062011-10-27 21:22:25 +000078#include "lldb/Target/TargetList.h"
Daniel Malea4244cbd2013-08-27 20:58:59 +000079#include "lldb/Utility/CleanUp.h"
Greg Clayton2bddd342010-09-07 20:11:56 +000080
Saleem Abdulrasool28606952014-06-27 05:17:41 +000081#include "llvm/ADT/STLExtras.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000082#include "llvm/ADT/SmallString.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000083#include "llvm/Support/Host.h"
Zachary Turner9e757b72014-07-28 16:45:05 +000084#include "llvm/Support/Path.h"
Daniel Maleafa7425d2013-08-06 21:40:08 +000085#include "llvm/Support/raw_ostream.h"
Stephen Wilsonbd588712011-02-24 19:15:09 +000086
Todd Fiala76747122014-01-23 00:52:28 +000087#if defined (__APPLE__)
88#ifndef _POSIX_SPAWN_DISABLE_ASLR
89#define _POSIX_SPAWN_DISABLE_ASLR 0x0100
90#endif
91
92extern "C"
93{
94 int __pthread_chdir(const char *path);
95 int __pthread_fchdir (int fildes);
96}
97
98#endif
Greg Clayton32e0a752011-03-30 18:16:51 +000099
Greg Clayton2bddd342010-09-07 20:11:56 +0000100using namespace lldb;
101using namespace lldb_private;
102
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000103#if !defined (__APPLE__) && !defined (_WIN32)
Greg Clayton2bddd342010-09-07 20:11:56 +0000104struct MonitorInfo
105{
106 lldb::pid_t pid; // The process ID to monitor
107 Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
108 void *callback_baton; // The callback baton for the callback function
109 bool monitor_signals; // If true, call the callback when "pid" gets signaled.
110};
111
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000112static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000113MonitorChildProcessThreadFunction (void *arg);
114
Zachary Turner39de3112014-09-09 20:54:56 +0000115HostThread
116Host::StartMonitoringChildProcess(Host::MonitorChildProcessCallback callback, void *callback_baton, lldb::pid_t pid, bool monitor_signals)
Greg Clayton2bddd342010-09-07 20:11:56 +0000117{
Greg Claytone4e45922011-11-16 05:37:56 +0000118 MonitorInfo * info_ptr = new MonitorInfo();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000119
Greg Claytone4e45922011-11-16 05:37:56 +0000120 info_ptr->pid = pid;
121 info_ptr->callback = callback;
122 info_ptr->callback_baton = callback_baton;
123 info_ptr->monitor_signals = monitor_signals;
124
125 char thread_name[256];
Zachary Turner39de3112014-09-09 20:54:56 +0000126 ::snprintf(thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
127 return ThreadLauncher::LaunchThread(thread_name, MonitorChildProcessThreadFunction, info_ptr, NULL);
Greg Clayton2bddd342010-09-07 20:11:56 +0000128}
129
130//------------------------------------------------------------------
131// Scoped class that will disable thread canceling when it is
132// constructed, and exception safely restore the previous value it
133// when it goes out of scope.
134//------------------------------------------------------------------
135class ScopedPThreadCancelDisabler
136{
137public:
138 ScopedPThreadCancelDisabler()
139 {
140 // Disable the ability for this thread to be cancelled
141 int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
142 if (err != 0)
143 m_old_state = -1;
144
145 }
146
147 ~ScopedPThreadCancelDisabler()
148 {
149 // Restore the ability for this thread to be cancelled to what it
150 // previously was.
151 if (m_old_state != -1)
152 ::pthread_setcancelstate (m_old_state, 0);
153 }
154private:
155 int m_old_state; // Save the old cancelability state.
156};
157
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000158static thread_result_t
Greg Clayton2bddd342010-09-07 20:11:56 +0000159MonitorChildProcessThreadFunction (void *arg)
160{
Greg Clayton5160ce52013-03-27 23:08:40 +0000161 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
Greg Clayton2bddd342010-09-07 20:11:56 +0000162 const char *function = __FUNCTION__;
163 if (log)
164 log->Printf ("%s (arg = %p) thread starting...", function, arg);
165
166 MonitorInfo *info = (MonitorInfo *)arg;
167
168 const Host::MonitorChildProcessCallback callback = info->callback;
169 void * const callback_baton = info->callback_baton;
Greg Clayton2bddd342010-09-07 20:11:56 +0000170 const bool monitor_signals = info->monitor_signals;
171
Daniel Malea4244cbd2013-08-27 20:58:59 +0000172 assert (info->pid <= UINT32_MAX);
Andrew MacPherson82aae0d2014-04-02 06:57:45 +0000173 const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000174
Greg Clayton2bddd342010-09-07 20:11:56 +0000175 delete info;
176
177 int status = -1;
Sylvestre Ledru59405832013-07-01 08:21:36 +0000178#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
Ashok Thirumurthi0f3b9b82013-05-01 20:38:19 +0000179 #define __WALL 0
180#endif
Matt Kopec650648f2013-01-08 16:30:18 +0000181 const int options = __WALL;
182
Greg Clayton2bddd342010-09-07 20:11:56 +0000183 while (1)
184 {
Caroline Tice20ad3c42010-10-29 21:48:37 +0000185 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000186 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000187 log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000188
189 // Wait for all child processes
190 ::pthread_testcancel ();
Matt Kopec650648f2013-01-08 16:30:18 +0000191 // Get signals from all children with same process group of pid
Daniel Malea4244cbd2013-08-27 20:58:59 +0000192 const ::pid_t wait_pid = ::waitpid (pid, &status, options);
Greg Clayton2bddd342010-09-07 20:11:56 +0000193 ::pthread_testcancel ();
194
195 if (wait_pid == -1)
196 {
197 if (errno == EINTR)
198 continue;
199 else
Andrew Kaylor93132f52013-05-28 23:04:25 +0000200 {
201 if (log)
202 log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
Greg Clayton2bddd342010-09-07 20:11:56 +0000203 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000204 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000205 }
Matt Kopec650648f2013-01-08 16:30:18 +0000206 else if (wait_pid > 0)
Greg Clayton2bddd342010-09-07 20:11:56 +0000207 {
208 bool exited = false;
209 int signal = 0;
210 int exit_status = 0;
211 const char *status_cstr = NULL;
212 if (WIFSTOPPED(status))
213 {
214 signal = WSTOPSIG(status);
215 status_cstr = "STOPPED";
216 }
217 else if (WIFEXITED(status))
218 {
219 exit_status = WEXITSTATUS(status);
220 status_cstr = "EXITED";
Andrew Kaylor93132f52013-05-28 23:04:25 +0000221 exited = true;
Greg Clayton2bddd342010-09-07 20:11:56 +0000222 }
223 else if (WIFSIGNALED(status))
224 {
225 signal = WTERMSIG(status);
226 status_cstr = "SIGNALED";
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000227 if (wait_pid == abs(pid)) {
Matt Kopec650648f2013-01-08 16:30:18 +0000228 exited = true;
229 exit_status = -1;
230 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000231 }
232 else
233 {
Johnny Chen44805302011-07-19 19:48:13 +0000234 status_cstr = "(\?\?\?)";
Greg Clayton2bddd342010-09-07 20:11:56 +0000235 }
236
237 // Scope for pthread_cancel_disabler
238 {
239 ScopedPThreadCancelDisabler pthread_cancel_disabler;
240
Caroline Tice20ad3c42010-10-29 21:48:37 +0000241 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000242 if (log)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000243 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 +0000244 function,
245 wait_pid,
246 options,
Greg Clayton2bddd342010-09-07 20:11:56 +0000247 pid,
248 status,
249 status_cstr,
250 signal,
251 exit_status);
252
253 if (exited || (signal != 0 && monitor_signals))
254 {
Greg Claytone4e45922011-11-16 05:37:56 +0000255 bool callback_return = false;
256 if (callback)
Matt Kopec650648f2013-01-08 16:30:18 +0000257 callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
Greg Clayton2bddd342010-09-07 20:11:56 +0000258
259 // If our process exited, then this thread should exit
Andrew Kaylor7d2abdf2013-09-04 16:06:04 +0000260 if (exited && wait_pid == abs(pid))
Andrew Kaylor93132f52013-05-28 23:04:25 +0000261 {
262 if (log)
263 log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000264 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000265 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000266 // If the callback returns true, it means this process should
267 // exit
268 if (callback_return)
Andrew Kaylor93132f52013-05-28 23:04:25 +0000269 {
270 if (log)
271 log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
Greg Clayton2bddd342010-09-07 20:11:56 +0000272 break;
Andrew Kaylor93132f52013-05-28 23:04:25 +0000273 }
Greg Clayton2bddd342010-09-07 20:11:56 +0000274 }
275 }
276 }
277 }
278
Caroline Tice20ad3c42010-10-29 21:48:37 +0000279 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
Greg Clayton2bddd342010-09-07 20:11:56 +0000280 if (log)
281 log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
282
283 return NULL;
284}
285
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000286#endif // #if !defined (__APPLE__) && !defined (_WIN32)
287
288#if !defined (__APPLE__)
Greg Claytone38a5ed2012-01-05 03:57:59 +0000289
290void
291Host::SystemLog (SystemLogType type, const char *format, va_list args)
292{
293 vfprintf (stderr, format, args);
294}
295
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000296#endif
Greg Claytone4e45922011-11-16 05:37:56 +0000297
Greg Claytone38a5ed2012-01-05 03:57:59 +0000298void
299Host::SystemLog (SystemLogType type, const char *format, ...)
300{
301 va_list args;
302 va_start (args, format);
303 SystemLog (type, format, args);
304 va_end (args);
305}
306
Greg Clayton2bddd342010-09-07 20:11:56 +0000307lldb::pid_t
308Host::GetCurrentProcessID()
309{
310 return ::getpid();
311}
312
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000313#ifndef _WIN32
314
Greg Clayton2bddd342010-09-07 20:11:56 +0000315lldb::tid_t
316Host::GetCurrentThreadID()
317{
318#if defined (__APPLE__)
Jean-Daniel Dupas3cfa8e22013-12-06 09:35:53 +0000319 // Calling "mach_thread_self()" bumps the reference count on the thread
Greg Clayton813ddfc2012-09-18 18:19:49 +0000320 // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
321 // count.
322 thread_port_t thread_self = mach_thread_self();
323 mach_port_deallocate(mach_task_self(), thread_self);
324 return thread_self;
Johnny Chen8f3d8382011-08-02 20:52:42 +0000325#elif defined(__FreeBSD__)
326 return lldb::tid_t(pthread_getthreadid_np());
Michael Sartainc2052432013-08-01 18:51:08 +0000327#elif defined(__linux__)
328 return lldb::tid_t(syscall(SYS_gettid));
Greg Clayton2bddd342010-09-07 20:11:56 +0000329#else
330 return lldb::tid_t(pthread_self());
331#endif
332}
333
Jim Ingham372787f2012-04-07 00:00:41 +0000334lldb::thread_t
335Host::GetCurrentThread ()
336{
337 return lldb::thread_t(pthread_self());
338}
339
Greg Clayton2bddd342010-09-07 20:11:56 +0000340const char *
341Host::GetSignalAsCString (int signo)
342{
343 switch (signo)
344 {
345 case SIGHUP: return "SIGHUP"; // 1 hangup
346 case SIGINT: return "SIGINT"; // 2 interrupt
347 case SIGQUIT: return "SIGQUIT"; // 3 quit
348 case SIGILL: return "SIGILL"; // 4 illegal instruction (not reset when caught)
349 case SIGTRAP: return "SIGTRAP"; // 5 trace trap (not reset when caught)
350 case SIGABRT: return "SIGABRT"; // 6 abort()
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000351#if defined(SIGPOLL)
Sylvestre Ledrua4cc7de2013-12-13 09:51:39 +0000352#if !defined(SIGIO) || (SIGPOLL != SIGIO)
353// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
354// fail with 'multiple define cases with same value'
Greg Clayton2bddd342010-09-07 20:11:56 +0000355 case SIGPOLL: 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
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000358#if defined(SIGEMT)
Greg Clayton2bddd342010-09-07 20:11:56 +0000359 case SIGEMT: return "SIGEMT"; // 7 EMT instruction
Benjamin Kramer44030f12011-11-04 16:06:40 +0000360#endif
Greg Clayton2bddd342010-09-07 20:11:56 +0000361 case SIGFPE: return "SIGFPE"; // 8 floating point exception
362 case SIGKILL: return "SIGKILL"; // 9 kill (cannot be caught or ignored)
363 case SIGBUS: return "SIGBUS"; // 10 bus error
364 case SIGSEGV: return "SIGSEGV"; // 11 segmentation violation
365 case SIGSYS: return "SIGSYS"; // 12 bad argument to system call
366 case SIGPIPE: return "SIGPIPE"; // 13 write on a pipe with no one to read it
367 case SIGALRM: return "SIGALRM"; // 14 alarm clock
368 case SIGTERM: return "SIGTERM"; // 15 software termination signal from kill
369 case SIGURG: return "SIGURG"; // 16 urgent condition on IO channel
370 case SIGSTOP: return "SIGSTOP"; // 17 sendable stop signal not from tty
371 case SIGTSTP: return "SIGTSTP"; // 18 stop signal from tty
372 case SIGCONT: return "SIGCONT"; // 19 continue a stopped process
373 case SIGCHLD: return "SIGCHLD"; // 20 to parent on child stop or exit
374 case SIGTTIN: return "SIGTTIN"; // 21 to readers pgrp upon background tty read
375 case SIGTTOU: return "SIGTTOU"; // 22 like TTIN for output if (tp->t_local&LTOSTOP)
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000376#if defined(SIGIO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000377 case SIGIO: return "SIGIO"; // 23 input/output possible signal
378#endif
379 case SIGXCPU: return "SIGXCPU"; // 24 exceeded CPU time limit
380 case SIGXFSZ: return "SIGXFSZ"; // 25 exceeded file size limit
381 case SIGVTALRM: return "SIGVTALRM"; // 26 virtual time alarm
382 case SIGPROF: return "SIGPROF"; // 27 profiling time alarm
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000383#if defined(SIGWINCH)
Greg Clayton2bddd342010-09-07 20:11:56 +0000384 case SIGWINCH: return "SIGWINCH"; // 28 window size changes
Jean-Daniel Dupas13698b22013-12-12 18:12:16 +0000385#endif
386#if defined(SIGINFO)
Greg Clayton2bddd342010-09-07 20:11:56 +0000387 case SIGINFO: return "SIGINFO"; // 29 information request
388#endif
389 case SIGUSR1: return "SIGUSR1"; // 30 user defined signal 1
390 case SIGUSR2: return "SIGUSR2"; // 31 user defined signal 2
391 default:
392 break;
393 }
394 return NULL;
395}
396
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000397#endif
398
Greg Clayton2bddd342010-09-07 20:11:56 +0000399void
400Host::WillTerminate ()
401{
402}
403
Sylvestre Ledru59405832013-07-01 08:21:36 +0000404#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
Matt Kopec62502c62013-05-13 19:33:58 +0000405
Greg Clayton2bddd342010-09-07 20:11:56 +0000406void
Greg Claytone5219662010-12-03 06:02:24 +0000407Host::Backtrace (Stream &strm, uint32_t max_frames)
408{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000409 // TODO: Is there a way to backtrace the current process on other systems?
Greg Claytone5219662010-12-03 06:02:24 +0000410}
411
Greg Clayton85851dd2010-12-04 00:10:17 +0000412size_t
413Host::GetEnvironment (StringList &env)
414{
Michael Sartain3cf443d2013-07-17 00:26:30 +0000415 // TODO: Is there a way to the host environment for this process on other systems?
Greg Clayton85851dd2010-12-04 00:10:17 +0000416 return 0;
417}
418
Sylvestre Ledru59405832013-07-01 08:21:36 +0000419#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
Greg Clayton2bddd342010-09-07 20:11:56 +0000420
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000421#ifndef _WIN32
422
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000423lldb::thread_key_t
424Host::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
425{
426 pthread_key_t key;
427 ::pthread_key_create (&key, callback);
428 return key;
429}
430
431void*
432Host::ThreadLocalStorageGet(lldb::thread_key_t key)
433{
434 return ::pthread_getspecific (key);
435}
436
437void
438Host::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
439{
440 ::pthread_setspecific (key, value);
441}
442
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000443#endif
444
Greg Clayton2bddd342010-09-07 20:11:56 +0000445#if !defined (__APPLE__) // see Host.mm
Greg Claytonc859e2d2012-02-13 23:10:39 +0000446
447bool
448Host::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
449{
450 bundle.Clear();
451 return false;
452}
453
Greg Clayton2bddd342010-09-07 20:11:56 +0000454bool
Greg Claytondd36def2010-10-17 22:03:32 +0000455Host::ResolveExecutableInBundle (FileSpec &file)
Greg Clayton2bddd342010-09-07 20:11:56 +0000456{
Greg Claytondd36def2010-10-17 22:03:32 +0000457 return false;
Greg Clayton2bddd342010-09-07 20:11:56 +0000458}
459#endif
460
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000461#ifndef _WIN32
462
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000463FileSpec
464Host::GetModuleFileSpecForHostAddress (const void *host_addr)
465{
466 FileSpec module_filespec;
467 Dl_info info;
468 if (::dladdr (host_addr, &info))
469 {
470 if (info.dli_fname)
471 module_filespec.SetFile(info.dli_fname, true);
472 }
473 return module_filespec;
474}
475
476#endif
477
Matt Kopec085d6ce2013-05-31 22:00:07 +0000478#if !defined(__linux__)
479bool
480Host::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
481{
482 return false;
483}
484#endif
485
Sean Callananc0a6e062011-10-27 21:22:25 +0000486lldb::TargetSP
487Host::GetDummyTarget (lldb_private::Debugger &debugger)
488{
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +0000489 static TargetSP g_dummy_target_sp;
Filipe Cabecinhasb0183452012-05-17 15:48:02 +0000490
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +0000491 // FIXME: Maybe the dummy target should be per-Debugger
492 if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
493 {
494 ArchSpec arch(Target::GetDefaultArchitecture());
495 if (!arch.IsValid())
Zachary Turner13b18262014-08-20 16:42:51 +0000496 arch = HostInfo::GetArchitecture();
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +0000497 Error err = debugger.GetTargetList().CreateTarget(debugger,
Greg Claytona0ca6602012-10-18 16:33:33 +0000498 NULL,
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +0000499 arch.GetTriple().getTriple().c_str(),
500 false,
501 NULL,
502 g_dummy_target_sp);
503 }
Filipe Cabecinhasb0183452012-05-17 15:48:02 +0000504
Filipe Cabecinhas721ba3f2012-05-19 09:59:08 +0000505 return g_dummy_target_sp;
Sean Callananc0a6e062011-10-27 21:22:25 +0000506}
507
Greg Claytond1cf11a2012-04-14 01:42:46 +0000508struct ShellInfo
509{
510 ShellInfo () :
511 process_reaped (false),
512 can_delete (false),
513 pid (LLDB_INVALID_PROCESS_ID),
514 signo(-1),
515 status(-1)
516 {
517 }
518
519 lldb_private::Predicate<bool> process_reaped;
520 lldb_private::Predicate<bool> can_delete;
521 lldb::pid_t pid;
522 int signo;
523 int status;
524};
525
526static bool
527MonitorShellCommand (void *callback_baton,
528 lldb::pid_t pid,
529 bool exited, // True if the process did exit
530 int signo, // Zero for no signal
531 int status) // Exit value of process if signal is zero
532{
533 ShellInfo *shell_info = (ShellInfo *)callback_baton;
534 shell_info->pid = pid;
535 shell_info->signo = signo;
536 shell_info->status = status;
537 // Let the thread running Host::RunShellCommand() know that the process
538 // exited and that ShellInfo has been filled in by broadcasting to it
539 shell_info->process_reaped.SetValue(1, eBroadcastAlways);
540 // Now wait for a handshake back from that thread running Host::RunShellCommand
541 // so we know that we can delete shell_info_ptr
542 shell_info->can_delete.WaitForValueEqualTo(true);
543 // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
544 usleep(1000);
545 // Now delete the shell info that was passed into this function
546 delete shell_info;
547 return true;
548}
549
550Error
551Host::RunShellCommand (const char *command,
552 const char *working_dir,
553 int *status_ptr,
554 int *signo_ptr,
555 std::string *command_output_ptr,
Greg Claytonc8f814d2012-09-27 03:13:55 +0000556 uint32_t timeout_sec,
557 const char *shell)
Greg Claytond1cf11a2012-04-14 01:42:46 +0000558{
559 Error error;
560 ProcessLaunchInfo launch_info;
Greg Claytonc8f814d2012-09-27 03:13:55 +0000561 if (shell && shell[0])
562 {
563 // Run the command in a shell
564 launch_info.SetShell(shell);
565 launch_info.GetArguments().AppendArgument(command);
566 const bool localhost = true;
567 const bool will_debug = false;
568 const bool first_arg_is_full_shell_command = true;
569 launch_info.ConvertArgumentsForLaunchingInShell (error,
570 localhost,
571 will_debug,
Jim Inghamdf0ae222013-09-10 02:09:47 +0000572 first_arg_is_full_shell_command,
573 0);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000574 }
575 else
576 {
577 // No shell, just run it
578 Args args (command);
579 const bool first_arg_is_executable = true;
Greg Clayton45392552012-10-17 22:57:12 +0000580 launch_info.SetArguments(args, first_arg_is_executable);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000581 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000582
583 if (working_dir)
584 launch_info.SetWorkingDirectory(working_dir);
Greg Claytonc6931fc2013-12-04 18:53:50 +0000585 char output_file_path_buffer[PATH_MAX];
Greg Claytond1cf11a2012-04-14 01:42:46 +0000586 const char *output_file_path = NULL;
Greg Claytonc6931fc2013-12-04 18:53:50 +0000587
Greg Claytond1cf11a2012-04-14 01:42:46 +0000588 if (command_output_ptr)
589 {
590 // Create a temporary file to get the stdout/stderr and redirect the
591 // output of the command into this file. We will later read this file
592 // if all goes well and fill the data into "command_output_ptr"
Greg Claytonc6931fc2013-12-04 18:53:50 +0000593 FileSpec tmpdir_file_spec;
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000594 if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
Greg Claytonc6931fc2013-12-04 18:53:50 +0000595 {
Zachary Turnerc25146b2014-08-21 23:56:55 +0000596 tmpdir_file_spec.AppendPathComponent("lldb-shell-output.XXXXXX");
Greg Claytonc6931fc2013-12-04 18:53:50 +0000597 strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
598 }
599 else
600 {
601 strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
602 }
603
604 output_file_path = ::mktemp(output_file_path_buffer);
605 }
606
607 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
608 if (output_file_path)
609 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000610 launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
Greg Claytonc8f814d2012-09-27 03:13:55 +0000611 launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000612 }
613 else
614 {
Greg Claytond1cf11a2012-04-14 01:42:46 +0000615 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
616 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
617 }
618
619 // The process monitor callback will delete the 'shell_info_ptr' below...
Greg Clayton7b0992d2013-04-18 22:45:39 +0000620 std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
Greg Claytond1cf11a2012-04-14 01:42:46 +0000621
622 const bool monitor_signals = false;
623 launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
624
625 error = LaunchProcess (launch_info);
626 const lldb::pid_t pid = launch_info.GetProcessID();
Daniel Maleae0f8f572013-08-26 23:57:52 +0000627
628 if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
629 error.SetErrorString("failed to get process ID");
630
631 if (error.Success())
Greg Claytond1cf11a2012-04-14 01:42:46 +0000632 {
633 // The process successfully launched, so we can defer ownership of
634 // "shell_info" to the MonitorShellCommand callback function that will
Greg Claytone01e07b2013-04-18 18:10:51 +0000635 // get called when the process dies. We release the unique pointer as it
Greg Claytond1cf11a2012-04-14 01:42:46 +0000636 // doesn't need to delete the ShellInfo anymore.
637 ShellInfo *shell_info = shell_info_ap.release();
Daniel Malea4244cbd2013-08-27 20:58:59 +0000638 TimeValue *timeout_ptr = nullptr;
Greg Claytond1cf11a2012-04-14 01:42:46 +0000639 TimeValue timeout_time(TimeValue::Now());
Daniel Malea4244cbd2013-08-27 20:58:59 +0000640 if (timeout_sec > 0) {
641 timeout_time.OffsetWithSeconds(timeout_sec);
642 timeout_ptr = &timeout_time;
643 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000644 bool timed_out = false;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000645 shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000646 if (timed_out)
647 {
648 error.SetErrorString("timed out waiting for shell command to complete");
Daniel Malea4244cbd2013-08-27 20:58:59 +0000649
Bruce Mitchenerd93c4a32014-07-01 21:22:11 +0000650 // Kill the process since it didn't complete within the timeout specified
Virgile Bellob2f1fb22013-08-23 12:44:05 +0000651 Kill (pid, SIGKILL);
Greg Claytond1cf11a2012-04-14 01:42:46 +0000652 // Wait for the monitor callback to get the message
653 timeout_time = TimeValue::Now();
654 timeout_time.OffsetWithSeconds(1);
655 timed_out = false;
656 shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
657 }
658 else
659 {
660 if (status_ptr)
661 *status_ptr = shell_info->status;
662
663 if (signo_ptr)
664 *signo_ptr = shell_info->signo;
665
666 if (command_output_ptr)
667 {
668 command_output_ptr->clear();
669 FileSpec file_spec(output_file_path, File::eOpenOptionRead);
670 uint64_t file_size = file_spec.GetByteSize();
671 if (file_size > 0)
672 {
673 if (file_size > command_output_ptr->max_size())
674 {
675 error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
676 }
677 else
678 {
679 command_output_ptr->resize(file_size);
680 file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
681 }
682 }
683 }
684 }
685 shell_info->can_delete.SetValue(true, eBroadcastAlways);
686 }
Greg Claytond1cf11a2012-04-14 01:42:46 +0000687
688 if (output_file_path)
689 ::unlink (output_file_path);
690 // Handshake with the monitor thread, or just let it know in advance that
691 // it can delete "shell_info" in case we timed out and were not able to kill
692 // the process...
693 return error;
694}
695
Daniel Malea4244cbd2013-08-27 20:58:59 +0000696
Todd Fiala76747122014-01-23 00:52:28 +0000697// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
698// systems
699
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +0000700#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
Todd Fiala76747122014-01-23 00:52:28 +0000701
702// this method needs to be visible to macosx/Host.cpp and
703// common/Host.cpp.
704
705short
706Host::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
707{
708 short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
709
710#if defined (__APPLE__)
711 if (launch_info.GetFlags().Test (eLaunchFlagExec))
712 flags |= POSIX_SPAWN_SETEXEC; // Darwin specific posix_spawn flag
713
714 if (launch_info.GetFlags().Test (eLaunchFlagDebug))
715 flags |= POSIX_SPAWN_START_SUSPENDED; // Darwin specific posix_spawn flag
716
717 if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
718 flags |= _POSIX_SPAWN_DISABLE_ASLR; // Darwin specific posix_spawn flag
719
720 if (launch_info.GetLaunchInSeparateProcessGroup())
721 flags |= POSIX_SPAWN_SETPGROUP;
722
723#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
724#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
725 static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
726 if (g_use_close_on_exec_flag == eLazyBoolCalculate)
727 {
728 g_use_close_on_exec_flag = eLazyBoolNo;
729
730 uint32_t major, minor, update;
Zachary Turner97a14e62014-08-19 17:18:29 +0000731 if (HostInfo::GetOSVersion(major, minor, update))
Todd Fiala76747122014-01-23 00:52:28 +0000732 {
733 // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
734 if (major > 10 || (major == 10 && minor > 7))
735 {
736 // Only enable for 10.8 and later OS versions
737 g_use_close_on_exec_flag = eLazyBoolYes;
738 }
739 }
740 }
741#else
742 static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
743#endif
744 // Close all files exception those with file actions if this is supported.
745 if (g_use_close_on_exec_flag == eLazyBoolYes)
746 flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
747#endif
748#endif // #if defined (__APPLE__)
749 return flags;
750}
751
752Error
753Host::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000754{
755 Error error;
756 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
757
Daniel Malea4244cbd2013-08-27 20:58:59 +0000758 posix_spawnattr_t attr;
Daniel Malea4244cbd2013-08-27 20:58:59 +0000759 error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000760
761 if (error.Fail() || log)
762 error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
Daniel Malea4244cbd2013-08-27 20:58:59 +0000763 if (error.Fail())
764 return error;
765
766 // Make a quick class that will cleanup the posix spawn attributes in case
767 // we return in the middle of this function.
768 lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
769
770 sigset_t no_signals;
771 sigset_t all_signals;
772 sigemptyset (&no_signals);
773 sigfillset (&all_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000774 ::posix_spawnattr_setsigmask(&attr, &no_signals);
Todd Fiala571768c2014-01-23 17:07:54 +0000775#if defined (__linux__) || defined (__FreeBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000776 ::posix_spawnattr_setsigdefault(&attr, &no_signals);
Todd Fiala76747122014-01-23 00:52:28 +0000777#else
778 ::posix_spawnattr_setsigdefault(&attr, &all_signals);
779#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000780
Todd Fiala76747122014-01-23 00:52:28 +0000781 short flags = GetPosixspawnFlags(launch_info);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000782
783 error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
Todd Fiala76747122014-01-23 00:52:28 +0000784 if (error.Fail() || log)
785 error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
Daniel Malea4244cbd2013-08-27 20:58:59 +0000786 if (error.Fail())
787 return error;
788
Todd Fiala76747122014-01-23 00:52:28 +0000789 // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
790 // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
791#if defined (__APPLE__) && !defined (__arm__)
Jim Ingham90331d52014-02-21 01:25:21 +0000792
793 // Don't set the binpref if a shell was provided. After all, that's only going to affect what version of the shell
794 // is launched, not what fork of the binary is launched. We insert "arch --arch <ARCH> as part of the shell invocation
795 // to do that job on OSX.
796
797 if (launch_info.GetShell() == nullptr)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000798 {
Jim Ingham90331d52014-02-21 01:25:21 +0000799 // We don't need to do this for ARM, and we really shouldn't now that we
800 // have multiple CPU subtypes and no posix_spawnattr call that allows us
801 // to set which CPU subtype to launch...
802 const ArchSpec &arch_spec = launch_info.GetArchitecture();
803 cpu_type_t cpu = arch_spec.GetMachOCPUType();
804 cpu_type_t sub = arch_spec.GetMachOCPUSubType();
805 if (cpu != 0 &&
Saleem Abdulrasool3985c8c2014-04-02 03:51:35 +0000806 cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
807 cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
Jim Ingham90331d52014-02-21 01:25:21 +0000808 !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
809 {
810 size_t ocount = 0;
811 error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
812 if (error.Fail() || log)
813 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 +0000814
Jim Ingham90331d52014-02-21 01:25:21 +0000815 if (error.Fail() || ocount != 1)
816 return error;
817 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000818 }
819
Todd Fiala76747122014-01-23 00:52:28 +0000820#endif
821
822 const char *tmp_argv[2];
823 char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
824 char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
825 if (argv == NULL)
826 {
827 // posix_spawn gets very unhappy if it doesn't have at least the program
828 // name in argv[0]. One of the side affects I have noticed is the environment
829 // variables don't make it into the child process if "argv == NULL"!!!
830 tmp_argv[0] = exe_path;
831 tmp_argv[1] = NULL;
832 argv = (char * const*)tmp_argv;
833 }
834
835#if !defined (__APPLE__)
836 // manage the working directory
Daniel Malea4244cbd2013-08-27 20:58:59 +0000837 char current_dir[PATH_MAX];
838 current_dir[0] = '\0';
Todd Fiala76747122014-01-23 00:52:28 +0000839#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000840
841 const char *working_dir = launch_info.GetWorkingDirectory();
Todd Fiala76747122014-01-23 00:52:28 +0000842 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000843 {
Todd Fiala76747122014-01-23 00:52:28 +0000844#if defined (__APPLE__)
845 // Set the working directory on this thread only
846 if (__pthread_chdir (working_dir) < 0) {
847 if (errno == ENOENT) {
848 error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
849 } else if (errno == ENOTDIR) {
850 error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
851 } else {
852 error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
853 }
854 return error;
855 }
856#else
Daniel Malea4244cbd2013-08-27 20:58:59 +0000857 if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
858 {
859 error.SetError(errno, eErrorTypePOSIX);
860 error.LogIfError(log, "unable to save the current directory");
861 return error;
862 }
863
864 if (::chdir(working_dir) == -1)
865 {
866 error.SetError(errno, eErrorTypePOSIX);
867 error.LogIfError(log, "unable to change working directory to %s", working_dir);
868 return error;
869 }
Todd Fiala76747122014-01-23 00:52:28 +0000870#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000871 }
872
Todd Fiala76747122014-01-23 00:52:28 +0000873 const size_t num_file_actions = launch_info.GetNumFileActions ();
874 if (num_file_actions > 0)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000875 {
Todd Fiala76747122014-01-23 00:52:28 +0000876 posix_spawn_file_actions_t file_actions;
877 error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
878 if (error.Fail() || log)
879 error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
880 if (error.Fail())
881 return error;
882
883 // Make a quick class that will cleanup the posix spawn attributes in case
884 // we return in the middle of this function.
885 lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
886
887 for (size_t i=0; i<num_file_actions; ++i)
888 {
Zachary Turner696b5282014-08-14 16:01:25 +0000889 const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
Todd Fiala76747122014-01-23 00:52:28 +0000890 if (launch_file_action)
891 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000892 if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
Todd Fiala76747122014-01-23 00:52:28 +0000893 return error;
894 }
895 }
896
897 error.SetError (::posix_spawnp (&pid,
898 exe_path,
899 &file_actions,
900 &attr,
901 argv,
902 envp),
903 eErrorTypePOSIX);
904
905 if (error.Fail() || log)
906 {
907 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000908 pid, exe_path, static_cast<void*>(&file_actions),
909 static_cast<void*>(&attr),
910 reinterpret_cast<const void*>(argv),
911 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000912 if (log)
913 {
914 for (int ii=0; argv[ii]; ++ii)
915 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
916 }
917 }
918
919 }
920 else
921 {
922 error.SetError (::posix_spawnp (&pid,
923 exe_path,
924 NULL,
925 &attr,
926 argv,
927 envp),
928 eErrorTypePOSIX);
929
930 if (error.Fail() || log)
931 {
932 error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
Saleem Abdulrasool324a1032014-04-04 04:06:10 +0000933 pid, exe_path, static_cast<void*>(&attr),
934 reinterpret_cast<const void*>(argv),
935 reinterpret_cast<const void*>(envp));
Todd Fiala76747122014-01-23 00:52:28 +0000936 if (log)
937 {
938 for (int ii=0; argv[ii]; ++ii)
939 log->Printf("argv[%i] = '%s'", ii, argv[ii]);
940 }
941 }
Daniel Malea4244cbd2013-08-27 20:58:59 +0000942 }
943
Todd Fiala76747122014-01-23 00:52:28 +0000944 if (working_dir)
Daniel Malea4244cbd2013-08-27 20:58:59 +0000945 {
Todd Fiala76747122014-01-23 00:52:28 +0000946#if defined (__APPLE__)
947 // No more thread specific current working directory
948 __pthread_fchdir (-1);
949#else
950 if (::chdir(current_dir) == -1 && error.Success())
951 {
952 error.SetError(errno, eErrorTypePOSIX);
953 error.LogIfError(log, "unable to change current directory back to %s",
954 current_dir);
955 }
956#endif
Daniel Malea4244cbd2013-08-27 20:58:59 +0000957 }
958
959 return error;
960}
961
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000962bool
963Host::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
Zachary Turner696b5282014-08-14 16:01:25 +0000964{
965 if (info == NULL)
966 return false;
967
968 posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
969
970 switch (info->GetAction())
971 {
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000972 case FileAction::eFileActionNone:
973 error.Clear();
974 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000975
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000976 case FileAction::eFileActionClose:
977 if (info->GetFD() == -1)
978 error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
979 else
980 {
981 error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
982 if (log && (error.Fail() || log))
983 error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
984 static_cast<void *>(file_actions), info->GetFD());
985 }
986 break;
Zachary Turner696b5282014-08-14 16:01:25 +0000987
Zachary Turnerc00cf4a2014-08-15 22:04:21 +0000988 case FileAction::eFileActionDuplicate:
989 if (info->GetFD() == -1)
990 error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
991 else if (info->GetActionArgument() == -1)
992 error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
993 else
994 {
995 error.SetError(
996 ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
997 eErrorTypePOSIX);
998 if (log && (error.Fail() || log))
999 error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
1000 static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
1001 }
1002 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001003
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001004 case FileAction::eFileActionOpen:
1005 if (info->GetFD() == -1)
1006 error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
1007 else
1008 {
1009 int oflag = info->GetActionArgument();
Zachary Turner696b5282014-08-14 16:01:25 +00001010
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001011 mode_t mode = 0;
Zachary Turner696b5282014-08-14 16:01:25 +00001012
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001013 if (oflag & O_CREAT)
1014 mode = 0640;
Zachary Turner696b5282014-08-14 16:01:25 +00001015
Zachary Turnerc00cf4a2014-08-15 22:04:21 +00001016 error.SetError(
1017 ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
1018 eErrorTypePOSIX);
1019 if (error.Fail() || log)
1020 error.PutToLog(log,
1021 "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
1022 static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
1023 }
1024 break;
Zachary Turner696b5282014-08-14 16:01:25 +00001025 }
1026 return error.Success();
1027}
1028
Todd Fiala76747122014-01-23 00:52:28 +00001029#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1030
1031
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001032#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
1033// The functions below implement process launching via posix_spawn() for Linux,
1034// FreeBSD and NetBSD.
Daniel Malea4244cbd2013-08-27 20:58:59 +00001035
1036Error
1037Host::LaunchProcess (ProcessLaunchInfo &launch_info)
1038{
1039 Error error;
1040 char exe_path[PATH_MAX];
1041
1042 PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1043
1044 const ArchSpec &arch_spec = launch_info.GetArchitecture();
1045
1046 FileSpec exe_spec(launch_info.GetExecutableFile());
1047
1048 FileSpec::FileType file_type = exe_spec.GetFileType();
1049 if (file_type != FileSpec::eFileTypeRegular)
1050 {
1051 lldb::ModuleSP exe_module_sp;
1052 error = host_platform_sp->ResolveExecutable (exe_spec,
1053 arch_spec,
1054 exe_module_sp,
1055 NULL);
1056
1057 if (error.Fail())
1058 return error;
1059
1060 if (exe_module_sp)
1061 exe_spec = exe_module_sp->GetFileSpec();
1062 }
1063
1064 if (exe_spec.Exists())
1065 {
1066 exe_spec.GetPath (exe_path, sizeof(exe_path));
1067 }
1068 else
1069 {
1070 launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1071 error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1072 return error;
1073 }
1074
1075 assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1076
1077 ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1078
1079 error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1080
1081 if (pid != LLDB_INVALID_PROCESS_ID)
1082 {
1083 // If all went well, then set the process ID into the launch info
1084 launch_info.SetProcessID(pid);
1085
Todd Fiala76747122014-01-23 00:52:28 +00001086 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1087
Daniel Malea4244cbd2013-08-27 20:58:59 +00001088 // Make sure we reap any processes we spawn or we will have zombies.
1089 if (!launch_info.MonitorProcess())
1090 {
1091 const bool monitor_signals = false;
1092 StartMonitoringChildProcess (Process::SetProcessExitStatus,
1093 NULL,
1094 pid,
1095 monitor_signals);
Todd Fiala76747122014-01-23 00:52:28 +00001096 if (log)
1097 log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
1098 }
1099 else
1100 {
1101 if (log)
1102 log->PutCString ("monitored child process with user-specified process monitor.");
Daniel Malea4244cbd2013-08-27 20:58:59 +00001103 }
1104 }
1105 else
1106 {
1107 // Invalid process ID, something didn't go well
1108 if (error.Success())
1109 error.SetErrorString ("process launch failed for unknown reasons");
1110 }
1111 return error;
1112}
1113
Joerg Sonnenbergera53b3592014-05-02 19:09:40 +00001114#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
Daniel Malea4244cbd2013-08-27 20:58:59 +00001115
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001116#ifndef _WIN32
1117
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001118void
1119Host::Kill(lldb::pid_t pid, int signo)
1120{
1121 ::kill(pid, signo);
1122}
Greg Claytone3e3fee2013-02-17 20:46:30 +00001123
Virgile Bellob2f1fb22013-08-23 12:44:05 +00001124#endif
Greg Claytond1cf11a2012-04-14 01:42:46 +00001125
Johnny Chen8f3d8382011-08-02 20:52:42 +00001126#if !defined (__APPLE__)
Greg Clayton2bddd342010-09-07 20:11:56 +00001127bool
Greg Clayton3b147632010-12-18 01:54:34 +00001128Host::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
Greg Clayton2bddd342010-09-07 20:11:56 +00001129{
1130 return false;
1131}
Greg Claytondd36def2010-10-17 22:03:32 +00001132
Greg Clayton2d95dc9b2010-11-10 04:57:04 +00001133void
1134Host::SetCrashDescriptionWithFormat (const char *format, ...)
1135{
1136}
1137
1138void
1139Host::SetCrashDescription (const char *description)
1140{
1141}
Greg Claytondd36def2010-10-17 22:03:32 +00001142
1143lldb::pid_t
Daniel Maleae0f8f572013-08-26 23:57:52 +00001144Host::LaunchApplication (const FileSpec &app_file_spec)
Greg Claytondd36def2010-10-17 22:03:32 +00001145{
1146 return LLDB_INVALID_PROCESS_ID;
1147}
1148
Greg Claytonfbb76342013-11-20 21:07:01 +00001149#endif
Todd Fiala4ceced32014-08-29 17:35:57 +00001150
1151#if !defined (__linux__) && !defined (__FreeBSD__) && !defined (__NetBSD__)
1152
1153const lldb_private::UnixSignalsSP&
1154Host::GetUnixSignals ()
1155{
1156 static UnixSignalsSP s_unix_signals_sp (new UnixSignals ());
1157 return s_unix_signals_sp;
1158}
1159
1160#endif