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