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