Host.cpp revision 276479
1254721Semaste//===-- Host.cpp ------------------------------------------------*- C++ -*-===//
2254721Semaste//
3254721Semaste//                     The LLVM Compiler Infrastructure
4254721Semaste//
5254721Semaste// This file is distributed under the University of Illinois Open Source
6254721Semaste// License. See LICENSE.TXT for details.
7254721Semaste//
8254721Semaste//===----------------------------------------------------------------------===//
9254721Semaste
10254721Semaste#include "lldb/lldb-python.h"
11254721Semaste
12254721Semaste// C includes
13258054Semaste#include <errno.h>
14258054Semaste#include <limits.h>
15276479Sdim#include <stdlib.h>
16258054Semaste#include <sys/types.h>
17258054Semaste#ifdef _WIN32
18258054Semaste#include "lldb/Host/windows/windows.h"
19258054Semaste#include <winsock2.h>
20276479Sdim#include <ws2tcpip.h>
21258054Semaste#else
22262528Semaste#include <unistd.h>
23254721Semaste#include <dlfcn.h>
24254721Semaste#include <grp.h>
25254721Semaste#include <netdb.h>
26254721Semaste#include <pwd.h>
27258884Semaste#include <sys/stat.h>
28258054Semaste#endif
29258054Semaste
30258054Semaste#if !defined (__GNU__) && !defined (_WIN32)
31258054Semaste// Does not exist under GNU/HURD or Windows
32254721Semaste#include <sys/sysctl.h>
33258054Semaste#endif
34254721Semaste
35254721Semaste#if defined (__APPLE__)
36258054Semaste#include <mach/mach_port.h>
37258054Semaste#include <mach/mach_init.h>
38254721Semaste#include <mach-o/dyld.h>
39254721Semaste#endif
40254721Semaste
41276479Sdim#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__APPLE__) || defined(__NetBSD__)
42258054Semaste#include <spawn.h>
43254721Semaste#include <sys/wait.h>
44254721Semaste#include <sys/syscall.h>
45254721Semaste#endif
46254721Semaste
47254721Semaste#if defined (__FreeBSD__)
48254721Semaste#include <pthread_np.h>
49254721Semaste#endif
50254721Semaste
51276479Sdim// C++ includes
52276479Sdim#include <limits>
53276479Sdim
54254721Semaste#include "lldb/Host/Host.h"
55276479Sdim#include "lldb/Host/HostInfo.h"
56254721Semaste#include "lldb/Core/ArchSpec.h"
57254721Semaste#include "lldb/Core/ConstString.h"
58254721Semaste#include "lldb/Core/Debugger.h"
59254721Semaste#include "lldb/Core/Error.h"
60254721Semaste#include "lldb/Core/Log.h"
61258054Semaste#include "lldb/Core/Module.h"
62254721Semaste#include "lldb/Core/StreamString.h"
63254721Semaste#include "lldb/Core/ThreadSafeSTLMap.h"
64254721Semaste#include "lldb/Host/Config.h"
65254721Semaste#include "lldb/Host/Endian.h"
66254721Semaste#include "lldb/Host/FileSpec.h"
67276479Sdim#include "lldb/Host/FileSystem.h"
68254721Semaste#include "lldb/Host/Mutex.h"
69276479Sdim#include "lldb/lldb-private-forward.h"
70276479Sdim#include "lldb/Target/FileAction.h"
71254721Semaste#include "lldb/Target/Process.h"
72276479Sdim#include "lldb/Target/ProcessLaunchInfo.h"
73254721Semaste#include "lldb/Target/TargetList.h"
74258054Semaste#include "lldb/Utility/CleanUp.h"
75254721Semaste
76276479Sdim#include "llvm/ADT/STLExtras.h"
77254721Semaste#include "llvm/ADT/SmallString.h"
78254721Semaste#include "llvm/Support/Host.h"
79276479Sdim#include "llvm/Support/Path.h"
80254721Semaste#include "llvm/Support/raw_ostream.h"
81254721Semaste
82262528Semaste#if defined (__APPLE__)
83262528Semaste#ifndef _POSIX_SPAWN_DISABLE_ASLR
84262528Semaste#define _POSIX_SPAWN_DISABLE_ASLR       0x0100
85262528Semaste#endif
86254721Semaste
87262528Semasteextern "C"
88262528Semaste{
89262528Semaste    int __pthread_chdir(const char *path);
90262528Semaste    int __pthread_fchdir (int fildes);
91262528Semaste}
92262528Semaste
93262528Semaste#endif
94262528Semaste
95254721Semasteusing namespace lldb;
96254721Semasteusing namespace lldb_private;
97254721Semaste
98276479Sdim// Define maximum thread name length
99276479Sdim#if defined (__linux__) || defined (__FreeBSD__) || defined (__FreeBSD_kernel__) || defined (__NetBSD__)
100276479Sdimuint32_t const Host::MAX_THREAD_NAME_LENGTH = 16;
101276479Sdim#else
102276479Sdimuint32_t const Host::MAX_THREAD_NAME_LENGTH = std::numeric_limits<uint32_t>::max ();
103276479Sdim#endif
104254721Semaste
105258054Semaste#if !defined (__APPLE__) && !defined (_WIN32)
106254721Semastestruct MonitorInfo
107254721Semaste{
108254721Semaste    lldb::pid_t pid;                            // The process ID to monitor
109254721Semaste    Host::MonitorChildProcessCallback callback; // The callback function to call when "pid" exits or signals
110254721Semaste    void *callback_baton;                       // The callback baton for the callback function
111254721Semaste    bool monitor_signals;                       // If true, call the callback when "pid" gets signaled.
112254721Semaste};
113254721Semaste
114258054Semastestatic thread_result_t
115254721SemasteMonitorChildProcessThreadFunction (void *arg);
116254721Semaste
117254721Semastelldb::thread_t
118254721SemasteHost::StartMonitoringChildProcess
119254721Semaste(
120254721Semaste    Host::MonitorChildProcessCallback callback,
121254721Semaste    void *callback_baton,
122254721Semaste    lldb::pid_t pid,
123254721Semaste    bool monitor_signals
124254721Semaste)
125254721Semaste{
126254721Semaste    lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
127254721Semaste    MonitorInfo * info_ptr = new MonitorInfo();
128258054Semaste
129254721Semaste    info_ptr->pid = pid;
130254721Semaste    info_ptr->callback = callback;
131254721Semaste    info_ptr->callback_baton = callback_baton;
132254721Semaste    info_ptr->monitor_signals = monitor_signals;
133254721Semaste
134254721Semaste    char thread_name[256];
135276479Sdim
136276479Sdim    if (Host::MAX_THREAD_NAME_LENGTH <= 16)
137276479Sdim    {
138276479Sdim        // On some platforms, the thread name is limited to 16 characters.  We need to
139276479Sdim        // abbreviate there or the pid info would get truncated.
140276479Sdim        ::snprintf (thread_name, sizeof(thread_name), "wait4(%" PRIu64 ")", pid);
141276479Sdim    }
142276479Sdim    else
143276479Sdim    {
144276479Sdim        ::snprintf (thread_name, sizeof(thread_name), "<lldb.host.wait4(pid=%" PRIu64 ")>", pid);
145276479Sdim    }
146276479Sdim
147254721Semaste    thread = ThreadCreate (thread_name,
148254721Semaste                           MonitorChildProcessThreadFunction,
149254721Semaste                           info_ptr,
150254721Semaste                           NULL);
151254721Semaste
152254721Semaste    return thread;
153254721Semaste}
154254721Semaste
155254721Semaste//------------------------------------------------------------------
156254721Semaste// Scoped class that will disable thread canceling when it is
157254721Semaste// constructed, and exception safely restore the previous value it
158254721Semaste// when it goes out of scope.
159254721Semaste//------------------------------------------------------------------
160254721Semasteclass ScopedPThreadCancelDisabler
161254721Semaste{
162254721Semastepublic:
163254721Semaste    ScopedPThreadCancelDisabler()
164254721Semaste    {
165254721Semaste        // Disable the ability for this thread to be cancelled
166254721Semaste        int err = ::pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &m_old_state);
167254721Semaste        if (err != 0)
168254721Semaste            m_old_state = -1;
169254721Semaste
170254721Semaste    }
171254721Semaste
172254721Semaste    ~ScopedPThreadCancelDisabler()
173254721Semaste    {
174254721Semaste        // Restore the ability for this thread to be cancelled to what it
175254721Semaste        // previously was.
176254721Semaste        if (m_old_state != -1)
177254721Semaste            ::pthread_setcancelstate (m_old_state, 0);
178254721Semaste    }
179254721Semasteprivate:
180254721Semaste    int m_old_state;    // Save the old cancelability state.
181254721Semaste};
182254721Semaste
183258054Semastestatic thread_result_t
184254721SemasteMonitorChildProcessThreadFunction (void *arg)
185254721Semaste{
186254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
187254721Semaste    const char *function = __FUNCTION__;
188254721Semaste    if (log)
189254721Semaste        log->Printf ("%s (arg = %p) thread starting...", function, arg);
190254721Semaste
191254721Semaste    MonitorInfo *info = (MonitorInfo *)arg;
192254721Semaste
193254721Semaste    const Host::MonitorChildProcessCallback callback = info->callback;
194254721Semaste    void * const callback_baton = info->callback_baton;
195254721Semaste    const bool monitor_signals = info->monitor_signals;
196254721Semaste
197258054Semaste    assert (info->pid <= UINT32_MAX);
198276479Sdim    const ::pid_t pid = monitor_signals ? -1 * getpgid(info->pid) : info->pid;
199258054Semaste
200254721Semaste    delete info;
201254721Semaste
202254721Semaste    int status = -1;
203254721Semaste#if defined (__FreeBSD__) || defined (__FreeBSD_kernel__)
204254721Semaste    #define __WALL 0
205254721Semaste#endif
206254721Semaste    const int options = __WALL;
207254721Semaste
208254721Semaste    while (1)
209254721Semaste    {
210254721Semaste        log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
211254721Semaste        if (log)
212258054Semaste            log->Printf("%s ::wait_pid (pid = %" PRIi32 ", &status, options = %i)...", function, pid, options);
213254721Semaste
214254721Semaste        // Wait for all child processes
215254721Semaste        ::pthread_testcancel ();
216254721Semaste        // Get signals from all children with same process group of pid
217258054Semaste        const ::pid_t wait_pid = ::waitpid (pid, &status, options);
218254721Semaste        ::pthread_testcancel ();
219254721Semaste
220254721Semaste        if (wait_pid == -1)
221254721Semaste        {
222254721Semaste            if (errno == EINTR)
223254721Semaste                continue;
224254721Semaste            else
225254721Semaste            {
226254721Semaste                if (log)
227254721Semaste                    log->Printf ("%s (arg = %p) thread exiting because waitpid failed (%s)...", __FUNCTION__, arg, strerror(errno));
228254721Semaste                break;
229254721Semaste            }
230254721Semaste        }
231254721Semaste        else if (wait_pid > 0)
232254721Semaste        {
233254721Semaste            bool exited = false;
234254721Semaste            int signal = 0;
235254721Semaste            int exit_status = 0;
236254721Semaste            const char *status_cstr = NULL;
237254721Semaste            if (WIFSTOPPED(status))
238254721Semaste            {
239254721Semaste                signal = WSTOPSIG(status);
240254721Semaste                status_cstr = "STOPPED";
241254721Semaste            }
242254721Semaste            else if (WIFEXITED(status))
243254721Semaste            {
244254721Semaste                exit_status = WEXITSTATUS(status);
245254721Semaste                status_cstr = "EXITED";
246254721Semaste                exited = true;
247254721Semaste            }
248254721Semaste            else if (WIFSIGNALED(status))
249254721Semaste            {
250254721Semaste                signal = WTERMSIG(status);
251254721Semaste                status_cstr = "SIGNALED";
252258054Semaste                if (wait_pid == abs(pid)) {
253254721Semaste                    exited = true;
254254721Semaste                    exit_status = -1;
255254721Semaste                }
256254721Semaste            }
257254721Semaste            else
258254721Semaste            {
259254721Semaste                status_cstr = "(\?\?\?)";
260254721Semaste            }
261254721Semaste
262254721Semaste            // Scope for pthread_cancel_disabler
263254721Semaste            {
264254721Semaste                ScopedPThreadCancelDisabler pthread_cancel_disabler;
265254721Semaste
266254721Semaste                log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
267254721Semaste                if (log)
268258054Semaste                    log->Printf ("%s ::waitpid (pid = %" PRIi32 ", &status, options = %i) => pid = %" PRIi32 ", status = 0x%8.8x (%s), signal = %i, exit_state = %i",
269254721Semaste                                 function,
270254721Semaste                                 wait_pid,
271254721Semaste                                 options,
272254721Semaste                                 pid,
273254721Semaste                                 status,
274254721Semaste                                 status_cstr,
275254721Semaste                                 signal,
276254721Semaste                                 exit_status);
277254721Semaste
278254721Semaste                if (exited || (signal != 0 && monitor_signals))
279254721Semaste                {
280254721Semaste                    bool callback_return = false;
281254721Semaste                    if (callback)
282254721Semaste                        callback_return = callback (callback_baton, wait_pid, exited, signal, exit_status);
283254721Semaste
284254721Semaste                    // If our process exited, then this thread should exit
285258054Semaste                    if (exited && wait_pid == abs(pid))
286254721Semaste                    {
287254721Semaste                        if (log)
288254721Semaste                            log->Printf ("%s (arg = %p) thread exiting because pid received exit signal...", __FUNCTION__, arg);
289254721Semaste                        break;
290254721Semaste                    }
291254721Semaste                    // If the callback returns true, it means this process should
292254721Semaste                    // exit
293254721Semaste                    if (callback_return)
294254721Semaste                    {
295254721Semaste                        if (log)
296254721Semaste                            log->Printf ("%s (arg = %p) thread exiting because callback returned true...", __FUNCTION__, arg);
297254721Semaste                        break;
298254721Semaste                    }
299254721Semaste                }
300254721Semaste            }
301254721Semaste        }
302254721Semaste    }
303254721Semaste
304254721Semaste    log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS);
305254721Semaste    if (log)
306254721Semaste        log->Printf ("%s (arg = %p) thread exiting...", __FUNCTION__, arg);
307254721Semaste
308254721Semaste    return NULL;
309254721Semaste}
310254721Semaste
311258054Semaste#endif // #if !defined (__APPLE__) && !defined (_WIN32)
312254721Semaste
313258054Semaste#if !defined (__APPLE__)
314258054Semaste
315254721Semastevoid
316254721SemasteHost::SystemLog (SystemLogType type, const char *format, va_list args)
317254721Semaste{
318254721Semaste    vfprintf (stderr, format, args);
319254721Semaste}
320254721Semaste
321258054Semaste#endif
322254721Semaste
323254721Semastevoid
324254721SemasteHost::SystemLog (SystemLogType type, const char *format, ...)
325254721Semaste{
326254721Semaste    va_list args;
327254721Semaste    va_start (args, format);
328254721Semaste    SystemLog (type, format, args);
329254721Semaste    va_end (args);
330254721Semaste}
331254721Semaste
332254721Semastelldb::pid_t
333254721SemasteHost::GetCurrentProcessID()
334254721Semaste{
335254721Semaste    return ::getpid();
336254721Semaste}
337254721Semaste
338258054Semaste#ifndef _WIN32
339258054Semaste
340254721Semastelldb::tid_t
341254721SemasteHost::GetCurrentThreadID()
342254721Semaste{
343254721Semaste#if defined (__APPLE__)
344262528Semaste    // Calling "mach_thread_self()" bumps the reference count on the thread
345254721Semaste    // port, so we need to deallocate it. mach_task_self() doesn't bump the ref
346254721Semaste    // count.
347254721Semaste    thread_port_t thread_self = mach_thread_self();
348254721Semaste    mach_port_deallocate(mach_task_self(), thread_self);
349254721Semaste    return thread_self;
350254721Semaste#elif defined(__FreeBSD__)
351254721Semaste    return lldb::tid_t(pthread_getthreadid_np());
352254721Semaste#elif defined(__linux__)
353254721Semaste    return lldb::tid_t(syscall(SYS_gettid));
354254721Semaste#else
355254721Semaste    return lldb::tid_t(pthread_self());
356254721Semaste#endif
357254721Semaste}
358254721Semaste
359254721Semastelldb::thread_t
360254721SemasteHost::GetCurrentThread ()
361254721Semaste{
362254721Semaste    return lldb::thread_t(pthread_self());
363254721Semaste}
364254721Semaste
365254721Semasteconst char *
366254721SemasteHost::GetSignalAsCString (int signo)
367254721Semaste{
368254721Semaste    switch (signo)
369254721Semaste    {
370254721Semaste    case SIGHUP:    return "SIGHUP";    // 1    hangup
371254721Semaste    case SIGINT:    return "SIGINT";    // 2    interrupt
372254721Semaste    case SIGQUIT:   return "SIGQUIT";   // 3    quit
373254721Semaste    case SIGILL:    return "SIGILL";    // 4    illegal instruction (not reset when caught)
374254721Semaste    case SIGTRAP:   return "SIGTRAP";   // 5    trace trap (not reset when caught)
375254721Semaste    case SIGABRT:   return "SIGABRT";   // 6    abort()
376262528Semaste#if  defined(SIGPOLL)
377262528Semaste#if !defined(SIGIO) || (SIGPOLL != SIGIO)
378262528Semaste// Under some GNU/Linux, SIGPOLL and SIGIO are the same. Causing the build to
379262528Semaste// fail with 'multiple define cases with same value'
380254721Semaste    case SIGPOLL:   return "SIGPOLL";   // 7    pollable event ([XSR] generated, not supported)
381254721Semaste#endif
382262528Semaste#endif
383262528Semaste#if  defined(SIGEMT)
384254721Semaste    case SIGEMT:    return "SIGEMT";    // 7    EMT instruction
385254721Semaste#endif
386254721Semaste    case SIGFPE:    return "SIGFPE";    // 8    floating point exception
387254721Semaste    case SIGKILL:   return "SIGKILL";   // 9    kill (cannot be caught or ignored)
388254721Semaste    case SIGBUS:    return "SIGBUS";    // 10    bus error
389254721Semaste    case SIGSEGV:   return "SIGSEGV";   // 11    segmentation violation
390254721Semaste    case SIGSYS:    return "SIGSYS";    // 12    bad argument to system call
391254721Semaste    case SIGPIPE:   return "SIGPIPE";   // 13    write on a pipe with no one to read it
392254721Semaste    case SIGALRM:   return "SIGALRM";   // 14    alarm clock
393254721Semaste    case SIGTERM:   return "SIGTERM";   // 15    software termination signal from kill
394254721Semaste    case SIGURG:    return "SIGURG";    // 16    urgent condition on IO channel
395254721Semaste    case SIGSTOP:   return "SIGSTOP";   // 17    sendable stop signal not from tty
396254721Semaste    case SIGTSTP:   return "SIGTSTP";   // 18    stop signal from tty
397254721Semaste    case SIGCONT:   return "SIGCONT";   // 19    continue a stopped process
398254721Semaste    case SIGCHLD:   return "SIGCHLD";   // 20    to parent on child stop or exit
399254721Semaste    case SIGTTIN:   return "SIGTTIN";   // 21    to readers pgrp upon background tty read
400254721Semaste    case SIGTTOU:   return "SIGTTOU";   // 22    like TTIN for output if (tp->t_local&LTOSTOP)
401262528Semaste#if  defined(SIGIO)
402254721Semaste    case SIGIO:     return "SIGIO";     // 23    input/output possible signal
403254721Semaste#endif
404254721Semaste    case SIGXCPU:   return "SIGXCPU";   // 24    exceeded CPU time limit
405254721Semaste    case SIGXFSZ:   return "SIGXFSZ";   // 25    exceeded file size limit
406254721Semaste    case SIGVTALRM: return "SIGVTALRM"; // 26    virtual time alarm
407254721Semaste    case SIGPROF:   return "SIGPROF";   // 27    profiling time alarm
408262528Semaste#if  defined(SIGWINCH)
409254721Semaste    case SIGWINCH:  return "SIGWINCH";  // 28    window size changes
410262528Semaste#endif
411262528Semaste#if  defined(SIGINFO)
412254721Semaste    case SIGINFO:   return "SIGINFO";   // 29    information request
413254721Semaste#endif
414254721Semaste    case SIGUSR1:   return "SIGUSR1";   // 30    user defined signal 1
415254721Semaste    case SIGUSR2:   return "SIGUSR2";   // 31    user defined signal 2
416254721Semaste    default:
417254721Semaste        break;
418254721Semaste    }
419254721Semaste    return NULL;
420254721Semaste}
421254721Semaste
422258054Semaste#endif
423258054Semaste
424254721Semastevoid
425254721SemasteHost::WillTerminate ()
426254721Semaste{
427254721Semaste}
428254721Semaste
429254721Semaste#if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__) // see macosx/Host.mm
430254721Semaste
431254721Semastevoid
432254721SemasteHost::ThreadCreated (const char *thread_name)
433254721Semaste{
434254721Semaste}
435254721Semaste
436254721Semastevoid
437254721SemasteHost::Backtrace (Stream &strm, uint32_t max_frames)
438254721Semaste{
439254721Semaste    // TODO: Is there a way to backtrace the current process on other systems?
440254721Semaste}
441254721Semaste
442254721Semastesize_t
443254721SemasteHost::GetEnvironment (StringList &env)
444254721Semaste{
445254721Semaste    // TODO: Is there a way to the host environment for this process on other systems?
446254721Semaste    return 0;
447254721Semaste}
448254721Semaste
449254721Semaste#endif // #if !defined (__APPLE__) && !defined (__FreeBSD__) && !defined (__FreeBSD_kernel__) && !defined (__linux__)
450254721Semaste
451254721Semastestruct HostThreadCreateInfo
452254721Semaste{
453254721Semaste    std::string thread_name;
454254721Semaste    thread_func_t thread_fptr;
455254721Semaste    thread_arg_t thread_arg;
456254721Semaste
457254721Semaste    HostThreadCreateInfo (const char *name, thread_func_t fptr, thread_arg_t arg) :
458254721Semaste        thread_name (name ? name : ""),
459254721Semaste        thread_fptr (fptr),
460254721Semaste        thread_arg (arg)
461254721Semaste    {
462254721Semaste    }
463254721Semaste};
464254721Semaste
465254721Semastestatic thread_result_t
466258054Semaste#ifdef _WIN32
467258054Semaste__stdcall
468258054Semaste#endif
469254721SemasteThreadCreateTrampoline (thread_arg_t arg)
470254721Semaste{
471254721Semaste    HostThreadCreateInfo *info = (HostThreadCreateInfo *)arg;
472254721Semaste    Host::ThreadCreated (info->thread_name.c_str());
473254721Semaste    thread_func_t thread_fptr = info->thread_fptr;
474254721Semaste    thread_arg_t thread_arg = info->thread_arg;
475254721Semaste
476254721Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_THREAD));
477254721Semaste    if (log)
478254721Semaste        log->Printf("thread created");
479254721Semaste
480254721Semaste    delete info;
481254721Semaste    return thread_fptr (thread_arg);
482254721Semaste}
483254721Semaste
484254721Semastelldb::thread_t
485254721SemasteHost::ThreadCreate
486254721Semaste(
487254721Semaste    const char *thread_name,
488254721Semaste    thread_func_t thread_fptr,
489254721Semaste    thread_arg_t thread_arg,
490254721Semaste    Error *error
491254721Semaste)
492254721Semaste{
493254721Semaste    lldb::thread_t thread = LLDB_INVALID_HOST_THREAD;
494254721Semaste
495254721Semaste    // Host::ThreadCreateTrampoline will delete this pointer for us.
496254721Semaste    HostThreadCreateInfo *info_ptr = new HostThreadCreateInfo (thread_name, thread_fptr, thread_arg);
497254721Semaste
498258054Semaste#ifdef _WIN32
499258054Semaste    thread = ::_beginthreadex(0, 0, ThreadCreateTrampoline, info_ptr, 0, NULL);
500258054Semaste    int err = thread <= 0 ? GetLastError() : 0;
501258054Semaste#else
502254721Semaste    int err = ::pthread_create (&thread, NULL, ThreadCreateTrampoline, info_ptr);
503258054Semaste#endif
504254721Semaste    if (err == 0)
505254721Semaste    {
506254721Semaste        if (error)
507254721Semaste            error->Clear();
508254721Semaste        return thread;
509254721Semaste    }
510254721Semaste
511254721Semaste    if (error)
512254721Semaste        error->SetError (err, eErrorTypePOSIX);
513254721Semaste
514254721Semaste    return LLDB_INVALID_HOST_THREAD;
515254721Semaste}
516254721Semaste
517258054Semaste#ifndef _WIN32
518258054Semaste
519254721Semastebool
520254721SemasteHost::ThreadCancel (lldb::thread_t thread, Error *error)
521254721Semaste{
522254721Semaste    int err = ::pthread_cancel (thread);
523254721Semaste    if (error)
524254721Semaste        error->SetError(err, eErrorTypePOSIX);
525254721Semaste    return err == 0;
526254721Semaste}
527254721Semaste
528254721Semastebool
529254721SemasteHost::ThreadDetach (lldb::thread_t thread, Error *error)
530254721Semaste{
531254721Semaste    int err = ::pthread_detach (thread);
532254721Semaste    if (error)
533254721Semaste        error->SetError(err, eErrorTypePOSIX);
534254721Semaste    return err == 0;
535254721Semaste}
536254721Semaste
537254721Semastebool
538254721SemasteHost::ThreadJoin (lldb::thread_t thread, thread_result_t *thread_result_ptr, Error *error)
539254721Semaste{
540254721Semaste    int err = ::pthread_join (thread, thread_result_ptr);
541254721Semaste    if (error)
542254721Semaste        error->SetError(err, eErrorTypePOSIX);
543254721Semaste    return err == 0;
544254721Semaste}
545254721Semaste
546258054Semastelldb::thread_key_t
547258054SemasteHost::ThreadLocalStorageCreate(ThreadLocalStorageCleanupCallback callback)
548258054Semaste{
549258054Semaste    pthread_key_t key;
550258054Semaste    ::pthread_key_create (&key, callback);
551258054Semaste    return key;
552258054Semaste}
553258054Semaste
554258054Semastevoid*
555258054SemasteHost::ThreadLocalStorageGet(lldb::thread_key_t key)
556258054Semaste{
557258054Semaste    return ::pthread_getspecific (key);
558258054Semaste}
559258054Semaste
560258054Semastevoid
561258054SemasteHost::ThreadLocalStorageSet(lldb::thread_key_t key, void *value)
562258054Semaste{
563258054Semaste   ::pthread_setspecific (key, value);
564258054Semaste}
565258054Semaste
566254721Semastebool
567254721SemasteHost::SetThreadName (lldb::pid_t pid, lldb::tid_t tid, const char *name)
568254721Semaste{
569254721Semaste#if defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED > MAC_OS_X_VERSION_10_5
570254721Semaste    lldb::pid_t curr_pid = Host::GetCurrentProcessID();
571254721Semaste    lldb::tid_t curr_tid = Host::GetCurrentThreadID();
572254721Semaste    if (pid == LLDB_INVALID_PROCESS_ID)
573254721Semaste        pid = curr_pid;
574254721Semaste
575254721Semaste    if (tid == LLDB_INVALID_THREAD_ID)
576254721Semaste        tid = curr_tid;
577254721Semaste
578254721Semaste    // Set the pthread name if possible
579254721Semaste    if (pid == curr_pid && tid == curr_tid)
580254721Semaste    {
581254721Semaste        if (::pthread_setname_np (name) == 0)
582254721Semaste            return true;
583254721Semaste    }
584254721Semaste    return false;
585254721Semaste#elif defined (__FreeBSD__)
586254721Semaste    lldb::pid_t curr_pid = Host::GetCurrentProcessID();
587254721Semaste    lldb::tid_t curr_tid = Host::GetCurrentThreadID();
588254721Semaste    if (pid == LLDB_INVALID_PROCESS_ID)
589254721Semaste        pid = curr_pid;
590254721Semaste
591254721Semaste    if (tid == LLDB_INVALID_THREAD_ID)
592254721Semaste        tid = curr_tid;
593254721Semaste
594254721Semaste    // Set the pthread name if possible
595254721Semaste    if (pid == curr_pid && tid == curr_tid)
596254721Semaste    {
597254721Semaste        ::pthread_set_name_np (::pthread_self(), name);
598254721Semaste        return true;
599254721Semaste    }
600254721Semaste    return false;
601254721Semaste#elif defined (__linux__) || defined (__GLIBC__)
602254721Semaste    void *fn = dlsym (RTLD_DEFAULT, "pthread_setname_np");
603254721Semaste    if (fn)
604254721Semaste    {
605254721Semaste        lldb::pid_t curr_pid = Host::GetCurrentProcessID();
606254721Semaste        lldb::tid_t curr_tid = Host::GetCurrentThreadID();
607254721Semaste        if (pid == LLDB_INVALID_PROCESS_ID)
608254721Semaste            pid = curr_pid;
609254721Semaste
610254721Semaste        if (tid == LLDB_INVALID_THREAD_ID)
611254721Semaste            tid = curr_tid;
612254721Semaste
613254721Semaste        if (pid == curr_pid && tid == curr_tid)
614254721Semaste        {
615254721Semaste            int (*pthread_setname_np_func)(pthread_t thread, const char *name);
616254721Semaste            *reinterpret_cast<void **> (&pthread_setname_np_func) = fn;
617254721Semaste
618254721Semaste            if (pthread_setname_np_func (::pthread_self(), name) == 0)
619254721Semaste                return true;
620254721Semaste        }
621254721Semaste    }
622254721Semaste    return false;
623254721Semaste#else
624254721Semaste    return false;
625254721Semaste#endif
626254721Semaste}
627254721Semaste
628254721Semastebool
629254721SemasteHost::SetShortThreadName (lldb::pid_t pid, lldb::tid_t tid,
630254721Semaste                          const char *thread_name, size_t len)
631254721Semaste{
632262528Semaste    std::unique_ptr<char[]> namebuf(new char[len+1]);
633262528Semaste
634254721Semaste    // Thread names are coming in like '<lldb.comm.debugger.edit>' and
635254721Semaste    // '<lldb.comm.debugger.editline>'.  So just chopping the end of the string
636254721Semaste    // off leads to a lot of similar named threads.  Go through the thread name
637254721Semaste    // and search for the last dot and use that.
638254721Semaste    const char *lastdot = ::strrchr (thread_name, '.');
639254721Semaste
640254721Semaste    if (lastdot && lastdot != thread_name)
641254721Semaste        thread_name = lastdot + 1;
642262528Semaste    ::strncpy (namebuf.get(), thread_name, len);
643254721Semaste    namebuf[len] = 0;
644254721Semaste
645262528Semaste    int namebuflen = strlen(namebuf.get());
646254721Semaste    if (namebuflen > 0)
647254721Semaste    {
648254721Semaste        if (namebuf[namebuflen - 1] == '(' || namebuf[namebuflen - 1] == '>')
649254721Semaste        {
650254721Semaste            // Trim off trailing '(' and '>' characters for a bit more cleanup.
651254721Semaste            namebuflen--;
652254721Semaste            namebuf[namebuflen] = 0;
653254721Semaste        }
654262528Semaste        return Host::SetThreadName (pid, tid, namebuf.get());
655254721Semaste    }
656254721Semaste    return false;
657254721Semaste}
658254721Semaste
659258054Semaste#endif
660258054Semaste
661254721Semaste#if !defined (__APPLE__) // see Host.mm
662254721Semaste
663254721Semastebool
664254721SemasteHost::GetBundleDirectory (const FileSpec &file, FileSpec &bundle)
665254721Semaste{
666254721Semaste    bundle.Clear();
667254721Semaste    return false;
668254721Semaste}
669254721Semaste
670254721Semastebool
671254721SemasteHost::ResolveExecutableInBundle (FileSpec &file)
672254721Semaste{
673254721Semaste    return false;
674254721Semaste}
675254721Semaste#endif
676254721Semaste
677258054Semaste#ifndef _WIN32
678258054Semaste
679258054SemasteFileSpec
680258054SemasteHost::GetModuleFileSpecForHostAddress (const void *host_addr)
681258054Semaste{
682258054Semaste    FileSpec module_filespec;
683258054Semaste    Dl_info info;
684258054Semaste    if (::dladdr (host_addr, &info))
685258054Semaste    {
686258054Semaste        if (info.dli_fname)
687258054Semaste            module_filespec.SetFile(info.dli_fname, true);
688258054Semaste    }
689258054Semaste    return module_filespec;
690258054Semaste}
691258054Semaste
692258054Semaste#endif
693258054Semaste
694254721Semaste#if !defined(__linux__)
695254721Semastebool
696254721SemasteHost::FindProcessThreads (const lldb::pid_t pid, TidMap &tids_to_attach)
697254721Semaste{
698254721Semaste    return false;
699254721Semaste}
700254721Semaste#endif
701254721Semaste
702254721Semastelldb::TargetSP
703254721SemasteHost::GetDummyTarget (lldb_private::Debugger &debugger)
704254721Semaste{
705254721Semaste    static TargetSP g_dummy_target_sp;
706254721Semaste
707254721Semaste    // FIXME: Maybe the dummy target should be per-Debugger
708254721Semaste    if (!g_dummy_target_sp || !g_dummy_target_sp->IsValid())
709254721Semaste    {
710254721Semaste        ArchSpec arch(Target::GetDefaultArchitecture());
711254721Semaste        if (!arch.IsValid())
712276479Sdim            arch = HostInfo::GetArchitecture();
713254721Semaste        Error err = debugger.GetTargetList().CreateTarget(debugger,
714254721Semaste                                                          NULL,
715254721Semaste                                                          arch.GetTriple().getTriple().c_str(),
716254721Semaste                                                          false,
717254721Semaste                                                          NULL,
718254721Semaste                                                          g_dummy_target_sp);
719254721Semaste    }
720254721Semaste
721254721Semaste    return g_dummy_target_sp;
722254721Semaste}
723254721Semaste
724254721Semastestruct ShellInfo
725254721Semaste{
726254721Semaste    ShellInfo () :
727254721Semaste        process_reaped (false),
728254721Semaste        can_delete (false),
729254721Semaste        pid (LLDB_INVALID_PROCESS_ID),
730254721Semaste        signo(-1),
731254721Semaste        status(-1)
732254721Semaste    {
733254721Semaste    }
734254721Semaste
735254721Semaste    lldb_private::Predicate<bool> process_reaped;
736254721Semaste    lldb_private::Predicate<bool> can_delete;
737254721Semaste    lldb::pid_t pid;
738254721Semaste    int signo;
739254721Semaste    int status;
740254721Semaste};
741254721Semaste
742254721Semastestatic bool
743254721SemasteMonitorShellCommand (void *callback_baton,
744254721Semaste                     lldb::pid_t pid,
745254721Semaste                     bool exited,       // True if the process did exit
746254721Semaste                     int signo,         // Zero for no signal
747254721Semaste                     int status)   // Exit value of process if signal is zero
748254721Semaste{
749254721Semaste    ShellInfo *shell_info = (ShellInfo *)callback_baton;
750254721Semaste    shell_info->pid = pid;
751254721Semaste    shell_info->signo = signo;
752254721Semaste    shell_info->status = status;
753254721Semaste    // Let the thread running Host::RunShellCommand() know that the process
754254721Semaste    // exited and that ShellInfo has been filled in by broadcasting to it
755254721Semaste    shell_info->process_reaped.SetValue(1, eBroadcastAlways);
756254721Semaste    // Now wait for a handshake back from that thread running Host::RunShellCommand
757254721Semaste    // so we know that we can delete shell_info_ptr
758254721Semaste    shell_info->can_delete.WaitForValueEqualTo(true);
759254721Semaste    // Sleep a bit to allow the shell_info->can_delete.SetValue() to complete...
760254721Semaste    usleep(1000);
761254721Semaste    // Now delete the shell info that was passed into this function
762254721Semaste    delete shell_info;
763254721Semaste    return true;
764254721Semaste}
765254721Semaste
766254721SemasteError
767254721SemasteHost::RunShellCommand (const char *command,
768254721Semaste                       const char *working_dir,
769254721Semaste                       int *status_ptr,
770254721Semaste                       int *signo_ptr,
771254721Semaste                       std::string *command_output_ptr,
772254721Semaste                       uint32_t timeout_sec,
773254721Semaste                       const char *shell)
774254721Semaste{
775254721Semaste    Error error;
776254721Semaste    ProcessLaunchInfo launch_info;
777254721Semaste    if (shell && shell[0])
778254721Semaste    {
779254721Semaste        // Run the command in a shell
780254721Semaste        launch_info.SetShell(shell);
781254721Semaste        launch_info.GetArguments().AppendArgument(command);
782254721Semaste        const bool localhost = true;
783254721Semaste        const bool will_debug = false;
784254721Semaste        const bool first_arg_is_full_shell_command = true;
785254721Semaste        launch_info.ConvertArgumentsForLaunchingInShell (error,
786254721Semaste                                                         localhost,
787254721Semaste                                                         will_debug,
788258054Semaste                                                         first_arg_is_full_shell_command,
789258054Semaste                                                         0);
790254721Semaste    }
791254721Semaste    else
792254721Semaste    {
793254721Semaste        // No shell, just run it
794254721Semaste        Args args (command);
795254721Semaste        const bool first_arg_is_executable = true;
796254721Semaste        launch_info.SetArguments(args, first_arg_is_executable);
797254721Semaste    }
798254721Semaste
799254721Semaste    if (working_dir)
800254721Semaste        launch_info.SetWorkingDirectory(working_dir);
801262528Semaste    char output_file_path_buffer[PATH_MAX];
802254721Semaste    const char *output_file_path = NULL;
803262528Semaste
804254721Semaste    if (command_output_ptr)
805254721Semaste    {
806254721Semaste        // Create a temporary file to get the stdout/stderr and redirect the
807254721Semaste        // output of the command into this file. We will later read this file
808254721Semaste        // if all goes well and fill the data into "command_output_ptr"
809262528Semaste        FileSpec tmpdir_file_spec;
810276479Sdim        if (HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
811262528Semaste        {
812276479Sdim            tmpdir_file_spec.AppendPathComponent("lldb-shell-output.XXXXXX");
813262528Semaste            strncpy(output_file_path_buffer, tmpdir_file_spec.GetPath().c_str(), sizeof(output_file_path_buffer));
814262528Semaste        }
815262528Semaste        else
816262528Semaste        {
817262528Semaste            strncpy(output_file_path_buffer, "/tmp/lldb-shell-output.XXXXXX", sizeof(output_file_path_buffer));
818262528Semaste        }
819262528Semaste
820262528Semaste        output_file_path = ::mktemp(output_file_path_buffer);
821262528Semaste    }
822262528Semaste
823262528Semaste    launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
824262528Semaste    if (output_file_path)
825262528Semaste    {
826254721Semaste        launch_info.AppendOpenFileAction(STDOUT_FILENO, output_file_path, false, true);
827254721Semaste        launch_info.AppendDuplicateFileAction(STDOUT_FILENO, STDERR_FILENO);
828254721Semaste    }
829254721Semaste    else
830254721Semaste    {
831254721Semaste        launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
832254721Semaste        launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
833254721Semaste    }
834254721Semaste
835254721Semaste    // The process monitor callback will delete the 'shell_info_ptr' below...
836254721Semaste    std::unique_ptr<ShellInfo> shell_info_ap (new ShellInfo());
837254721Semaste
838254721Semaste    const bool monitor_signals = false;
839254721Semaste    launch_info.SetMonitorProcessCallback(MonitorShellCommand, shell_info_ap.get(), monitor_signals);
840254721Semaste
841254721Semaste    error = LaunchProcess (launch_info);
842254721Semaste    const lldb::pid_t pid = launch_info.GetProcessID();
843258054Semaste
844258054Semaste    if (error.Success() && pid == LLDB_INVALID_PROCESS_ID)
845258054Semaste        error.SetErrorString("failed to get process ID");
846258054Semaste
847258054Semaste    if (error.Success())
848254721Semaste    {
849254721Semaste        // The process successfully launched, so we can defer ownership of
850254721Semaste        // "shell_info" to the MonitorShellCommand callback function that will
851254721Semaste        // get called when the process dies. We release the unique pointer as it
852254721Semaste        // doesn't need to delete the ShellInfo anymore.
853254721Semaste        ShellInfo *shell_info = shell_info_ap.release();
854258054Semaste        TimeValue *timeout_ptr = nullptr;
855254721Semaste        TimeValue timeout_time(TimeValue::Now());
856258054Semaste        if (timeout_sec > 0) {
857258054Semaste            timeout_time.OffsetWithSeconds(timeout_sec);
858258054Semaste            timeout_ptr = &timeout_time;
859258054Semaste        }
860254721Semaste        bool timed_out = false;
861258054Semaste        shell_info->process_reaped.WaitForValueEqualTo(true, timeout_ptr, &timed_out);
862254721Semaste        if (timed_out)
863254721Semaste        {
864254721Semaste            error.SetErrorString("timed out waiting for shell command to complete");
865258054Semaste
866276479Sdim            // Kill the process since it didn't complete within the timeout specified
867258054Semaste            Kill (pid, SIGKILL);
868254721Semaste            // Wait for the monitor callback to get the message
869254721Semaste            timeout_time = TimeValue::Now();
870254721Semaste            timeout_time.OffsetWithSeconds(1);
871254721Semaste            timed_out = false;
872254721Semaste            shell_info->process_reaped.WaitForValueEqualTo(true, &timeout_time, &timed_out);
873254721Semaste        }
874254721Semaste        else
875254721Semaste        {
876254721Semaste            if (status_ptr)
877254721Semaste                *status_ptr = shell_info->status;
878254721Semaste
879254721Semaste            if (signo_ptr)
880254721Semaste                *signo_ptr = shell_info->signo;
881254721Semaste
882254721Semaste            if (command_output_ptr)
883254721Semaste            {
884254721Semaste                command_output_ptr->clear();
885254721Semaste                FileSpec file_spec(output_file_path, File::eOpenOptionRead);
886254721Semaste                uint64_t file_size = file_spec.GetByteSize();
887254721Semaste                if (file_size > 0)
888254721Semaste                {
889254721Semaste                    if (file_size > command_output_ptr->max_size())
890254721Semaste                    {
891254721Semaste                        error.SetErrorStringWithFormat("shell command output is too large to fit into a std::string");
892254721Semaste                    }
893254721Semaste                    else
894254721Semaste                    {
895254721Semaste                        command_output_ptr->resize(file_size);
896254721Semaste                        file_spec.ReadFileContents(0, &((*command_output_ptr)[0]), command_output_ptr->size(), &error);
897254721Semaste                    }
898254721Semaste                }
899254721Semaste            }
900254721Semaste        }
901254721Semaste        shell_info->can_delete.SetValue(true, eBroadcastAlways);
902254721Semaste    }
903254721Semaste
904254721Semaste    if (output_file_path)
905254721Semaste        ::unlink (output_file_path);
906254721Semaste    // Handshake with the monitor thread, or just let it know in advance that
907254721Semaste    // it can delete "shell_info" in case we timed out and were not able to kill
908254721Semaste    // the process...
909254721Semaste    return error;
910254721Semaste}
911254721Semaste
912254721Semaste
913262528Semaste// LaunchProcessPosixSpawn for Apple, Linux, FreeBSD and other GLIBC
914262528Semaste// systems
915262528Semaste
916276479Sdim#if defined (__APPLE__) || defined (__linux__) || defined (__FreeBSD__) || defined (__GLIBC__) || defined(__NetBSD__)
917262528Semaste
918262528Semaste// this method needs to be visible to macosx/Host.cpp and
919262528Semaste// common/Host.cpp.
920262528Semaste
921262528Semasteshort
922262528SemasteHost::GetPosixspawnFlags (ProcessLaunchInfo &launch_info)
923258054Semaste{
924262528Semaste    short flags = POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
925262528Semaste
926262528Semaste#if defined (__APPLE__)
927262528Semaste    if (launch_info.GetFlags().Test (eLaunchFlagExec))
928262528Semaste        flags |= POSIX_SPAWN_SETEXEC;           // Darwin specific posix_spawn flag
929262528Semaste
930262528Semaste    if (launch_info.GetFlags().Test (eLaunchFlagDebug))
931262528Semaste        flags |= POSIX_SPAWN_START_SUSPENDED;   // Darwin specific posix_spawn flag
932262528Semaste
933262528Semaste    if (launch_info.GetFlags().Test (eLaunchFlagDisableASLR))
934262528Semaste        flags |= _POSIX_SPAWN_DISABLE_ASLR;     // Darwin specific posix_spawn flag
935262528Semaste
936262528Semaste    if (launch_info.GetLaunchInSeparateProcessGroup())
937262528Semaste        flags |= POSIX_SPAWN_SETPGROUP;
938262528Semaste
939262528Semaste#ifdef POSIX_SPAWN_CLOEXEC_DEFAULT
940262528Semaste#if defined (__APPLE__) && (defined (__x86_64__) || defined (__i386__))
941262528Semaste    static LazyBool g_use_close_on_exec_flag = eLazyBoolCalculate;
942262528Semaste    if (g_use_close_on_exec_flag == eLazyBoolCalculate)
943262528Semaste    {
944262528Semaste        g_use_close_on_exec_flag = eLazyBoolNo;
945262528Semaste
946262528Semaste        uint32_t major, minor, update;
947276479Sdim        if (HostInfo::GetOSVersion(major, minor, update))
948262528Semaste        {
949262528Semaste            // Kernel panic if we use the POSIX_SPAWN_CLOEXEC_DEFAULT on 10.7 or earlier
950262528Semaste            if (major > 10 || (major == 10 && minor > 7))
951262528Semaste            {
952262528Semaste                // Only enable for 10.8 and later OS versions
953262528Semaste                g_use_close_on_exec_flag = eLazyBoolYes;
954262528Semaste            }
955262528Semaste        }
956262528Semaste    }
957262528Semaste#else
958262528Semaste    static LazyBool g_use_close_on_exec_flag = eLazyBoolYes;
959262528Semaste#endif
960262528Semaste    // Close all files exception those with file actions if this is supported.
961262528Semaste    if (g_use_close_on_exec_flag == eLazyBoolYes)
962262528Semaste        flags |= POSIX_SPAWN_CLOEXEC_DEFAULT;
963262528Semaste#endif
964262528Semaste#endif // #if defined (__APPLE__)
965262528Semaste    return flags;
966262528Semaste}
967262528Semaste
968262528SemasteError
969262528SemasteHost::LaunchProcessPosixSpawn (const char *exe_path, ProcessLaunchInfo &launch_info, ::pid_t &pid)
970262528Semaste{
971258054Semaste    Error error;
972258054Semaste    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_HOST | LIBLLDB_LOG_PROCESS));
973258054Semaste
974258054Semaste    posix_spawnattr_t attr;
975262528Semaste    error.SetError( ::posix_spawnattr_init (&attr), eErrorTypePOSIX);
976258054Semaste
977262528Semaste    if (error.Fail() || log)
978262528Semaste        error.PutToLog(log, "::posix_spawnattr_init ( &attr )");
979258054Semaste    if (error.Fail())
980258054Semaste        return error;
981258054Semaste
982258054Semaste    // Make a quick class that will cleanup the posix spawn attributes in case
983258054Semaste    // we return in the middle of this function.
984258054Semaste    lldb_utility::CleanUp <posix_spawnattr_t *, int> posix_spawnattr_cleanup(&attr, posix_spawnattr_destroy);
985258054Semaste
986258054Semaste    sigset_t no_signals;
987258054Semaste    sigset_t all_signals;
988258054Semaste    sigemptyset (&no_signals);
989258054Semaste    sigfillset (&all_signals);
990262528Semaste    ::posix_spawnattr_setsigmask(&attr, &no_signals);
991262528Semaste#if defined (__linux__)  || defined (__FreeBSD__)
992258054Semaste    ::posix_spawnattr_setsigdefault(&attr, &no_signals);
993262528Semaste#else
994262528Semaste    ::posix_spawnattr_setsigdefault(&attr, &all_signals);
995262528Semaste#endif
996258054Semaste
997262528Semaste    short flags = GetPosixspawnFlags(launch_info);
998258054Semaste
999258054Semaste    error.SetError( ::posix_spawnattr_setflags (&attr, flags), eErrorTypePOSIX);
1000262528Semaste    if (error.Fail() || log)
1001262528Semaste        error.PutToLog(log, "::posix_spawnattr_setflags ( &attr, flags=0x%8.8x )", flags);
1002258054Semaste    if (error.Fail())
1003258054Semaste        return error;
1004258054Semaste
1005262528Semaste    // posix_spawnattr_setbinpref_np appears to be an Apple extension per:
1006262528Semaste    // http://www.unix.com/man-page/OSX/3/posix_spawnattr_setbinpref_np/
1007262528Semaste#if defined (__APPLE__) && !defined (__arm__)
1008262528Semaste
1009262528Semaste    // Don't set the binpref if a shell was provided.  After all, that's only going to affect what version of the shell
1010262528Semaste    // is launched, not what fork of the binary is launched.  We insert "arch --arch <ARCH> as part of the shell invocation
1011262528Semaste    // to do that job on OSX.
1012262528Semaste
1013262528Semaste    if (launch_info.GetShell() == nullptr)
1014258054Semaste    {
1015262528Semaste        // We don't need to do this for ARM, and we really shouldn't now that we
1016262528Semaste        // have multiple CPU subtypes and no posix_spawnattr call that allows us
1017262528Semaste        // to set which CPU subtype to launch...
1018262528Semaste        const ArchSpec &arch_spec = launch_info.GetArchitecture();
1019262528Semaste        cpu_type_t cpu = arch_spec.GetMachOCPUType();
1020262528Semaste        cpu_type_t sub = arch_spec.GetMachOCPUSubType();
1021262528Semaste        if (cpu != 0 &&
1022276479Sdim            cpu != static_cast<cpu_type_t>(UINT32_MAX) &&
1023276479Sdim            cpu != static_cast<cpu_type_t>(LLDB_INVALID_CPUTYPE) &&
1024262528Semaste            !(cpu == 0x01000007 && sub == 8)) // If haswell is specified, don't try to set the CPU type or we will fail
1025262528Semaste        {
1026262528Semaste            size_t ocount = 0;
1027262528Semaste            error.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu, &ocount), eErrorTypePOSIX);
1028262528Semaste            if (error.Fail() || log)
1029262528Semaste                error.PutToLog(log, "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu, (uint64_t)ocount);
1030258054Semaste
1031262528Semaste            if (error.Fail() || ocount != 1)
1032258054Semaste                return error;
1033258054Semaste        }
1034258054Semaste    }
1035258054Semaste
1036262528Semaste#endif
1037262528Semaste
1038262528Semaste    const char *tmp_argv[2];
1039262528Semaste    char * const *argv = (char * const*)launch_info.GetArguments().GetConstArgumentVector();
1040262528Semaste    char * const *envp = (char * const*)launch_info.GetEnvironmentEntries().GetConstArgumentVector();
1041262528Semaste    if (argv == NULL)
1042262528Semaste    {
1043262528Semaste        // posix_spawn gets very unhappy if it doesn't have at least the program
1044262528Semaste        // name in argv[0]. One of the side affects I have noticed is the environment
1045262528Semaste        // variables don't make it into the child process if "argv == NULL"!!!
1046262528Semaste        tmp_argv[0] = exe_path;
1047262528Semaste        tmp_argv[1] = NULL;
1048262528Semaste        argv = (char * const*)tmp_argv;
1049262528Semaste    }
1050262528Semaste
1051262528Semaste#if !defined (__APPLE__)
1052262528Semaste    // manage the working directory
1053258054Semaste    char current_dir[PATH_MAX];
1054258054Semaste    current_dir[0] = '\0';
1055262528Semaste#endif
1056258054Semaste
1057258054Semaste    const char *working_dir = launch_info.GetWorkingDirectory();
1058262528Semaste    if (working_dir)
1059258054Semaste    {
1060262528Semaste#if defined (__APPLE__)
1061262528Semaste        // Set the working directory on this thread only
1062262528Semaste        if (__pthread_chdir (working_dir) < 0) {
1063262528Semaste            if (errno == ENOENT) {
1064262528Semaste                error.SetErrorStringWithFormat("No such file or directory: %s", working_dir);
1065262528Semaste            } else if (errno == ENOTDIR) {
1066262528Semaste                error.SetErrorStringWithFormat("Path doesn't name a directory: %s", working_dir);
1067262528Semaste            } else {
1068262528Semaste                error.SetErrorStringWithFormat("An unknown error occurred when changing directory for process execution.");
1069262528Semaste            }
1070262528Semaste            return error;
1071262528Semaste        }
1072262528Semaste#else
1073258054Semaste        if (::getcwd(current_dir, sizeof(current_dir)) == NULL)
1074258054Semaste        {
1075258054Semaste            error.SetError(errno, eErrorTypePOSIX);
1076258054Semaste            error.LogIfError(log, "unable to save the current directory");
1077258054Semaste            return error;
1078258054Semaste        }
1079258054Semaste
1080258054Semaste        if (::chdir(working_dir) == -1)
1081258054Semaste        {
1082258054Semaste            error.SetError(errno, eErrorTypePOSIX);
1083258054Semaste            error.LogIfError(log, "unable to change working directory to %s", working_dir);
1084258054Semaste            return error;
1085258054Semaste        }
1086262528Semaste#endif
1087258054Semaste    }
1088258054Semaste
1089262528Semaste    const size_t num_file_actions = launch_info.GetNumFileActions ();
1090262528Semaste    if (num_file_actions > 0)
1091258054Semaste    {
1092262528Semaste        posix_spawn_file_actions_t file_actions;
1093262528Semaste        error.SetError( ::posix_spawn_file_actions_init (&file_actions), eErrorTypePOSIX);
1094262528Semaste        if (error.Fail() || log)
1095262528Semaste            error.PutToLog(log, "::posix_spawn_file_actions_init ( &file_actions )");
1096262528Semaste        if (error.Fail())
1097262528Semaste            return error;
1098258054Semaste
1099262528Semaste        // Make a quick class that will cleanup the posix spawn attributes in case
1100262528Semaste        // we return in the middle of this function.
1101262528Semaste        lldb_utility::CleanUp <posix_spawn_file_actions_t *, int> posix_spawn_file_actions_cleanup (&file_actions, posix_spawn_file_actions_destroy);
1102258054Semaste
1103262528Semaste        for (size_t i=0; i<num_file_actions; ++i)
1104262528Semaste        {
1105276479Sdim            const FileAction *launch_file_action = launch_info.GetFileActionAtIndex(i);
1106262528Semaste            if (launch_file_action)
1107262528Semaste            {
1108276479Sdim                if (!AddPosixSpawnFileAction(&file_actions, launch_file_action, log, error))
1109262528Semaste                    return error;
1110262528Semaste            }
1111262528Semaste        }
1112258054Semaste
1113262528Semaste        error.SetError (::posix_spawnp (&pid,
1114262528Semaste                                        exe_path,
1115262528Semaste                                        &file_actions,
1116262528Semaste                                        &attr,
1117262528Semaste                                        argv,
1118262528Semaste                                        envp),
1119262528Semaste                        eErrorTypePOSIX);
1120262528Semaste
1121262528Semaste        if (error.Fail() || log)
1122262528Semaste        {
1123262528Semaste            error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )",
1124276479Sdim                           pid, exe_path, static_cast<void*>(&file_actions),
1125276479Sdim                           static_cast<void*>(&attr),
1126276479Sdim                           reinterpret_cast<const void*>(argv),
1127276479Sdim                           reinterpret_cast<const void*>(envp));
1128262528Semaste            if (log)
1129262528Semaste            {
1130262528Semaste                for (int ii=0; argv[ii]; ++ii)
1131262528Semaste                    log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1132262528Semaste            }
1133262528Semaste        }
1134262528Semaste
1135262528Semaste    }
1136262528Semaste    else
1137258054Semaste    {
1138262528Semaste        error.SetError (::posix_spawnp (&pid,
1139262528Semaste                                        exe_path,
1140262528Semaste                                        NULL,
1141262528Semaste                                        &attr,
1142262528Semaste                                        argv,
1143262528Semaste                                        envp),
1144262528Semaste                        eErrorTypePOSIX);
1145262528Semaste
1146262528Semaste        if (error.Fail() || log)
1147262528Semaste        {
1148262528Semaste            error.PutToLog(log, "::posix_spawnp ( pid => %i, path = '%s', file_actions = NULL, attr = %p, argv = %p, envp = %p )",
1149276479Sdim                           pid, exe_path, static_cast<void*>(&attr),
1150276479Sdim                           reinterpret_cast<const void*>(argv),
1151276479Sdim                           reinterpret_cast<const void*>(envp));
1152262528Semaste            if (log)
1153262528Semaste            {
1154262528Semaste                for (int ii=0; argv[ii]; ++ii)
1155262528Semaste                    log->Printf("argv[%i] = '%s'", ii, argv[ii]);
1156262528Semaste            }
1157262528Semaste        }
1158258054Semaste    }
1159258054Semaste
1160262528Semaste    if (working_dir)
1161262528Semaste    {
1162262528Semaste#if defined (__APPLE__)
1163262528Semaste        // No more thread specific current working directory
1164262528Semaste        __pthread_fchdir (-1);
1165262528Semaste#else
1166262528Semaste        if (::chdir(current_dir) == -1 && error.Success())
1167262528Semaste        {
1168262528Semaste            error.SetError(errno, eErrorTypePOSIX);
1169262528Semaste            error.LogIfError(log, "unable to change current directory back to %s",
1170262528Semaste                    current_dir);
1171262528Semaste        }
1172262528Semaste#endif
1173262528Semaste    }
1174262528Semaste
1175258054Semaste    return error;
1176258054Semaste}
1177258054Semaste
1178276479Sdimbool
1179276479SdimHost::AddPosixSpawnFileAction(void *_file_actions, const FileAction *info, Log *log, Error &error)
1180276479Sdim{
1181276479Sdim    if (info == NULL)
1182276479Sdim        return false;
1183276479Sdim
1184276479Sdim    posix_spawn_file_actions_t *file_actions = reinterpret_cast<posix_spawn_file_actions_t *>(_file_actions);
1185276479Sdim
1186276479Sdim    switch (info->GetAction())
1187276479Sdim    {
1188276479Sdim        case FileAction::eFileActionNone:
1189276479Sdim            error.Clear();
1190276479Sdim            break;
1191276479Sdim
1192276479Sdim        case FileAction::eFileActionClose:
1193276479Sdim            if (info->GetFD() == -1)
1194276479Sdim                error.SetErrorString("invalid fd for posix_spawn_file_actions_addclose(...)");
1195276479Sdim            else
1196276479Sdim            {
1197276479Sdim                error.SetError(::posix_spawn_file_actions_addclose(file_actions, info->GetFD()), eErrorTypePOSIX);
1198276479Sdim                if (log && (error.Fail() || log))
1199276479Sdim                    error.PutToLog(log, "posix_spawn_file_actions_addclose (action=%p, fd=%i)",
1200276479Sdim                                   static_cast<void *>(file_actions), info->GetFD());
1201276479Sdim            }
1202276479Sdim            break;
1203276479Sdim
1204276479Sdim        case FileAction::eFileActionDuplicate:
1205276479Sdim            if (info->GetFD() == -1)
1206276479Sdim                error.SetErrorString("invalid fd for posix_spawn_file_actions_adddup2(...)");
1207276479Sdim            else if (info->GetActionArgument() == -1)
1208276479Sdim                error.SetErrorString("invalid duplicate fd for posix_spawn_file_actions_adddup2(...)");
1209276479Sdim            else
1210276479Sdim            {
1211276479Sdim                error.SetError(
1212276479Sdim                    ::posix_spawn_file_actions_adddup2(file_actions, info->GetFD(), info->GetActionArgument()),
1213276479Sdim                    eErrorTypePOSIX);
1214276479Sdim                if (log && (error.Fail() || log))
1215276479Sdim                    error.PutToLog(log, "posix_spawn_file_actions_adddup2 (action=%p, fd=%i, dup_fd=%i)",
1216276479Sdim                                   static_cast<void *>(file_actions), info->GetFD(), info->GetActionArgument());
1217276479Sdim            }
1218276479Sdim            break;
1219276479Sdim
1220276479Sdim        case FileAction::eFileActionOpen:
1221276479Sdim            if (info->GetFD() == -1)
1222276479Sdim                error.SetErrorString("invalid fd in posix_spawn_file_actions_addopen(...)");
1223276479Sdim            else
1224276479Sdim            {
1225276479Sdim                int oflag = info->GetActionArgument();
1226276479Sdim
1227276479Sdim                mode_t mode = 0;
1228276479Sdim
1229276479Sdim                if (oflag & O_CREAT)
1230276479Sdim                    mode = 0640;
1231276479Sdim
1232276479Sdim                error.SetError(
1233276479Sdim                    ::posix_spawn_file_actions_addopen(file_actions, info->GetFD(), info->GetPath(), oflag, mode),
1234276479Sdim                    eErrorTypePOSIX);
1235276479Sdim                if (error.Fail() || log)
1236276479Sdim                    error.PutToLog(log,
1237276479Sdim                                   "posix_spawn_file_actions_addopen (action=%p, fd=%i, path='%s', oflag=%i, mode=%i)",
1238276479Sdim                                   static_cast<void *>(file_actions), info->GetFD(), info->GetPath(), oflag, mode);
1239276479Sdim            }
1240276479Sdim            break;
1241276479Sdim    }
1242276479Sdim    return error.Success();
1243276479Sdim}
1244276479Sdim
1245262528Semaste#endif // LaunchProcedssPosixSpawn: Apple, Linux, FreeBSD and other GLIBC systems
1246258054Semaste
1247262528Semaste
1248276479Sdim#if defined(__linux__) || defined(__FreeBSD__) || defined(__GLIBC__) || defined(__NetBSD__)
1249276479Sdim// The functions below implement process launching via posix_spawn() for Linux,
1250276479Sdim// FreeBSD and NetBSD.
1251262528Semaste
1252258054SemasteError
1253258054SemasteHost::LaunchProcess (ProcessLaunchInfo &launch_info)
1254258054Semaste{
1255258054Semaste    Error error;
1256258054Semaste    char exe_path[PATH_MAX];
1257258054Semaste
1258258054Semaste    PlatformSP host_platform_sp (Platform::GetDefaultPlatform ());
1259258054Semaste
1260258054Semaste    const ArchSpec &arch_spec = launch_info.GetArchitecture();
1261258054Semaste
1262258054Semaste    FileSpec exe_spec(launch_info.GetExecutableFile());
1263258054Semaste
1264258054Semaste    FileSpec::FileType file_type = exe_spec.GetFileType();
1265258054Semaste    if (file_type != FileSpec::eFileTypeRegular)
1266258054Semaste    {
1267258054Semaste        lldb::ModuleSP exe_module_sp;
1268258054Semaste        error = host_platform_sp->ResolveExecutable (exe_spec,
1269258054Semaste                                                     arch_spec,
1270258054Semaste                                                     exe_module_sp,
1271258054Semaste                                                     NULL);
1272258054Semaste
1273258054Semaste        if (error.Fail())
1274258054Semaste            return error;
1275258054Semaste
1276258054Semaste        if (exe_module_sp)
1277258054Semaste            exe_spec = exe_module_sp->GetFileSpec();
1278258054Semaste    }
1279258054Semaste
1280258054Semaste    if (exe_spec.Exists())
1281258054Semaste    {
1282258054Semaste        exe_spec.GetPath (exe_path, sizeof(exe_path));
1283258054Semaste    }
1284258054Semaste    else
1285258054Semaste    {
1286258054Semaste        launch_info.GetExecutableFile().GetPath (exe_path, sizeof(exe_path));
1287258054Semaste        error.SetErrorStringWithFormat ("executable doesn't exist: '%s'", exe_path);
1288258054Semaste        return error;
1289258054Semaste    }
1290258054Semaste
1291258054Semaste    assert(!launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY));
1292258054Semaste
1293258054Semaste    ::pid_t pid = LLDB_INVALID_PROCESS_ID;
1294258054Semaste
1295258054Semaste    error = LaunchProcessPosixSpawn(exe_path, launch_info, pid);
1296258054Semaste
1297258054Semaste    if (pid != LLDB_INVALID_PROCESS_ID)
1298258054Semaste    {
1299258054Semaste        // If all went well, then set the process ID into the launch info
1300258054Semaste        launch_info.SetProcessID(pid);
1301258054Semaste
1302262528Semaste        Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PROCESS));
1303262528Semaste
1304258054Semaste        // Make sure we reap any processes we spawn or we will have zombies.
1305258054Semaste        if (!launch_info.MonitorProcess())
1306258054Semaste        {
1307258054Semaste            const bool monitor_signals = false;
1308258054Semaste            StartMonitoringChildProcess (Process::SetProcessExitStatus,
1309258054Semaste                                         NULL,
1310258054Semaste                                         pid,
1311258054Semaste                                         monitor_signals);
1312262528Semaste            if (log)
1313262528Semaste                log->PutCString ("monitored child process with default Process::SetProcessExitStatus.");
1314258054Semaste        }
1315262528Semaste        else
1316262528Semaste        {
1317262528Semaste            if (log)
1318262528Semaste                log->PutCString ("monitored child process with user-specified process monitor.");
1319262528Semaste        }
1320258054Semaste    }
1321258054Semaste    else
1322258054Semaste    {
1323258054Semaste        // Invalid process ID, something didn't go well
1324258054Semaste        if (error.Success())
1325258054Semaste            error.SetErrorString ("process launch failed for unknown reasons");
1326258054Semaste    }
1327258054Semaste    return error;
1328258054Semaste}
1329258054Semaste
1330276479Sdim#endif // defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__)
1331258054Semaste
1332258054Semaste#ifndef _WIN32
1333258054Semaste
1334258054Semastevoid
1335258054SemasteHost::Kill(lldb::pid_t pid, int signo)
1336258054Semaste{
1337258054Semaste    ::kill(pid, signo);
1338258054Semaste}
1339254721Semaste
1340258054Semaste#endif
1341254721Semaste
1342254721Semaste#if !defined (__APPLE__)
1343254721Semastebool
1344254721SemasteHost::OpenFileInExternalEditor (const FileSpec &file_spec, uint32_t line_no)
1345254721Semaste{
1346254721Semaste    return false;
1347254721Semaste}
1348254721Semaste
1349254721Semastevoid
1350254721SemasteHost::SetCrashDescriptionWithFormat (const char *format, ...)
1351254721Semaste{
1352254721Semaste}
1353254721Semaste
1354254721Semastevoid
1355254721SemasteHost::SetCrashDescription (const char *description)
1356254721Semaste{
1357254721Semaste}
1358254721Semaste
1359254721Semastelldb::pid_t
1360258054SemasteHost::LaunchApplication (const FileSpec &app_file_spec)
1361254721Semaste{
1362254721Semaste    return LLDB_INVALID_PROCESS_ID;
1363254721Semaste}
1364254721Semaste
1365258884Semaste#endif
1366258884Semaste
1367276479Sdim#if !defined (__linux__) && !defined (__FreeBSD__) && !defined (__NetBSD__)
1368258884Semaste
1369276479Sdimconst lldb_private::UnixSignalsSP&
1370276479SdimHost::GetUnixSignals ()
1371258054Semaste{
1372276479Sdim    static UnixSignalsSP s_unix_signals_sp (new UnixSignals ());
1373276479Sdim    return s_unix_signals_sp;
1374258054Semaste}
1375258884Semaste
1376254721Semaste#endif
1377