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