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