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