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