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