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