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