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