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