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