MachProcess.cpp revision 0e8147bd867e4cdaae9400f56d02c7aacd40a9b3
1//===-- MachProcess.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//
10//  Created by Greg Clayton on 6/15/07.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DNB.h"
15#include <mach/mach.h>
16#include <signal.h>
17#include <spawn.h>
18#include <sys/fcntl.h>
19#include <sys/types.h>
20#include <sys/ptrace.h>
21#include <sys/stat.h>
22#include <sys/sysctl.h>
23#include <unistd.h>
24#include "MacOSX/CFUtils.h"
25#include "SysSignal.h"
26
27#include <algorithm>
28#include <map>
29
30#include "DNBDataRef.h"
31#include "DNBLog.h"
32#include "DNBThreadResumeActions.h"
33#include "DNBTimer.h"
34#include "MachProcess.h"
35#include "PseudoTerminal.h"
36
37#include "CFBundle.h"
38#include "CFData.h"
39#include "CFString.h"
40
41static CFStringRef CopyBundleIDForPath (const char *app_buncle_path, DNBError &err_str);
42
43#if defined (__arm__)
44
45#include <CoreFoundation/CoreFoundation.h>
46#include <SpringBoardServices/SpringBoardServer.h>
47#include <SpringBoardServices/SBSWatchdogAssertion.h>
48
49
50static bool
51IsSBProcess (nub_process_t pid)
52{
53    bool opt_runningApps = true;
54    bool opt_debuggable = false;
55
56    CFReleaser<CFArrayRef> sbsAppIDs (::SBSCopyApplicationDisplayIdentifiers (opt_runningApps, opt_debuggable));
57    if (sbsAppIDs.get() != NULL)
58    {
59        CFIndex count = ::CFArrayGetCount (sbsAppIDs.get());
60        CFIndex i = 0;
61        for (i = 0; i < count; i++)
62        {
63            CFStringRef displayIdentifier = (CFStringRef)::CFArrayGetValueAtIndex (sbsAppIDs.get(), i);
64
65            // Get the process id for the app (if there is one)
66            pid_t sbs_pid = INVALID_NUB_PROCESS;
67            if (::SBSProcessIDForDisplayIdentifier ((CFStringRef)displayIdentifier, &sbs_pid) == TRUE)
68            {
69                if (sbs_pid == pid)
70                    return true;
71            }
72        }
73    }
74    return false;
75}
76
77
78#endif
79
80#if 0
81#define DEBUG_LOG(fmt, ...) printf(fmt, ## __VA_ARGS__)
82#else
83#define DEBUG_LOG(fmt, ...)
84#endif
85
86#ifndef MACH_PROCESS_USE_POSIX_SPAWN
87#define MACH_PROCESS_USE_POSIX_SPAWN 1
88#endif
89
90#ifndef _POSIX_SPAWN_DISABLE_ASLR
91#define _POSIX_SPAWN_DISABLE_ASLR       0x0100
92#endif
93
94MachProcess::MachProcess() :
95    m_pid               (0),
96    m_cpu_type          (0),
97    m_child_stdin       (-1),
98    m_child_stdout      (-1),
99    m_child_stderr      (-1),
100    m_path              (),
101    m_args              (),
102    m_task              (this),
103    m_flags             (eMachProcessFlagsNone),
104    m_stdio_thread      (0),
105    m_stdio_mutex       (PTHREAD_MUTEX_RECURSIVE),
106    m_stdout_data       (),
107    m_thread_actions    (),
108    m_thread_list        (),
109    m_exception_messages (),
110    m_exception_messages_mutex (PTHREAD_MUTEX_RECURSIVE),
111    m_state             (eStateUnloaded),
112    m_state_mutex       (PTHREAD_MUTEX_RECURSIVE),
113    m_events            (0, kAllEventsMask),
114    m_breakpoints       (),
115    m_watchpoints       (),
116    m_name_to_addr_callback(NULL),
117    m_name_to_addr_baton(NULL),
118    m_image_infos_callback(NULL),
119    m_image_infos_baton(NULL)
120{
121    DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
122}
123
124MachProcess::~MachProcess()
125{
126    DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
127    Clear();
128}
129
130pid_t
131MachProcess::SetProcessID(pid_t pid)
132{
133    // Free any previous process specific data or resources
134    Clear();
135    // Set the current PID appropriately
136    if (pid == 0)
137        m_pid = ::getpid ();
138    else
139        m_pid = pid;
140    return m_pid;    // Return actualy PID in case a zero pid was passed in
141}
142
143nub_state_t
144MachProcess::GetState()
145{
146    // If any other threads access this we will need a mutex for it
147    PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
148    return m_state;
149}
150
151const char *
152MachProcess::ThreadGetName(nub_thread_t tid)
153{
154    return m_thread_list.GetName(tid);
155}
156
157nub_state_t
158MachProcess::ThreadGetState(nub_thread_t tid)
159{
160    return m_thread_list.GetState(tid);
161}
162
163
164nub_size_t
165MachProcess::GetNumThreads () const
166{
167    return m_thread_list.NumThreads();
168}
169
170nub_thread_t
171MachProcess::GetThreadAtIndex (nub_size_t thread_idx) const
172{
173    return m_thread_list.ThreadIDAtIndex(thread_idx);
174}
175
176nub_thread_t
177MachProcess::GetCurrentThread ()
178{
179    return m_thread_list.CurrentThreadID();
180}
181
182nub_thread_t
183MachProcess::SetCurrentThread(nub_thread_t tid)
184{
185    return m_thread_list.SetCurrentThread(tid);
186}
187
188bool
189MachProcess::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info) const
190{
191    return m_thread_list.GetThreadStoppedReason(tid, stop_info);
192}
193
194void
195MachProcess::DumpThreadStoppedReason(nub_thread_t tid) const
196{
197    return m_thread_list.DumpThreadStoppedReason(tid);
198}
199
200const char *
201MachProcess::GetThreadInfo(nub_thread_t tid) const
202{
203    return m_thread_list.GetThreadInfo(tid);
204}
205
206uint32_t
207MachProcess::GetCPUType ()
208{
209    if (m_cpu_type == 0 && m_pid != 0)
210        m_cpu_type = MachProcess::GetCPUTypeForLocalProcess (m_pid);
211    return m_cpu_type;
212}
213
214const DNBRegisterSetInfo *
215MachProcess::GetRegisterSetInfo (nub_thread_t tid, nub_size_t *num_reg_sets) const
216{
217    MachThreadSP thread_sp (m_thread_list.GetThreadByID (tid));
218    if (thread_sp)
219    {
220        DNBArchProtocol *arch = thread_sp->GetArchProtocol();
221        if (arch)
222            return arch->GetRegisterSetInfo (num_reg_sets);
223    }
224    *num_reg_sets = 0;
225    return NULL;
226}
227
228bool
229MachProcess::GetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value ) const
230{
231    return m_thread_list.GetRegisterValue(tid, set, reg, value);
232}
233
234bool
235MachProcess::SetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value ) const
236{
237    return m_thread_list.SetRegisterValue(tid, set, reg, value);
238}
239
240void
241MachProcess::SetState(nub_state_t new_state)
242{
243    // If any other threads access this we will need a mutex for it
244    uint32_t event_mask = 0;
245
246    // Scope for mutex locker
247    {
248        PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
249        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState ( %s )", DNBStateAsString(new_state));
250
251        const nub_state_t old_state = m_state;
252
253        if (old_state != new_state)
254        {
255            if (NUB_STATE_IS_STOPPED(new_state))
256                event_mask = eEventProcessStoppedStateChanged;
257            else
258                event_mask = eEventProcessRunningStateChanged;
259
260            m_state = new_state;
261            if (new_state == eStateStopped)
262                m_stop_count++;
263        }
264    }
265
266    if (event_mask != 0)
267    {
268        m_events.SetEvents (event_mask);
269
270        // Wait for the event bit to reset if a reset ACK is requested
271        m_events.WaitForResetAck(event_mask);
272    }
273
274}
275
276void
277MachProcess::Clear()
278{
279    // Clear any cached thread list while the pid and task are still valid
280
281    m_task.Clear();
282    // Now clear out all member variables
283    m_pid = INVALID_NUB_PROCESS;
284    CloseChildFileDescriptors();
285    m_path.clear();
286    m_args.clear();
287    SetState(eStateUnloaded);
288    m_flags = eMachProcessFlagsNone;
289    m_stop_count = 0;
290    m_thread_list.Clear();
291    {
292        PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
293        m_exception_messages.clear();
294    }
295}
296
297
298bool
299MachProcess::StartSTDIOThread()
300{
301    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);
302    // Create the thread that watches for the child STDIO
303    return ::pthread_create (&m_stdio_thread, NULL, MachProcess::STDIOThread, this) == 0;
304}
305
306
307nub_addr_t
308MachProcess::LookupSymbol(const char *name, const char *shlib)
309{
310    if (m_name_to_addr_callback != NULL && name && name[0])
311        return m_name_to_addr_callback(ProcessID(), name, shlib, m_name_to_addr_baton);
312    return INVALID_NUB_ADDRESS;
313}
314
315bool
316MachProcess::Resume (const DNBThreadResumeActions& thread_actions)
317{
318    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Resume ()");
319    nub_state_t state = GetState();
320
321    if (CanResume(state))
322    {
323        m_thread_actions = thread_actions;
324        PrivateResume();
325        return true;
326    }
327    else if (state == eStateRunning)
328    {
329        DNBLogThreadedIf(LOG_PROCESS, "Resume() - task 0x%x is running, ignoring...", m_task.TaskPort());
330        return true;
331    }
332    DNBLogThreadedIf(LOG_PROCESS, "Resume() - task 0x%x can't continue, ignoring...", m_task.TaskPort());
333    return false;
334}
335
336bool
337MachProcess::Kill (const struct timespec *timeout_abstime)
338{
339    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill ()");
340    nub_state_t state = DoSIGSTOP(true);
341    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() state = %s", DNBStateAsString(state));
342    errno = 0;
343    ::ptrace (PT_KILL, m_pid, 0, 0);
344    DNBError err;
345    err.SetErrorToErrno();
346    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() ::ptrace (PT_KILL, pid=%u, 0, 0) => 0x%8.8x (%s)", m_pid, err.Error(), err.AsString());
347    m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
348    PrivateResume ();
349    return true;
350}
351
352bool
353MachProcess::Signal (int signal, const struct timespec *timeout_abstime)
354{
355    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p)", signal, timeout_abstime);
356    nub_state_t state = GetState();
357    if (::kill (ProcessID(), signal) == 0)
358    {
359        // If we were running and we have a timeout, wait for the signal to stop
360        if (IsRunning(state) && timeout_abstime)
361        {
362            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) waiting for signal to stop process...", signal, timeout_abstime);
363            m_events.WaitForSetEvents(eEventProcessStoppedStateChanged, timeout_abstime);
364            state = GetState();
365            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) state = %s", signal, timeout_abstime, DNBStateAsString(state));
366            return !IsRunning (state);
367        }
368        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) not waiting...", signal, timeout_abstime);
369        return true;
370    }
371    DNBError err(errno, DNBError::POSIX);
372    err.LogThreadedIfError("kill (pid = %d, signo = %i)", ProcessID(), signal);
373    return false;
374
375}
376
377nub_state_t
378MachProcess::DoSIGSTOP (bool clear_bps_and_wps, uint32_t *thread_idx_ptr)
379{
380    nub_state_t state = GetState();
381    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s", DNBStateAsString (state));
382
383    if (!IsRunning(state))
384    {
385        if (clear_bps_and_wps)
386        {
387            DisableAllBreakpoints (true);
388            DisableAllWatchpoints (true);
389            clear_bps_and_wps = false;
390        }
391
392        // If we already have a thread stopped due to a SIGSTOP, we don't have
393        // to do anything...
394        uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
395        if (thread_idx_ptr)
396            *thread_idx_ptr = thread_idx;
397        if (thread_idx != UINT32_MAX)
398            return GetState();
399
400        // No threads were stopped with a SIGSTOP, we need to run and halt the
401        // process with a signal
402        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- resuming process", DNBStateAsString (state));
403        m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
404        PrivateResume ();
405
406        // Reset the event that says we were indeed running
407        m_events.ResetEvents(eEventProcessRunningStateChanged);
408        state = GetState();
409    }
410
411    // We need to be stopped in order to be able to detach, so we need
412    // to send ourselves a SIGSTOP
413
414    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- sending SIGSTOP", DNBStateAsString (state));
415    struct timespec sigstop_timeout;
416    DNBTimer::OffsetTimeOfDay(&sigstop_timeout, 2, 0);
417    Signal (SIGSTOP, &sigstop_timeout);
418    if (clear_bps_and_wps)
419    {
420        DisableAllBreakpoints (true);
421        DisableAllWatchpoints (true);
422        // The static analyzer complains about this, but just leave the following line in.
423         clear_bps_and_wps = false;
424    }
425    uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
426    if (thread_idx_ptr)
427        *thread_idx_ptr = thread_idx;
428    return GetState();
429}
430
431bool
432MachProcess::Detach()
433{
434    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach()");
435
436    uint32_t thread_idx = UINT32_MAX;
437    nub_state_t state = DoSIGSTOP(true, &thread_idx);
438    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach() DoSIGSTOP() returned %s", DNBStateAsString(state));
439
440    {
441        m_thread_actions.Clear();
442        DNBThreadResumeAction thread_action;
443        thread_action.tid = m_thread_list.ThreadIDAtIndex (thread_idx);
444        thread_action.state = eStateRunning;
445        thread_action.signal = -1;
446        thread_action.addr = INVALID_NUB_ADDRESS;
447
448        m_thread_actions.Append (thread_action);
449        m_thread_actions.SetDefaultThreadActionIfNeeded (eStateRunning, 0);
450
451        PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
452
453        ReplyToAllExceptions ();
454
455    }
456
457    m_task.ShutDownExcecptionThread();
458
459    // Detach from our process
460    errno = 0;
461    nub_process_t pid = m_pid;
462    int ret = ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
463    DNBError err(errno, DNBError::POSIX);
464    if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail() || (ret != 0))
465        err.LogThreaded("::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
466
467    // Resume our task
468    m_task.Resume();
469
470    // NULL our task out as we have already retored all exception ports
471    m_task.Clear();
472
473    // Clear out any notion of the process we once were
474    Clear();
475
476    SetState(eStateDetached);
477
478    return true;
479}
480
481
482nub_size_t
483MachProcess::RemoveTrapsFromBuffer (nub_addr_t addr, nub_size_t size, uint8_t *buf) const
484{
485    nub_size_t bytes_removed = 0;
486    const DNBBreakpoint *bp;
487    nub_addr_t intersect_addr;
488    nub_size_t intersect_size;
489    nub_size_t opcode_offset;
490    nub_size_t idx;
491    for (idx = 0; (bp = m_breakpoints.GetByIndex(idx)) != NULL; ++idx)
492    {
493        if (bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset))
494        {
495            assert(addr <= intersect_addr && intersect_addr < addr + size);
496            assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
497            assert(opcode_offset + intersect_size <= bp->ByteSize());
498            nub_size_t buf_offset = intersect_addr - addr;
499            ::memcpy(buf + buf_offset, bp->SavedOpcodeBytes() + opcode_offset, intersect_size);
500        }
501    }
502    return bytes_removed;
503}
504
505//----------------------------------------------------------------------
506// ReadMemory from the MachProcess level will always remove any software
507// breakpoints from the memory buffer before returning. If you wish to
508// read memory and see those traps, read from the MachTask
509// (m_task.ReadMemory()) as that version will give you what is actually
510// in inferior memory.
511//----------------------------------------------------------------------
512nub_size_t
513MachProcess::ReadMemory (nub_addr_t addr, nub_size_t size, void *buf)
514{
515    // We need to remove any current software traps (enabled software
516    // breakpoints) that we may have placed in our tasks memory.
517
518    // First just read the memory as is
519    nub_size_t bytes_read = m_task.ReadMemory(addr, size, buf);
520
521    // Then place any opcodes that fall into this range back into the buffer
522    // before we return this to callers.
523    if (bytes_read > 0)
524        RemoveTrapsFromBuffer (addr, size, (uint8_t *)buf);
525    return bytes_read;
526}
527
528//----------------------------------------------------------------------
529// WriteMemory from the MachProcess level will always write memory around
530// any software breakpoints. Any software breakpoints will have their
531// opcodes modified if they are enabled. Any memory that doesn't overlap
532// with software breakpoints will be written to. If you wish to write to
533// inferior memory without this interference, then write to the MachTask
534// (m_task.WriteMemory()) as that version will always modify inferior
535// memory.
536//----------------------------------------------------------------------
537nub_size_t
538MachProcess::WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf)
539{
540    // We need to write any data that would go where any current software traps
541    // (enabled software breakpoints) any software traps (breakpoints) that we
542    // may have placed in our tasks memory.
543
544    std::map<nub_addr_t, DNBBreakpoint *> addr_to_bp_map;
545    DNBBreakpoint *bp;
546    nub_size_t idx;
547    for (idx = 0; (bp = m_breakpoints.GetByIndex(idx)) != NULL; ++idx)
548    {
549        if (bp->IntersectsRange(addr, size, NULL, NULL, NULL))
550            addr_to_bp_map[bp->Address()] = bp;
551    }
552
553    // If we don't have any software breakpoints that are in this buffer, then
554    // we can just write memory and be done with it.
555    if (addr_to_bp_map.empty())
556        return m_task.WriteMemory(addr, size, buf);
557
558    // If we make it here, we have some breakpoints that overlap and we need
559    // to work around them.
560
561    nub_size_t bytes_written = 0;
562    nub_addr_t intersect_addr;
563    nub_size_t intersect_size;
564    nub_size_t opcode_offset;
565    const uint8_t *ubuf = (const uint8_t *)buf;
566    std::map<nub_addr_t, DNBBreakpoint *>::iterator pos, end = addr_to_bp_map.end();
567    for (pos = addr_to_bp_map.begin(); pos != end; ++pos)
568    {
569        bp = pos->second;
570
571        assert(bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset));
572        assert(addr <= intersect_addr && intersect_addr < addr + size);
573        assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
574        assert(opcode_offset + intersect_size <= bp->ByteSize());
575
576        // Check for bytes before this breakpoint
577        const nub_addr_t curr_addr = addr + bytes_written;
578        if (intersect_addr > curr_addr)
579        {
580            // There are some bytes before this breakpoint that we need to
581            // just write to memory
582            nub_size_t curr_size = intersect_addr - curr_addr;
583            nub_size_t curr_bytes_written = m_task.WriteMemory(curr_addr, curr_size, ubuf + bytes_written);
584            bytes_written += curr_bytes_written;
585            if (curr_bytes_written != curr_size)
586            {
587                // We weren't able to write all of the requested bytes, we
588                // are done looping and will return the number of bytes that
589                // we have written so far.
590                break;
591            }
592        }
593
594        // Now write any bytes that would cover up any software breakpoints
595        // directly into the breakpoint opcode buffer
596        ::memcpy(bp->SavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
597        bytes_written += intersect_size;
598    }
599
600    // Write any remaining bytes after the last breakpoint if we have any left
601    if (bytes_written < size)
602        bytes_written += m_task.WriteMemory(addr + bytes_written, size - bytes_written, ubuf + bytes_written);
603
604    return bytes_written;
605}
606
607
608void
609MachProcess::ReplyToAllExceptions ()
610{
611    PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
612    if (m_exception_messages.empty() == false)
613    {
614        MachException::Message::iterator pos;
615        MachException::Message::iterator begin = m_exception_messages.begin();
616        MachException::Message::iterator end = m_exception_messages.end();
617        for (pos = begin; pos != end; ++pos)
618        {
619            DNBLogThreadedIf(LOG_EXCEPTIONS, "Replying to exception %u...", (uint32_t)std::distance(begin, pos));
620            int thread_reply_signal = 0;
621
622            const DNBThreadResumeAction *action = m_thread_actions.GetActionForThread (pos->state.thread_port, false);
623
624            if (action)
625            {
626                thread_reply_signal = action->signal;
627                if (thread_reply_signal)
628                    m_thread_actions.SetSignalHandledForThread (pos->state.thread_port);
629            }
630
631            DNBError err (pos->Reply(this, thread_reply_signal));
632            if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
633                err.LogThreadedIfError("Error replying to exception");
634        }
635
636        // Erase all exception message as we should have used and replied
637        // to them all already.
638        m_exception_messages.clear();
639    }
640}
641void
642MachProcess::PrivateResume ()
643{
644    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
645
646    ReplyToAllExceptions ();
647//    bool stepOverBreakInstruction = step;
648
649    // Let the thread prepare to resume and see if any threads want us to
650    // step over a breakpoint instruction (ProcessWillResume will modify
651    // the value of stepOverBreakInstruction).
652    m_thread_list.ProcessWillResume (this, m_thread_actions);
653
654    // Set our state accordingly
655    if (m_thread_actions.NumActionsWithState(eStateStepping))
656        SetState (eStateStepping);
657    else
658        SetState (eStateRunning);
659
660    // Now resume our task.
661    m_task.Resume();
662}
663
664nub_break_t
665MachProcess::CreateBreakpoint(nub_addr_t addr, nub_size_t length, bool hardware, thread_t tid)
666{
667    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %zu, hardware = %i, tid = 0x%4.4x )", (uint64_t)addr, length, hardware, tid);
668    if (hardware && tid == INVALID_NUB_THREAD)
669        tid = GetCurrentThread();
670
671    DNBBreakpoint bp(addr, length, tid, hardware);
672    nub_break_t breakID = m_breakpoints.Add(bp);
673    if (EnableBreakpoint(breakID))
674    {
675        DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %zu, tid = 0x%4.4x ) => %u", (uint64_t)addr, length, tid, breakID);
676        return breakID;
677    }
678    else
679    {
680        m_breakpoints.Remove(breakID);
681    }
682    // We failed to enable the breakpoint
683    return INVALID_NUB_BREAK_ID;
684}
685
686nub_watch_t
687MachProcess::CreateWatchpoint(nub_addr_t addr, nub_size_t length, uint32_t watch_flags, bool hardware, thread_t tid)
688{
689    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %zu, flags = 0x%8.8x, hardware = %i, tid = 0x%4.4x )", (uint64_t)addr, length, watch_flags, hardware, tid);
690    if (hardware && tid == INVALID_NUB_THREAD)
691        tid = GetCurrentThread();
692
693    DNBBreakpoint watch(addr, length, tid, hardware);
694    watch.SetIsWatchpoint(watch_flags);
695
696    nub_watch_t watchID = m_watchpoints.Add(watch);
697    if (EnableWatchpoint(watchID))
698    {
699        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %zu, tid = 0x%x) => %u", (uint64_t)addr, length, tid, watchID);
700        return watchID;
701    }
702    else
703    {
704        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %zu, tid = 0x%x) => FAILED (%u)", (uint64_t)addr, length, tid, watchID);
705        m_watchpoints.Remove(watchID);
706    }
707    // We failed to enable the watchpoint
708    return INVALID_NUB_BREAK_ID;
709}
710
711nub_size_t
712MachProcess::DisableAllBreakpoints(bool remove)
713{
714    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
715    DNBBreakpoint *bp;
716    nub_size_t disabled_count = 0;
717    nub_size_t idx = 0;
718    while ((bp = m_breakpoints.GetByIndex(idx)) != NULL)
719    {
720        bool success = DisableBreakpoint(bp->GetID(), remove);
721
722        if (success)
723            disabled_count++;
724        // If we failed to disable the breakpoint or we aren't removing the breakpoint
725        // increment the breakpoint index. Otherwise DisableBreakpoint will have removed
726        // the breakpoint at this index and we don't need to change it.
727        if ((success == false) || (remove == false))
728            idx++;
729    }
730    return disabled_count;
731}
732
733nub_size_t
734MachProcess::DisableAllWatchpoints(bool remove)
735{
736    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
737    DNBBreakpoint *wp;
738    nub_size_t disabled_count = 0;
739    nub_size_t idx = 0;
740    while ((wp = m_watchpoints.GetByIndex(idx)) != NULL)
741    {
742        bool success = DisableWatchpoint(wp->GetID(), remove);
743
744        if (success)
745            disabled_count++;
746        // If we failed to disable the watchpoint or we aren't removing the watchpoint
747        // increment the watchpoint index. Otherwise DisableWatchpoint will have removed
748        // the watchpoint at this index and we don't need to change it.
749        if ((success == false) || (remove == false))
750            idx++;
751    }
752    return disabled_count;
753}
754
755bool
756MachProcess::DisableBreakpoint(nub_break_t breakID, bool remove)
757{
758    DNBBreakpoint *bp = m_breakpoints.FindByID (breakID);
759    if (bp)
760    {
761        nub_addr_t addr = bp->Address();
762        DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx", breakID, remove, (uint64_t)addr);
763
764        if (bp->IsHardware())
765        {
766            bool hw_disable_result = m_thread_list.DisableHardwareBreakpoint (bp);
767
768            if (hw_disable_result == true)
769            {
770                bp->SetEnabled(false);
771                // Let the thread list know that a breakpoint has been modified
772                if (remove)
773                {
774                    m_thread_list.NotifyBreakpointChanged(bp);
775                    m_breakpoints.Remove(breakID);
776                }
777                DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx (hardware) => success", breakID, remove, (uint64_t)addr);
778                return true;
779            }
780
781            return false;
782        }
783
784        const nub_size_t break_op_size = bp->ByteSize();
785        assert (break_op_size > 0);
786        const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (bp->ByteSize());
787        if (break_op_size > 0)
788        {
789            // Clear a software breakoint instruction
790            uint8_t curr_break_op[break_op_size];
791            bool break_op_found = false;
792
793            // Read the breakpoint opcode
794            if (m_task.ReadMemory(addr, break_op_size, curr_break_op) == break_op_size)
795            {
796                bool verify = false;
797                if (bp->IsEnabled())
798                {
799                    // Make sure we have the a breakpoint opcode exists at this address
800                    if (memcmp(curr_break_op, break_op, break_op_size) == 0)
801                    {
802                        break_op_found = true;
803                        // We found a valid breakpoint opcode at this address, now restore
804                        // the saved opcode.
805                        if (m_task.WriteMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
806                        {
807                            verify = true;
808                        }
809                        else
810                        {
811                            DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx memory write failed when restoring original opcode", breakID, remove, (uint64_t)addr);
812                        }
813                    }
814                    else
815                    {
816                        DNBLogWarning("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx expected a breakpoint opcode but didn't find one.", breakID, remove, (uint64_t)addr);
817                        // Set verify to true and so we can check if the original opcode has already been restored
818                        verify = true;
819                    }
820                }
821                else
822                {
823                    DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x$8.8llx is not enabled", breakID, remove, (uint64_t)addr);
824                    // Set verify to true and so we can check if the original opcode is there
825                    verify = true;
826                }
827
828                if (verify)
829                {
830                    uint8_t verify_opcode[break_op_size];
831                    // Verify that our original opcode made it back to the inferior
832                    if (m_task.ReadMemory(addr, break_op_size, verify_opcode) == break_op_size)
833                    {
834                        // compare the memory we just read with the original opcode
835                        if (memcmp(bp->SavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
836                        {
837                            // SUCCESS
838                            bp->SetEnabled(false);
839                            // Let the thread list know that a breakpoint has been modified
840                            if (remove)
841                            {
842                                m_thread_list.NotifyBreakpointChanged(bp);
843                                m_breakpoints.Remove(breakID);
844                            }
845                            DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx => success", breakID, remove, (uint64_t)addr);
846                            return true;
847                        }
848                        else
849                        {
850                            if (break_op_found)
851                                DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx: failed to restore original opcode", breakID, remove, (uint64_t)addr);
852                            else
853                                DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) addr = 0x%8.8llx: opcode changed", breakID, remove, (uint64_t)addr);
854                        }
855                    }
856                    else
857                    {
858                        DNBLogWarning("MachProcess::DisableBreakpoint: unable to disable breakpoint 0x%8.8llx", (uint64_t)addr);
859                    }
860                }
861            }
862            else
863            {
864                DNBLogWarning("MachProcess::DisableBreakpoint: unable to read memory at 0x%8.8llx", (uint64_t)addr);
865            }
866        }
867    }
868    else
869    {
870        DNBLogError("MachProcess::DisableBreakpoint ( breakID = %d, remove = %d ) invalid breakpoint ID", breakID, remove);
871    }
872    return false;
873}
874
875bool
876MachProcess::DisableWatchpoint(nub_watch_t watchID, bool remove)
877{
878    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s(watchID = %d, remove = %d)", __FUNCTION__, watchID, remove);
879    DNBBreakpoint *wp = m_watchpoints.FindByID (watchID);
880    if (wp)
881    {
882        nub_addr_t addr = wp->Address();
883        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::DisableWatchpoint ( watchID = %d, remove = %d ) addr = 0x%8.8llx", watchID, remove, (uint64_t)addr);
884
885        if (wp->IsHardware())
886        {
887            bool hw_disable_result = m_thread_list.DisableHardwareWatchpoint (wp);
888
889            if (hw_disable_result == true)
890            {
891                wp->SetEnabled(false);
892                if (remove)
893                    m_watchpoints.Remove(watchID);
894                DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::Disablewatchpoint ( watchID = %d, remove = %d ) addr = 0x%8.8llx (hardware) => success", watchID, remove, (uint64_t)addr);
895                return true;
896            }
897        }
898
899        // TODO: clear software watchpoints if we implement them
900    }
901    else
902    {
903        DNBLogError("MachProcess::DisableWatchpoint ( watchID = %d, remove = %d ) invalid watchpoint ID", watchID, remove);
904    }
905    return false;
906}
907
908
909void
910MachProcess::DumpBreakpoint(nub_break_t breakID) const
911{
912    DNBLogThreaded("MachProcess::DumpBreakpoint(breakID = %d)", breakID);
913
914    if (NUB_BREAK_ID_IS_VALID(breakID))
915    {
916        const DNBBreakpoint *bp = m_breakpoints.FindByID(breakID);
917        if (bp)
918            bp->Dump();
919        else
920            DNBLog("MachProcess::DumpBreakpoint(breakID = %d): invalid breakID", breakID);
921    }
922    else
923    {
924        m_breakpoints.Dump();
925    }
926}
927
928void
929MachProcess::DumpWatchpoint(nub_watch_t watchID) const
930{
931    DNBLogThreaded("MachProcess::DumpWatchpoint(watchID = %d)", watchID);
932
933    if (NUB_BREAK_ID_IS_VALID(watchID))
934    {
935        const DNBBreakpoint *wp = m_watchpoints.FindByID(watchID);
936        if (wp)
937            wp->Dump();
938        else
939            DNBLog("MachProcess::DumpWatchpoint(watchID = %d): invalid watchID", watchID);
940    }
941    else
942    {
943        m_watchpoints.Dump();
944    }
945}
946
947bool
948MachProcess::EnableBreakpoint(nub_break_t breakID)
949{
950    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( breakID = %d )", breakID);
951    DNBBreakpoint *bp = m_breakpoints.FindByID (breakID);
952    if (bp)
953    {
954        nub_addr_t addr = bp->Address();
955        if (bp->IsEnabled())
956        {
957            DNBLogWarning("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: breakpoint already enabled.", breakID, (uint64_t)addr);
958            return true;
959        }
960        else
961        {
962            if (bp->HardwarePreferred())
963            {
964                bp->SetHardwareIndex(m_thread_list.EnableHardwareBreakpoint(bp));
965                if (bp->IsHardware())
966                {
967                    bp->SetEnabled(true);
968                    return true;
969                }
970            }
971
972            const nub_size_t break_op_size = bp->ByteSize();
973            assert (break_op_size != 0);
974            const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (break_op_size);
975            if (break_op_size > 0)
976            {
977                // Save the original opcode by reading it
978                if (m_task.ReadMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
979                {
980                    // Write a software breakpoint in place of the original opcode
981                    if (m_task.WriteMemory(addr, break_op_size, break_op) == break_op_size)
982                    {
983                        uint8_t verify_break_op[4];
984                        if (m_task.ReadMemory(addr, break_op_size, verify_break_op) == break_op_size)
985                        {
986                            if (memcmp(break_op, verify_break_op, break_op_size) == 0)
987                            {
988                                bp->SetEnabled(true);
989                                // Let the thread list know that a breakpoint has been modified
990                                m_thread_list.NotifyBreakpointChanged(bp);
991                                DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: SUCCESS.", breakID, (uint64_t)addr);
992                                return true;
993                            }
994                            else
995                            {
996                                DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: breakpoint opcode verification failed.", breakID, (uint64_t)addr);
997                            }
998                        }
999                        else
1000                        {
1001                            DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to read memory to verify breakpoint opcode.", breakID, (uint64_t)addr);
1002                        }
1003                    }
1004                    else
1005                    {
1006                        DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to write breakpoint opcode to memory.", breakID, (uint64_t)addr);
1007                    }
1008                }
1009                else
1010                {
1011                    DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) addr = 0x%8.8llx: unable to read memory at breakpoint address.", breakID, (uint64_t)addr);
1012                }
1013            }
1014            else
1015            {
1016                DNBLogError("MachProcess::EnableBreakpoint ( breakID = %d ) no software breakpoint opcode for current architecture.", breakID);
1017            }
1018        }
1019    }
1020    return false;
1021}
1022
1023bool
1024MachProcess::EnableWatchpoint(nub_watch_t watchID)
1025{
1026    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::EnableWatchpoint(watchID = %d)", watchID);
1027    DNBBreakpoint *wp = m_watchpoints.FindByID (watchID);
1028    if (wp)
1029    {
1030        nub_addr_t addr = wp->Address();
1031        if (wp->IsEnabled())
1032        {
1033            DNBLogWarning("MachProcess::EnableWatchpoint(watchID = %d) addr = 0x%8.8llx: watchpoint already enabled.", watchID, (uint64_t)addr);
1034            return true;
1035        }
1036        else
1037        {
1038            // Currently only try and set hardware watchpoints.
1039            wp->SetHardwareIndex(m_thread_list.EnableHardwareWatchpoint(wp));
1040            if (wp->IsHardware())
1041            {
1042                wp->SetEnabled(true);
1043                return true;
1044            }
1045            // TODO: Add software watchpoints by doing page protection tricks.
1046        }
1047    }
1048    return false;
1049}
1050
1051// Called by the exception thread when an exception has been received from
1052// our process. The exception message is completely filled and the exception
1053// data has already been copied.
1054void
1055MachProcess::ExceptionMessageReceived (const MachException::Message& exceptionMessage)
1056{
1057    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
1058
1059    if (m_exception_messages.empty())
1060        m_task.Suspend();
1061
1062    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachProcess::ExceptionMessageReceived ( )");
1063
1064    // Use a locker to automatically unlock our mutex in case of exceptions
1065    // Add the exception to our internal exception stack
1066    m_exception_messages.push_back(exceptionMessage);
1067}
1068
1069void
1070MachProcess::ExceptionMessageBundleComplete()
1071{
1072    // We have a complete bundle of exceptions for our child process.
1073    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
1074    DNBLogThreadedIf(LOG_EXCEPTIONS, "%s: %zu exception messages.", __PRETTY_FUNCTION__, m_exception_messages.size());
1075    if (!m_exception_messages.empty())
1076    {
1077        // Let all threads recover from stopping and do any clean up based
1078        // on the previous thread state (if any).
1079        m_thread_list.ProcessDidStop(this);
1080
1081        // Let each thread know of any exceptions
1082        task_t task = m_task.TaskPort();
1083        size_t i;
1084        for (i=0; i<m_exception_messages.size(); ++i)
1085        {
1086            // Let the thread list figure use the MachProcess to forward all exceptions
1087            // on down to each thread.
1088            if (m_exception_messages[i].state.task_port == task)
1089                m_thread_list.NotifyException(m_exception_messages[i].state);
1090            if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
1091                m_exception_messages[i].Dump();
1092        }
1093
1094        if (DNBLogCheckLogBit(LOG_THREAD))
1095            m_thread_list.Dump();
1096
1097        bool step_more = false;
1098        if (m_thread_list.ShouldStop(step_more))
1099        {
1100            // Wait for the eEventProcessRunningStateChanged event to be reset
1101            // before changing state to stopped to avoid race condition with
1102            // very fast start/stops
1103            struct timespec timeout;
1104            //DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000);   // Wait for 250 ms
1105            DNBTimer::OffsetTimeOfDay(&timeout, 1, 0);  // Wait for 250 ms
1106            m_events.WaitForEventsToReset(eEventProcessRunningStateChanged, &timeout);
1107            SetState(eStateStopped);
1108        }
1109        else
1110        {
1111            // Resume without checking our current state.
1112            PrivateResume ();
1113        }
1114    }
1115    else
1116    {
1117        DNBLogThreadedIf(LOG_EXCEPTIONS, "%s empty exception messages bundle.", __PRETTY_FUNCTION__, m_exception_messages.size());
1118    }
1119}
1120
1121nub_size_t
1122MachProcess::CopyImageInfos ( struct DNBExecutableImageInfo **image_infos, bool only_changed)
1123{
1124    if (m_image_infos_callback != NULL)
1125        return m_image_infos_callback(ProcessID(), image_infos, only_changed, m_image_infos_baton);
1126    return 0;
1127}
1128
1129void
1130MachProcess::SharedLibrariesUpdated ( )
1131{
1132    uint32_t event_bits = eEventSharedLibsStateChange;
1133    // Set the shared library event bit to let clients know of shared library
1134    // changes
1135    m_events.SetEvents(event_bits);
1136    // Wait for the event bit to reset if a reset ACK is requested
1137    m_events.WaitForResetAck(event_bits);
1138}
1139
1140void
1141MachProcess::AppendSTDOUT (char* s, size_t len)
1142{
1143    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (<%zu> %s) ...", __FUNCTION__, len, s);
1144    PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1145    m_stdout_data.append(s, len);
1146    m_events.SetEvents(eEventStdioAvailable);
1147
1148    // Wait for the event bit to reset if a reset ACK is requested
1149    m_events.WaitForResetAck(eEventStdioAvailable);
1150}
1151
1152size_t
1153MachProcess::GetAvailableSTDOUT (char *buf, size_t buf_size)
1154{
1155    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%zu]) ...", __FUNCTION__, buf, buf_size);
1156    PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1157    size_t bytes_available = m_stdout_data.size();
1158    if (bytes_available > 0)
1159    {
1160        if (bytes_available > buf_size)
1161        {
1162            memcpy(buf, m_stdout_data.data(), buf_size);
1163            m_stdout_data.erase(0, buf_size);
1164            bytes_available = buf_size;
1165        }
1166        else
1167        {
1168            memcpy(buf, m_stdout_data.data(), bytes_available);
1169            m_stdout_data.clear();
1170        }
1171    }
1172    return bytes_available;
1173}
1174
1175nub_addr_t
1176MachProcess::GetDYLDAllImageInfosAddress ()
1177{
1178    DNBError err;
1179    return m_task.GetDYLDAllImageInfosAddress(err);
1180}
1181
1182size_t
1183MachProcess::GetAvailableSTDERR (char *buf, size_t buf_size)
1184{
1185    return 0;
1186}
1187
1188void *
1189MachProcess::STDIOThread(void *arg)
1190{
1191    MachProcess *proc = (MachProcess*) arg;
1192    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg);
1193
1194    // We start use a base and more options so we can control if we
1195    // are currently using a timeout on the mach_msg. We do this to get a
1196    // bunch of related exceptions on our exception port so we can process
1197    // then together. When we have multiple threads, we can get an exception
1198    // per thread and they will come in consecutively. The main thread loop
1199    // will start by calling mach_msg to without having the MACH_RCV_TIMEOUT
1200    // flag set in the options, so we will wait forever for an exception on
1201    // our exception port. After we get one exception, we then will use the
1202    // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
1203    // exceptions for our process. After we have received the last pending
1204    // exception, we will get a timeout which enables us to then notify
1205    // our main thread that we have an exception bundle avaiable. We then wait
1206    // for the main thread to tell this exception thread to start trying to get
1207    // exceptions messages again and we start again with a mach_msg read with
1208    // infinite timeout.
1209    DNBError err;
1210    int stdout_fd = proc->GetStdoutFileDescriptor();
1211    int stderr_fd = proc->GetStderrFileDescriptor();
1212    if (stdout_fd == stderr_fd)
1213        stderr_fd = -1;
1214
1215    while (stdout_fd >= 0 || stderr_fd >= 0)
1216    {
1217        ::pthread_testcancel ();
1218
1219        fd_set read_fds;
1220        FD_ZERO (&read_fds);
1221        if (stdout_fd >= 0)
1222            FD_SET (stdout_fd, &read_fds);
1223        if (stderr_fd >= 0)
1224            FD_SET (stderr_fd, &read_fds);
1225        int nfds = std::max<int>(stdout_fd, stderr_fd) + 1;
1226
1227        int num_set_fds = select (nfds, &read_fds, NULL, NULL, NULL);
1228        DNBLogThreadedIf(LOG_PROCESS, "select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1229
1230        if (num_set_fds < 0)
1231        {
1232            int select_errno = errno;
1233            if (DNBLogCheckLogBit(LOG_PROCESS))
1234            {
1235                err.SetError (select_errno, DNBError::POSIX);
1236                err.LogThreadedIfError("select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1237            }
1238
1239            switch (select_errno)
1240            {
1241            case EAGAIN:    // The kernel was (perhaps temporarily) unable to allocate the requested number of file descriptors, or we have non-blocking IO
1242                break;
1243            case EBADF:     // One of the descriptor sets specified an invalid descriptor.
1244                return NULL;
1245                break;
1246            case EINTR:     // A signal was delivered before the time limit expired and before any of the selected events occurred.
1247            case EINVAL:    // The specified time limit is invalid. One of its components is negative or too large.
1248            default:        // Other unknown error
1249                break;
1250            }
1251        }
1252        else if (num_set_fds == 0)
1253        {
1254        }
1255        else
1256        {
1257            char s[1024];
1258            s[sizeof(s)-1] = '\0';  // Ensure we have NULL termination
1259            int bytes_read = 0;
1260            if (stdout_fd >= 0 && FD_ISSET (stdout_fd, &read_fds))
1261            {
1262                do
1263                {
1264                    bytes_read = ::read (stdout_fd, s, sizeof(s)-1);
1265                    if (bytes_read < 0)
1266                    {
1267                        int read_errno = errno;
1268                        DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d   errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1269                    }
1270                    else if (bytes_read == 0)
1271                    {
1272                        // EOF...
1273                        DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d  (reached EOF for child STDOUT)", bytes_read);
1274                        stdout_fd = -1;
1275                    }
1276                    else if (bytes_read > 0)
1277                    {
1278                        proc->AppendSTDOUT(s, bytes_read);
1279                    }
1280
1281                } while (bytes_read > 0);
1282            }
1283
1284            if (stderr_fd >= 0 && FD_ISSET (stderr_fd, &read_fds))
1285            {
1286                do
1287                {
1288                    bytes_read = ::read (stderr_fd, s, sizeof(s)-1);
1289                    if (bytes_read < 0)
1290                    {
1291                        int read_errno = errno;
1292                        DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d   errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1293                    }
1294                    else if (bytes_read == 0)
1295                    {
1296                        // EOF...
1297                        DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d  (reached EOF for child STDERR)", bytes_read);
1298                        stderr_fd = -1;
1299                    }
1300                    else if (bytes_read > 0)
1301                    {
1302                        proc->AppendSTDOUT(s, bytes_read);
1303                    }
1304
1305                } while (bytes_read > 0);
1306            }
1307        }
1308    }
1309    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%p): thread exiting...", __FUNCTION__, arg);
1310    return NULL;
1311}
1312
1313pid_t
1314MachProcess::AttachForDebug (pid_t pid, char *err_str, size_t err_len)
1315{
1316    // Clear out and clean up from any current state
1317    Clear();
1318    if (pid != 0)
1319    {
1320        DNBError err;
1321        // Make sure the process exists...
1322        if (::getpgid (pid) < 0)
1323        {
1324            err.SetErrorToErrno();
1325            const char *err_cstr = err.AsString();
1326            ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "No such process");
1327            return INVALID_NUB_PROCESS;
1328        }
1329
1330        SetState(eStateAttaching);
1331        m_pid = pid;
1332        // Let ourselves know we are going to be using SBS if the correct flag bit is set...
1333#if defined (__arm__)
1334        if (IsSBProcess(pid))
1335            m_flags |= eMachProcessFlagsUsingSBS;
1336#endif
1337        if (!m_task.StartExceptionThread(err))
1338        {
1339            const char *err_cstr = err.AsString();
1340            ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "unable to start the exception thread");
1341            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1342            m_pid = INVALID_NUB_PROCESS;
1343            return INVALID_NUB_PROCESS;
1344        }
1345
1346        errno = 0;
1347        if (::ptrace (PT_ATTACHEXC, pid, 0, 0))
1348            err.SetError(errno);
1349        else
1350            err.Clear();
1351
1352        if (err.Success())
1353        {
1354            m_flags |= eMachProcessFlagsAttached;
1355            // Sleep a bit to let the exception get received and set our process status
1356            // to stopped.
1357            ::usleep(250000);
1358            DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", pid);
1359            return m_pid;
1360        }
1361        else
1362        {
1363            ::snprintf (err_str, err_len, "%s", err.AsString());
1364            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1365        }
1366    }
1367    return INVALID_NUB_PROCESS;
1368}
1369
1370// Do the process specific setup for attach.  If this returns NULL, then there's no
1371// platform specific stuff to be done to wait for the attach.  If you get non-null,
1372// pass that token to the CheckForProcess method, and then to CleanupAfterAttach.
1373
1374//  Call PrepareForAttach before attaching to a process that has not yet launched
1375// This returns a token that can be passed to CheckForProcess, and to CleanupAfterAttach.
1376// You should call CleanupAfterAttach to free the token, and do whatever other
1377// cleanup seems good.
1378
1379const void *
1380MachProcess::PrepareForAttach (const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &err_str)
1381{
1382#if defined (__arm__)
1383    // Tell SpringBoard to halt the next launch of this application on startup.
1384
1385    if (!waitfor)
1386        return NULL;
1387
1388    const char *app_ext = strstr(path, ".app");
1389    if (app_ext == NULL)
1390    {
1391        DNBLogThreadedIf(LOG_PROCESS, "%s: path '%s' doesn't contain .app, we can't tell springboard to wait for launch...", path);
1392        return NULL;
1393    }
1394
1395    if (launch_flavor != eLaunchFlavorSpringBoard
1396        && launch_flavor != eLaunchFlavorDefault)
1397        return NULL;
1398
1399    std::string app_bundle_path(path, app_ext + strlen(".app"));
1400
1401    CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path.c_str (), err_str);
1402    std::string bundleIDStr;
1403    CFString::UTF8(bundleIDCFStr, bundleIDStr);
1404    DNBLogThreadedIf(LOG_PROCESS, "CopyBundleIDForPath (%s, err_str) returned @\"%s\"", app_bundle_path.c_str (), bundleIDStr.c_str());
1405
1406    if (bundleIDCFStr == NULL)
1407    {
1408        return NULL;
1409    }
1410
1411    SBSApplicationLaunchError sbs_error = 0;
1412
1413    const char *stdout_err = "/dev/null";
1414    CFString stdio_path;
1415    stdio_path.SetFileSystemRepresentation (stdout_err);
1416
1417    DNBLogThreadedIf(LOG_PROCESS, "SBSLaunchApplicationForDebugging ( @\"%s\" , NULL, NULL, NULL, @\"%s\", @\"%s\", SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger )", bundleIDStr.c_str(), stdout_err, stdout_err);
1418    sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1419                                                  (CFURLRef)NULL,         // openURL
1420                                                  NULL, // launch_argv.get(),
1421                                                  NULL, // launch_envp.get(),  // CFDictionaryRef environment
1422                                                  stdio_path.get(),
1423                                                  stdio_path.get(),
1424                                                  SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger);
1425
1426    if (sbs_error != SBSApplicationLaunchErrorSuccess)
1427    {
1428        err_str.SetError(sbs_error, DNBError::SpringBoard);
1429        return NULL;
1430    }
1431
1432    DNBLogThreadedIf(LOG_PROCESS, "Successfully set DebugOnNextLaunch.");
1433    return bundleIDCFStr;
1434# else
1435  return NULL;
1436#endif
1437}
1438
1439// Pass in the token you got from PrepareForAttach.  If there is a process
1440// for that token, then the pid will be returned, otherwise INVALID_NUB_PROCESS
1441// will be returned.
1442
1443nub_process_t
1444MachProcess::CheckForProcess (const void *attach_token)
1445{
1446    if (attach_token == NULL)
1447        return INVALID_NUB_PROCESS;
1448
1449#if defined (__arm__)
1450    CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1451    Boolean got_it;
1452    nub_process_t attach_pid;
1453    got_it = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &attach_pid);
1454    if (got_it)
1455        return attach_pid;
1456    else
1457        return INVALID_NUB_PROCESS;
1458#endif
1459    return INVALID_NUB_PROCESS;
1460}
1461
1462// Call this to clean up after you have either attached or given up on the attach.
1463// Pass true for success if you have attached, false if you have not.
1464// The token will also be freed at this point, so you can't use it after calling
1465// this method.
1466
1467void
1468MachProcess::CleanupAfterAttach (const void *attach_token, bool success, DNBError &err_str)
1469{
1470#if defined (__arm__)
1471    if (attach_token == NULL)
1472        return;
1473
1474    // Tell SpringBoard to cancel the debug on next launch of this application
1475    // if we failed to attach
1476    if (!success)
1477    {
1478        SBSApplicationLaunchError sbs_error = 0;
1479        CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1480
1481        sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1482                                                      (CFURLRef)NULL,
1483                                                      NULL,
1484                                                      NULL,
1485                                                      NULL,
1486                                                      NULL,
1487                                                      SBSApplicationCancelDebugOnNextLaunch);
1488
1489        if (sbs_error != SBSApplicationLaunchErrorSuccess)
1490        {
1491            err_str.SetError(sbs_error, DNBError::SpringBoard);
1492            return;
1493        }
1494    }
1495
1496    CFRelease((CFStringRef) attach_token);
1497#endif
1498}
1499
1500pid_t
1501MachProcess::LaunchForDebug
1502(
1503    const char *path,
1504    char const *argv[],
1505    char const *envp[],
1506    const char *working_directory, // NULL => dont' change, non-NULL => set working directory for inferior to this
1507    const char *stdin_path,
1508    const char *stdout_path,
1509    const char *stderr_path,
1510    bool no_stdio,
1511    nub_launch_flavor_t launch_flavor,
1512    int disable_aslr,
1513    DNBError &launch_err
1514)
1515{
1516    // Clear out and clean up from any current state
1517    Clear();
1518
1519    DNBLogThreadedIf(LOG_PROCESS, "%s( path = '%s', argv = %p, envp = %p, launch_flavor = %u, disable_aslr = %d )", __FUNCTION__, path, argv, envp, launch_flavor, disable_aslr);
1520
1521    // Fork a child process for debugging
1522    SetState(eStateLaunching);
1523
1524    switch (launch_flavor)
1525    {
1526    case eLaunchFlavorForkExec:
1527        m_pid = MachProcess::ForkChildForPTraceDebugging (path, argv, envp, this, launch_err);
1528        break;
1529
1530    case eLaunchFlavorPosixSpawn:
1531        m_pid = MachProcess::PosixSpawnChildForPTraceDebugging (path,
1532                                                                DNBArchProtocol::GetArchitecture (),
1533                                                                argv,
1534                                                                envp,
1535                                                                working_directory,
1536                                                                stdin_path,
1537                                                                stdout_path,
1538                                                                stderr_path,
1539                                                                no_stdio,
1540                                                                this,
1541                                                                disable_aslr,
1542                                                                launch_err);
1543        break;
1544
1545#if defined (__arm__)
1546
1547    case eLaunchFlavorSpringBoard:
1548        {
1549            const char *app_ext = strstr(path, ".app");
1550            if (app_ext != NULL)
1551            {
1552                std::string app_bundle_path(path, app_ext + strlen(".app"));
1553                return SBLaunchForDebug (app_bundle_path.c_str(), argv, envp, no_stdio, launch_err);
1554            }
1555        }
1556        break;
1557
1558#endif
1559
1560    default:
1561        // Invalid  launch
1562        launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1563        return INVALID_NUB_PROCESS;
1564    }
1565
1566    if (m_pid == INVALID_NUB_PROCESS)
1567    {
1568        // If we don't have a valid process ID and no one has set the error,
1569        // then return a generic error
1570        if (launch_err.Success())
1571            launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1572    }
1573    else
1574    {
1575        m_path = path;
1576        size_t i;
1577        char const *arg;
1578        for (i=0; (arg = argv[i]) != NULL; i++)
1579            m_args.push_back(arg);
1580
1581        m_task.StartExceptionThread(launch_err);
1582        if (launch_err.Fail())
1583        {
1584            if (launch_err.AsString() == NULL)
1585                launch_err.SetErrorString("unable to start the exception thread");
1586            ::ptrace (PT_KILL, m_pid, 0, 0);
1587            m_pid = INVALID_NUB_PROCESS;
1588            return INVALID_NUB_PROCESS;
1589        }
1590
1591        StartSTDIOThread();
1592
1593        if (launch_flavor == eLaunchFlavorPosixSpawn)
1594        {
1595
1596            SetState (eStateAttaching);
1597            errno = 0;
1598            int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
1599            if (err == 0)
1600            {
1601                m_flags |= eMachProcessFlagsAttached;
1602                DNBLogThreadedIf(LOG_PROCESS, "successfully spawned pid %d", m_pid);
1603                launch_err.Clear();
1604            }
1605            else
1606            {
1607                SetState (eStateExited);
1608                DNBError ptrace_err(errno, DNBError::POSIX);
1609                DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to spawned pid %d (err = %i, errno = %i (%s))", m_pid, err, ptrace_err.Error(), ptrace_err.AsString());
1610                launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1611            }
1612        }
1613        else
1614        {
1615            launch_err.Clear();
1616        }
1617    }
1618    return m_pid;
1619}
1620
1621pid_t
1622MachProcess::PosixSpawnChildForPTraceDebugging
1623(
1624    const char *path,
1625    cpu_type_t cpu_type,
1626    char const *argv[],
1627    char const *envp[],
1628    const char *working_directory,
1629    const char *stdin_path,
1630    const char *stdout_path,
1631    const char *stderr_path,
1632    bool no_stdio,
1633    MachProcess* process,
1634    int disable_aslr,
1635    DNBError& err
1636)
1637{
1638    posix_spawnattr_t attr;
1639    short flags;
1640    DNBLogThreadedIf(LOG_PROCESS, "%s ( path='%s', argv=%p, envp=%p, working_dir=%s, stdin=%s, stdout=%s stderr=%s, no-stdio=%i)",
1641                     __FUNCTION__,
1642                     path,
1643                     argv,
1644                     envp,
1645                     working_directory,
1646                     stdin_path,
1647                     stdout_path,
1648                     stderr_path,
1649                     no_stdio);
1650
1651    err.SetError( ::posix_spawnattr_init (&attr), DNBError::POSIX);
1652    if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1653        err.LogThreaded("::posix_spawnattr_init ( &attr )");
1654    if (err.Fail())
1655        return INVALID_NUB_PROCESS;
1656
1657    flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
1658    if (disable_aslr)
1659        flags |= _POSIX_SPAWN_DISABLE_ASLR;
1660
1661    sigset_t no_signals;
1662    sigset_t all_signals;
1663    sigemptyset (&no_signals);
1664    sigfillset (&all_signals);
1665    ::posix_spawnattr_setsigmask(&attr, &no_signals);
1666    ::posix_spawnattr_setsigdefault(&attr, &all_signals);
1667
1668    err.SetError( ::posix_spawnattr_setflags (&attr, flags), DNBError::POSIX);
1669    if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1670        err.LogThreaded("::posix_spawnattr_setflags ( &attr, POSIX_SPAWN_START_SUSPENDED%s )", flags & _POSIX_SPAWN_DISABLE_ASLR ? " | _POSIX_SPAWN_DISABLE_ASLR" : "");
1671    if (err.Fail())
1672        return INVALID_NUB_PROCESS;
1673
1674    // Don't do this on SnowLeopard, _sometimes_ the TASK_BASIC_INFO will fail
1675    // and we will fail to continue with our process...
1676
1677    // On SnowLeopard we should set "DYLD_NO_PIE" in the inferior environment....
1678
1679#if !defined(__arm__)
1680
1681    // We don't need to do this for ARM, and we really shouldn't now that we
1682    // have multiple CPU subtypes and no posix_spawnattr call that allows us
1683    // to set which CPU subtype to launch...
1684    if (cpu_type != 0)
1685    {
1686        size_t ocount = 0;
1687        err.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), DNBError::POSIX);
1688        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1689            err.LogThreaded("::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %zu )", cpu_type, ocount);
1690
1691        if (err.Fail() != 0 || ocount != 1)
1692            return INVALID_NUB_PROCESS;
1693    }
1694#endif
1695
1696    PseudoTerminal pty;
1697
1698    posix_spawn_file_actions_t file_actions;
1699    err.SetError( ::posix_spawn_file_actions_init (&file_actions), DNBError::POSIX);
1700    int file_actions_valid = err.Success();
1701    if (!file_actions_valid || DNBLogCheckLogBit(LOG_PROCESS))
1702        err.LogThreaded("::posix_spawn_file_actions_init ( &file_actions )");
1703    int pty_error = -1;
1704    pid_t pid = INVALID_NUB_PROCESS;
1705    if (file_actions_valid)
1706    {
1707        if (stdin_path == NULL && stdout_path == NULL && stderr_path == NULL && !no_stdio)
1708        {
1709            pty_error = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
1710            if (pty_error == PseudoTerminal::success)
1711            {
1712                stdin_path = stdout_path = stderr_path = pty.SlaveName();
1713            }
1714        }
1715
1716		// if no_stdio, then do open file actions, opening /dev/null.
1717        if (no_stdio)
1718        {
1719            err.SetError( ::posix_spawn_file_actions_addopen (&file_actions, STDIN_FILENO, "/dev/null",
1720                                                              O_RDONLY | O_NOCTTY, 0), DNBError::POSIX);
1721            if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1722                err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDIN_FILENO, path=/dev/null)");
1723
1724            err.SetError( ::posix_spawn_file_actions_addopen (&file_actions, STDOUT_FILENO, "/dev/null",
1725                                                              O_WRONLY | O_NOCTTY, 0), DNBError::POSIX);
1726            if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1727                err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDOUT_FILENO, path=/dev/null)");
1728
1729            err.SetError( ::posix_spawn_file_actions_addopen (&file_actions, STDERR_FILENO, "/dev/null",
1730                                                              O_RDWR | O_NOCTTY, 0), DNBError::POSIX);
1731            if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
1732                err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDERR_FILENO, path=/dev/null)");
1733        }
1734        else
1735        {
1736            if ( stdin_path == NULL)  stdin_path = "/dev/null";
1737            if (stdout_path == NULL) stdout_path = "/dev/null";
1738            if (stderr_path == NULL) stderr_path = "/dev/null";
1739
1740            int slave_fd_err = open (stderr_path, O_NOCTTY | O_CREAT | O_RDWR   , 0640);
1741            int slave_fd_in  = open (stdin_path , O_NOCTTY | O_RDONLY);
1742            int slave_fd_out = open (stdout_path, O_NOCTTY | O_CREAT | O_WRONLY , 0640);
1743
1744            err.SetError( ::posix_spawn_file_actions_adddup2(&file_actions, slave_fd_err, STDERR_FILENO), DNBError::POSIX);
1745            if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1746                err.LogThreaded("::posix_spawn_file_actions_adddup2 ( &file_actions, filedes = %d (\"%s\"), newfiledes = STDERR_FILENO )", slave_fd_err, stderr_path);
1747
1748            err.SetError( ::posix_spawn_file_actions_adddup2(&file_actions, slave_fd_in, STDIN_FILENO), DNBError::POSIX);
1749            if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1750                err.LogThreaded("::posix_spawn_file_actions_adddup2 ( &file_actions, filedes = %d (\"%s\"), newfiledes = STDIN_FILENO )", slave_fd_in, stdin_path);
1751
1752            err.SetError( ::posix_spawn_file_actions_adddup2(&file_actions, slave_fd_out, STDOUT_FILENO), DNBError::POSIX);
1753            if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1754                err.LogThreaded("::posix_spawn_file_actions_adddup2 ( &file_actions, filedes = %d (\"%s\"), newfiledes = STDOUT_FILENO )", slave_fd_out, stdout_path);
1755        }
1756
1757        // TODO: Verify if we can set the working directory back immediately
1758        // after the posix_spawnp call without creating a race condition???
1759        if (working_directory)
1760            ::chdir (working_directory);
1761
1762        err.SetError( ::posix_spawnp (&pid, path, &file_actions, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
1763        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1764            err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, &file_actions, &attr, argv, envp);
1765    }
1766    else
1767    {
1768        // TODO: Verify if we can set the working directory back immediately
1769        // after the posix_spawnp call without creating a race condition???
1770        if (working_directory)
1771            ::chdir (working_directory);
1772
1773        err.SetError( ::posix_spawnp (&pid, path, NULL, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
1774        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1775            err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, NULL, &attr, argv, envp);
1776    }
1777
1778    // We have seen some cases where posix_spawnp was returning a valid
1779    // looking pid even when an error was returned, so clear it out
1780    if (err.Fail())
1781        pid = INVALID_NUB_PROCESS;
1782
1783    if (pty_error == 0)
1784    {
1785        if (process != NULL)
1786        {
1787            int master_fd = pty.ReleaseMasterFD();
1788            process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
1789        }
1790    }
1791    ::posix_spawnattr_destroy (&attr);
1792
1793    if (pid != INVALID_NUB_PROCESS)
1794    {
1795        cpu_type_t pid_cpu_type = MachProcess::GetCPUTypeForLocalProcess (pid);
1796        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( ) pid=%i, cpu_type=0x%8.8x", __FUNCTION__, pid, pid_cpu_type);
1797        if (pid_cpu_type)
1798            DNBArchProtocol::SetArchitecture (pid_cpu_type);
1799    }
1800
1801    if (file_actions_valid)
1802    {
1803        DNBError err2;
1804        err2.SetError( ::posix_spawn_file_actions_destroy (&file_actions), DNBError::POSIX);
1805        if (err2.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1806            err2.LogThreaded("::posix_spawn_file_actions_destroy ( &file_actions )");
1807    }
1808
1809    return pid;
1810}
1811
1812uint32_t
1813MachProcess::GetCPUTypeForLocalProcess (pid_t pid)
1814{
1815    int mib[CTL_MAXNAME]={0,};
1816    size_t len = CTL_MAXNAME;
1817    if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))
1818        return 0;
1819
1820    mib[len] = pid;
1821    len++;
1822
1823    cpu_type_t cpu;
1824    size_t cpu_len = sizeof(cpu);
1825    if (::sysctl (mib, len, &cpu, &cpu_len, 0, 0))
1826        cpu = 0;
1827    return cpu;
1828}
1829
1830pid_t
1831MachProcess::ForkChildForPTraceDebugging
1832(
1833    const char *path,
1834    char const *argv[],
1835    char const *envp[],
1836    MachProcess* process,
1837    DNBError& launch_err
1838)
1839{
1840    PseudoTerminal::Error pty_error = PseudoTerminal::success;
1841
1842    // Use a fork that ties the child process's stdin/out/err to a pseudo
1843    // terminal so we can read it in our MachProcess::STDIOThread
1844    // as unbuffered io.
1845    PseudoTerminal pty;
1846    pid_t pid = pty.Fork(pty_error);
1847
1848    if (pid < 0)
1849    {
1850        //--------------------------------------------------------------
1851        // Error during fork.
1852        //--------------------------------------------------------------
1853        return pid;
1854    }
1855    else if (pid == 0)
1856    {
1857        //--------------------------------------------------------------
1858        // Child process
1859        //--------------------------------------------------------------
1860        ::ptrace (PT_TRACE_ME, 0, 0, 0);    // Debug this process
1861        ::ptrace (PT_SIGEXC, 0, 0, 0);    // Get BSD signals as mach exceptions
1862
1863        // If our parent is setgid, lets make sure we don't inherit those
1864        // extra powers due to nepotism.
1865        ::setgid (getgid ());
1866
1867        // Let the child have its own process group. We need to execute
1868        // this call in both the child and parent to avoid a race condition
1869        // between the two processes.
1870        ::setpgid (0, 0);    // Set the child process group to match its pid
1871
1872        // Sleep a bit to before the exec call
1873        ::sleep (1);
1874
1875        // Turn this process into
1876        ::execv (path, (char * const *)argv);
1877        // Exit with error code. Child process should have taken
1878        // over in above exec call and if the exec fails it will
1879        // exit the child process below.
1880        ::exit (127);
1881    }
1882    else
1883    {
1884        //--------------------------------------------------------------
1885        // Parent process
1886        //--------------------------------------------------------------
1887        // Let the child have its own process group. We need to execute
1888        // this call in both the child and parent to avoid a race condition
1889        // between the two processes.
1890        ::setpgid (pid, pid);    // Set the child process group to match its pid
1891
1892        if (process != NULL)
1893        {
1894            // Release our master pty file descriptor so the pty class doesn't
1895            // close it and so we can continue to use it in our STDIO thread
1896            int master_fd = pty.ReleaseMasterFD();
1897            process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
1898        }
1899    }
1900    return pid;
1901}
1902
1903#if defined (__arm__)
1904
1905pid_t
1906MachProcess::SBLaunchForDebug (const char *path, char const *argv[], char const *envp[], bool no_stdio, DNBError &launch_err)
1907{
1908    // Clear out and clean up from any current state
1909    Clear();
1910
1911    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path);
1912
1913    // Fork a child process for debugging
1914    SetState(eStateLaunching);
1915    m_pid = MachProcess::SBForkChildForPTraceDebugging(path, argv, envp, no_stdio, this, launch_err);
1916    if (m_pid != 0)
1917    {
1918        m_flags |= eMachProcessFlagsUsingSBS;
1919        m_path = path;
1920        size_t i;
1921        char const *arg;
1922        for (i=0; (arg = argv[i]) != NULL; i++)
1923            m_args.push_back(arg);
1924        m_task.StartExceptionThread(launch_err);
1925
1926        if (launch_err.Fail())
1927        {
1928            if (launch_err.AsString() == NULL)
1929                launch_err.SetErrorString("unable to start the exception thread");
1930            ::ptrace (PT_KILL, m_pid, 0, 0);
1931            m_pid = INVALID_NUB_PROCESS;
1932            return INVALID_NUB_PROCESS;
1933        }
1934
1935        StartSTDIOThread();
1936        SetState (eStateAttaching);
1937        int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
1938        if (err == 0)
1939        {
1940            m_flags |= eMachProcessFlagsAttached;
1941            DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", m_pid);
1942        }
1943        else
1944        {
1945            SetState (eStateExited);
1946            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", m_pid);
1947        }
1948    }
1949    return m_pid;
1950}
1951
1952#include <servers/bootstrap.h>
1953
1954// This returns a CFRetained pointer to the Bundle ID for app_bundle_path,
1955// or NULL if there was some problem getting the bundle id.
1956static CFStringRef
1957CopyBundleIDForPath (const char *app_bundle_path, DNBError &err_str)
1958{
1959    CFBundle bundle(app_bundle_path);
1960    CFStringRef bundleIDCFStr = bundle.GetIdentifier();
1961    std::string bundleID;
1962    if (CFString::UTF8(bundleIDCFStr, bundleID) == NULL)
1963    {
1964        struct stat app_bundle_stat;
1965        char err_msg[PATH_MAX];
1966
1967        if (::stat (app_bundle_path, &app_bundle_stat) < 0)
1968        {
1969            err_str.SetError(errno, DNBError::POSIX);
1970            snprintf(err_msg, sizeof(err_msg), "%s: \"%s\"", err_str.AsString(), app_bundle_path);
1971            err_str.SetErrorString(err_msg);
1972            DNBLogThreadedIf(LOG_PROCESS, "%s() error: %s", __FUNCTION__, err_msg);
1973        }
1974        else
1975        {
1976            err_str.SetError(-1, DNBError::Generic);
1977            snprintf(err_msg, sizeof(err_msg), "failed to extract CFBundleIdentifier from %s", app_bundle_path);
1978            err_str.SetErrorString(err_msg);
1979            DNBLogThreadedIf(LOG_PROCESS, "%s() error: failed to extract CFBundleIdentifier from '%s'", __FUNCTION__, app_bundle_path);
1980        }
1981        return NULL;
1982    }
1983
1984    DNBLogThreadedIf(LOG_PROCESS, "%s() extracted CFBundleIdentifier: %s", __FUNCTION__, bundleID.c_str());
1985    CFRetain (bundleIDCFStr);
1986
1987    return bundleIDCFStr;
1988}
1989
1990pid_t
1991MachProcess::SBForkChildForPTraceDebugging (const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, MachProcess* process, DNBError &launch_err)
1992{
1993    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__, app_bundle_path, process);
1994    CFAllocatorRef alloc = kCFAllocatorDefault;
1995
1996    if (argv[0] == NULL)
1997        return INVALID_NUB_PROCESS;
1998
1999    size_t argc = 0;
2000    // Count the number of arguments
2001    while (argv[argc] != NULL)
2002        argc++;
2003
2004    // Enumerate the arguments
2005    size_t first_launch_arg_idx = 1;
2006    CFReleaser<CFMutableArrayRef> launch_argv;
2007
2008    if (argv[first_launch_arg_idx])
2009    {
2010        size_t launch_argc = argc > 0 ? argc - 1 : 0;
2011        launch_argv.reset (::CFArrayCreateMutable (alloc, launch_argc, &kCFTypeArrayCallBacks));
2012        size_t i;
2013        char const *arg;
2014        CFString launch_arg;
2015        for (i=first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL); i++)
2016        {
2017            launch_arg.reset(::CFStringCreateWithCString (alloc, arg, kCFStringEncodingUTF8));
2018            if (launch_arg.get() != NULL)
2019                CFArrayAppendValue(launch_argv.get(), launch_arg.get());
2020            else
2021                break;
2022        }
2023    }
2024
2025    // Next fill in the arguments dictionary.  Note, the envp array is of the form
2026    // Variable=value but SpringBoard wants a CF dictionary.  So we have to convert
2027    // this here.
2028
2029    CFReleaser<CFMutableDictionaryRef> launch_envp;
2030
2031    if (envp[0])
2032    {
2033        launch_envp.reset(::CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2034        const char *value;
2035        int name_len;
2036        CFString name_string, value_string;
2037
2038        for (int i = 0; envp[i] != NULL; i++)
2039        {
2040            value = strstr (envp[i], "=");
2041
2042            // If the name field is empty or there's no =, skip it.  Somebody's messing with us.
2043            if (value == NULL || value == envp[i])
2044                continue;
2045
2046            name_len = value - envp[i];
2047
2048            // Now move value over the "="
2049            value++;
2050
2051            name_string.reset(::CFStringCreateWithBytes(alloc, (const UInt8 *) envp[i], name_len, kCFStringEncodingUTF8, false));
2052            value_string.reset(::CFStringCreateWithCString(alloc, value, kCFStringEncodingUTF8));
2053            CFDictionarySetValue (launch_envp.get(), name_string.get(), value_string.get());
2054        }
2055    }
2056
2057    CFString stdio_path;
2058
2059    PseudoTerminal pty;
2060    if (!no_stdio)
2061    {
2062        PseudoTerminal::Error pty_err = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
2063        if (pty_err == PseudoTerminal::success)
2064        {
2065            const char* slave_name = pty.SlaveName();
2066            DNBLogThreadedIf(LOG_PROCESS, "%s() successfully opened master pty, slave is %s", __FUNCTION__, slave_name);
2067            if (slave_name && slave_name[0])
2068            {
2069                ::chmod (slave_name, S_IRWXU | S_IRWXG | S_IRWXO);
2070                stdio_path.SetFileSystemRepresentation (slave_name);
2071            }
2072        }
2073    }
2074
2075    if (stdio_path.get() == NULL)
2076    {
2077        stdio_path.SetFileSystemRepresentation ("/dev/null");
2078    }
2079
2080    CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path, launch_err);
2081    if (bundleIDCFStr == NULL)
2082        return INVALID_NUB_PROCESS;
2083
2084    std::string bundleID;
2085    CFString::UTF8(bundleIDCFStr, bundleID);
2086
2087    CFData argv_data(NULL);
2088
2089    if (launch_argv.get())
2090    {
2091        if (argv_data.Serialize(launch_argv.get(), kCFPropertyListBinaryFormat_v1_0) == NULL)
2092        {
2093            DNBLogThreadedIf(LOG_PROCESS, "%s() error: failed to serialize launch arg array...", __FUNCTION__);
2094            return INVALID_NUB_PROCESS;
2095        }
2096    }
2097
2098    DNBLogThreadedIf(LOG_PROCESS, "%s() serialized launch arg array", __FUNCTION__);
2099
2100    // Find SpringBoard
2101    SBSApplicationLaunchError sbs_error = 0;
2102    sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
2103                                                  (CFURLRef)NULL,         // openURL
2104                                                  launch_argv.get(),
2105                                                  launch_envp.get(),  // CFDictionaryRef environment
2106                                                  stdio_path.get(),
2107                                                  stdio_path.get(),
2108                                                  SBSApplicationLaunchWaitForDebugger | SBSApplicationLaunchUnlockDevice);
2109
2110
2111    launch_err.SetError(sbs_error, DNBError::SpringBoard);
2112
2113    if (sbs_error == SBSApplicationLaunchErrorSuccess)
2114    {
2115        static const useconds_t pid_poll_interval = 200000;
2116        static const useconds_t pid_poll_timeout = 30000000;
2117
2118        useconds_t pid_poll_total = 0;
2119
2120        nub_process_t pid = INVALID_NUB_PROCESS;
2121        Boolean pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2122        // Poll until the process is running, as long as we are getting valid responses and the timeout hasn't expired
2123        // A return PID of 0 means the process is not running, which may be because it hasn't been (asynchronously) started
2124        // yet, or that it died very quickly (if you weren't using waitForDebugger).
2125        while (!pid_found && pid_poll_total < pid_poll_timeout)
2126        {
2127            usleep (pid_poll_interval);
2128            pid_poll_total += pid_poll_interval;
2129            DNBLogThreadedIf(LOG_PROCESS, "%s() polling Springboard for pid for %s...", __FUNCTION__, bundleID.c_str());
2130            pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2131        }
2132
2133        CFRelease (bundleIDCFStr);
2134        if (pid_found)
2135        {
2136            if (process != NULL)
2137            {
2138                // Release our master pty file descriptor so the pty class doesn't
2139                // close it and so we can continue to use it in our STDIO thread
2140                int master_fd = pty.ReleaseMasterFD();
2141                process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
2142            }
2143            DNBLogThreadedIf(LOG_PROCESS, "%s() => pid = %4.4x", __FUNCTION__, pid);
2144        }
2145        else
2146        {
2147            DNBLogError("failed to lookup the process ID for CFBundleIdentifier %s.", bundleID.c_str());
2148        }
2149        return pid;
2150    }
2151
2152    DNBLogError("unable to launch the application with CFBundleIdentifier '%s' sbs_error = %u", bundleID.c_str(), sbs_error);
2153    return INVALID_NUB_PROCESS;
2154}
2155
2156#endif // #if defined (__arm__)
2157
2158
2159