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