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