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