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_bundle_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 // WITH_SPRINGBOARD
58
59#ifdef WITH_BKS
60#import <Foundation/Foundation.h>
61extern "C"
62{
63#import <BackBoardServices/BackBoardServices.h>
64#import <BackBoardServices/BKSSystemService_LaunchServices.h>
65#import <BackBoardServices/BKSOpenApplicationConstants_Private.h>
66}
67
68static bool
69IsBKSProcess (nub_process_t pid)
70{
71    BKSApplicationStateMonitor *state_monitor = [[BKSApplicationStateMonitor alloc] init];
72    BKSApplicationState app_state = [state_monitor mostElevatedApplicationStateForPID: pid];
73    return app_state != BKSApplicationStateUnknown;
74}
75
76static void
77SetBKSError (BKSOpenApplicationErrorCode error_code, DNBError &error)
78{
79    error.SetError (error_code, DNBError::BackBoard);
80    NSString *err_nsstr = ::BKSOpenApplicationErrorCodeToString(error_code);
81    const char *err_str = NULL;
82    if (err_nsstr == NULL)
83        err_str = "unknown BKS error";
84    else
85    {
86        err_str = [err_nsstr UTF8String];
87        if (err_str == NULL)
88            err_str = "unknown BKS error";
89    }
90    error.SetErrorString(err_str);
91}
92
93static const int BKS_OPEN_APPLICATION_TIMEOUT_ERROR = 111;
94#endif // WITH_BKS
95#if 0
96#define DEBUG_LOG(fmt, ...) printf(fmt, ## __VA_ARGS__)
97#else
98#define DEBUG_LOG(fmt, ...)
99#endif
100
101#ifndef MACH_PROCESS_USE_POSIX_SPAWN
102#define MACH_PROCESS_USE_POSIX_SPAWN 1
103#endif
104
105#ifndef _POSIX_SPAWN_DISABLE_ASLR
106#define _POSIX_SPAWN_DISABLE_ASLR       0x0100
107#endif
108
109MachProcess::MachProcess() :
110    m_pid               (0),
111    m_cpu_type          (0),
112    m_child_stdin       (-1),
113    m_child_stdout      (-1),
114    m_child_stderr      (-1),
115    m_path              (),
116    m_args              (),
117    m_task              (this),
118    m_flags             (eMachProcessFlagsNone),
119    m_stdio_thread      (0),
120    m_stdio_mutex       (PTHREAD_MUTEX_RECURSIVE),
121    m_stdout_data       (),
122    m_thread_actions    (),
123    m_profile_enabled   (false),
124    m_profile_interval_usec (0),
125    m_profile_thread    (0),
126    m_profile_data_mutex(PTHREAD_MUTEX_RECURSIVE),
127    m_profile_data      (),
128    m_thread_list        (),
129    m_exception_messages (),
130    m_exception_messages_mutex (PTHREAD_MUTEX_RECURSIVE),
131    m_state             (eStateUnloaded),
132    m_state_mutex       (PTHREAD_MUTEX_RECURSIVE),
133    m_events            (0, kAllEventsMask),
134    m_private_events    (0, kAllEventsMask),
135    m_breakpoints       (),
136    m_watchpoints       (),
137    m_name_to_addr_callback(NULL),
138    m_name_to_addr_baton(NULL),
139    m_image_infos_callback(NULL),
140    m_image_infos_baton(NULL),
141    m_did_exec (false)
142{
143    DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
144}
145
146MachProcess::~MachProcess()
147{
148    DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);
149    Clear();
150}
151
152pid_t
153MachProcess::SetProcessID(pid_t pid)
154{
155    // Free any previous process specific data or resources
156    Clear();
157    // Set the current PID appropriately
158    if (pid == 0)
159        m_pid = ::getpid ();
160    else
161        m_pid = pid;
162    return m_pid;    // Return actualy PID in case a zero pid was passed in
163}
164
165nub_state_t
166MachProcess::GetState()
167{
168    // If any other threads access this we will need a mutex for it
169    PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
170    return m_state;
171}
172
173const char *
174MachProcess::ThreadGetName(nub_thread_t tid)
175{
176    return m_thread_list.GetName(tid);
177}
178
179nub_state_t
180MachProcess::ThreadGetState(nub_thread_t tid)
181{
182    return m_thread_list.GetState(tid);
183}
184
185
186nub_size_t
187MachProcess::GetNumThreads () const
188{
189    return m_thread_list.NumThreads();
190}
191
192nub_thread_t
193MachProcess::GetThreadAtIndex (nub_size_t thread_idx) const
194{
195    return m_thread_list.ThreadIDAtIndex(thread_idx);
196}
197
198nub_thread_t
199MachProcess::GetThreadIDForMachPortNumber (thread_t mach_port_number) const
200{
201    return m_thread_list.GetThreadIDByMachPortNumber (mach_port_number);
202}
203
204nub_bool_t
205MachProcess::SyncThreadState (nub_thread_t tid)
206{
207    MachThreadSP thread_sp(m_thread_list.GetThreadByID(tid));
208    if (!thread_sp)
209        return false;
210    kern_return_t kret = ::thread_abort_safely(thread_sp->MachPortNumber());
211    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());
212
213    if (kret == KERN_SUCCESS)
214        return true;
215    else
216        return false;
217
218}
219
220nub_thread_t
221MachProcess::GetCurrentThread ()
222{
223    return m_thread_list.CurrentThreadID();
224}
225
226nub_thread_t
227MachProcess::GetCurrentThreadMachPort ()
228{
229    return m_thread_list.GetMachPortNumberByThreadID(m_thread_list.CurrentThreadID());
230}
231
232nub_thread_t
233MachProcess::SetCurrentThread(nub_thread_t tid)
234{
235    return m_thread_list.SetCurrentThread(tid);
236}
237
238bool
239MachProcess::GetThreadStoppedReason(nub_thread_t tid, struct DNBThreadStopInfo *stop_info)
240{
241    if (m_thread_list.GetThreadStoppedReason(tid, stop_info))
242    {
243        if (m_did_exec)
244            stop_info->reason = eStopTypeExec;
245        return true;
246    }
247    return false;
248}
249
250void
251MachProcess::DumpThreadStoppedReason(nub_thread_t tid) const
252{
253    return m_thread_list.DumpThreadStoppedReason(tid);
254}
255
256const char *
257MachProcess::GetThreadInfo(nub_thread_t tid) const
258{
259    return m_thread_list.GetThreadInfo(tid);
260}
261
262uint32_t
263MachProcess::GetCPUType ()
264{
265    if (m_cpu_type == 0 && m_pid != 0)
266        m_cpu_type = MachProcess::GetCPUTypeForLocalProcess (m_pid);
267    return m_cpu_type;
268}
269
270const DNBRegisterSetInfo *
271MachProcess::GetRegisterSetInfo (nub_thread_t tid, nub_size_t *num_reg_sets) const
272{
273    MachThreadSP thread_sp (m_thread_list.GetThreadByID (tid));
274    if (thread_sp)
275    {
276        DNBArchProtocol *arch = thread_sp->GetArchProtocol();
277        if (arch)
278            return arch->GetRegisterSetInfo (num_reg_sets);
279    }
280    *num_reg_sets = 0;
281    return NULL;
282}
283
284bool
285MachProcess::GetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value ) const
286{
287    return m_thread_list.GetRegisterValue(tid, set, reg, value);
288}
289
290bool
291MachProcess::SetRegisterValue ( nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value ) const
292{
293    return m_thread_list.SetRegisterValue(tid, set, reg, value);
294}
295
296void
297MachProcess::SetState(nub_state_t new_state)
298{
299    // If any other threads access this we will need a mutex for it
300    uint32_t event_mask = 0;
301
302    // Scope for mutex locker
303    {
304        PTHREAD_MUTEX_LOCKER(locker, m_state_mutex);
305        const nub_state_t old_state = m_state;
306
307        if (old_state == eStateExited)
308        {
309            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState(%s) ignoring new state since current state is exited", DNBStateAsString(new_state));
310        }
311        else if (old_state == new_state)
312        {
313            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState(%s) ignoring redundant state change...", DNBStateAsString(new_state));
314        }
315        else
316        {
317            if (NUB_STATE_IS_STOPPED(new_state))
318                event_mask = eEventProcessStoppedStateChanged;
319            else
320                event_mask = eEventProcessRunningStateChanged;
321
322            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState(%s) upating state (previous state was %s), event_mask = 0x%8.8x", DNBStateAsString(new_state), DNBStateAsString(old_state), event_mask);
323
324            m_state = new_state;
325            if (new_state == eStateStopped)
326                m_stop_count++;
327        }
328    }
329
330    if (event_mask != 0)
331    {
332        m_events.SetEvents (event_mask);
333        m_private_events.SetEvents (event_mask);
334        if (event_mask == eEventProcessStoppedStateChanged)
335            m_private_events.ResetEvents (eEventProcessRunningStateChanged);
336        else
337            m_private_events.ResetEvents (eEventProcessStoppedStateChanged);
338
339        // Wait for the event bit to reset if a reset ACK is requested
340        m_events.WaitForResetAck(event_mask);
341    }
342
343}
344
345void
346MachProcess::Clear(bool detaching)
347{
348    // Clear any cached thread list while the pid and task are still valid
349
350    m_task.Clear();
351    // Now clear out all member variables
352    m_pid = INVALID_NUB_PROCESS;
353    if (!detaching)
354        CloseChildFileDescriptors();
355
356    m_path.clear();
357    m_args.clear();
358    SetState(eStateUnloaded);
359    m_flags = eMachProcessFlagsNone;
360    m_stop_count = 0;
361    m_thread_list.Clear();
362    {
363        PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
364        m_exception_messages.clear();
365    }
366    if (m_profile_thread)
367    {
368        pthread_join(m_profile_thread, NULL);
369        m_profile_thread = NULL;
370    }
371}
372
373
374bool
375MachProcess::StartSTDIOThread()
376{
377    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);
378    // Create the thread that watches for the child STDIO
379    return ::pthread_create (&m_stdio_thread, NULL, MachProcess::STDIOThread, this) == 0;
380}
381
382void
383MachProcess::SetEnableAsyncProfiling(bool enable, uint64_t interval_usec, DNBProfileDataScanType scan_type)
384{
385    m_profile_enabled = enable;
386    m_profile_interval_usec = interval_usec;
387    m_profile_scan_type = scan_type;
388
389    if (m_profile_enabled && (m_profile_thread == NULL))
390    {
391        StartProfileThread();
392    }
393    else if (!m_profile_enabled && m_profile_thread)
394    {
395        pthread_join(m_profile_thread, NULL);
396        m_profile_thread = NULL;
397    }
398}
399
400bool
401MachProcess::StartProfileThread()
402{
403    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);
404    // Create the thread that profiles the inferior and reports back if enabled
405    return ::pthread_create (&m_profile_thread, NULL, MachProcess::ProfileThread, this) == 0;
406}
407
408
409nub_addr_t
410MachProcess::LookupSymbol(const char *name, const char *shlib)
411{
412    if (m_name_to_addr_callback != NULL && name && name[0])
413        return m_name_to_addr_callback(ProcessID(), name, shlib, m_name_to_addr_baton);
414    return INVALID_NUB_ADDRESS;
415}
416
417bool
418MachProcess::Resume (const DNBThreadResumeActions& thread_actions)
419{
420    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Resume ()");
421    nub_state_t state = GetState();
422
423    if (CanResume(state))
424    {
425        m_thread_actions = thread_actions;
426        PrivateResume();
427        return true;
428    }
429    else if (state == eStateRunning)
430    {
431        DNBLog("Resume() - task 0x%x is already running, ignoring...", m_task.TaskPort());
432        return true;
433    }
434    DNBLog("Resume() - task 0x%x has state %s, can't continue...", m_task.TaskPort(), DNBStateAsString(state));
435    return false;
436}
437
438bool
439MachProcess::Kill (const struct timespec *timeout_abstime)
440{
441    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill ()");
442    nub_state_t state = DoSIGSTOP(true, false, NULL);
443    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() state = %s", DNBStateAsString(state));
444    errno = 0;
445    DNBLog ("Sending ptrace PT_KILL to terminate inferior process.");
446    ::ptrace (PT_KILL, m_pid, 0, 0);
447    DNBError err;
448    err.SetErrorToErrno();
449    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() ::ptrace (PT_KILL, pid=%u, 0, 0) => 0x%8.8x (%s)", m_pid, err.Error(), err.AsString());
450    m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
451    PrivateResume ();
452
453    // Try and reap the process without touching our m_events since
454    // we want the code above this to still get the eStateExited event
455    const uint32_t reap_timeout_usec = 1000000;    // Wait 1 second and try to reap the process
456    const uint32_t reap_interval_usec = 10000;  //
457    uint32_t reap_time_elapsed;
458    for (reap_time_elapsed = 0;
459         reap_time_elapsed < reap_timeout_usec;
460         reap_time_elapsed += reap_interval_usec)
461    {
462        if (GetState() == eStateExited)
463            break;
464        usleep(reap_interval_usec);
465    }
466    DNBLog ("Waited %u ms for process to be reaped (state = %s)", reap_time_elapsed/1000, DNBStateAsString(GetState()));
467    return true;
468}
469
470bool
471MachProcess::Signal (int signal, const struct timespec *timeout_abstime)
472{
473    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p)", signal, timeout_abstime);
474    nub_state_t state = GetState();
475    if (::kill (ProcessID(), signal) == 0)
476    {
477        // If we were running and we have a timeout, wait for the signal to stop
478        if (IsRunning(state) && timeout_abstime)
479        {
480            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) waiting for signal to stop process...", signal, timeout_abstime);
481            m_private_events.WaitForSetEvents(eEventProcessStoppedStateChanged, timeout_abstime);
482            state = GetState();
483            DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) state = %s", signal, timeout_abstime, DNBStateAsString(state));
484            return !IsRunning (state);
485        }
486        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Signal (signal = %d, timeout = %p) not waiting...", signal, timeout_abstime);
487        return true;
488    }
489    DNBError err(errno, DNBError::POSIX);
490    err.LogThreadedIfError("kill (pid = %d, signo = %i)", ProcessID(), signal);
491    return false;
492
493}
494
495bool
496MachProcess::SendEvent (const char *event, DNBError &send_err)
497{
498    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SendEvent (event = %s) to pid: %d", event, m_pid);
499    if (m_pid == INVALID_NUB_PROCESS)
500        return false;
501#if WITH_BKS
502    return BKSSendEvent (event, send_err);
503#endif
504    return true;
505}
506
507nub_state_t
508MachProcess::DoSIGSTOP (bool clear_bps_and_wps, bool allow_running, uint32_t *thread_idx_ptr)
509{
510    nub_state_t state = GetState();
511    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s", DNBStateAsString (state));
512
513    if (!IsRunning(state))
514    {
515        if (clear_bps_and_wps)
516        {
517            DisableAllBreakpoints (true);
518            DisableAllWatchpoints (true);
519            clear_bps_and_wps = false;
520        }
521
522        // If we already have a thread stopped due to a SIGSTOP, we don't have
523        // to do anything...
524        uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
525        if (thread_idx_ptr)
526            *thread_idx_ptr = thread_idx;
527        if (thread_idx != UINT32_MAX)
528            return GetState();
529
530        // No threads were stopped with a SIGSTOP, we need to run and halt the
531        // process with a signal
532        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- resuming process", DNBStateAsString (state));
533        if (allow_running)
534            m_thread_actions = DNBThreadResumeActions (eStateRunning, 0);
535        else
536            m_thread_actions = DNBThreadResumeActions (eStateSuspended, 0);
537
538        PrivateResume ();
539
540        // Reset the event that says we were indeed running
541        m_events.ResetEvents(eEventProcessRunningStateChanged);
542        state = GetState();
543    }
544
545    // We need to be stopped in order to be able to detach, so we need
546    // to send ourselves a SIGSTOP
547
548    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s -- sending SIGSTOP", DNBStateAsString (state));
549    struct timespec sigstop_timeout;
550    DNBTimer::OffsetTimeOfDay(&sigstop_timeout, 2, 0);
551    Signal (SIGSTOP, &sigstop_timeout);
552    if (clear_bps_and_wps)
553    {
554        DisableAllBreakpoints (true);
555        DisableAllWatchpoints (true);
556        //clear_bps_and_wps = false;
557    }
558    uint32_t thread_idx = m_thread_list.GetThreadIndexForThreadStoppedWithSignal (SIGSTOP);
559    if (thread_idx_ptr)
560        *thread_idx_ptr = thread_idx;
561    return GetState();
562}
563
564bool
565MachProcess::Detach()
566{
567    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach()");
568
569    uint32_t thread_idx = UINT32_MAX;
570    nub_state_t state = DoSIGSTOP(true, true, &thread_idx);
571    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach() DoSIGSTOP() returned %s", DNBStateAsString(state));
572
573    {
574        m_thread_actions.Clear();
575        DNBThreadResumeAction thread_action;
576        thread_action.tid = m_thread_list.ThreadIDAtIndex (thread_idx);
577        thread_action.state = eStateRunning;
578        thread_action.signal = -1;
579        thread_action.addr = INVALID_NUB_ADDRESS;
580
581        m_thread_actions.Append (thread_action);
582        m_thread_actions.SetDefaultThreadActionIfNeeded (eStateRunning, 0);
583
584        PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
585
586        ReplyToAllExceptions ();
587
588    }
589
590    m_task.ShutDownExcecptionThread();
591
592    // Detach from our process
593    errno = 0;
594    nub_process_t pid = m_pid;
595    int ret = ::ptrace (PT_DETACH, pid, (caddr_t)1, 0);
596    DNBError err(errno, DNBError::POSIX);
597    if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail() || (ret != 0))
598        err.LogThreaded("::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);
599
600    // Resume our task
601    m_task.Resume();
602
603    // NULL our task out as we have already retored all exception ports
604    m_task.Clear();
605
606    // Clear out any notion of the process we once were
607    const bool detaching = true;
608    Clear(detaching);
609
610    SetState(eStateDetached);
611
612    return true;
613}
614
615//----------------------------------------------------------------------
616// ReadMemory from the MachProcess level will always remove any software
617// breakpoints from the memory buffer before returning. If you wish to
618// read memory and see those traps, read from the MachTask
619// (m_task.ReadMemory()) as that version will give you what is actually
620// in inferior memory.
621//----------------------------------------------------------------------
622nub_size_t
623MachProcess::ReadMemory (nub_addr_t addr, nub_size_t size, void *buf)
624{
625    // We need to remove any current software traps (enabled software
626    // breakpoints) that we may have placed in our tasks memory.
627
628    // First just read the memory as is
629    nub_size_t bytes_read = m_task.ReadMemory(addr, size, buf);
630
631    // Then place any opcodes that fall into this range back into the buffer
632    // before we return this to callers.
633    if (bytes_read > 0)
634        m_breakpoints.RemoveTrapsFromBuffer (addr, bytes_read, buf);
635    return bytes_read;
636}
637
638//----------------------------------------------------------------------
639// WriteMemory from the MachProcess level will always write memory around
640// any software breakpoints. Any software breakpoints will have their
641// opcodes modified if they are enabled. Any memory that doesn't overlap
642// with software breakpoints will be written to. If you wish to write to
643// inferior memory without this interference, then write to the MachTask
644// (m_task.WriteMemory()) as that version will always modify inferior
645// memory.
646//----------------------------------------------------------------------
647nub_size_t
648MachProcess::WriteMemory (nub_addr_t addr, nub_size_t size, const void *buf)
649{
650    // We need to write any data that would go where any current software traps
651    // (enabled software breakpoints) any software traps (breakpoints) that we
652    // may have placed in our tasks memory.
653
654    std::vector<DNBBreakpoint *> bps;
655
656    const size_t num_bps = m_breakpoints.FindBreakpointsThatOverlapRange(addr, size, bps);
657    if (num_bps == 0)
658        return m_task.WriteMemory(addr, size, buf);
659
660    nub_size_t bytes_written = 0;
661    nub_addr_t intersect_addr;
662    nub_size_t intersect_size;
663    nub_size_t opcode_offset;
664    const uint8_t *ubuf = (const uint8_t *)buf;
665
666    for (size_t i=0; i<num_bps; ++i)
667    {
668        DNBBreakpoint *bp = bps[i];
669
670        const bool intersects = bp->IntersectsRange(addr, size, &intersect_addr, &intersect_size, &opcode_offset);
671        assert(intersects);
672        assert(addr <= intersect_addr && intersect_addr < addr + size);
673        assert(addr < intersect_addr + intersect_size && intersect_addr + intersect_size <= addr + size);
674        assert(opcode_offset + intersect_size <= bp->ByteSize());
675
676        // Check for bytes before this breakpoint
677        const nub_addr_t curr_addr = addr + bytes_written;
678        if (intersect_addr > curr_addr)
679        {
680            // There are some bytes before this breakpoint that we need to
681            // just write to memory
682            nub_size_t curr_size = intersect_addr - curr_addr;
683            nub_size_t curr_bytes_written = m_task.WriteMemory(curr_addr, curr_size, ubuf + bytes_written);
684            bytes_written += curr_bytes_written;
685            if (curr_bytes_written != curr_size)
686            {
687                // We weren't able to write all of the requested bytes, we
688                // are done looping and will return the number of bytes that
689                // we have written so far.
690                break;
691            }
692        }
693
694        // Now write any bytes that would cover up any software breakpoints
695        // directly into the breakpoint opcode buffer
696        ::memcpy(bp->SavedOpcodeBytes() + opcode_offset, ubuf + bytes_written, intersect_size);
697        bytes_written += intersect_size;
698    }
699
700    // Write any remaining bytes after the last breakpoint if we have any left
701    if (bytes_written < size)
702        bytes_written += m_task.WriteMemory(addr + bytes_written, size - bytes_written, ubuf + bytes_written);
703
704    return bytes_written;
705}
706
707void
708MachProcess::ReplyToAllExceptions ()
709{
710    PTHREAD_MUTEX_LOCKER(locker, m_exception_messages_mutex);
711    if (m_exception_messages.empty() == false)
712    {
713        MachException::Message::iterator pos;
714        MachException::Message::iterator begin = m_exception_messages.begin();
715        MachException::Message::iterator end = m_exception_messages.end();
716        for (pos = begin; pos != end; ++pos)
717        {
718            DNBLogThreadedIf(LOG_EXCEPTIONS, "Replying to exception %u...", (uint32_t)std::distance(begin, pos));
719            int thread_reply_signal = 0;
720
721            nub_thread_t tid = m_thread_list.GetThreadIDByMachPortNumber (pos->state.thread_port);
722            const DNBThreadResumeAction *action = NULL;
723            if (tid != INVALID_NUB_THREAD)
724            {
725                action = m_thread_actions.GetActionForThread (tid, false);
726            }
727
728            if (action)
729            {
730                thread_reply_signal = action->signal;
731                if (thread_reply_signal)
732                    m_thread_actions.SetSignalHandledForThread (tid);
733            }
734
735            DNBError err (pos->Reply(this, thread_reply_signal));
736            if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
737                err.LogThreadedIfError("Error replying to exception");
738        }
739
740        // Erase all exception message as we should have used and replied
741        // to them all already.
742        m_exception_messages.clear();
743    }
744}
745void
746MachProcess::PrivateResume ()
747{
748    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
749
750    ReplyToAllExceptions ();
751//    bool stepOverBreakInstruction = step;
752
753    // Let the thread prepare to resume and see if any threads want us to
754    // step over a breakpoint instruction (ProcessWillResume will modify
755    // the value of stepOverBreakInstruction).
756    m_thread_list.ProcessWillResume (this, m_thread_actions);
757
758    // Set our state accordingly
759    if (m_thread_actions.NumActionsWithState(eStateStepping))
760        SetState (eStateStepping);
761    else
762        SetState (eStateRunning);
763
764    // Now resume our task.
765    m_task.Resume();
766}
767
768DNBBreakpoint *
769MachProcess::CreateBreakpoint(nub_addr_t addr, nub_size_t length, bool hardware)
770{
771    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %llu, hardware = %i)", (uint64_t)addr, (uint64_t)length, hardware);
772
773    DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr);
774    if (bp)
775        bp->Retain();
776    else
777        bp =  m_breakpoints.Add(addr, length, hardware);
778
779    if (EnableBreakpoint(addr))
780    {
781        DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = 0x%8.8llx, length = %llu) => %p", (uint64_t)addr, (uint64_t)length, bp);
782        return bp;
783    }
784    else if (bp->Release() == 0)
785    {
786        m_breakpoints.Remove(addr);
787    }
788    // We failed to enable the breakpoint
789    return NULL;
790}
791
792DNBBreakpoint *
793MachProcess::CreateWatchpoint(nub_addr_t addr, nub_size_t length, uint32_t watch_flags, bool hardware)
794{
795    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %llu, flags = 0x%8.8x, hardware = %i)", (uint64_t)addr, (uint64_t)length, watch_flags, hardware);
796
797    DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr);
798    // since the Z packets only send an address, we can only have one watchpoint at
799    // an address. If there is already one, we must refuse to create another watchpoint
800    if (wp)
801        return NULL;
802
803    wp = m_watchpoints.Add(addr, length, hardware);
804    wp->SetIsWatchpoint(watch_flags);
805
806    if (EnableWatchpoint(addr))
807    {
808        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %llu) => %p", (uint64_t)addr, (uint64_t)length, wp);
809        return wp;
810    }
811    else
812    {
813        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = 0x%8.8llx, length = %llu) => FAILED", (uint64_t)addr, (uint64_t)length);
814        m_watchpoints.Remove(addr);
815    }
816    // We failed to enable the watchpoint
817    return NULL;
818}
819
820void
821MachProcess::DisableAllBreakpoints (bool remove)
822{
823    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
824
825    m_breakpoints.DisableAllBreakpoints (this);
826
827    if (remove)
828        m_breakpoints.RemoveDisabled();
829}
830
831void
832MachProcess::DisableAllWatchpoints(bool remove)
833{
834    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s (remove = %d )", __FUNCTION__, remove);
835
836    m_watchpoints.DisableAllWatchpoints(this);
837
838    if (remove)
839        m_watchpoints.RemoveDisabled();
840}
841
842bool
843MachProcess::DisableBreakpoint(nub_addr_t addr, bool remove)
844{
845    DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr);
846    if (bp)
847    {
848        // After "exec" we might end up with a bunch of breakpoints that were disabled
849        // manually, just ignore them
850        if (!bp->IsEnabled())
851        {
852            // Breakpoint might have been disabled by an exec
853            if (remove && bp->Release() == 0)
854            {
855                m_thread_list.NotifyBreakpointChanged(bp);
856                m_breakpoints.Remove(addr);
857            }
858            return true;
859        }
860
861        // We have multiple references to this breakpoint, decrement the ref count
862        // and if it isn't zero, then return true;
863        if (remove && bp->Release() > 0)
864            return true;
865
866        DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d )", (uint64_t)addr, remove);
867
868        if (bp->IsHardware())
869        {
870            bool hw_disable_result = m_thread_list.DisableHardwareBreakpoint (bp);
871
872            if (hw_disable_result == true)
873            {
874                bp->SetEnabled(false);
875                // Let the thread list know that a breakpoint has been modified
876                if (remove)
877                {
878                    m_thread_list.NotifyBreakpointChanged(bp);
879                    m_breakpoints.Remove(addr);
880                }
881                DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) (hardware) => success", (uint64_t)addr, remove);
882                return true;
883            }
884
885            return false;
886        }
887
888        const nub_size_t break_op_size = bp->ByteSize();
889        assert (break_op_size > 0);
890        const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (bp->ByteSize());
891        if (break_op_size > 0)
892        {
893            // Clear a software breakoint instruction
894            uint8_t curr_break_op[break_op_size];
895            bool break_op_found = false;
896
897            // Read the breakpoint opcode
898            if (m_task.ReadMemory(addr, break_op_size, curr_break_op) == break_op_size)
899            {
900                bool verify = false;
901                if (bp->IsEnabled())
902                {
903                    // Make sure we have the a breakpoint opcode exists at this address
904                    if (memcmp(curr_break_op, break_op, break_op_size) == 0)
905                    {
906                        break_op_found = true;
907                        // We found a valid breakpoint opcode at this address, now restore
908                        // the saved opcode.
909                        if (m_task.WriteMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
910                        {
911                            verify = true;
912                        }
913                        else
914                        {
915                            DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) memory write failed when restoring original opcode", (uint64_t)addr, remove);
916                        }
917                    }
918                    else
919                    {
920                        DNBLogWarning("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) expected a breakpoint opcode but didn't find one.", (uint64_t)addr, remove);
921                        // Set verify to true and so we can check if the original opcode has already been restored
922                        verify = true;
923                    }
924                }
925                else
926                {
927                    DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE, "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) is not enabled", (uint64_t)addr, remove);
928                    // Set verify to true and so we can check if the original opcode is there
929                    verify = true;
930                }
931
932                if (verify)
933                {
934                    uint8_t verify_opcode[break_op_size];
935                    // Verify that our original opcode made it back to the inferior
936                    if (m_task.ReadMemory(addr, break_op_size, verify_opcode) == break_op_size)
937                    {
938                        // compare the memory we just read with the original opcode
939                        if (memcmp(bp->SavedOpcodeBytes(), verify_opcode, break_op_size) == 0)
940                        {
941                            // SUCCESS
942                            bp->SetEnabled(false);
943                            // Let the thread list know that a breakpoint has been modified
944                            if (remove && bp->Release() == 0)
945                            {
946                                m_thread_list.NotifyBreakpointChanged(bp);
947                                m_breakpoints.Remove(addr);
948                            }
949                            DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) => success", (uint64_t)addr, remove);
950                            return true;
951                        }
952                        else
953                        {
954                            if (break_op_found)
955                                DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) : failed to restore original opcode", (uint64_t)addr, remove);
956                            else
957                                DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) : opcode changed", (uint64_t)addr, remove);
958                        }
959                    }
960                    else
961                    {
962                        DNBLogWarning("MachProcess::DisableBreakpoint: unable to disable breakpoint 0x%8.8llx", (uint64_t)addr);
963                    }
964                }
965            }
966            else
967            {
968                DNBLogWarning("MachProcess::DisableBreakpoint: unable to read memory at 0x%8.8llx", (uint64_t)addr);
969            }
970        }
971    }
972    else
973    {
974        DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d ) invalid breakpoint address", (uint64_t)addr, remove);
975    }
976    return false;
977}
978
979bool
980MachProcess::DisableWatchpoint(nub_addr_t addr, bool remove)
981{
982    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s(addr = 0x%8.8llx, remove = %d)", __FUNCTION__, (uint64_t)addr, remove);
983    DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr);
984    if (wp)
985    {
986        // If we have multiple references to a watchpoint, removing the watchpoint shouldn't clear it
987        if (remove && wp->Release() > 0)
988            return true;
989
990        nub_addr_t addr = wp->Address();
991        DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::DisableWatchpoint ( addr = 0x%8.8llx, remove = %d )", (uint64_t)addr, remove);
992
993        if (wp->IsHardware())
994        {
995            bool hw_disable_result = m_thread_list.DisableHardwareWatchpoint (wp);
996
997            if (hw_disable_result == true)
998            {
999                wp->SetEnabled(false);
1000                if (remove)
1001                    m_watchpoints.Remove(addr);
1002                DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::Disablewatchpoint ( addr = 0x%8.8llx, remove = %d ) (hardware) => success", (uint64_t)addr, remove);
1003                return true;
1004            }
1005        }
1006
1007        // TODO: clear software watchpoints if we implement them
1008    }
1009    else
1010    {
1011        DNBLogError("MachProcess::DisableWatchpoint ( addr = 0x%8.8llx, remove = %d ) invalid watchpoint ID", (uint64_t)addr, remove);
1012    }
1013    return false;
1014}
1015
1016
1017uint32_t
1018MachProcess::GetNumSupportedHardwareWatchpoints () const
1019{
1020    return m_thread_list.NumSupportedHardwareWatchpoints();
1021}
1022
1023bool
1024MachProcess::EnableBreakpoint(nub_addr_t addr)
1025{
1026    DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( addr = 0x%8.8llx )", (uint64_t)addr);
1027    DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr);
1028    if (bp)
1029    {
1030        if (bp->IsEnabled())
1031        {
1032            DNBLogWarning("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): breakpoint already enabled.", (uint64_t)addr);
1033            return true;
1034        }
1035        else
1036        {
1037            if (bp->HardwarePreferred())
1038            {
1039                bp->SetHardwareIndex(m_thread_list.EnableHardwareBreakpoint(bp));
1040                if (bp->IsHardware())
1041                {
1042                    bp->SetEnabled(true);
1043                    return true;
1044                }
1045            }
1046
1047            const nub_size_t break_op_size = bp->ByteSize();
1048            assert (break_op_size != 0);
1049            const uint8_t * const break_op = DNBArchProtocol::GetBreakpointOpcode (break_op_size);
1050            if (break_op_size > 0)
1051            {
1052                // Save the original opcode by reading it
1053                if (m_task.ReadMemory(addr, break_op_size, bp->SavedOpcodeBytes()) == break_op_size)
1054                {
1055                    // Write a software breakpoint in place of the original opcode
1056                    if (m_task.WriteMemory(addr, break_op_size, break_op) == break_op_size)
1057                    {
1058                        uint8_t verify_break_op[4];
1059                        if (m_task.ReadMemory(addr, break_op_size, verify_break_op) == break_op_size)
1060                        {
1061                            if (memcmp(break_op, verify_break_op, break_op_size) == 0)
1062                            {
1063                                bp->SetEnabled(true);
1064                                // Let the thread list know that a breakpoint has been modified
1065                                m_thread_list.NotifyBreakpointChanged(bp);
1066                                DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ) : SUCCESS.", (uint64_t)addr);
1067                                return true;
1068                            }
1069                            else
1070                            {
1071                                DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): breakpoint opcode verification failed.", (uint64_t)addr);
1072                            }
1073                        }
1074                        else
1075                        {
1076                            DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): unable to read memory to verify breakpoint opcode.", (uint64_t)addr);
1077                        }
1078                    }
1079                    else
1080                    {
1081                        DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): unable to write breakpoint opcode to memory.", (uint64_t)addr);
1082                    }
1083                }
1084                else
1085                {
1086                    DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): unable to read memory at breakpoint address.", (uint64_t)addr);
1087                }
1088            }
1089            else
1090            {
1091                DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ) no software breakpoint opcode for current architecture.", (uint64_t)addr);
1092            }
1093        }
1094    }
1095    return false;
1096}
1097
1098bool
1099MachProcess::EnableWatchpoint(nub_addr_t addr)
1100{
1101    DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::EnableWatchpoint(addr = 0x%8.8llx)", (uint64_t)addr);
1102    DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr);
1103    if (wp)
1104    {
1105        nub_addr_t addr = wp->Address();
1106        if (wp->IsEnabled())
1107        {
1108            DNBLogWarning("MachProcess::EnableWatchpoint(addr = 0x%8.8llx): watchpoint already enabled.", (uint64_t)addr);
1109            return true;
1110        }
1111        else
1112        {
1113            // Currently only try and set hardware watchpoints.
1114            wp->SetHardwareIndex(m_thread_list.EnableHardwareWatchpoint(wp));
1115            if (wp->IsHardware())
1116            {
1117                wp->SetEnabled(true);
1118                return true;
1119            }
1120            // TODO: Add software watchpoints by doing page protection tricks.
1121        }
1122    }
1123    return false;
1124}
1125
1126// Called by the exception thread when an exception has been received from
1127// our process. The exception message is completely filled and the exception
1128// data has already been copied.
1129void
1130MachProcess::ExceptionMessageReceived (const MachException::Message& exceptionMessage)
1131{
1132    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
1133
1134    if (m_exception_messages.empty())
1135        m_task.Suspend();
1136
1137    DNBLogThreadedIf(LOG_EXCEPTIONS, "MachProcess::ExceptionMessageReceived ( )");
1138
1139    // Use a locker to automatically unlock our mutex in case of exceptions
1140    // Add the exception to our internal exception stack
1141    m_exception_messages.push_back(exceptionMessage);
1142}
1143
1144void
1145MachProcess::ExceptionMessageBundleComplete()
1146{
1147    // We have a complete bundle of exceptions for our child process.
1148    PTHREAD_MUTEX_LOCKER (locker, m_exception_messages_mutex);
1149    DNBLogThreadedIf(LOG_EXCEPTIONS, "%s: %llu exception messages.", __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size());
1150    if (!m_exception_messages.empty())
1151    {
1152        m_did_exec = false;
1153        // First check for any SIGTRAP and make sure we didn't exec
1154        const task_t task = m_task.TaskPort();
1155        size_t i;
1156        if (m_pid != 0)
1157        {
1158            for (i=0; i<m_exception_messages.size(); ++i)
1159            {
1160                if (m_exception_messages[i].state.task_port == task)
1161                {
1162                    const int signo = m_exception_messages[i].state.SoftSignal();
1163                    if (signo == SIGTRAP)
1164                    {
1165                        // SIGTRAP could mean that we exec'ed. We need to check the
1166                        // dyld all_image_infos.infoArray to see if it is NULL and if
1167                        // so, say that we exec'ed.
1168                        const nub_addr_t aii_addr = GetDYLDAllImageInfosAddress();
1169                        if (aii_addr != INVALID_NUB_ADDRESS)
1170                        {
1171                            const nub_addr_t info_array_count_addr = aii_addr + 4;
1172                            uint32_t info_array_count = 0;
1173                            if (m_task.ReadMemory(info_array_count_addr, 4, &info_array_count) == 4)
1174                            {
1175                                if (info_array_count == 0)
1176                                    m_did_exec = true;
1177                            }
1178                            else
1179                            {
1180                                DNBLog ("error: failed to read all_image_infos.infoArrayCount from 0x%8.8llx", (uint64_t)info_array_count_addr);
1181                            }
1182                        }
1183                        break;
1184                    }
1185                }
1186            }
1187
1188            if (m_did_exec)
1189            {
1190                cpu_type_t process_cpu_type = MachProcess::GetCPUTypeForLocalProcess (m_pid);
1191                if (m_cpu_type != process_cpu_type)
1192                {
1193                    DNBLog ("arch changed from 0x%8.8x to 0x%8.8x", m_cpu_type, process_cpu_type);
1194                    m_cpu_type = process_cpu_type;
1195                    DNBArchProtocol::SetArchitecture (process_cpu_type);
1196                }
1197                m_thread_list.Clear();
1198                m_breakpoints.DisableAll();
1199            }
1200        }
1201
1202        // Let all threads recover from stopping and do any clean up based
1203        // on the previous thread state (if any).
1204        m_thread_list.ProcessDidStop(this);
1205
1206        // Let each thread know of any exceptions
1207        for (i=0; i<m_exception_messages.size(); ++i)
1208        {
1209            // Let the thread list figure use the MachProcess to forward all exceptions
1210            // on down to each thread.
1211            if (m_exception_messages[i].state.task_port == task)
1212                m_thread_list.NotifyException(m_exception_messages[i].state);
1213            if (DNBLogCheckLogBit(LOG_EXCEPTIONS))
1214                m_exception_messages[i].Dump();
1215        }
1216
1217        if (DNBLogCheckLogBit(LOG_THREAD))
1218            m_thread_list.Dump();
1219
1220        bool step_more = false;
1221        if (m_thread_list.ShouldStop(step_more))
1222        {
1223            // Wait for the eEventProcessRunningStateChanged event to be reset
1224            // before changing state to stopped to avoid race condition with
1225            // very fast start/stops
1226            struct timespec timeout;
1227            //DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000);   // Wait for 250 ms
1228            DNBTimer::OffsetTimeOfDay(&timeout, 1, 0);  // Wait for 250 ms
1229            m_events.WaitForEventsToReset(eEventProcessRunningStateChanged, &timeout);
1230            SetState(eStateStopped);
1231        }
1232        else
1233        {
1234            // Resume without checking our current state.
1235            PrivateResume ();
1236        }
1237    }
1238    else
1239    {
1240        DNBLogThreadedIf(LOG_EXCEPTIONS, "%s empty exception messages bundle (%llu exceptions).", __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size());
1241    }
1242}
1243
1244nub_size_t
1245MachProcess::CopyImageInfos ( struct DNBExecutableImageInfo **image_infos, bool only_changed)
1246{
1247    if (m_image_infos_callback != NULL)
1248        return m_image_infos_callback(ProcessID(), image_infos, only_changed, m_image_infos_baton);
1249    return 0;
1250}
1251
1252void
1253MachProcess::SharedLibrariesUpdated ( )
1254{
1255    uint32_t event_bits = eEventSharedLibsStateChange;
1256    // Set the shared library event bit to let clients know of shared library
1257    // changes
1258    m_events.SetEvents(event_bits);
1259    // Wait for the event bit to reset if a reset ACK is requested
1260    m_events.WaitForResetAck(event_bits);
1261}
1262
1263void
1264MachProcess::AppendSTDOUT (char* s, size_t len)
1265{
1266    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (<%llu> %s) ...", __FUNCTION__, (uint64_t)len, s);
1267    PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1268    m_stdout_data.append(s, len);
1269    m_events.SetEvents(eEventStdioAvailable);
1270
1271    // Wait for the event bit to reset if a reset ACK is requested
1272    m_events.WaitForResetAck(eEventStdioAvailable);
1273}
1274
1275size_t
1276MachProcess::GetAvailableSTDOUT (char *buf, size_t buf_size)
1277{
1278    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__, buf, (uint64_t)buf_size);
1279    PTHREAD_MUTEX_LOCKER (locker, m_stdio_mutex);
1280    size_t bytes_available = m_stdout_data.size();
1281    if (bytes_available > 0)
1282    {
1283        if (bytes_available > buf_size)
1284        {
1285            memcpy(buf, m_stdout_data.data(), buf_size);
1286            m_stdout_data.erase(0, buf_size);
1287            bytes_available = buf_size;
1288        }
1289        else
1290        {
1291            memcpy(buf, m_stdout_data.data(), bytes_available);
1292            m_stdout_data.clear();
1293        }
1294    }
1295    return bytes_available;
1296}
1297
1298nub_addr_t
1299MachProcess::GetDYLDAllImageInfosAddress ()
1300{
1301    DNBError err;
1302    return m_task.GetDYLDAllImageInfosAddress(err);
1303}
1304
1305size_t
1306MachProcess::GetAvailableSTDERR (char *buf, size_t buf_size)
1307{
1308    return 0;
1309}
1310
1311void *
1312MachProcess::STDIOThread(void *arg)
1313{
1314    MachProcess *proc = (MachProcess*) arg;
1315    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg);
1316
1317    // We start use a base and more options so we can control if we
1318    // are currently using a timeout on the mach_msg. We do this to get a
1319    // bunch of related exceptions on our exception port so we can process
1320    // then together. When we have multiple threads, we can get an exception
1321    // per thread and they will come in consecutively. The main thread loop
1322    // will start by calling mach_msg to without having the MACH_RCV_TIMEOUT
1323    // flag set in the options, so we will wait forever for an exception on
1324    // our exception port. After we get one exception, we then will use the
1325    // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current
1326    // exceptions for our process. After we have received the last pending
1327    // exception, we will get a timeout which enables us to then notify
1328    // our main thread that we have an exception bundle avaiable. We then wait
1329    // for the main thread to tell this exception thread to start trying to get
1330    // exceptions messages again and we start again with a mach_msg read with
1331    // infinite timeout.
1332    DNBError err;
1333    int stdout_fd = proc->GetStdoutFileDescriptor();
1334    int stderr_fd = proc->GetStderrFileDescriptor();
1335    if (stdout_fd == stderr_fd)
1336        stderr_fd = -1;
1337
1338    while (stdout_fd >= 0 || stderr_fd >= 0)
1339    {
1340        ::pthread_testcancel ();
1341
1342        fd_set read_fds;
1343        FD_ZERO (&read_fds);
1344        if (stdout_fd >= 0)
1345            FD_SET (stdout_fd, &read_fds);
1346        if (stderr_fd >= 0)
1347            FD_SET (stderr_fd, &read_fds);
1348        int nfds = std::max<int>(stdout_fd, stderr_fd) + 1;
1349
1350        int num_set_fds = select (nfds, &read_fds, NULL, NULL, NULL);
1351        DNBLogThreadedIf(LOG_PROCESS, "select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1352
1353        if (num_set_fds < 0)
1354        {
1355            int select_errno = errno;
1356            if (DNBLogCheckLogBit(LOG_PROCESS))
1357            {
1358                err.SetError (select_errno, DNBError::POSIX);
1359                err.LogThreadedIfError("select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);
1360            }
1361
1362            switch (select_errno)
1363            {
1364            case EAGAIN:    // The kernel was (perhaps temporarily) unable to allocate the requested number of file descriptors, or we have non-blocking IO
1365                break;
1366            case EBADF:     // One of the descriptor sets specified an invalid descriptor.
1367                return NULL;
1368                break;
1369            case EINTR:     // A signal was delivered before the time limit expired and before any of the selected events occurred.
1370            case EINVAL:    // The specified time limit is invalid. One of its components is negative or too large.
1371            default:        // Other unknown error
1372                break;
1373            }
1374        }
1375        else if (num_set_fds == 0)
1376        {
1377        }
1378        else
1379        {
1380            char s[1024];
1381            s[sizeof(s)-1] = '\0';  // Ensure we have NULL termination
1382            int bytes_read = 0;
1383            if (stdout_fd >= 0 && FD_ISSET (stdout_fd, &read_fds))
1384            {
1385                do
1386                {
1387                    bytes_read = ::read (stdout_fd, s, sizeof(s)-1);
1388                    if (bytes_read < 0)
1389                    {
1390                        int read_errno = errno;
1391                        DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d   errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1392                    }
1393                    else if (bytes_read == 0)
1394                    {
1395                        // EOF...
1396                        DNBLogThreadedIf(LOG_PROCESS, "read (stdout_fd, ) => %d  (reached EOF for child STDOUT)", bytes_read);
1397                        stdout_fd = -1;
1398                    }
1399                    else if (bytes_read > 0)
1400                    {
1401                        proc->AppendSTDOUT(s, bytes_read);
1402                    }
1403
1404                } while (bytes_read > 0);
1405            }
1406
1407            if (stderr_fd >= 0 && FD_ISSET (stderr_fd, &read_fds))
1408            {
1409                do
1410                {
1411                    bytes_read = ::read (stderr_fd, s, sizeof(s)-1);
1412                    if (bytes_read < 0)
1413                    {
1414                        int read_errno = errno;
1415                        DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d   errno: %d (%s)", bytes_read, read_errno, strerror(read_errno));
1416                    }
1417                    else if (bytes_read == 0)
1418                    {
1419                        // EOF...
1420                        DNBLogThreadedIf(LOG_PROCESS, "read (stderr_fd, ) => %d  (reached EOF for child STDERR)", bytes_read);
1421                        stderr_fd = -1;
1422                    }
1423                    else if (bytes_read > 0)
1424                    {
1425                        proc->AppendSTDOUT(s, bytes_read);
1426                    }
1427
1428                } while (bytes_read > 0);
1429            }
1430        }
1431    }
1432    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%p): thread exiting...", __FUNCTION__, arg);
1433    return NULL;
1434}
1435
1436
1437void
1438MachProcess::SignalAsyncProfileData (const char *info)
1439{
1440    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%s) ...", __FUNCTION__, info);
1441    PTHREAD_MUTEX_LOCKER (locker, m_profile_data_mutex);
1442    m_profile_data.push_back(info);
1443    m_events.SetEvents(eEventProfileDataAvailable);
1444
1445    // Wait for the event bit to reset if a reset ACK is requested
1446    m_events.WaitForResetAck(eEventProfileDataAvailable);
1447}
1448
1449
1450size_t
1451MachProcess::GetAsyncProfileData (char *buf, size_t buf_size)
1452{
1453    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__, buf, (uint64_t)buf_size);
1454    PTHREAD_MUTEX_LOCKER (locker, m_profile_data_mutex);
1455    if (m_profile_data.empty())
1456        return 0;
1457
1458    size_t bytes_available = m_profile_data.front().size();
1459    if (bytes_available > 0)
1460    {
1461        if (bytes_available > buf_size)
1462        {
1463            memcpy(buf, m_profile_data.front().data(), buf_size);
1464            m_profile_data.front().erase(0, buf_size);
1465            bytes_available = buf_size;
1466        }
1467        else
1468        {
1469            memcpy(buf, m_profile_data.front().data(), bytes_available);
1470            m_profile_data.erase(m_profile_data.begin());
1471        }
1472    }
1473    return bytes_available;
1474}
1475
1476
1477void *
1478MachProcess::ProfileThread(void *arg)
1479{
1480    MachProcess *proc = (MachProcess*) arg;
1481    DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( arg = %p ) thread starting...", __FUNCTION__, arg);
1482
1483    while (proc->IsProfilingEnabled())
1484    {
1485        nub_state_t state = proc->GetState();
1486        if (state == eStateRunning)
1487        {
1488            std::string data = proc->Task().GetProfileData(proc->GetProfileScanType());
1489            if (!data.empty())
1490            {
1491                proc->SignalAsyncProfileData(data.c_str());
1492            }
1493        }
1494        else if ((state == eStateUnloaded) || (state == eStateDetached) || (state == eStateUnloaded))
1495        {
1496            // Done. Get out of this thread.
1497            break;
1498        }
1499
1500        // A simple way to set up the profile interval. We can also use select() or dispatch timer source if necessary.
1501        usleep(proc->ProfileInterval());
1502    }
1503    return NULL;
1504}
1505
1506
1507pid_t
1508MachProcess::AttachForDebug (pid_t pid, char *err_str, size_t err_len)
1509{
1510    // Clear out and clean up from any current state
1511    Clear();
1512    if (pid != 0)
1513    {
1514        DNBError err;
1515        // Make sure the process exists...
1516        if (::getpgid (pid) < 0)
1517        {
1518            err.SetErrorToErrno();
1519            const char *err_cstr = err.AsString();
1520            ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "No such process");
1521            return INVALID_NUB_PROCESS;
1522        }
1523
1524        SetState(eStateAttaching);
1525        m_pid = pid;
1526        // Let ourselves know we are going to be using SBS or BKS if the correct flag bit is set...
1527#if defined (WITH_BKS)
1528        if (IsBKSProcess (pid))
1529            m_flags |= eMachProcessFlagsUsingBKS;
1530#elif defined (WITH_SPRINGBOARD)
1531        if (IsSBProcess(pid))
1532            m_flags |= eMachProcessFlagsUsingSBS;
1533#endif
1534        if (!m_task.StartExceptionThread(err))
1535        {
1536            const char *err_cstr = err.AsString();
1537            ::snprintf (err_str, err_len, "%s", err_cstr ? err_cstr : "unable to start the exception thread");
1538            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1539            m_pid = INVALID_NUB_PROCESS;
1540            return INVALID_NUB_PROCESS;
1541        }
1542
1543        errno = 0;
1544        if (::ptrace (PT_ATTACHEXC, pid, 0, 0))
1545            err.SetError(errno);
1546        else
1547            err.Clear();
1548
1549        if (err.Success())
1550        {
1551            m_flags |= eMachProcessFlagsAttached;
1552            // Sleep a bit to let the exception get received and set our process status
1553            // to stopped.
1554            ::usleep(250000);
1555            DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", pid);
1556            return m_pid;
1557        }
1558        else
1559        {
1560            ::snprintf (err_str, err_len, "%s", err.AsString());
1561            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);
1562        }
1563    }
1564    return INVALID_NUB_PROCESS;
1565}
1566
1567// Do the process specific setup for attach.  If this returns NULL, then there's no
1568// platform specific stuff to be done to wait for the attach.  If you get non-null,
1569// pass that token to the CheckForProcess method, and then to CleanupAfterAttach.
1570
1571//  Call PrepareForAttach before attaching to a process that has not yet launched
1572// This returns a token that can be passed to CheckForProcess, and to CleanupAfterAttach.
1573// You should call CleanupAfterAttach to free the token, and do whatever other
1574// cleanup seems good.
1575
1576const void *
1577MachProcess::PrepareForAttach (const char *path, nub_launch_flavor_t launch_flavor, bool waitfor, DNBError &attach_err)
1578{
1579#if defined (WITH_SPRINGBOARD) || defined (WITH_BKS)
1580    // Tell SpringBoard to halt the next launch of this application on startup.
1581
1582    if (!waitfor)
1583        return NULL;
1584
1585    const char *app_ext = strstr(path, ".app");
1586    const bool is_app = app_ext != NULL && (app_ext[4] == '\0' || app_ext[4] == '/');
1587    if (!is_app)
1588    {
1589        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::PrepareForAttach(): path '%s' doesn't contain .app, "
1590                                      "we can't tell springboard to wait for launch...",
1591                                      path);
1592        return NULL;
1593    }
1594
1595#if defined (WITH_BKS)
1596    if (launch_flavor == eLaunchFlavorDefault)
1597        launch_flavor = eLaunchFlavorBKS;
1598    if (launch_flavor != eLaunchFlavorBKS)
1599        return NULL;
1600#elif defined (WITH_SPRINGBOARD)
1601    if (launch_flavor == eLaunchFlavorDefault)
1602        launch_flavor = eLaunchFlavorSpringBoard;
1603    if (launch_flavor != eLaunchFlavorSpringBoard)
1604        return NULL;
1605#endif
1606
1607    std::string app_bundle_path(path, app_ext + strlen(".app"));
1608
1609    CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path.c_str (), attach_err);
1610    std::string bundleIDStr;
1611    CFString::UTF8(bundleIDCFStr, bundleIDStr);
1612    DNBLogThreadedIf(LOG_PROCESS,
1613                     "CopyBundleIDForPath (%s, err_str) returned @\"%s\"",
1614                     app_bundle_path.c_str (),
1615                     bundleIDStr.c_str());
1616
1617    if (bundleIDCFStr == NULL)
1618    {
1619        return NULL;
1620    }
1621
1622#if defined (WITH_BKS)
1623    if (launch_flavor == eLaunchFlavorBKS)
1624    {
1625        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
1626
1627        NSString *stdio_path = nil;
1628        NSFileManager *file_manager = [NSFileManager defaultManager];
1629        const char *null_path = "/dev/null";
1630        stdio_path = [file_manager stringWithFileSystemRepresentation: null_path length: strlen(null_path)];
1631
1632        NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];
1633        NSMutableDictionary *options       = [NSMutableDictionary dictionary];
1634
1635        DNBLogThreadedIf(LOG_PROCESS, "Calling BKSSystemService openApplication: @\"%s\",options include stdio path: \"%s\", "
1636                                      "BKSDebugOptionKeyDebugOnNextLaunch & BKSDebugOptionKeyWaitForDebugger )",
1637                                      bundleIDStr.c_str(),
1638                                      null_path);
1639
1640        [debug_options setObject: stdio_path forKey: BKSDebugOptionKeyStandardOutPath];
1641        [debug_options setObject: stdio_path forKey: BKSDebugOptionKeyStandardErrorPath];
1642        [debug_options setObject: [NSNumber numberWithBool: YES] forKey: BKSDebugOptionKeyWaitForDebugger];
1643        [debug_options setObject: [NSNumber numberWithBool: YES] forKey: BKSDebugOptionKeyDebugOnNextLaunch];
1644
1645        [options setObject: debug_options forKey: BKSOpenApplicationOptionKeyDebuggingOptions];
1646
1647        BKSSystemService *system_service = [[BKSSystemService alloc] init];
1648
1649        mach_port_t client_port = [system_service createClientPort];
1650        __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
1651        __block BKSOpenApplicationErrorCode attach_error_code = BKSOpenApplicationErrorCodeNone;
1652
1653        NSString *bundleIDNSStr = (NSString *) bundleIDCFStr;
1654
1655        [system_service openApplication: bundleIDNSStr
1656                       options: options
1657                       clientPort: client_port
1658                       withResult: ^(NSError *error)
1659                       {
1660                            // The system service will cleanup the client port we created for us.
1661                            if (error)
1662                                attach_error_code = (BKSOpenApplicationErrorCode)[error code];
1663
1664                            [system_service release];
1665                            dispatch_semaphore_signal(semaphore);
1666                        }
1667        ];
1668
1669        const uint32_t timeout_secs = 9;
1670
1671        dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC);
1672
1673        long success = dispatch_semaphore_wait(semaphore, timeout) == 0;
1674
1675        if (!success)
1676        {
1677            DNBLogError("timed out trying to launch %s.", bundleIDStr.c_str());
1678            attach_err.SetErrorString("debugserver timed out waiting for openApplication to complete.");
1679            attach_err.SetError (BKS_OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic);
1680        }
1681        else if (attach_error_code != BKSOpenApplicationErrorCodeNone)
1682        {
1683            SetBKSError (attach_error_code, attach_err);
1684            DNBLogError("unable to launch the application with CFBundleIdentifier '%s' bks_error = %u",
1685                        bundleIDStr.c_str(),
1686                        attach_error_code);
1687        }
1688        dispatch_release(semaphore);
1689        [pool drain];
1690    }
1691#elif defined (WITH_SPRINGBOARD)
1692    if (launch_flavor == eLaunchFlavorSpringBoard)
1693    {
1694        SBSApplicationLaunchError sbs_error = 0;
1695
1696        const char *stdout_err = "/dev/null";
1697        CFString stdio_path;
1698        stdio_path.SetFileSystemRepresentation (stdout_err);
1699
1700        DNBLogThreadedIf(LOG_PROCESS, "SBSLaunchApplicationForDebugging ( @\"%s\" , NULL, NULL, NULL, @\"%s\", @\"%s\", "
1701                                      "SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger )",
1702                                      bundleIDStr.c_str(),
1703                                      stdout_err,
1704                                      stdout_err);
1705
1706        sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1707                                                      (CFURLRef)NULL,         // openURL
1708                                                      NULL, // launch_argv.get(),
1709                                                      NULL, // launch_envp.get(),  // CFDictionaryRef environment
1710                                                      stdio_path.get(),
1711                                                      stdio_path.get(),
1712                                                      SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger);
1713
1714        if (sbs_error != SBSApplicationLaunchErrorSuccess)
1715        {
1716            attach_err.SetError(sbs_error, DNBError::SpringBoard);
1717            return NULL;
1718        }
1719    }
1720#endif // WITH_SPRINGBOARD
1721
1722    DNBLogThreadedIf(LOG_PROCESS, "Successfully set DebugOnNextLaunch.");
1723    return bundleIDCFStr;
1724# else  // defined (WITH_SPRINGBOARD) || defined (WITH_BKS)
1725  return NULL;
1726#endif
1727}
1728
1729// Pass in the token you got from PrepareForAttach.  If there is a process
1730// for that token, then the pid will be returned, otherwise INVALID_NUB_PROCESS
1731// will be returned.
1732
1733nub_process_t
1734MachProcess::CheckForProcess (const void *attach_token)
1735{
1736    if (attach_token == NULL)
1737        return INVALID_NUB_PROCESS;
1738
1739#if defined (WITH_BKS)
1740    NSString *bundleIDNSStr = (NSString *) attach_token;
1741    BKSSystemService *systemService = [[BKSSystemService alloc] init];
1742    pid_t pid = [systemService pidForApplication: bundleIDNSStr];
1743    [systemService release];
1744    if (pid == 0)
1745        return INVALID_NUB_PROCESS;
1746    else
1747        return pid;
1748#elif defined (WITH_SPRINGBOARD)
1749    CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1750    Boolean got_it;
1751    nub_process_t attach_pid;
1752    got_it = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &attach_pid);
1753    if (got_it)
1754        return attach_pid;
1755    else
1756        return INVALID_NUB_PROCESS;
1757#else
1758    return INVALID_NUB_PROCESS;
1759#endif
1760}
1761
1762// Call this to clean up after you have either attached or given up on the attach.
1763// Pass true for success if you have attached, false if you have not.
1764// The token will also be freed at this point, so you can't use it after calling
1765// this method.
1766
1767void
1768MachProcess::CleanupAfterAttach (const void *attach_token, bool success, DNBError &err_str)
1769{
1770    if (attach_token == NULL)
1771        return;
1772
1773#if defined (WITH_BKS)
1774
1775    if (!success)
1776    {
1777        BKSCleanupAfterAttach (attach_token, err_str);
1778    }
1779    CFRelease((CFStringRef) attach_token);
1780
1781#elif defined (WITH_SPRINGBOARD)
1782    // Tell SpringBoard to cancel the debug on next launch of this application
1783    // if we failed to attach
1784    if (!success)
1785    {
1786        SBSApplicationLaunchError sbs_error = 0;
1787        CFStringRef bundleIDCFStr = (CFStringRef) attach_token;
1788
1789        sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
1790                                                      (CFURLRef)NULL,
1791                                                      NULL,
1792                                                      NULL,
1793                                                      NULL,
1794                                                      NULL,
1795                                                      SBSApplicationCancelDebugOnNextLaunch);
1796
1797        if (sbs_error != SBSApplicationLaunchErrorSuccess)
1798        {
1799            err_str.SetError(sbs_error, DNBError::SpringBoard);
1800            return;
1801        }
1802    }
1803
1804    CFRelease((CFStringRef) attach_token);
1805#endif
1806}
1807
1808pid_t
1809MachProcess::LaunchForDebug
1810(
1811    const char *path,
1812    char const *argv[],
1813    char const *envp[],
1814    const char *working_directory, // NULL => dont' change, non-NULL => set working directory for inferior to this
1815    const char *stdin_path,
1816    const char *stdout_path,
1817    const char *stderr_path,
1818    bool no_stdio,
1819    nub_launch_flavor_t launch_flavor,
1820    int disable_aslr,
1821    const char *event_data,
1822    DNBError &launch_err
1823)
1824{
1825    // Clear out and clean up from any current state
1826    Clear();
1827
1828    DNBLogThreadedIf(LOG_PROCESS, "%s( path = '%s', argv = %p, envp = %p, launch_flavor = %u, disable_aslr = %d )", __FUNCTION__, path, argv, envp, launch_flavor, disable_aslr);
1829
1830    // Fork a child process for debugging
1831    SetState(eStateLaunching);
1832
1833    switch (launch_flavor)
1834    {
1835    case eLaunchFlavorForkExec:
1836        m_pid = MachProcess::ForkChildForPTraceDebugging (path, argv, envp, this, launch_err);
1837        break;
1838#ifdef WITH_BKS
1839    case eLaunchFlavorBKS:
1840        {
1841            const char *app_ext = strstr(path, ".app");
1842            if (app_ext && (app_ext[4] == '\0' || app_ext[4] == '/'))
1843            {
1844                std::string app_bundle_path(path, app_ext + strlen(".app"));
1845                if (BKSLaunchForDebug (app_bundle_path.c_str(), argv, envp, no_stdio, disable_aslr, event_data, launch_err) != 0)
1846                    return m_pid; // A successful SBLaunchForDebug() returns and assigns a non-zero m_pid.
1847                else
1848                    break; // We tried a BKS launch, but didn't succeed lets get out
1849            }
1850        }
1851        // In case the executable name has a ".app" fragment which confuses our debugserver,
1852        // let's do an intentional fallthrough here...
1853        launch_flavor = eLaunchFlavorPosixSpawn;
1854#endif
1855#ifdef WITH_SPRINGBOARD
1856
1857    case eLaunchFlavorSpringBoard:
1858        {
1859            //  .../whatever.app/whatever ?
1860            //  Or .../com.apple.whatever.app/whatever -- be careful of ".app" in "com.apple.whatever" here
1861            const char *app_ext = strstr (path, ".app/");
1862            if (app_ext == NULL)
1863            {
1864                // .../whatever.app ?
1865                int len = strlen (path);
1866                if (len > 5)
1867                {
1868                    if (strcmp (path + len - 4, ".app") == 0)
1869                    {
1870                        app_ext = path + len - 4;
1871                    }
1872                }
1873            }
1874            if (app_ext)
1875            {
1876                std::string app_bundle_path(path, app_ext + strlen(".app"));
1877                if (SBLaunchForDebug (app_bundle_path.c_str(), argv, envp, no_stdio, disable_aslr, launch_err) != 0)
1878                    return m_pid; // A successful SBLaunchForDebug() returns and assigns a non-zero m_pid.
1879                else
1880                    break; // We tried a springboard launch, but didn't succeed lets get out
1881            }
1882        }
1883        // In case the executable name has a ".app" fragment which confuses our debugserver,
1884        // let's do an intentional fallthrough here...
1885        launch_flavor = eLaunchFlavorPosixSpawn;
1886
1887#endif
1888
1889    case eLaunchFlavorPosixSpawn:
1890        m_pid = MachProcess::PosixSpawnChildForPTraceDebugging (path,
1891                                                                DNBArchProtocol::GetArchitecture (),
1892                                                                argv,
1893                                                                envp,
1894                                                                working_directory,
1895                                                                stdin_path,
1896                                                                stdout_path,
1897                                                                stderr_path,
1898                                                                no_stdio,
1899                                                                this,
1900                                                                disable_aslr,
1901                                                                launch_err);
1902        break;
1903
1904    default:
1905        // Invalid  launch
1906        launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1907        return INVALID_NUB_PROCESS;
1908    }
1909
1910    if (m_pid == INVALID_NUB_PROCESS)
1911    {
1912        // If we don't have a valid process ID and no one has set the error,
1913        // then return a generic error
1914        if (launch_err.Success())
1915            launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1916    }
1917    else
1918    {
1919        m_path = path;
1920        size_t i;
1921        char const *arg;
1922        for (i=0; (arg = argv[i]) != NULL; i++)
1923            m_args.push_back(arg);
1924
1925        m_task.StartExceptionThread(launch_err);
1926        if (launch_err.Fail())
1927        {
1928            if (launch_err.AsString() == NULL)
1929                launch_err.SetErrorString("unable to start the exception thread");
1930            DNBLog ("Could not get inferior's Mach exception port, sending ptrace PT_KILL and exiting.");
1931            ::ptrace (PT_KILL, m_pid, 0, 0);
1932            m_pid = INVALID_NUB_PROCESS;
1933            return INVALID_NUB_PROCESS;
1934        }
1935
1936        StartSTDIOThread();
1937
1938        if (launch_flavor == eLaunchFlavorPosixSpawn)
1939        {
1940
1941            SetState (eStateAttaching);
1942            errno = 0;
1943            int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
1944            if (err == 0)
1945            {
1946                m_flags |= eMachProcessFlagsAttached;
1947                DNBLogThreadedIf(LOG_PROCESS, "successfully spawned pid %d", m_pid);
1948                launch_err.Clear();
1949            }
1950            else
1951            {
1952                SetState (eStateExited);
1953                DNBError ptrace_err(errno, DNBError::POSIX);
1954                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());
1955                launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);
1956            }
1957        }
1958        else
1959        {
1960            launch_err.Clear();
1961        }
1962    }
1963    return m_pid;
1964}
1965
1966pid_t
1967MachProcess::PosixSpawnChildForPTraceDebugging
1968(
1969    const char *path,
1970    cpu_type_t cpu_type,
1971    char const *argv[],
1972    char const *envp[],
1973    const char *working_directory,
1974    const char *stdin_path,
1975    const char *stdout_path,
1976    const char *stderr_path,
1977    bool no_stdio,
1978    MachProcess* process,
1979    int disable_aslr,
1980    DNBError& err
1981)
1982{
1983    posix_spawnattr_t attr;
1984    short flags;
1985    DNBLogThreadedIf(LOG_PROCESS, "%s ( path='%s', argv=%p, envp=%p, working_dir=%s, stdin=%s, stdout=%s stderr=%s, no-stdio=%i)",
1986                     __FUNCTION__,
1987                     path,
1988                     argv,
1989                     envp,
1990                     working_directory,
1991                     stdin_path,
1992                     stdout_path,
1993                     stderr_path,
1994                     no_stdio);
1995
1996    err.SetError( ::posix_spawnattr_init (&attr), DNBError::POSIX);
1997    if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
1998        err.LogThreaded("::posix_spawnattr_init ( &attr )");
1999    if (err.Fail())
2000        return INVALID_NUB_PROCESS;
2001
2002    flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK;
2003    if (disable_aslr)
2004        flags |= _POSIX_SPAWN_DISABLE_ASLR;
2005
2006    sigset_t no_signals;
2007    sigset_t all_signals;
2008    sigemptyset (&no_signals);
2009    sigfillset (&all_signals);
2010    ::posix_spawnattr_setsigmask(&attr, &no_signals);
2011    ::posix_spawnattr_setsigdefault(&attr, &all_signals);
2012
2013    err.SetError( ::posix_spawnattr_setflags (&attr, flags), DNBError::POSIX);
2014    if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
2015        err.LogThreaded("::posix_spawnattr_setflags ( &attr, POSIX_SPAWN_START_SUSPENDED%s )", flags & _POSIX_SPAWN_DISABLE_ASLR ? " | _POSIX_SPAWN_DISABLE_ASLR" : "");
2016    if (err.Fail())
2017        return INVALID_NUB_PROCESS;
2018
2019    // Don't do this on SnowLeopard, _sometimes_ the TASK_BASIC_INFO will fail
2020    // and we will fail to continue with our process...
2021
2022    // On SnowLeopard we should set "DYLD_NO_PIE" in the inferior environment....
2023
2024#if !defined(__arm__)
2025
2026    // We don't need to do this for ARM, and we really shouldn't now that we
2027    // have multiple CPU subtypes and no posix_spawnattr call that allows us
2028    // to set which CPU subtype to launch...
2029    if (cpu_type != 0)
2030    {
2031        size_t ocount = 0;
2032        err.SetError( ::posix_spawnattr_setbinpref_np (&attr, 1, &cpu_type, &ocount), DNBError::POSIX);
2033        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
2034            err.LogThreaded("::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = 0x%8.8x, count => %llu )", cpu_type, (uint64_t)ocount);
2035
2036        if (err.Fail() != 0 || ocount != 1)
2037            return INVALID_NUB_PROCESS;
2038    }
2039#endif
2040
2041    PseudoTerminal pty;
2042
2043    posix_spawn_file_actions_t file_actions;
2044    err.SetError( ::posix_spawn_file_actions_init (&file_actions), DNBError::POSIX);
2045    int file_actions_valid = err.Success();
2046    if (!file_actions_valid || DNBLogCheckLogBit(LOG_PROCESS))
2047        err.LogThreaded("::posix_spawn_file_actions_init ( &file_actions )");
2048    int pty_error = -1;
2049    pid_t pid = INVALID_NUB_PROCESS;
2050    if (file_actions_valid)
2051    {
2052        if (stdin_path == NULL && stdout_path == NULL && stderr_path == NULL && !no_stdio)
2053        {
2054            pty_error = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
2055            if (pty_error == PseudoTerminal::success)
2056            {
2057                stdin_path = stdout_path = stderr_path = pty.SlaveName();
2058            }
2059        }
2060
2061        // if no_stdio or std paths not supplied, then route to "/dev/null".
2062        if (no_stdio || stdin_path == NULL || stdin_path[0] == '\0')
2063            stdin_path = "/dev/null";
2064        if (no_stdio || stdout_path == NULL || stdout_path[0] == '\0')
2065            stdout_path = "/dev/null";
2066        if (no_stdio || stderr_path == NULL || stderr_path[0] == '\0')
2067            stderr_path = "/dev/null";
2068
2069        err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
2070                                                          STDIN_FILENO,
2071                                                          stdin_path,
2072                                                          O_RDONLY | O_NOCTTY,
2073                                                          0),
2074                     DNBError::POSIX);
2075        if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
2076            err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDIN_FILENO, path='%s')", stdin_path);
2077
2078        err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
2079                                                          STDOUT_FILENO,
2080                                                          stdout_path,
2081                                                          O_WRONLY | O_NOCTTY | O_CREAT,
2082                                                          0640),
2083                     DNBError::POSIX);
2084        if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
2085            err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDOUT_FILENO, path='%s')", stdout_path);
2086
2087        err.SetError( ::posix_spawn_file_actions_addopen (&file_actions,
2088                                                          STDERR_FILENO,
2089                                                          stderr_path,
2090                                                          O_WRONLY | O_NOCTTY | O_CREAT,
2091                                                          0640),
2092                     DNBError::POSIX);
2093        if (err.Fail() || DNBLogCheckLogBit (LOG_PROCESS))
2094            err.LogThreaded ("::posix_spawn_file_actions_addopen (&file_actions, filedes=STDERR_FILENO, path='%s')", stderr_path);
2095
2096        // TODO: Verify if we can set the working directory back immediately
2097        // after the posix_spawnp call without creating a race condition???
2098        if (working_directory)
2099            ::chdir (working_directory);
2100
2101        err.SetError( ::posix_spawnp (&pid, path, &file_actions, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
2102        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
2103            err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, &file_actions, &attr, argv, envp);
2104    }
2105    else
2106    {
2107        // TODO: Verify if we can set the working directory back immediately
2108        // after the posix_spawnp call without creating a race condition???
2109        if (working_directory)
2110            ::chdir (working_directory);
2111
2112        err.SetError( ::posix_spawnp (&pid, path, NULL, &attr, (char * const*)argv, (char * const*)envp), DNBError::POSIX);
2113        if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
2114            err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = %p, attr = %p, argv = %p, envp = %p )", pid, path, NULL, &attr, argv, envp);
2115    }
2116
2117    // We have seen some cases where posix_spawnp was returning a valid
2118    // looking pid even when an error was returned, so clear it out
2119    if (err.Fail())
2120        pid = INVALID_NUB_PROCESS;
2121
2122    if (pty_error == 0)
2123    {
2124        if (process != NULL)
2125        {
2126            int master_fd = pty.ReleaseMasterFD();
2127            process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
2128        }
2129    }
2130    ::posix_spawnattr_destroy (&attr);
2131
2132    if (pid != INVALID_NUB_PROCESS)
2133    {
2134        cpu_type_t pid_cpu_type = MachProcess::GetCPUTypeForLocalProcess (pid);
2135        DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( ) pid=%i, cpu_type=0x%8.8x", __FUNCTION__, pid, pid_cpu_type);
2136        if (pid_cpu_type)
2137            DNBArchProtocol::SetArchitecture (pid_cpu_type);
2138    }
2139
2140    if (file_actions_valid)
2141    {
2142        DNBError err2;
2143        err2.SetError( ::posix_spawn_file_actions_destroy (&file_actions), DNBError::POSIX);
2144        if (err2.Fail() || DNBLogCheckLogBit(LOG_PROCESS))
2145            err2.LogThreaded("::posix_spawn_file_actions_destroy ( &file_actions )");
2146    }
2147
2148    return pid;
2149}
2150
2151uint32_t
2152MachProcess::GetCPUTypeForLocalProcess (pid_t pid)
2153{
2154    int mib[CTL_MAXNAME]={0,};
2155    size_t len = CTL_MAXNAME;
2156    if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))
2157        return 0;
2158
2159    mib[len] = pid;
2160    len++;
2161
2162    cpu_type_t cpu;
2163    size_t cpu_len = sizeof(cpu);
2164    if (::sysctl (mib, len, &cpu, &cpu_len, 0, 0))
2165        cpu = 0;
2166    return cpu;
2167}
2168
2169pid_t
2170MachProcess::ForkChildForPTraceDebugging
2171(
2172    const char *path,
2173    char const *argv[],
2174    char const *envp[],
2175    MachProcess* process,
2176    DNBError& launch_err
2177)
2178{
2179    PseudoTerminal::Error pty_error = PseudoTerminal::success;
2180
2181    // Use a fork that ties the child process's stdin/out/err to a pseudo
2182    // terminal so we can read it in our MachProcess::STDIOThread
2183    // as unbuffered io.
2184    PseudoTerminal pty;
2185    pid_t pid = pty.Fork(pty_error);
2186
2187    if (pid < 0)
2188    {
2189        //--------------------------------------------------------------
2190        // Error during fork.
2191        //--------------------------------------------------------------
2192        return pid;
2193    }
2194    else if (pid == 0)
2195    {
2196        //--------------------------------------------------------------
2197        // Child process
2198        //--------------------------------------------------------------
2199        ::ptrace (PT_TRACE_ME, 0, 0, 0);    // Debug this process
2200        ::ptrace (PT_SIGEXC, 0, 0, 0);    // Get BSD signals as mach exceptions
2201
2202        // If our parent is setgid, lets make sure we don't inherit those
2203        // extra powers due to nepotism.
2204        if (::setgid (getgid ()) == 0)
2205        {
2206
2207            // Let the child have its own process group. We need to execute
2208            // this call in both the child and parent to avoid a race condition
2209            // between the two processes.
2210            ::setpgid (0, 0);    // Set the child process group to match its pid
2211
2212            // Sleep a bit to before the exec call
2213            ::sleep (1);
2214
2215            // Turn this process into
2216            ::execv (path, (char * const *)argv);
2217        }
2218        // Exit with error code. Child process should have taken
2219        // over in above exec call and if the exec fails it will
2220        // exit the child process below.
2221        ::exit (127);
2222    }
2223    else
2224    {
2225        //--------------------------------------------------------------
2226        // Parent process
2227        //--------------------------------------------------------------
2228        // Let the child have its own process group. We need to execute
2229        // this call in both the child and parent to avoid a race condition
2230        // between the two processes.
2231        ::setpgid (pid, pid);    // Set the child process group to match its pid
2232
2233        if (process != NULL)
2234        {
2235            // Release our master pty file descriptor so the pty class doesn't
2236            // close it and so we can continue to use it in our STDIO thread
2237            int master_fd = pty.ReleaseMasterFD();
2238            process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
2239        }
2240    }
2241    return pid;
2242}
2243
2244#if defined (WITH_SPRINGBOARD) || defined (WITH_BKS)
2245// This returns a CFRetained pointer to the Bundle ID for app_bundle_path,
2246// or NULL if there was some problem getting the bundle id.
2247static CFStringRef
2248CopyBundleIDForPath (const char *app_bundle_path, DNBError &err_str)
2249{
2250    CFBundle bundle(app_bundle_path);
2251    CFStringRef bundleIDCFStr = bundle.GetIdentifier();
2252    std::string bundleID;
2253    if (CFString::UTF8(bundleIDCFStr, bundleID) == NULL)
2254    {
2255        struct stat app_bundle_stat;
2256        char err_msg[PATH_MAX];
2257
2258        if (::stat (app_bundle_path, &app_bundle_stat) < 0)
2259        {
2260            err_str.SetError(errno, DNBError::POSIX);
2261            snprintf(err_msg, sizeof(err_msg), "%s: \"%s\"", err_str.AsString(), app_bundle_path);
2262            err_str.SetErrorString(err_msg);
2263            DNBLogThreadedIf(LOG_PROCESS, "%s() error: %s", __FUNCTION__, err_msg);
2264        }
2265        else
2266        {
2267            err_str.SetError(-1, DNBError::Generic);
2268            snprintf(err_msg, sizeof(err_msg), "failed to extract CFBundleIdentifier from %s", app_bundle_path);
2269            err_str.SetErrorString(err_msg);
2270            DNBLogThreadedIf(LOG_PROCESS, "%s() error: failed to extract CFBundleIdentifier from '%s'", __FUNCTION__, app_bundle_path);
2271        }
2272        return NULL;
2273    }
2274
2275    DNBLogThreadedIf(LOG_PROCESS, "%s() extracted CFBundleIdentifier: %s", __FUNCTION__, bundleID.c_str());
2276    CFRetain (bundleIDCFStr);
2277
2278    return bundleIDCFStr;
2279}
2280#endif // #if defined 9WITH_SPRINGBOARD) || defined (WITH_BKS)
2281#ifdef WITH_SPRINGBOARD
2282
2283pid_t
2284MachProcess::SBLaunchForDebug (const char *path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, DNBError &launch_err)
2285{
2286    // Clear out and clean up from any current state
2287    Clear();
2288
2289    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path);
2290
2291    // Fork a child process for debugging
2292    SetState(eStateLaunching);
2293    m_pid = MachProcess::SBForkChildForPTraceDebugging(path, argv, envp, no_stdio, this, launch_err);
2294    if (m_pid != 0)
2295    {
2296        m_flags |= eMachProcessFlagsUsingSBS;
2297        m_path = path;
2298        size_t i;
2299        char const *arg;
2300        for (i=0; (arg = argv[i]) != NULL; i++)
2301            m_args.push_back(arg);
2302        m_task.StartExceptionThread(launch_err);
2303
2304        if (launch_err.Fail())
2305        {
2306            if (launch_err.AsString() == NULL)
2307                launch_err.SetErrorString("unable to start the exception thread");
2308            DNBLog ("Could not get inferior's Mach exception port, sending ptrace PT_KILL and exiting.");
2309            ::ptrace (PT_KILL, m_pid, 0, 0);
2310            m_pid = INVALID_NUB_PROCESS;
2311            return INVALID_NUB_PROCESS;
2312        }
2313
2314        StartSTDIOThread();
2315        SetState (eStateAttaching);
2316        int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
2317        if (err == 0)
2318        {
2319            m_flags |= eMachProcessFlagsAttached;
2320            DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", m_pid);
2321        }
2322        else
2323        {
2324            SetState (eStateExited);
2325            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", m_pid);
2326        }
2327    }
2328    return m_pid;
2329}
2330
2331#include <servers/bootstrap.h>
2332
2333pid_t
2334MachProcess::SBForkChildForPTraceDebugging (const char *app_bundle_path, char const *argv[], char const *envp[], bool no_stdio, MachProcess* process, DNBError &launch_err)
2335{
2336    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__, app_bundle_path, process);
2337    CFAllocatorRef alloc = kCFAllocatorDefault;
2338
2339    if (argv[0] == NULL)
2340        return INVALID_NUB_PROCESS;
2341
2342    size_t argc = 0;
2343    // Count the number of arguments
2344    while (argv[argc] != NULL)
2345        argc++;
2346
2347    // Enumerate the arguments
2348    size_t first_launch_arg_idx = 1;
2349    CFReleaser<CFMutableArrayRef> launch_argv;
2350
2351    if (argv[first_launch_arg_idx])
2352    {
2353        size_t launch_argc = argc > 0 ? argc - 1 : 0;
2354        launch_argv.reset (::CFArrayCreateMutable (alloc, launch_argc, &kCFTypeArrayCallBacks));
2355        size_t i;
2356        char const *arg;
2357        CFString launch_arg;
2358        for (i=first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL); i++)
2359        {
2360            launch_arg.reset(::CFStringCreateWithCString (alloc, arg, kCFStringEncodingUTF8));
2361            if (launch_arg.get() != NULL)
2362                CFArrayAppendValue(launch_argv.get(), launch_arg.get());
2363            else
2364                break;
2365        }
2366    }
2367
2368    // Next fill in the arguments dictionary.  Note, the envp array is of the form
2369    // Variable=value but SpringBoard wants a CF dictionary.  So we have to convert
2370    // this here.
2371
2372    CFReleaser<CFMutableDictionaryRef> launch_envp;
2373
2374    if (envp[0])
2375    {
2376        launch_envp.reset(::CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
2377        const char *value;
2378        int name_len;
2379        CFString name_string, value_string;
2380
2381        for (int i = 0; envp[i] != NULL; i++)
2382        {
2383            value = strstr (envp[i], "=");
2384
2385            // If the name field is empty or there's no =, skip it.  Somebody's messing with us.
2386            if (value == NULL || value == envp[i])
2387                continue;
2388
2389            name_len = value - envp[i];
2390
2391            // Now move value over the "="
2392            value++;
2393
2394            name_string.reset(::CFStringCreateWithBytes(alloc, (const UInt8 *) envp[i], name_len, kCFStringEncodingUTF8, false));
2395            value_string.reset(::CFStringCreateWithCString(alloc, value, kCFStringEncodingUTF8));
2396            CFDictionarySetValue (launch_envp.get(), name_string.get(), value_string.get());
2397        }
2398    }
2399
2400    CFString stdio_path;
2401
2402    PseudoTerminal pty;
2403    if (!no_stdio)
2404    {
2405        PseudoTerminal::Error pty_err = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
2406        if (pty_err == PseudoTerminal::success)
2407        {
2408            const char* slave_name = pty.SlaveName();
2409            DNBLogThreadedIf(LOG_PROCESS, "%s() successfully opened master pty, slave is %s", __FUNCTION__, slave_name);
2410            if (slave_name && slave_name[0])
2411            {
2412                ::chmod (slave_name, S_IRWXU | S_IRWXG | S_IRWXO);
2413                stdio_path.SetFileSystemRepresentation (slave_name);
2414            }
2415        }
2416    }
2417
2418    if (stdio_path.get() == NULL)
2419    {
2420        stdio_path.SetFileSystemRepresentation ("/dev/null");
2421    }
2422
2423    CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path, launch_err);
2424    if (bundleIDCFStr == NULL)
2425        return INVALID_NUB_PROCESS;
2426
2427    // This is just for logging:
2428    std::string bundleID;
2429    CFString::UTF8(bundleIDCFStr, bundleID);
2430
2431    DNBLogThreadedIf(LOG_PROCESS, "%s() serialized launch arg array", __FUNCTION__);
2432
2433    // Find SpringBoard
2434    SBSApplicationLaunchError sbs_error = 0;
2435    sbs_error = SBSLaunchApplicationForDebugging (bundleIDCFStr,
2436                                                  (CFURLRef)NULL,         // openURL
2437                                                  launch_argv.get(),
2438                                                  launch_envp.get(),  // CFDictionaryRef environment
2439                                                  stdio_path.get(),
2440                                                  stdio_path.get(),
2441                                                  SBSApplicationLaunchWaitForDebugger | SBSApplicationLaunchUnlockDevice);
2442
2443
2444    launch_err.SetError(sbs_error, DNBError::SpringBoard);
2445
2446    if (sbs_error == SBSApplicationLaunchErrorSuccess)
2447    {
2448        static const useconds_t pid_poll_interval = 200000;
2449        static const useconds_t pid_poll_timeout = 30000000;
2450
2451        useconds_t pid_poll_total = 0;
2452
2453        nub_process_t pid = INVALID_NUB_PROCESS;
2454        Boolean pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2455        // Poll until the process is running, as long as we are getting valid responses and the timeout hasn't expired
2456        // A return PID of 0 means the process is not running, which may be because it hasn't been (asynchronously) started
2457        // yet, or that it died very quickly (if you weren't using waitForDebugger).
2458        while (!pid_found && pid_poll_total < pid_poll_timeout)
2459        {
2460            usleep (pid_poll_interval);
2461            pid_poll_total += pid_poll_interval;
2462            DNBLogThreadedIf(LOG_PROCESS, "%s() polling Springboard for pid for %s...", __FUNCTION__, bundleID.c_str());
2463            pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);
2464        }
2465
2466        CFRelease (bundleIDCFStr);
2467        if (pid_found)
2468        {
2469            if (process != NULL)
2470            {
2471                // Release our master pty file descriptor so the pty class doesn't
2472                // close it and so we can continue to use it in our STDIO thread
2473                int master_fd = pty.ReleaseMasterFD();
2474                process->SetChildFileDescriptors(master_fd, master_fd, master_fd);
2475            }
2476            DNBLogThreadedIf(LOG_PROCESS, "%s() => pid = %4.4x", __FUNCTION__, pid);
2477        }
2478        else
2479        {
2480            DNBLogError("failed to lookup the process ID for CFBundleIdentifier %s.", bundleID.c_str());
2481        }
2482        return pid;
2483    }
2484
2485    DNBLogError("unable to launch the application with CFBundleIdentifier '%s' sbs_error = %u", bundleID.c_str(), sbs_error);
2486    return INVALID_NUB_PROCESS;
2487}
2488
2489#endif // #ifdef WITH_SPRINGBOARD
2490
2491#ifdef WITH_BKS
2492
2493
2494// This function runs the BKSSystemService method openApplication:options:clientPort:withResult,
2495// messaging the app passed in bundleIDNSStr.
2496// The function should be run inside of an NSAutoReleasePool.
2497//
2498// It will use the "options" dictionary passed in, and fill the error passed in if there is an error.
2499// If return_pid is not NULL, we'll fetch the pid that was made for the bundleID.
2500// If bundleIDNSStr is NULL, then the system application will be messaged.
2501
2502static bool
2503CallBKSSystemServiceOpenApplication (NSString *bundleIDNSStr, NSDictionary *options, DNBError &error, pid_t *return_pid)
2504{
2505    // Now make our systemService:
2506    BKSSystemService *system_service = [[BKSSystemService alloc] init];
2507
2508    if (bundleIDNSStr == nil)
2509    {
2510        bundleIDNSStr = [system_service systemApplicationBundleIdentifier];
2511        if (bundleIDNSStr == nil)
2512        {
2513            // Okay, no system app...
2514            error.SetErrorString("No system application to message.");
2515            return false;
2516        }
2517    }
2518
2519    mach_port_t client_port = [system_service createClientPort];
2520    __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
2521    __block BKSOpenApplicationErrorCode open_app_error = BKSOpenApplicationErrorCodeNone;
2522    bool wants_pid = (return_pid != NULL);
2523    __block pid_t pid_in_block;
2524
2525    const char *cstr = [bundleIDNSStr UTF8String];
2526    if (!cstr)
2527        cstr = "<Unknown Bundle ID>";
2528
2529    DNBLog ("About to launch process for bundle ID: %s", cstr);
2530    [system_service openApplication: bundleIDNSStr
2531                    options: options
2532                    clientPort: client_port
2533                    withResult: ^(NSError *bks_error)
2534                    {
2535                        // The system service will cleanup the client port we created for us.
2536                        if (bks_error)
2537                            open_app_error = (BKSOpenApplicationErrorCode)[bks_error code];
2538
2539                        if (open_app_error == BKSOpenApplicationErrorCodeNone)
2540                        {
2541                            if (wants_pid)
2542                            {
2543                                pid_in_block = [system_service pidForApplication: bundleIDNSStr];
2544                                DNBLog("In completion handler, got pid for bundle id, pid: %d.", pid_in_block);
2545                                DNBLogThreadedIf(LOG_PROCESS, "In completion handler, got pid for bundle id, pid: %d.", pid_in_block);
2546                            }
2547                            else
2548                                DNBLogThreadedIf (LOG_PROCESS, "In completion handler: success.");
2549                        }
2550                        else
2551                        {
2552                            const char *error_str = [[bks_error localizedDescription] UTF8String];
2553                            DNBLogThreadedIf(LOG_PROCESS, "In completion handler for send event, got error \"%s\"(%d).",
2554                                             error_str ? error_str : "<unknown error>",
2555                                             open_app_error);
2556                            // REMOVE ME
2557                            DNBLogError ("In completion handler for send event, got error \"%s\"(%d).",
2558                                             error_str ? error_str : "<unknown error>",
2559                                             open_app_error);
2560                        }
2561
2562                        [system_service release];
2563                        dispatch_semaphore_signal(semaphore);
2564                    }
2565
2566    ];
2567
2568    const uint32_t timeout_secs = 9;
2569
2570    dispatch_time_t timeout = dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC);
2571
2572    long success = dispatch_semaphore_wait(semaphore, timeout) == 0;
2573
2574    dispatch_release(semaphore);
2575
2576    if (!success)
2577    {
2578        DNBLogError("timed out trying to send openApplication to %s.", cstr);
2579        error.SetError (BKS_OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic);
2580        error.SetErrorString ("timed out trying to launch app");
2581    }
2582    else if (open_app_error != BKSOpenApplicationErrorCodeNone)
2583    {
2584        SetBKSError (open_app_error, error);
2585        DNBLogError("unable to launch the application with CFBundleIdentifier '%s' bks_error = %u", cstr, open_app_error);
2586        success = false;
2587    }
2588    else if (wants_pid)
2589    {
2590        *return_pid = pid_in_block;
2591        DNBLogThreadedIf (LOG_PROCESS, "Out of completion handler, pid from block %d and passing out: %d", pid_in_block, *return_pid);
2592    }
2593
2594
2595    return success;
2596}
2597
2598void
2599MachProcess::BKSCleanupAfterAttach (const void *attach_token, DNBError &err_str)
2600{
2601    bool success;
2602
2603    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2604
2605    // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use toll-free bridging here:
2606    NSString *bundleIDNSStr = (NSString *) attach_token;
2607
2608    // Okay, now let's assemble all these goodies into the BackBoardServices options mega-dictionary:
2609
2610    // First we have the debug sub-dictionary:
2611    NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];
2612    [debug_options setObject: [NSNumber numberWithBool: YES] forKey: BKSDebugOptionKeyCancelDebugOnNextLaunch];
2613
2614    // That will go in the overall dictionary:
2615
2616    NSMutableDictionary *options = [NSMutableDictionary dictionary];
2617    [options setObject: debug_options forKey: BKSOpenApplicationOptionKeyDebuggingOptions];
2618
2619    success = CallBKSSystemServiceOpenApplication(bundleIDNSStr, options, err_str, NULL);
2620
2621    if (!success)
2622    {
2623        DNBLogError ("error trying to cancel debug on next launch for %s: %s", [bundleIDNSStr UTF8String], err_str.AsString());
2624    }
2625
2626    [pool drain];
2627}
2628
2629bool
2630AddEventDataToOptions (NSMutableDictionary *options, const char *event_data, DNBError &option_error)
2631{
2632    if (strcmp (event_data, "BackgroundContentFetching") == 0)
2633    {
2634        DNBLog("Setting ActivateForEvent key in options dictionary.");
2635        NSDictionary *event_details = [NSDictionary dictionary];
2636        NSDictionary *event_dictionary = [NSDictionary dictionaryWithObject:event_details forKey:BKSActivateForEventOptionTypeBackgroundContentFetching];
2637        [options setObject: event_dictionary forKey: BKSOpenApplicationOptionKeyActivateForEvent];
2638        return true;
2639    }
2640    else
2641    {
2642        DNBLogError ("Unrecognized event type: %s.  Ignoring.", event_data);
2643        option_error.SetErrorString("Unrecognized event data.");
2644        return false;
2645    }
2646
2647}
2648
2649pid_t
2650MachProcess::BKSLaunchForDebug (const char *path, char const *argv[], char const *envp[], bool no_stdio, bool disable_aslr, const char *event_data, DNBError &launch_err)
2651{
2652    // Clear out and clean up from any current state
2653    Clear();
2654
2655    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path);
2656
2657    // Fork a child process for debugging
2658    SetState(eStateLaunching);
2659    m_pid = BKSForkChildForPTraceDebugging(path, argv, envp, no_stdio, disable_aslr, event_data, launch_err);
2660    if (m_pid != 0)
2661    {
2662        m_flags |= eMachProcessFlagsUsingBKS;
2663        m_path = path;
2664        size_t i;
2665        char const *arg;
2666        for (i=0; (arg = argv[i]) != NULL; i++)
2667            m_args.push_back(arg);
2668        m_task.StartExceptionThread(launch_err);
2669
2670        if (launch_err.Fail())
2671        {
2672            if (launch_err.AsString() == NULL)
2673                launch_err.SetErrorString("unable to start the exception thread");
2674            DNBLog ("Could not get inferior's Mach exception port, sending ptrace PT_KILL and exiting.");
2675            ::ptrace (PT_KILL, m_pid, 0, 0);
2676            m_pid = INVALID_NUB_PROCESS;
2677            return INVALID_NUB_PROCESS;
2678        }
2679
2680        StartSTDIOThread();
2681        SetState (eStateAttaching);
2682        int err = ::ptrace (PT_ATTACHEXC, m_pid, 0, 0);
2683        if (err == 0)
2684        {
2685            m_flags |= eMachProcessFlagsAttached;
2686            DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", m_pid);
2687        }
2688        else
2689        {
2690            SetState (eStateExited);
2691            DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", m_pid);
2692        }
2693    }
2694    return m_pid;
2695}
2696
2697pid_t
2698MachProcess::BKSForkChildForPTraceDebugging (const char *app_bundle_path,
2699                                             char const *argv[],
2700                                             char const *envp[],
2701                                             bool no_stdio,
2702                                             bool disable_aslr,
2703                                             const char *event_data,
2704                                             DNBError &launch_err)
2705{
2706    if (argv[0] == NULL)
2707        return INVALID_NUB_PROCESS;
2708
2709    DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__, app_bundle_path, this);
2710
2711    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2712
2713    size_t argc = 0;
2714    // Count the number of arguments
2715    while (argv[argc] != NULL)
2716        argc++;
2717
2718    // Enumerate the arguments
2719    size_t first_launch_arg_idx = 1;
2720
2721    NSMutableArray *launch_argv = nil;
2722
2723    if (argv[first_launch_arg_idx])
2724    {
2725        size_t launch_argc = argc > 0 ? argc - 1 : 0;
2726        launch_argv = [NSMutableArray arrayWithCapacity: launch_argc];
2727        size_t i;
2728        char const *arg;
2729        NSString *launch_arg;
2730        for (i=first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL); i++)
2731        {
2732            launch_arg = [NSString stringWithUTF8String: arg];
2733            // FIXME: Should we silently eat an argument that we can't convert into a UTF8 string?
2734            if (launch_arg != nil)
2735                [launch_argv addObject: launch_arg];
2736            else
2737                break;
2738        }
2739    }
2740
2741    NSMutableDictionary *launch_envp = nil;
2742    if (envp[0])
2743    {
2744        launch_envp = [[NSMutableDictionary alloc] init];
2745        const char *value;
2746        int name_len;
2747        NSString *name_string, *value_string;
2748
2749        for (int i = 0; envp[i] != NULL; i++)
2750        {
2751            value = strstr (envp[i], "=");
2752
2753            // If the name field is empty or there's no =, skip it.  Somebody's messing with us.
2754            if (value == NULL || value == envp[i])
2755                continue;
2756
2757            name_len = value - envp[i];
2758
2759            // Now move value over the "="
2760            value++;
2761            name_string = [[NSString alloc] initWithBytes: envp[i] length: name_len encoding: NSUTF8StringEncoding];
2762            value_string = [NSString stringWithUTF8String: value];
2763            [launch_envp setObject: value_string forKey: name_string];
2764        }
2765    }
2766
2767    NSString *stdio_path = nil;
2768    NSFileManager *file_manager = [NSFileManager defaultManager];
2769
2770    PseudoTerminal pty;
2771    if (!no_stdio)
2772    {
2773        PseudoTerminal::Error pty_err = pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY);
2774        if (pty_err == PseudoTerminal::success)
2775        {
2776            const char* slave_name = pty.SlaveName();
2777            DNBLogThreadedIf(LOG_PROCESS, "%s() successfully opened master pty, slave is %s", __FUNCTION__, slave_name);
2778            if (slave_name && slave_name[0])
2779            {
2780                ::chmod (slave_name, S_IRWXU | S_IRWXG | S_IRWXO);
2781                stdio_path = [file_manager stringWithFileSystemRepresentation: slave_name length: strlen(slave_name)];
2782            }
2783        }
2784    }
2785
2786    if (stdio_path == nil)
2787    {
2788        const char *null_path = "/dev/null";
2789        stdio_path = [file_manager stringWithFileSystemRepresentation: null_path length: strlen(null_path)];
2790    }
2791
2792    CFStringRef bundleIDCFStr = CopyBundleIDForPath (app_bundle_path, launch_err);
2793    if (bundleIDCFStr == NULL)
2794    {
2795        [pool drain];
2796        return INVALID_NUB_PROCESS;
2797    }
2798
2799    // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use toll-free bridging here:
2800    NSString *bundleIDNSStr = (NSString *) bundleIDCFStr;
2801
2802    // Okay, now let's assemble all these goodies into the BackBoardServices options mega-dictionary:
2803
2804    // First we have the debug sub-dictionary:
2805    NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];
2806    if (launch_argv != nil)
2807        [debug_options setObject: launch_argv forKey: BKSDebugOptionKeyArguments];
2808    if (launch_envp != nil)
2809        [debug_options setObject: launch_envp forKey: BKSDebugOptionKeyEnvironment];
2810
2811    [debug_options setObject: stdio_path forKey: BKSDebugOptionKeyStandardOutPath];
2812    [debug_options setObject: stdio_path forKey: BKSDebugOptionKeyStandardErrorPath];
2813    [debug_options setObject: [NSNumber numberWithBool: YES] forKey: BKSDebugOptionKeyWaitForDebugger];
2814    if (disable_aslr)
2815        [debug_options setObject: [NSNumber numberWithBool: YES] forKey: BKSDebugOptionKeyDisableASLR];
2816
2817    // That will go in the overall dictionary:
2818
2819    NSMutableDictionary *options = [NSMutableDictionary dictionary];
2820    [options setObject: debug_options forKey: BKSOpenApplicationOptionKeyDebuggingOptions];
2821
2822    // For now we only support one kind of event: the "fetch" event, which is indicated by the fact that its data
2823    // is an empty dictionary.
2824    if (event_data != NULL && *event_data != '\0')
2825    {
2826        if (!AddEventDataToOptions(options, event_data, launch_err))
2827        {
2828            [pool drain];
2829            return INVALID_NUB_PROCESS;
2830        }
2831    }
2832
2833    // And there are some other options at the top level in this dictionary:
2834    [options setObject: [NSNumber numberWithBool: YES] forKey: BKSOpenApplicationOptionKeyUnlockDevice];
2835
2836    pid_t return_pid = INVALID_NUB_PROCESS;
2837    bool success = CallBKSSystemServiceOpenApplication(bundleIDNSStr, options, launch_err, &return_pid);
2838
2839    if (success)
2840    {
2841        int master_fd = pty.ReleaseMasterFD();
2842        SetChildFileDescriptors(master_fd, master_fd, master_fd);
2843        CFString::UTF8(bundleIDCFStr, m_bundle_id);
2844    }
2845
2846    [pool drain];
2847
2848    return return_pid;
2849}
2850
2851bool
2852MachProcess::BKSSendEvent (const char *event_data, DNBError &send_err)
2853{
2854    bool return_value = true;
2855
2856    if (event_data == NULL || *event_data == '\0')
2857    {
2858        DNBLogError ("SendEvent called with NULL event data.");
2859        send_err.SetErrorString("SendEvent called with empty event data");
2860        return false;
2861    }
2862
2863    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
2864
2865    if (strcmp (event_data, "BackgroundApplication") == 0)
2866    {
2867        // This is an event I cooked up.  What you actually do is foreground the system app, so:
2868        return_value = CallBKSSystemServiceOpenApplication(nil, nil, send_err, NULL);
2869        if (!return_value)
2870        {
2871            DNBLogError ("Failed to background application, error: %s.", send_err.AsString());
2872        }
2873    }
2874    else
2875    {
2876        if (m_bundle_id.empty())
2877        {
2878            // See if we can figure out the bundle ID for this PID:
2879
2880            DNBLogError ("Tried to send event \"%s\" to a process that has no bundle ID.", event_data);
2881            return false;
2882        }
2883
2884        NSString *bundleIDNSStr = [NSString stringWithUTF8String:m_bundle_id.c_str()];
2885
2886        NSMutableDictionary *options = [NSMutableDictionary dictionary];
2887
2888        if (!AddEventDataToOptions(options, event_data, send_err))
2889        {
2890            [pool drain];
2891            return false;
2892        }
2893
2894
2895        return_value = CallBKSSystemServiceOpenApplication(bundleIDNSStr, options, send_err, NULL);
2896
2897        if (!return_value)
2898        {
2899            DNBLogError ("Failed to send event: %s, error: %s.", event_data, send_err.AsString());
2900        }
2901    }
2902
2903    [pool drain];
2904    return return_value;
2905}
2906#endif // WITH_BKS
2907