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