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