4551 lines · plain
1//===-- MachProcess.cpp -----------------------------------------*- C++ -*-===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8//9// Created by Greg Clayton on 6/15/07.10//11//===----------------------------------------------------------------------===//12 13#include "DNB.h"14#include "MacOSX/CFUtils.h"15#include "SysSignal.h"16#include <dlfcn.h>17#include <inttypes.h>18#include <mach-o/loader.h>19#include <mach/mach.h>20#include <mach/task.h>21#include <pthread.h>22#include <signal.h>23#include <spawn.h>24#include <sys/fcntl.h>25#include <sys/ptrace.h>26#include <sys/stat.h>27#include <sys/sysctl.h>28#include <sys/time.h>29#include <sys/types.h>30#include <unistd.h>31#include <uuid/uuid.h>32 33#include <algorithm>34#include <chrono>35#include <map>36#include <unordered_set>37 38#include <TargetConditionals.h>39#import <Foundation/Foundation.h>40 41#include "DNBDataRef.h"42#include "DNBLog.h"43#include "DNBThreadResumeActions.h"44#include "DNBTimer.h"45#include "MachProcess.h"46#include "PseudoTerminal.h"47 48#include "CFBundle.h"49#include "CFString.h"50 51#ifndef PLATFORM_BRIDGEOS52#define PLATFORM_BRIDGEOS 553#endif54 55#ifndef PLATFORM_MACCATALYST56#define PLATFORM_MACCATALYST 657#endif58 59#ifndef PLATFORM_IOSSIMULATOR60#define PLATFORM_IOSSIMULATOR 761#endif62 63#ifndef PLATFORM_TVOSSIMULATOR64#define PLATFORM_TVOSSIMULATOR 865#endif66 67#ifndef PLATFORM_WATCHOSSIMULATOR68#define PLATFORM_WATCHOSSIMULATOR 969#endif70 71#ifndef PLATFORM_DRIVERKIT72#define PLATFORM_DRIVERKIT 1073#endif74 75#ifndef PLATFORM_VISIONOS76#define PLATFORM_VISIONOS 1177#endif78 79#ifndef PLATFORM_VISIONOSSIMULATOR80#define PLATFORM_VISIONOSSIMULATOR 1281#endif82 83#ifdef WITH_SPRINGBOARD84 85#include <CoreFoundation/CoreFoundation.h>86#include <SpringBoardServices/SBSWatchdogAssertion.h>87#include <SpringBoardServices/SpringBoardServer.h>88 89#endif // WITH_SPRINGBOARD90 91#if WITH_CAROUSEL92// For definition of CSLSOpenApplicationOptionForClockKit.93#include <CarouselServices/CSLSOpenApplicationOptions.h>94#endif // WITH_CAROUSEL95 96#if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS)97// This returns a CFRetained pointer to the Bundle ID for app_bundle_path,98// or NULL if there was some problem getting the bundle id.99static CFStringRef CopyBundleIDForPath(const char *app_bundle_path,100 DNBError &err_str);101#endif102 103#if defined(WITH_BKS) || defined(WITH_FBS)104#import <Foundation/Foundation.h>105static const int OPEN_APPLICATION_TIMEOUT_ERROR = 111;106typedef void (*SetErrorFunction)(NSInteger, std::string, DNBError &);107typedef bool (*CallOpenApplicationFunction)(NSString *bundleIDNSStr,108 NSDictionary *options,109 DNBError &error, pid_t *return_pid);110 111// This function runs the BKSSystemService (or FBSSystemService) method112// openApplication:options:clientPort:withResult,113// messaging the app passed in bundleIDNSStr.114// The function should be run inside of an NSAutoReleasePool.115//116// It will use the "options" dictionary passed in, and fill the error passed in117// if there is an error.118// If return_pid is not NULL, we'll fetch the pid that was made for the119// bundleID.120// If bundleIDNSStr is NULL, then the system application will be messaged.121 122template <typename OpenFlavor, typename ErrorFlavor,123 ErrorFlavor no_error_enum_value, SetErrorFunction error_function>124static bool CallBoardSystemServiceOpenApplication(NSString *bundleIDNSStr,125 NSDictionary *options,126 DNBError &error,127 pid_t *return_pid) {128 // Now make our systemService:129 OpenFlavor *system_service = [[OpenFlavor alloc] init];130 131 if (bundleIDNSStr == nil) {132 bundleIDNSStr = [system_service systemApplicationBundleIdentifier];133 if (bundleIDNSStr == nil) {134 // Okay, no system app...135 error.SetErrorString("No system application to message.");136 return false;137 }138 }139 140 mach_port_t client_port = [system_service createClientPort];141 __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);142 __block ErrorFlavor open_app_error = no_error_enum_value;143 __block std::string open_app_error_string;144 bool wants_pid = (return_pid != NULL);145 __block pid_t pid_in_block;146 147 const char *cstr = [bundleIDNSStr UTF8String];148 if (!cstr)149 cstr = "<Unknown Bundle ID>";150 151 NSString *description = [options description];152 DNBLog("[LaunchAttach] START (%d) templated *Board launcher: app lunch "153 "request for "154 "'%s' - options:\n%s",155 getpid(), cstr, [description UTF8String]);156 [system_service157 openApplication:bundleIDNSStr158 options:options159 clientPort:client_port160 withResult:^(NSError *bks_error) {161 // The system service will cleanup the client port we created for162 // us.163 if (bks_error)164 open_app_error = (ErrorFlavor)[bks_error code];165 166 if (open_app_error == no_error_enum_value) {167 if (wants_pid) {168 pid_in_block =169 [system_service pidForApplication:bundleIDNSStr];170 DNBLog("[LaunchAttach] In completion handler, got pid for "171 "bundle id "172 "'%s', pid: %d.",173 cstr, pid_in_block);174 } else {175 DNBLog("[LaunchAttach] In completion handler, launch was "176 "successful, "177 "debugserver did not ask for the pid");178 }179 } else {180 const char *error_str =181 [(NSString *)[bks_error localizedDescription] UTF8String];182 if (error_str) {183 open_app_error_string = error_str;184 DNBLogError(185 "[LaunchAttach] END (%d) In app launch attempt, got error "186 "localizedDescription '%s'.",187 getpid(), error_str);188 const char *obj_desc = 189 [NSString stringWithFormat:@"%@", bks_error].UTF8String;190 DNBLogError(191 "[LaunchAttach] END (%d) In app launch attempt, got error "192 "NSError object description: '%s'.",193 getpid(), obj_desc);194 }195 DNBLogThreadedIf(LOG_PROCESS,196 "In completion handler for send "197 "event, got error \"%s\"(%ld).",198 error_str ? error_str : "<unknown error>",199 (long)open_app_error);200 }201 202 [system_service release];203 dispatch_semaphore_signal(semaphore);204 }205 206 ];207 208 const uint32_t timeout_secs = 30;209 210 dispatch_time_t timeout =211 dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC);212 213 long success = dispatch_semaphore_wait(semaphore, timeout) == 0;214 215 dispatch_release(semaphore);216 217 DNBLog("[LaunchAttach] END (%d) templated *Board launcher finished app lunch "218 "request for "219 "'%s'",220 getpid(), cstr);221 222 if (!success) {223 DNBLogError("[LaunchAttach] END (%d) timed out trying to send "224 "openApplication to %s.",225 getpid(), cstr);226 error.SetError(OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic);227 error.SetErrorString("timed out trying to launch app");228 } else if (open_app_error != no_error_enum_value) {229 error_function(open_app_error, open_app_error_string, error);230 DNBLogError("[LaunchAttach] END (%d) unable to launch the application with "231 "CFBundleIdentifier '%s' "232 "bks_error = %ld",233 getpid(), cstr, (long)open_app_error);234 success = false;235 } else if (wants_pid) {236 *return_pid = pid_in_block;237 DNBLogThreadedIf(238 LOG_PROCESS,239 "Out of completion handler, pid from block %d and passing out: %d",240 pid_in_block, *return_pid);241 }242 243 return success;244}245#endif246 247#if defined(WITH_BKS) || defined(WITH_FBS)248static void SplitEventData(const char *data, std::vector<std::string> &elements)249{250 elements.clear();251 if (!data)252 return;253 254 const char *start = data;255 256 while (*start != '\0') {257 const char *token = strchr(start, ':');258 if (!token) {259 elements.push_back(std::string(start));260 return;261 }262 if (token != start)263 elements.push_back(std::string(start, token - start));264 start = ++token;265 }266}267#endif268 269#ifdef WITH_BKS270#import <Foundation/Foundation.h>271extern "C" {272#import <BackBoardServices/BKSOpenApplicationConstants_Private.h>273#import <BackBoardServices/BKSSystemService_LaunchServices.h>274#import <BackBoardServices/BackBoardServices.h>275}276 277static bool IsBKSProcess(nub_process_t pid) {278 BKSApplicationStateMonitor *state_monitor =279 [[BKSApplicationStateMonitor alloc] init];280 BKSApplicationState app_state =281 [state_monitor mostElevatedApplicationStateForPID:pid];282 return app_state != BKSApplicationStateUnknown;283}284 285static void SetBKSError(NSInteger error_code, 286 std::string error_description, 287 DNBError &error) {288 error.SetError(error_code, DNBError::BackBoard);289 NSString *err_nsstr = ::BKSOpenApplicationErrorCodeToString(290 (BKSOpenApplicationErrorCode)error_code);291 std::string err_str = "unknown BKS error";292 if (error_description.empty() == false) {293 err_str = error_description;294 } else if (err_nsstr != nullptr) {295 err_str = [err_nsstr UTF8String];296 }297 error.SetErrorString(err_str.c_str());298}299 300static bool BKSAddEventDataToOptions(NSMutableDictionary *options,301 const char *event_data,302 DNBError &option_error) {303 std::vector<std::string> values;304 SplitEventData(event_data, values);305 bool found_one = false;306 for (std::string value : values)307 {308 if (value.compare("BackgroundContentFetching") == 0) {309 DNBLog("Setting ActivateForEvent key in options dictionary.");310 NSDictionary *event_details = [NSDictionary dictionary];311 NSDictionary *event_dictionary = [NSDictionary312 dictionaryWithObject:event_details313 forKey:314 BKSActivateForEventOptionTypeBackgroundContentFetching];315 [options setObject:event_dictionary316 forKey:BKSOpenApplicationOptionKeyActivateForEvent];317 found_one = true;318 } else if (value.compare("ActivateSuspended") == 0) {319 DNBLog("Setting ActivateSuspended key in options dictionary.");320 [options setObject:@YES forKey: BKSOpenApplicationOptionKeyActivateSuspended];321 found_one = true;322 } else {323 DNBLogError("Unrecognized event type: %s. Ignoring.", value.c_str());324 option_error.SetErrorString("Unrecognized event data");325 }326 }327 return found_one;328}329 330static NSMutableDictionary *BKSCreateOptionsDictionary(331 const char *app_bundle_path, NSMutableArray *launch_argv,332 NSMutableDictionary *launch_envp, NSString *stdio_path, bool disable_aslr,333 const char *event_data) {334 NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];335 if (launch_argv != nil)336 [debug_options setObject:launch_argv forKey:BKSDebugOptionKeyArguments];337 if (launch_envp != nil)338 [debug_options setObject:launch_envp forKey:BKSDebugOptionKeyEnvironment];339 340 [debug_options setObject:stdio_path forKey:BKSDebugOptionKeyStandardOutPath];341 [debug_options setObject:stdio_path342 forKey:BKSDebugOptionKeyStandardErrorPath];343 [debug_options setObject:[NSNumber numberWithBool:YES]344 forKey:BKSDebugOptionKeyWaitForDebugger];345 if (disable_aslr)346 [debug_options setObject:[NSNumber numberWithBool:YES]347 forKey:BKSDebugOptionKeyDisableASLR];348 349 // That will go in the overall dictionary:350 351 NSMutableDictionary *options = [NSMutableDictionary dictionary];352 [options setObject:debug_options353 forKey:BKSOpenApplicationOptionKeyDebuggingOptions];354 // And there are some other options at the top level in this dictionary:355 [options setObject:[NSNumber numberWithBool:YES]356 forKey:BKSOpenApplicationOptionKeyUnlockDevice];357 358 DNBError error;359 BKSAddEventDataToOptions(options, event_data, error);360 361 return options;362}363 364static CallOpenApplicationFunction BKSCallOpenApplicationFunction =365 CallBoardSystemServiceOpenApplication<366 BKSSystemService, BKSOpenApplicationErrorCode,367 BKSOpenApplicationErrorCodeNone, SetBKSError>;368#endif // WITH_BKS369 370#ifdef WITH_FBS371#import <Foundation/Foundation.h>372extern "C" {373#import <FrontBoardServices/FBSOpenApplicationConstants_Private.h>374#import <FrontBoardServices/FBSSystemService_LaunchServices.h>375#import <FrontBoardServices/FrontBoardServices.h>376#import <MobileCoreServices/LSResourceProxy.h>377#import <MobileCoreServices/MobileCoreServices.h>378}379 380#ifdef WITH_BKS381static bool IsFBSProcess(nub_process_t pid) {382 BKSApplicationStateMonitor *state_monitor =383 [[BKSApplicationStateMonitor alloc] init];384 BKSApplicationState app_state =385 [state_monitor mostElevatedApplicationStateForPID:pid];386 return app_state != BKSApplicationStateUnknown;387}388#else389static bool IsFBSProcess(nub_process_t pid) {390 // FIXME: What is the FBS equivalent of BKSApplicationStateMonitor391 return false;392}393#endif394 395static void SetFBSError(NSInteger error_code, 396 std::string error_description, 397 DNBError &error) {398 error.SetError((DNBError::ValueType)error_code, DNBError::FrontBoard);399 NSString *err_nsstr = ::FBSOpenApplicationErrorCodeToString(400 (FBSOpenApplicationErrorCode)error_code);401 std::string err_str = "unknown FBS error";402 if (error_description.empty() == false) {403 err_str = error_description;404 } else if (err_nsstr != nullptr) {405 err_str = [err_nsstr UTF8String];406 }407 error.SetErrorString(err_str.c_str());408}409 410static bool FBSAddEventDataToOptions(NSMutableDictionary *options,411 const char *event_data,412 DNBError &option_error) {413 std::vector<std::string> values;414 SplitEventData(event_data, values);415 bool found_one = false;416 for (std::string value : values)417 {418 if (value.compare("BackgroundContentFetching") == 0) {419 DNBLog("Setting ActivateForEvent key in options dictionary.");420 NSDictionary *event_details = [NSDictionary dictionary];421 NSDictionary *event_dictionary = [NSDictionary422 dictionaryWithObject:event_details423 forKey:424 FBSActivateForEventOptionTypeBackgroundContentFetching];425 [options setObject:event_dictionary426 forKey:FBSOpenApplicationOptionKeyActivateForEvent];427 found_one = true;428 } else if (value.compare("ActivateSuspended") == 0) {429 DNBLog("Setting ActivateSuspended key in options dictionary.");430 [options setObject:@YES forKey: FBSOpenApplicationOptionKeyActivateSuspended];431 found_one = true;432#if WITH_CAROUSEL433 } else if (value.compare("WatchComplicationLaunch") == 0) {434 DNBLog("Setting FBSOpenApplicationOptionKeyActivateSuspended key in options dictionary.");435 [options setObject:@YES forKey: CSLSOpenApplicationOptionForClockKit];436 found_one = true;437#endif // WITH_CAROUSEL438 } else {439 DNBLogError("Unrecognized event type: %s. Ignoring.", value.c_str());440 option_error.SetErrorString("Unrecognized event data.");441 }442 }443 return found_one;444}445 446static NSMutableDictionary *447FBSCreateOptionsDictionary(const char *app_bundle_path,448 NSMutableArray *launch_argv,449 NSDictionary *launch_envp, NSString *stdio_path,450 bool disable_aslr, const char *event_data) {451 NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];452 453 if (launch_argv != nil)454 [debug_options setObject:launch_argv forKey:FBSDebugOptionKeyArguments];455 if (launch_envp != nil)456 [debug_options setObject:launch_envp forKey:FBSDebugOptionKeyEnvironment];457 458 [debug_options setObject:stdio_path forKey:FBSDebugOptionKeyStandardOutPath];459 [debug_options setObject:stdio_path460 forKey:FBSDebugOptionKeyStandardErrorPath];461 [debug_options setObject:[NSNumber numberWithBool:YES]462 forKey:FBSDebugOptionKeyWaitForDebugger];463 if (disable_aslr)464 [debug_options setObject:[NSNumber numberWithBool:YES]465 forKey:FBSDebugOptionKeyDisableASLR];466 467 // That will go in the overall dictionary:468 469 NSMutableDictionary *options = [NSMutableDictionary dictionary];470 [options setObject:debug_options471 forKey:FBSOpenApplicationOptionKeyDebuggingOptions];472 // And there are some other options at the top level in this dictionary:473 [options setObject:[NSNumber numberWithBool:YES]474 forKey:FBSOpenApplicationOptionKeyUnlockDevice];475 [options setObject:[NSNumber numberWithBool:YES]476 forKey:FBSOpenApplicationOptionKeyPromptUnlockDevice];477 478 // We have to get the "sequence ID & UUID" for this app bundle path and send479 // them to FBS:480 481 NSURL *app_bundle_url =482 [NSURL fileURLWithPath:[NSString stringWithUTF8String:app_bundle_path]483 isDirectory:YES];484 LSApplicationProxy *app_proxy =485 [LSApplicationProxy applicationProxyForBundleURL:app_bundle_url];486 if (app_proxy) {487 DNBLog("Sending AppProxy info: sequence no: %lu, GUID: %s.",488 app_proxy.sequenceNumber,489 [app_proxy.cacheGUID.UUIDString UTF8String]);490 [options491 setObject:[NSNumber numberWithUnsignedInteger:app_proxy.sequenceNumber]492 forKey:FBSOpenApplicationOptionKeyLSSequenceNumber];493 [options setObject:app_proxy.cacheGUID.UUIDString494 forKey:FBSOpenApplicationOptionKeyLSCacheGUID];495 }496 497 DNBError error;498 FBSAddEventDataToOptions(options, event_data, error);499 500 return options;501}502static CallOpenApplicationFunction FBSCallOpenApplicationFunction =503 CallBoardSystemServiceOpenApplication<504 FBSSystemService, FBSOpenApplicationErrorCode,505 FBSOpenApplicationErrorCodeNone, SetFBSError>;506#endif // WITH_FBS507 508#if 0509#define DEBUG_LOG(fmt, ...) printf(fmt, ##__VA_ARGS__)510#else511#define DEBUG_LOG(fmt, ...)512#endif513 514#ifndef MACH_PROCESS_USE_POSIX_SPAWN515#define MACH_PROCESS_USE_POSIX_SPAWN 1516#endif517 518#ifndef _POSIX_SPAWN_DISABLE_ASLR519#define _POSIX_SPAWN_DISABLE_ASLR 0x0100520#endif521 522MachProcess::MachProcess()523 : m_pid(0), m_cpu_type(0), m_child_stdin(-1), m_child_stdout(-1),524 m_child_stderr(-1), m_path(), m_args(), m_task(this),525 m_flags(eMachProcessFlagsNone), m_stdio_thread(0), m_stdio_mutex(),526 m_stdout_data(), m_profile_enabled(false), m_profile_interval_usec(0),527 m_profile_thread(0), m_profile_data_mutex(), m_profile_data(),528 m_profile_events(0, eMachProcessProfileCancel), m_thread_actions(),529 m_exception_messages(), m_exception_and_signal_mutex(), m_thread_list(),530 m_activities(), m_state(eStateUnloaded), m_state_mutex(),531 m_events(0, kAllEventsMask), m_private_events(0, kAllEventsMask),532 m_breakpoints(), m_watchpoints(), m_name_to_addr_callback(NULL),533 m_name_to_addr_baton(NULL), m_image_infos_callback(NULL),534 m_image_infos_baton(NULL), m_sent_interrupt_signo(0),535 m_auto_resume_signo(0), m_did_exec(false),536 m_dyld_process_info_create(nullptr),537 m_dyld_process_create_for_task(nullptr),538 m_dyld_process_snapshot_create_for_process(nullptr),539 m_dyld_process_snapshot_get_shared_cache(nullptr),540 m_dyld_shared_cache_for_each_file(nullptr),541 m_dyld_process_snapshot_dispose(nullptr), m_dyld_process_dispose(nullptr),542 m_dyld_process_info_for_each_image(nullptr),543 m_dyld_process_info_release(nullptr),544 m_dyld_process_info_get_cache(nullptr),545 m_dyld_process_info_get_state(nullptr),546 m_dyld_shared_cache_file_path(nullptr) {547 m_dyld_process_info_create =548 (void *(*)(task_t task, uint64_t timestamp, kern_return_t * kernelError))549 dlsym(RTLD_DEFAULT, "_dyld_process_info_create");550 551 m_dyld_process_create_for_task =552 (void *(*)(task_read_t, kern_return_t *))dlsym(553 RTLD_DEFAULT, "dyld_process_create_for_task");554 m_dyld_process_snapshot_create_for_process =555 (void *(*)(void *, kern_return_t *))dlsym(556 RTLD_DEFAULT, "dyld_process_snapshot_create_for_process");557 m_dyld_process_snapshot_get_shared_cache = (void *(*)(void *))dlsym(558 RTLD_DEFAULT, "dyld_process_snapshot_get_shared_cache");559 m_dyld_shared_cache_for_each_file =560 (void (*)(void *, void (^)(const char *)))dlsym(561 RTLD_DEFAULT, "dyld_shared_cache_for_each_file");562 m_dyld_process_snapshot_dispose =563 (void (*)(void *))dlsym(RTLD_DEFAULT, "dyld_process_snapshot_dispose");564 m_dyld_process_dispose =565 (void (*)(void *))dlsym(RTLD_DEFAULT, "dyld_process_dispose");566 m_dyld_process_info_for_each_image =567 (void (*)(void *info, void (^)(uint64_t machHeaderAddress,568 const uuid_t uuid, const char *path)))569 dlsym(RTLD_DEFAULT, "_dyld_process_info_for_each_image");570 m_dyld_process_info_release =571 (void (*)(void *info))dlsym(RTLD_DEFAULT, "_dyld_process_info_release");572 m_dyld_process_info_get_cache = (void (*)(void *info, void *cacheInfo))dlsym(573 RTLD_DEFAULT, "_dyld_process_info_get_cache");574 m_dyld_process_info_get_platform = (uint32_t (*)(void *info))dlsym(575 RTLD_DEFAULT, "_dyld_process_info_get_platform");576 m_dyld_process_info_get_state = (void (*)(void *info, void *stateInfo))dlsym(577 RTLD_DEFAULT, "_dyld_process_info_get_state");578 m_dyld_shared_cache_file_path =579 (const char *(*)())dlsym(RTLD_DEFAULT, "dyld_shared_cache_file_path");580 581 DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);582}583 584MachProcess::~MachProcess() {585 DNBLogThreadedIf(LOG_PROCESS | LOG_VERBOSE, "%s", __PRETTY_FUNCTION__);586 Clear();587}588 589pid_t MachProcess::SetProcessID(pid_t pid) {590 // Free any previous process specific data or resources591 Clear();592 // Set the current PID appropriately593 if (pid == 0)594 m_pid = ::getpid();595 else596 m_pid = pid;597 return m_pid; // Return actually PID in case a zero pid was passed in598}599 600nub_state_t MachProcess::GetState() {601 // If any other threads access this we will need a mutex for it602 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);603 return m_state;604}605 606const char *MachProcess::ThreadGetName(nub_thread_t tid) {607 return m_thread_list.GetName(tid);608}609 610nub_state_t MachProcess::ThreadGetState(nub_thread_t tid) {611 return m_thread_list.GetState(tid);612}613 614nub_size_t MachProcess::GetNumThreads() const {615 return m_thread_list.NumThreads();616}617 618nub_thread_t MachProcess::GetThreadAtIndex(nub_size_t thread_idx) const {619 return m_thread_list.ThreadIDAtIndex(thread_idx);620}621 622nub_thread_t623MachProcess::GetThreadIDForMachPortNumber(thread_t mach_port_number) const {624 return m_thread_list.GetThreadIDByMachPortNumber(mach_port_number);625}626 627nub_bool_t MachProcess::SyncThreadState(nub_thread_t tid) {628 MachThreadSP thread_sp(m_thread_list.GetThreadByID(tid));629 if (!thread_sp)630 return false;631 kern_return_t kret = ::thread_abort_safely(thread_sp->MachPortNumber());632 DNBLogThreadedIf(LOG_THREAD, "thread = 0x%8.8" PRIx32633 " calling thread_abort_safely (tid) => %u "634 "(GetGPRState() for stop_count = %u)",635 thread_sp->MachPortNumber(), kret,636 thread_sp->Process()->StopCount());637 638 if (kret == KERN_SUCCESS)639 return true;640 else641 return false;642}643 644ThreadInfo::QoS MachProcess::GetRequestedQoS(nub_thread_t tid, nub_addr_t tsd,645 uint64_t dti_qos_class_index) {646 return m_thread_list.GetRequestedQoS(tid, tsd, dti_qos_class_index);647}648 649nub_addr_t MachProcess::GetPThreadT(nub_thread_t tid) {650 return m_thread_list.GetPThreadT(tid);651}652 653nub_addr_t MachProcess::GetDispatchQueueT(nub_thread_t tid) {654 return m_thread_list.GetDispatchQueueT(tid);655}656 657nub_addr_t MachProcess::GetTSDAddressForThread(658 nub_thread_t tid, uint64_t plo_pthread_tsd_base_address_offset,659 uint64_t plo_pthread_tsd_base_offset, uint64_t plo_pthread_tsd_entry_size) {660 return m_thread_list.GetTSDAddressForThread(661 tid, plo_pthread_tsd_base_address_offset, plo_pthread_tsd_base_offset,662 plo_pthread_tsd_entry_size);663}664 665MachProcess::DeploymentInfo666MachProcess::GetDeploymentInfo(const struct load_command &lc,667 uint64_t load_command_address,668 bool is_executable) {669 DeploymentInfo info;670 uint32_t cmd = lc.cmd & ~LC_REQ_DYLD;671 672 // Handle the older LC_VERSION load commands, which don't673 // distinguish between simulator and real hardware.674 auto handle_version_min = [&](char platform) {675 struct version_min_command vers_cmd;676 if (ReadMemory(load_command_address, sizeof(struct version_min_command),677 &vers_cmd) != sizeof(struct version_min_command))678 return;679 info.platform = platform;680 info.major_version = vers_cmd.version >> 16;681 info.minor_version = (vers_cmd.version >> 8) & 0xffu;682 info.patch_version = vers_cmd.version & 0xffu;683 684 // Disambiguate legacy simulator platforms.685#if (defined(__x86_64__) || defined(__i386__))686 // If we are running on Intel macOS, it is safe to assume this is687 // really a back-deploying simulator binary.688 switch (info.platform) {689 case PLATFORM_IOS:690 info.platform = PLATFORM_IOSSIMULATOR;691 break;692 case PLATFORM_TVOS:693 info.platform = PLATFORM_TVOSSIMULATOR;694 break;695 case PLATFORM_WATCHOS:696 info.platform = PLATFORM_WATCHOSSIMULATOR;697 break;698 }699#else700 // On an Apple Silicon macOS host, there is no ambiguity. The only701 // binaries that use legacy load commands are back-deploying702 // native iOS binaries. All simulator binaries use the newer,703 // unambiguous LC_BUILD_VERSION load commands.704#endif705 };706 707 switch (cmd) {708 case LC_VERSION_MIN_IPHONEOS:709 handle_version_min(PLATFORM_IOS);710 break;711 case LC_VERSION_MIN_MACOSX:712 handle_version_min(PLATFORM_MACOS);713 break;714 case LC_VERSION_MIN_TVOS:715 handle_version_min(PLATFORM_TVOS);716 break;717 case LC_VERSION_MIN_WATCHOS:718 handle_version_min(PLATFORM_WATCHOS);719 break;720#if defined(LC_BUILD_VERSION)721 case LC_BUILD_VERSION: {722 struct build_version_command build_vers;723 if (ReadMemory(load_command_address, sizeof(struct build_version_command),724 &build_vers) != sizeof(struct build_version_command))725 break;726 info.platform = build_vers.platform;727 info.major_version = build_vers.minos >> 16;728 info.minor_version = (build_vers.minos >> 8) & 0xffu;729 info.patch_version = build_vers.minos & 0xffu;730 break;731 }732#endif733 }734 735 // The xctest binary is a pure macOS binary but is launched with736 // DYLD_FORCE_PLATFORM=6. In that case, force the platform to737 // macCatalyst and use the macCatalyst version of the host OS738 // instead of the macOS deployment target.739 if (is_executable && GetPlatform() == PLATFORM_MACCATALYST) {740 info.platform = PLATFORM_MACCATALYST;741 std::string catalyst_version = GetMacCatalystVersionString();742 const char *major = catalyst_version.c_str();743 char *minor = nullptr;744 char *patch = nullptr;745 info.major_version = std::strtoul(major, &minor, 10);746 info.minor_version = 0;747 info.patch_version = 0;748 if (minor && *minor == '.') {749 info.minor_version = std::strtoul(++minor, &patch, 10);750 if (patch && *patch == '.')751 info.patch_version = std::strtoul(++patch, nullptr, 10);752 }753 }754 755 return info;756}757 758std::optional<std::string>759MachProcess::GetPlatformString(unsigned char platform) {760 switch (platform) {761 case PLATFORM_MACOS:762 return "macosx";763 case PLATFORM_MACCATALYST:764 return "maccatalyst";765 case PLATFORM_IOS:766 return "ios";767 case PLATFORM_IOSSIMULATOR:768 return "iossimulator";769 case PLATFORM_TVOS:770 return "tvos";771 case PLATFORM_TVOSSIMULATOR:772 return "tvossimulator";773 case PLATFORM_WATCHOS:774 return "watchos";775 case PLATFORM_WATCHOSSIMULATOR:776 return "watchossimulator";777 case PLATFORM_BRIDGEOS:778 return "bridgeos";779 case PLATFORM_DRIVERKIT:780 return "driverkit";781 case PLATFORM_VISIONOS:782 return "xros";783 case PLATFORM_VISIONOSSIMULATOR:784 return "xrossimulator";785 default:786 DNBLogError("Unknown platform %u found for one binary", platform);787 return std::nullopt;788 }789}790 791static bool mach_header_validity_test(uint32_t magic, uint32_t cputype) {792 if (magic != MH_MAGIC && magic != MH_CIGAM && magic != MH_MAGIC_64 &&793 magic != MH_CIGAM_64)794 return false;795 if (cputype != CPU_TYPE_I386 && cputype != CPU_TYPE_X86_64 &&796 cputype != CPU_TYPE_ARM && cputype != CPU_TYPE_ARM64 &&797 cputype != CPU_TYPE_ARM64_32)798 return false;799 return true;800}801 802// Given an address, read the mach-o header and load commands out of memory to803// fill in804// the mach_o_information "inf" object.805//806// Returns false if there was an error in reading this mach-o file header/load807// commands.808 809bool MachProcess::GetMachOInformationFromMemory(810 uint32_t dyld_platform, nub_addr_t mach_o_header_addr, int wordsize,811 struct mach_o_information &inf) {812 uint64_t load_cmds_p;813 814 if (wordsize == 4) {815 struct mach_header header;816 if (ReadMemory(mach_o_header_addr, sizeof(struct mach_header), &header) !=817 sizeof(struct mach_header)) {818 return false;819 }820 if (!mach_header_validity_test(header.magic, header.cputype))821 return false;822 823 load_cmds_p = mach_o_header_addr + sizeof(struct mach_header);824 inf.mach_header.magic = header.magic;825 inf.mach_header.cputype = header.cputype;826 // high byte of cpusubtype is used for "capability bits", v.827 // CPU_SUBTYPE_MASK, CPU_SUBTYPE_LIB64 in machine.h828 inf.mach_header.cpusubtype = header.cpusubtype & 0x00ffffff;829 inf.mach_header.filetype = header.filetype;830 inf.mach_header.ncmds = header.ncmds;831 inf.mach_header.sizeofcmds = header.sizeofcmds;832 inf.mach_header.flags = header.flags;833 } else {834 struct mach_header_64 header;835 if (ReadMemory(mach_o_header_addr, sizeof(struct mach_header_64),836 &header) != sizeof(struct mach_header_64)) {837 return false;838 }839 if (!mach_header_validity_test(header.magic, header.cputype))840 return false;841 load_cmds_p = mach_o_header_addr + sizeof(struct mach_header_64);842 inf.mach_header.magic = header.magic;843 inf.mach_header.cputype = header.cputype;844 // high byte of cpusubtype is used for "capability bits", v.845 // CPU_SUBTYPE_MASK, CPU_SUBTYPE_LIB64 in machine.h846 inf.mach_header.cpusubtype = header.cpusubtype & 0x00ffffff;847 inf.mach_header.filetype = header.filetype;848 inf.mach_header.ncmds = header.ncmds;849 inf.mach_header.sizeofcmds = header.sizeofcmds;850 inf.mach_header.flags = header.flags;851 }852 for (uint32_t j = 0; j < inf.mach_header.ncmds; j++) {853 struct load_command lc;854 if (ReadMemory(load_cmds_p, sizeof(struct load_command), &lc) !=855 sizeof(struct load_command)) {856 return false;857 }858 if (lc.cmd == LC_SEGMENT) {859 struct segment_command seg;860 if (ReadMemory(load_cmds_p, sizeof(struct segment_command), &seg) !=861 sizeof(struct segment_command)) {862 return false;863 }864 struct mach_o_segment this_seg;865 char name[17];866 ::memset(name, 0, sizeof(name));867 memcpy(name, seg.segname, sizeof(seg.segname));868 this_seg.name = name;869 this_seg.vmaddr = seg.vmaddr;870 this_seg.vmsize = seg.vmsize;871 this_seg.fileoff = seg.fileoff;872 this_seg.filesize = seg.filesize;873 this_seg.maxprot = seg.maxprot;874 this_seg.initprot = seg.initprot;875 this_seg.nsects = seg.nsects;876 this_seg.flags = seg.flags;877 inf.segments.push_back(this_seg);878 if (this_seg.name == "ExecExtraSuspend")879 m_task.TaskWillExecProcessesSuspended();880 }881 if (lc.cmd == LC_SEGMENT_64) {882 struct segment_command_64 seg;883 if (ReadMemory(load_cmds_p, sizeof(struct segment_command_64), &seg) !=884 sizeof(struct segment_command_64)) {885 return false;886 }887 struct mach_o_segment this_seg;888 char name[17];889 ::memset(name, 0, sizeof(name));890 memcpy(name, seg.segname, sizeof(seg.segname));891 this_seg.name = name;892 this_seg.vmaddr = seg.vmaddr;893 this_seg.vmsize = seg.vmsize;894 this_seg.fileoff = seg.fileoff;895 this_seg.filesize = seg.filesize;896 this_seg.maxprot = seg.maxprot;897 this_seg.initprot = seg.initprot;898 this_seg.nsects = seg.nsects;899 this_seg.flags = seg.flags;900 inf.segments.push_back(this_seg);901 if (this_seg.name == "ExecExtraSuspend")902 m_task.TaskWillExecProcessesSuspended();903 }904 if (lc.cmd == LC_UUID) {905 struct uuid_command uuidcmd;906 if (ReadMemory(load_cmds_p, sizeof(struct uuid_command), &uuidcmd) ==907 sizeof(struct uuid_command))908 uuid_copy(inf.uuid, uuidcmd.uuid);909 }910 if (DeploymentInfo deployment_info = GetDeploymentInfo(911 lc, load_cmds_p, inf.mach_header.filetype == MH_EXECUTE)) {912 std::optional<std::string> lc_platform =913 GetPlatformString(deployment_info.platform);914 if (dyld_platform != PLATFORM_MACCATALYST &&915 inf.min_version_os_name == "macosx") {916 // macCatalyst support.917 //918 // This the special case of "zippered" frameworks that have both919 // a PLATFORM_MACOS and a PLATFORM_MACCATALYST load command.920 //921 // When we are in this block, this is a binary with both922 // PLATFORM_MACOS and PLATFORM_MACCATALYST load commands and923 // the process is not running as PLATFORM_MACCATALYST. Stick924 // with the "macosx" load command that we've already925 // processed, ignore this one, which is presumed to be a926 // PLATFORM_MACCATALYST one.927 } else {928 inf.min_version_os_name = lc_platform.value_or("");929 inf.min_version_os_version = "";930 inf.min_version_os_version +=931 std::to_string(deployment_info.major_version);932 inf.min_version_os_version += ".";933 inf.min_version_os_version +=934 std::to_string(deployment_info.minor_version);935 if (deployment_info.patch_version != 0) {936 inf.min_version_os_version += ".";937 inf.min_version_os_version +=938 std::to_string(deployment_info.patch_version);939 }940 }941 }942 943 load_cmds_p += lc.cmdsize;944 }945 return true;946}947 948// Given completely filled in array of binary_image_information structures,949// create a JSONGenerator object950// with all the details we want to send to lldb.951JSONGenerator::ObjectSP MachProcess::FormatDynamicLibrariesIntoJSON(952 const std::vector<struct binary_image_information> &image_infos,953 bool report_load_commands) {954 955 JSONGenerator::ArraySP image_infos_array_sp(new JSONGenerator::Array());956 957 const size_t image_count = image_infos.size();958 959 for (size_t i = 0; i < image_count; i++) {960 // If we should report the Mach-O header and load commands,961 // and those were unreadable, don't report anything about this962 // binary.963 if (report_load_commands && !image_infos[i].is_valid_mach_header)964 continue;965 JSONGenerator::DictionarySP image_info_dict_sp(966 new JSONGenerator::Dictionary());967 image_info_dict_sp->AddIntegerItem("load_address",968 image_infos[i].load_address);969 // TODO: lldb currently rejects a response without this, but it970 // is always zero from dyld. It can be removed once we've had time971 // for lldb's that require it to be present are obsolete.972 image_info_dict_sp->AddIntegerItem("mod_date", 0);973 image_info_dict_sp->AddStringItem("pathname", image_infos[i].filename);974 975 if (!report_load_commands) {976 image_infos_array_sp->AddItem(image_info_dict_sp);977 continue;978 }979 980 uuid_string_t uuidstr;981 uuid_unparse_upper(image_infos[i].macho_info.uuid, uuidstr);982 image_info_dict_sp->AddStringItem("uuid", uuidstr);983 984 if (!image_infos[i].macho_info.min_version_os_name.empty() &&985 !image_infos[i].macho_info.min_version_os_version.empty()) {986 image_info_dict_sp->AddStringItem(987 "min_version_os_name", image_infos[i].macho_info.min_version_os_name);988 image_info_dict_sp->AddStringItem(989 "min_version_os_sdk",990 image_infos[i].macho_info.min_version_os_version);991 }992 993 JSONGenerator::DictionarySP mach_header_dict_sp(994 new JSONGenerator::Dictionary());995 mach_header_dict_sp->AddIntegerItem(996 "magic", image_infos[i].macho_info.mach_header.magic);997 mach_header_dict_sp->AddIntegerItem(998 "cputype", (uint32_t)image_infos[i].macho_info.mach_header.cputype);999 mach_header_dict_sp->AddIntegerItem(1000 "cpusubtype",1001 (uint32_t)image_infos[i].macho_info.mach_header.cpusubtype);1002 mach_header_dict_sp->AddIntegerItem(1003 "filetype", image_infos[i].macho_info.mach_header.filetype);1004 mach_header_dict_sp->AddIntegerItem ("flags", 1005 image_infos[i].macho_info.mach_header.flags);1006 1007 // DynamicLoaderMacOSX doesn't currently need these fields, so1008 // don't send them.1009 // mach_header_dict_sp->AddIntegerItem ("ncmds",1010 // image_infos[i].macho_info.mach_header.ncmds);1011 // mach_header_dict_sp->AddIntegerItem ("sizeofcmds",1012 // image_infos[i].macho_info.mach_header.sizeofcmds);1013 image_info_dict_sp->AddItem("mach_header", mach_header_dict_sp);1014 1015 JSONGenerator::ArraySP segments_sp(new JSONGenerator::Array());1016 for (size_t j = 0; j < image_infos[i].macho_info.segments.size(); j++) {1017 JSONGenerator::DictionarySP segment_sp(new JSONGenerator::Dictionary());1018 segment_sp->AddStringItem("name",1019 image_infos[i].macho_info.segments[j].name);1020 segment_sp->AddIntegerItem("vmaddr",1021 image_infos[i].macho_info.segments[j].vmaddr);1022 segment_sp->AddIntegerItem("vmsize",1023 image_infos[i].macho_info.segments[j].vmsize);1024 segment_sp->AddIntegerItem("fileoff",1025 image_infos[i].macho_info.segments[j].fileoff);1026 segment_sp->AddIntegerItem(1027 "filesize", image_infos[i].macho_info.segments[j].filesize);1028 segment_sp->AddIntegerItem("maxprot",1029 image_infos[i].macho_info.segments[j].maxprot);1030 1031 // DynamicLoaderMacOSX doesn't currently need these fields,1032 // so don't send them.1033 // segment_sp->AddIntegerItem ("initprot",1034 // image_infos[i].macho_info.segments[j].initprot);1035 // segment_sp->AddIntegerItem ("nsects",1036 // image_infos[i].macho_info.segments[j].nsects);1037 // segment_sp->AddIntegerItem ("flags",1038 // image_infos[i].macho_info.segments[j].flags);1039 segments_sp->AddItem(segment_sp);1040 }1041 image_info_dict_sp->AddItem("segments", segments_sp);1042 1043 image_infos_array_sp->AddItem(image_info_dict_sp);1044 }1045 1046 JSONGenerator::DictionarySP reply_sp(new JSONGenerator::Dictionary());1047 reply_sp->AddItem("images", image_infos_array_sp);1048 1049 return reply_sp;1050}1051 1052/// From dyld SPI header dyld_process_info.h1053typedef void *dyld_process_info;1054struct dyld_process_cache_info {1055 /// UUID of cache used by process.1056 uuid_t cacheUUID;1057 /// Load address of dyld shared cache.1058 uint64_t cacheBaseAddress;1059 /// Process is running without a dyld cache.1060 bool noCache;1061 /// Process is using a private copy of its dyld cache.1062 bool privateCache;1063};1064 1065uint32_t MachProcess::GetPlatform() {1066 if (m_platform == 0)1067 m_platform = MachProcess::GetProcessPlatformViaDYLDSPI();1068 return m_platform;1069}1070 1071uint32_t MachProcess::GetProcessPlatformViaDYLDSPI() {1072 kern_return_t kern_ret;1073 uint32_t platform = 0;1074 if (m_dyld_process_info_create) {1075 dyld_process_info info =1076 m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret);1077 if (info) {1078 if (m_dyld_process_info_get_platform)1079 platform = m_dyld_process_info_get_platform(info);1080 m_dyld_process_info_release(info);1081 }1082 }1083 return platform;1084}1085 1086void MachProcess::GetAllLoadedBinariesViaDYLDSPI(1087 std::vector<struct binary_image_information> &image_infos) {1088 kern_return_t kern_ret;1089 if (m_dyld_process_info_create) {1090 dyld_process_info info =1091 m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret);1092 if (info) {1093 // There's a bug in the interaction between dyld and older dyld_sim's1094 // (e.g. from the iOS 15 simulator) that causes dyld to report the same1095 // binary twice. We use this set to eliminate the duplicates.1096 __block std::unordered_set<uint64_t> seen_header_addrs;1097 m_dyld_process_info_for_each_image(1098 info,1099 ^(uint64_t mach_header_addr, const uuid_t uuid, const char *path) {1100 auto res_pair = seen_header_addrs.insert(mach_header_addr);1101 if (!res_pair.second)1102 return;1103 struct binary_image_information image;1104 image.filename = path;1105 uuid_copy(image.macho_info.uuid, uuid);1106 image.load_address = mach_header_addr;1107 image_infos.push_back(image);1108 });1109 m_dyld_process_info_release(info);1110 }1111 }1112}1113 1114// Fetch information about all shared libraries using the dyld SPIs that exist1115// in1116// macOS 10.12, iOS 10, tvOS 10, watchOS 3 and newer.1117JSONGenerator::ObjectSP1118MachProcess::GetAllLoadedLibrariesInfos(nub_process_t pid,1119 bool report_load_commands) {1120 1121 int pointer_size = GetInferiorAddrSize(pid);1122 std::vector<struct binary_image_information> image_infos;1123 GetAllLoadedBinariesViaDYLDSPI(image_infos);1124 if (report_load_commands) {1125 uint32_t platform = GetPlatform();1126 const size_t image_count = image_infos.size();1127 for (size_t i = 0; i < image_count; i++) {1128 if (GetMachOInformationFromMemory(platform, image_infos[i].load_address,1129 pointer_size,1130 image_infos[i].macho_info)) {1131 image_infos[i].is_valid_mach_header = true;1132 }1133 }1134 }1135 return FormatDynamicLibrariesIntoJSON(image_infos, report_load_commands);1136}1137 1138std::optional<std::pair<cpu_type_t, cpu_subtype_t>>1139MachProcess::GetMainBinaryCPUTypes(nub_process_t pid) {1140 int pointer_size = GetInferiorAddrSize(pid);1141 std::vector<struct binary_image_information> image_infos;1142 GetAllLoadedBinariesViaDYLDSPI(image_infos);1143 uint32_t platform = GetPlatform();1144 for (auto &image_info : image_infos)1145 if (GetMachOInformationFromMemory(platform, image_info.load_address,1146 pointer_size, image_info.macho_info))1147 if (image_info.macho_info.mach_header.filetype == MH_EXECUTE)1148 return {1149 {static_cast<cpu_type_t>(image_info.macho_info.mach_header.cputype),1150 static_cast<cpu_subtype_t>(1151 image_info.macho_info.mach_header.cpusubtype)}};1152 return {};1153}1154 1155// Fetch information about the shared libraries at the given load addresses1156// using the1157// dyld SPIs that exist in macOS 10.12, iOS 10, tvOS 10, watchOS 3 and newer.1158JSONGenerator::ObjectSP MachProcess::GetLibrariesInfoForAddresses(1159 nub_process_t pid, std::vector<uint64_t> &macho_addresses) {1160 1161 int pointer_size = GetInferiorAddrSize(pid);1162 1163 // Collect the list of all binaries that dyld knows about in1164 // the inferior process.1165 std::vector<struct binary_image_information> all_image_infos;1166 GetAllLoadedBinariesViaDYLDSPI(all_image_infos);1167 uint32_t platform = GetPlatform();1168 1169 std::vector<struct binary_image_information> image_infos;1170 const size_t macho_addresses_count = macho_addresses.size();1171 const size_t all_image_infos_count = all_image_infos.size();1172 1173 for (size_t i = 0; i < macho_addresses_count; i++) {1174 bool found_matching_entry = false;1175 for (size_t j = 0; j < all_image_infos_count; j++) {1176 if (all_image_infos[j].load_address == macho_addresses[i]) {1177 image_infos.push_back(all_image_infos[j]);1178 found_matching_entry = true;1179 }1180 }1181 if (!found_matching_entry) {1182 // dyld doesn't think there is a binary at this address,1183 // but maybe there isn't a binary YET - let's look in memory1184 // for a proper mach-o header etc and return what we can.1185 // We will have an empty filename for the binary (because dyld1186 // doesn't know about it yet) but we can read all of the mach-o1187 // load commands from memory directly.1188 struct binary_image_information entry;1189 entry.load_address = macho_addresses[i];1190 image_infos.push_back(entry);1191 }1192 }1193 1194 const size_t image_infos_count = image_infos.size();1195 for (size_t i = 0; i < image_infos_count; i++) {1196 if (GetMachOInformationFromMemory(platform, image_infos[i].load_address,1197 pointer_size,1198 image_infos[i].macho_info)) {1199 image_infos[i].is_valid_mach_header = true;1200 }1201 }1202 return FormatDynamicLibrariesIntoJSON(image_infos,1203 /* report_load_commands = */ true);1204}1205 1206bool MachProcess::GetDebugserverSharedCacheInfo(1207 uuid_t &uuid, std::string &shared_cache_path) {1208 uuid_clear(uuid);1209 shared_cache_path.clear();1210 1211 if (m_dyld_process_info_create && m_dyld_process_info_get_cache) {1212 kern_return_t kern_ret;1213 dyld_process_info info =1214 m_dyld_process_info_create(mach_task_self(), 0, &kern_ret);1215 if (info) {1216 struct dyld_process_cache_info shared_cache_info;1217 m_dyld_process_info_get_cache(info, &shared_cache_info);1218 uuid_copy(uuid, shared_cache_info.cacheUUID);1219 m_dyld_process_info_release(info);1220 }1221 }1222 if (m_dyld_shared_cache_file_path) {1223 const char *cache_path = m_dyld_shared_cache_file_path();1224 if (cache_path)1225 shared_cache_path = cache_path;1226 }1227 if (!uuid_is_null(uuid))1228 return true;1229 return false;1230}1231 1232bool MachProcess::GetInferiorSharedCacheFilepath(1233 std::string &inferior_sc_path) {1234 inferior_sc_path.clear();1235 1236 if (!m_dyld_process_create_for_task ||1237 !m_dyld_process_snapshot_create_for_process ||1238 !m_dyld_process_snapshot_get_shared_cache ||1239 !m_dyld_shared_cache_for_each_file || !m_dyld_process_snapshot_dispose ||1240 !m_dyld_process_dispose)1241 return false;1242 1243 __block std::string sc_path;1244 kern_return_t kr;1245 void *process = m_dyld_process_create_for_task(m_task.TaskPort(), &kr);1246 if (kr != KERN_SUCCESS)1247 return false;1248 void *snapshot = m_dyld_process_snapshot_create_for_process(process, &kr);1249 if (kr != KERN_SUCCESS)1250 return false;1251 void *cache = m_dyld_process_snapshot_get_shared_cache(snapshot);1252 1253 // The shared cache is a collection of files on disk, this callback1254 // will iterate over all of them.1255 // The first filepath provided is the base filename of the cache.1256 __block bool done = false;1257 m_dyld_shared_cache_for_each_file(cache, ^(const char *path) {1258 if (done) {1259 return;1260 }1261 done = true;1262 sc_path = path;1263 });1264 m_dyld_process_snapshot_dispose(snapshot);1265 m_dyld_process_dispose(process);1266 1267 inferior_sc_path = sc_path;1268 if (!sc_path.empty())1269 return true;1270 return false;1271}1272 1273// From dyld's internal dyld_process_info.h:1274 1275JSONGenerator::ObjectSP1276MachProcess::GetInferiorSharedCacheInfo(nub_process_t pid) {1277 JSONGenerator::DictionarySP reply_sp(new JSONGenerator::Dictionary());1278 1279 uuid_t inferior_sc_uuid;1280 if (m_dyld_process_info_create && m_dyld_process_info_get_cache) {1281 kern_return_t kern_ret;1282 dyld_process_info info =1283 m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret);1284 if (info) {1285 struct dyld_process_cache_info shared_cache_info;1286 m_dyld_process_info_get_cache(info, &shared_cache_info);1287 1288 reply_sp->AddIntegerItem("shared_cache_base_address",1289 shared_cache_info.cacheBaseAddress);1290 1291 uuid_string_t uuidstr;1292 uuid_unparse_upper(shared_cache_info.cacheUUID, uuidstr);1293 uuid_copy(inferior_sc_uuid, shared_cache_info.cacheUUID);1294 reply_sp->AddStringItem("shared_cache_uuid", uuidstr);1295 1296 reply_sp->AddBooleanItem("no_shared_cache", shared_cache_info.noCache);1297 reply_sp->AddBooleanItem("shared_cache_private_cache",1298 shared_cache_info.privateCache);1299 1300 m_dyld_process_info_release(info);1301 }1302 }1303 1304 // If debugserver and the inferior are have the same cache UUID,1305 // use the simple call to get the filepath to debugserver's shared1306 // cache, return that.1307 uuid_t debugserver_sc_uuid;1308 std::string debugserver_sc_path;1309 bool found_sc_filepath = false;1310 if (GetDebugserverSharedCacheInfo(debugserver_sc_uuid, debugserver_sc_path)) {1311 if (uuid_compare(inferior_sc_uuid, debugserver_sc_uuid) == 0 &&1312 !debugserver_sc_path.empty()) {1313 reply_sp->AddStringItem("shared_cache_path", debugserver_sc_path);1314 found_sc_filepath = true;1315 }1316 }1317 1318 // Use SPI that are only available on newer OSes to fetch the1319 // filepath of the shared cache of the inferior, if available.1320 if (!found_sc_filepath) {1321 std::string inferior_sc_path;1322 if (GetInferiorSharedCacheFilepath(inferior_sc_path))1323 reply_sp->AddStringItem("shared_cache_path", inferior_sc_path);1324 }1325 1326 return reply_sp;1327}1328 1329nub_thread_t MachProcess::GetCurrentThread() {1330 return m_thread_list.CurrentThreadID();1331}1332 1333nub_thread_t MachProcess::GetCurrentThreadMachPort() {1334 return m_thread_list.GetMachPortNumberByThreadID(1335 m_thread_list.CurrentThreadID());1336}1337 1338nub_thread_t MachProcess::SetCurrentThread(nub_thread_t tid) {1339 return m_thread_list.SetCurrentThread(tid);1340}1341 1342bool MachProcess::GetThreadStoppedReason(nub_thread_t tid,1343 struct DNBThreadStopInfo *stop_info) {1344 if (m_thread_list.GetThreadStoppedReason(tid, stop_info)) {1345 if (m_did_exec)1346 stop_info->reason = eStopTypeExec;1347 if (stop_info->reason == eStopTypeWatchpoint)1348 RefineWatchpointStopInfo(tid, stop_info);1349 return true;1350 }1351 return false;1352}1353 1354void MachProcess::DumpThreadStoppedReason(nub_thread_t tid) const {1355 return m_thread_list.DumpThreadStoppedReason(tid);1356}1357 1358const char *MachProcess::GetThreadInfo(nub_thread_t tid) const {1359 return m_thread_list.GetThreadInfo(tid);1360}1361 1362uint32_t MachProcess::GetCPUType() {1363 if (m_cpu_type == 0 && m_pid != 0)1364 m_cpu_type = MachProcess::GetCPUTypeForLocalProcess(m_pid);1365 return m_cpu_type;1366}1367 1368const DNBRegisterSetInfo *1369MachProcess::GetRegisterSetInfo(nub_thread_t tid,1370 nub_size_t *num_reg_sets) const {1371 MachThreadSP thread_sp(m_thread_list.GetThreadByID(tid));1372 if (thread_sp) {1373 DNBArchProtocol *arch = thread_sp->GetArchProtocol();1374 if (arch)1375 return arch->GetRegisterSetInfo(num_reg_sets);1376 }1377 *num_reg_sets = 0;1378 return NULL;1379}1380 1381bool MachProcess::GetRegisterValue(nub_thread_t tid, uint32_t set, uint32_t reg,1382 DNBRegisterValue *value) const {1383 return m_thread_list.GetRegisterValue(tid, set, reg, value);1384}1385 1386bool MachProcess::SetRegisterValue(nub_thread_t tid, uint32_t set, uint32_t reg,1387 const DNBRegisterValue *value) const {1388 return m_thread_list.SetRegisterValue(tid, set, reg, value);1389}1390 1391void MachProcess::SetState(nub_state_t new_state) {1392 // If any other threads access this we will need a mutex for it1393 uint32_t event_mask = 0;1394 1395 // Scope for mutex locker1396 {1397 std::lock_guard<std::recursive_mutex> guard(m_state_mutex);1398 const nub_state_t old_state = m_state;1399 1400 if (old_state == eStateExited) {1401 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::SetState(%s) ignoring new "1402 "state since current state is exited",1403 DNBStateAsString(new_state));1404 } else if (old_state == new_state) {1405 DNBLogThreadedIf(1406 LOG_PROCESS,1407 "MachProcess::SetState(%s) ignoring redundant state change...",1408 DNBStateAsString(new_state));1409 } else {1410 if (NUB_STATE_IS_STOPPED(new_state))1411 event_mask = eEventProcessStoppedStateChanged;1412 else1413 event_mask = eEventProcessRunningStateChanged;1414 1415 DNBLogThreadedIf(1416 LOG_PROCESS, "MachProcess::SetState(%s) upating state (previous "1417 "state was %s), event_mask = 0x%8.8x",1418 DNBStateAsString(new_state), DNBStateAsString(old_state), event_mask);1419 1420 m_state = new_state;1421 if (new_state == eStateStopped)1422 m_stop_count++;1423 }1424 }1425 1426 if (event_mask != 0) {1427 m_events.SetEvents(event_mask);1428 m_private_events.SetEvents(event_mask);1429 if (event_mask == eEventProcessStoppedStateChanged)1430 m_private_events.ResetEvents(eEventProcessRunningStateChanged);1431 else1432 m_private_events.ResetEvents(eEventProcessStoppedStateChanged);1433 1434 // Wait for the event bit to reset if a reset ACK is requested1435 m_events.WaitForResetAck(event_mask);1436 }1437}1438 1439void MachProcess::Clear(bool detaching) {1440 // Clear any cached thread list while the pid and task are still valid1441 1442 m_task.Clear();1443 m_platform = 0;1444 // Now clear out all member variables1445 m_pid = INVALID_NUB_PROCESS;1446 if (!detaching)1447 CloseChildFileDescriptors();1448 1449 m_path.clear();1450 m_args.clear();1451 SetState(eStateUnloaded);1452 m_flags = eMachProcessFlagsNone;1453 m_stop_count = 0;1454 m_thread_list.Clear();1455 {1456 std::lock_guard<std::recursive_mutex> guard(m_exception_and_signal_mutex);1457 m_exception_messages.clear();1458 m_sent_interrupt_signo = 0;1459 m_auto_resume_signo = 0;1460 1461 }1462 m_activities.Clear();1463 StopProfileThread();1464}1465 1466bool MachProcess::StartSTDIOThread() {1467 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);1468 // Create the thread that watches for the child STDIO1469 return ::pthread_create(&m_stdio_thread, NULL, MachProcess::STDIOThread,1470 this) == 0;1471}1472 1473void MachProcess::SetEnableAsyncProfiling(bool enable, uint64_t interval_usec,1474 DNBProfileDataScanType scan_type) {1475 m_profile_enabled = enable;1476 m_profile_interval_usec = static_cast<useconds_t>(interval_usec);1477 m_profile_scan_type = scan_type;1478 1479 if (m_profile_enabled && (m_profile_thread == NULL)) {1480 StartProfileThread();1481 } else if (!m_profile_enabled && m_profile_thread) {1482 StopProfileThread();1483 }1484}1485 1486void MachProcess::StopProfileThread() {1487 if (m_profile_thread == NULL)1488 return;1489 m_profile_events.SetEvents(eMachProcessProfileCancel);1490 pthread_join(m_profile_thread, NULL);1491 m_profile_thread = NULL;1492 m_profile_events.ResetEvents(eMachProcessProfileCancel);1493}1494 1495/// return 1 if bit position \a bit is set in \a value1496static uint32_t bit(uint32_t value, uint32_t bit) {1497 return (value >> bit) & 1u;1498}1499 1500// return the bitfield "value[msbit:lsbit]".1501static uint64_t bits(uint64_t value, uint32_t msbit, uint32_t lsbit) {1502 assert(msbit >= lsbit);1503 uint64_t shift_left = sizeof(value) * 8 - 1 - msbit;1504 value <<=1505 shift_left; // shift anything above the msbit off of the unsigned edge1506 value >>= shift_left + lsbit; // shift it back again down to the lsbit1507 // (including undoing any shift from above)1508 return value; // return our result1509}1510 1511void MachProcess::RefineWatchpointStopInfo(1512 nub_thread_t tid, struct DNBThreadStopInfo *stop_info) {1513 const DNBBreakpoint *wp = m_watchpoints.FindNearestWatchpoint(1514 stop_info->details.watchpoint.mach_exception_addr);1515 if (wp) {1516 stop_info->details.watchpoint.addr = wp->Address();1517 stop_info->details.watchpoint.hw_idx = wp->GetHardwareIndex();1518 DNBLogThreadedIf(LOG_WATCHPOINTS,1519 "MachProcess::RefineWatchpointStopInfo "1520 "mach exception addr 0x%llx moved in to nearest "1521 "watchpoint, 0x%llx-0x%llx",1522 stop_info->details.watchpoint.mach_exception_addr,1523 wp->Address(), wp->Address() + wp->ByteSize() - 1);1524 } else {1525 stop_info->details.watchpoint.addr =1526 stop_info->details.watchpoint.mach_exception_addr;1527 }1528 1529 stop_info->details.watchpoint.esr_fields_set = false;1530 std::optional<uint64_t> esr, far;1531 nub_size_t num_reg_sets = 0;1532 const DNBRegisterSetInfo *reg_sets = GetRegisterSetInfo(tid, &num_reg_sets);1533 for (nub_size_t set = 0; set < num_reg_sets; set++) {1534 if (reg_sets[set].registers == NULL)1535 continue;1536 for (uint32_t reg = 0; reg < reg_sets[set].num_registers; ++reg) {1537 if (strcmp(reg_sets[set].registers[reg].name, "esr") == 0) {1538 std::unique_ptr<DNBRegisterValue> reg_value =1539 std::make_unique<DNBRegisterValue>();1540 if (GetRegisterValue(tid, set, reg, reg_value.get())) {1541 esr = reg_value->value.uint64;1542 }1543 }1544 if (strcmp(reg_sets[set].registers[reg].name, "far") == 0) {1545 std::unique_ptr<DNBRegisterValue> reg_value =1546 std::make_unique<DNBRegisterValue>();1547 if (GetRegisterValue(tid, set, reg, reg_value.get())) {1548 far = reg_value->value.uint64;1549 }1550 }1551 }1552 }1553 1554 if (esr && far) {1555 if (*far != stop_info->details.watchpoint.mach_exception_addr) {1556 // AFAIK the kernel is going to put the FAR value in the mach1557 // exception, if they don't match, it's interesting enough to log it.1558 DNBLogThreadedIf(LOG_WATCHPOINTS,1559 "MachProcess::RefineWatchpointStopInfo mach exception "1560 "addr 0x%llx but FAR register has value 0x%llx",1561 stop_info->details.watchpoint.mach_exception_addr, *far);1562 }1563 uint32_t exception_class = bits(*esr, 31, 26);1564 1565 // "Watchpoint exception from a lower Exception level"1566 if (exception_class == 0b110100) {1567 stop_info->details.watchpoint.esr_fields_set = true;1568 // Documented in the ARM ARM A-Profile Dec 2022 edition1569 // Section D17.2 ("General system control registers"),1570 // Section D17.2.37 "ESR_EL1, Exception Syndrome Register (EL1)",1571 // "Field Descriptions"1572 // "ISS encoding for an exception from a Watchpoint exception"1573 uint32_t iss = bits(*esr, 23, 0);1574 stop_info->details.watchpoint.esr_fields.iss = iss;1575 stop_info->details.watchpoint.esr_fields.wpt =1576 bits(iss, 23, 18); // Watchpoint number1577 stop_info->details.watchpoint.esr_fields.wptv =1578 bit(iss, 17); // Watchpoint number Valid1579 stop_info->details.watchpoint.esr_fields.wpf =1580 bit(iss, 16); // Watchpoint might be false-positive1581 stop_info->details.watchpoint.esr_fields.fnp =1582 bit(iss, 15); // FAR not Precise1583 stop_info->details.watchpoint.esr_fields.vncr =1584 bit(iss, 13); // watchpoint from use of VNCR_EL2 reg by EL11585 stop_info->details.watchpoint.esr_fields.fnv =1586 bit(iss, 10); // FAR not Valid1587 stop_info->details.watchpoint.esr_fields.cm =1588 bit(iss, 6); // Cache maintenance1589 stop_info->details.watchpoint.esr_fields.wnr =1590 bit(iss, 6); // Write not Read1591 stop_info->details.watchpoint.esr_fields.dfsc =1592 bits(iss, 5, 0); // Data Fault Status Code1593 1594 DNBLogThreadedIf(LOG_WATCHPOINTS,1595 "ESR watchpoint fields parsed: "1596 "iss = 0x%x, wpt = %u, wptv = %d, wpf = %d, fnp = %d, "1597 "vncr = %d, fnv = %d, cm = %d, wnr = %d, dfsc = 0x%x",1598 stop_info->details.watchpoint.esr_fields.iss,1599 stop_info->details.watchpoint.esr_fields.wpt,1600 stop_info->details.watchpoint.esr_fields.wptv,1601 stop_info->details.watchpoint.esr_fields.wpf,1602 stop_info->details.watchpoint.esr_fields.fnp,1603 stop_info->details.watchpoint.esr_fields.vncr,1604 stop_info->details.watchpoint.esr_fields.fnv,1605 stop_info->details.watchpoint.esr_fields.cm,1606 stop_info->details.watchpoint.esr_fields.wnr,1607 stop_info->details.watchpoint.esr_fields.dfsc);1608 1609 if (stop_info->details.watchpoint.esr_fields.wptv) {1610 DNBLogThreadedIf(LOG_WATCHPOINTS,1611 "Watchpoint Valid field true, "1612 "finding startaddr of watchpoint %d",1613 stop_info->details.watchpoint.esr_fields.wpt);1614 stop_info->details.watchpoint.hw_idx =1615 stop_info->details.watchpoint.esr_fields.wpt;1616 const DNBBreakpoint *wp = m_watchpoints.FindByHardwareIndex(1617 stop_info->details.watchpoint.esr_fields.wpt);1618 if (wp) {1619 stop_info->details.watchpoint.addr = wp->Address();1620 }1621 }1622 }1623 }1624}1625 1626bool MachProcess::StartProfileThread() {1627 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s ( )", __FUNCTION__);1628 // Create the thread that profiles the inferior and reports back if enabled1629 return ::pthread_create(&m_profile_thread, NULL, MachProcess::ProfileThread,1630 this) == 0;1631}1632 1633nub_addr_t MachProcess::LookupSymbol(const char *name, const char *shlib) {1634 if (m_name_to_addr_callback != NULL && name && name[0])1635 return m_name_to_addr_callback(ProcessID(), name, shlib,1636 m_name_to_addr_baton);1637 return INVALID_NUB_ADDRESS;1638}1639 1640bool MachProcess::Resume(const DNBThreadResumeActions &thread_actions) {1641 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Resume ()");1642 nub_state_t state = GetState();1643 1644 if (CanResume(state)) {1645 m_thread_actions = thread_actions;1646 PrivateResume();1647 return true;1648 } else if (state == eStateRunning) {1649 DNBLog("Resume() - task 0x%x is already running, ignoring...",1650 m_task.TaskPort());1651 return true;1652 }1653 DNBLog("Resume() - task 0x%x has state %s, can't continue...",1654 m_task.TaskPort(), DNBStateAsString(state));1655 return false;1656}1657 1658bool MachProcess::Kill(const struct timespec *timeout_abstime) {1659 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill ()");1660 nub_state_t state = DoSIGSTOP(true, false, NULL);1661 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Kill() DoSIGSTOP() state = %s",1662 DNBStateAsString(state));1663 errno = 0;1664 DNBLog("Sending ptrace PT_KILL to terminate inferior process pid %d.", m_pid);1665 ::ptrace(PT_KILL, m_pid, 0, 0);1666 DNBError err;1667 err.SetErrorToErrno();1668 if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail()) {1669 err.LogThreaded("MachProcess::Kill() DoSIGSTOP() ::ptrace "1670 "(PT_KILL, pid=%u, 0, 0) => 0x%8.8x (%s)",1671 m_pid, err.Status(), err.AsString());1672 }1673 m_thread_actions = DNBThreadResumeActions(eStateRunning, 0);1674 PrivateResume();1675 1676 // Try and reap the process without touching our m_events since1677 // we want the code above this to still get the eStateExited event1678 const uint32_t reap_timeout_usec =1679 1000000; // Wait 1 second and try to reap the process1680 const uint32_t reap_interval_usec = 10000; //1681 uint32_t reap_time_elapsed;1682 for (reap_time_elapsed = 0; reap_time_elapsed < reap_timeout_usec;1683 reap_time_elapsed += reap_interval_usec) {1684 if (GetState() == eStateExited)1685 break;1686 usleep(reap_interval_usec);1687 }1688 DNBLog("Waited %u ms for process to be reaped (state = %s)",1689 reap_time_elapsed / 1000, DNBStateAsString(GetState()));1690 return true;1691}1692 1693bool MachProcess::Interrupt() {1694 nub_state_t state = GetState();1695 if (IsRunning(state)) {1696 std::lock_guard<std::recursive_mutex> guard(m_exception_and_signal_mutex);1697 if (m_sent_interrupt_signo == 0) {1698 m_sent_interrupt_signo = SIGSTOP;1699 if (Signal(m_sent_interrupt_signo)) {1700 DNBLogThreadedIf(1701 LOG_PROCESS,1702 "MachProcess::Interrupt() - sent %i signal to interrupt process",1703 m_sent_interrupt_signo);1704 return true;1705 } else {1706 m_sent_interrupt_signo = 0;1707 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Interrupt() - failed to "1708 "send %i signal to interrupt process",1709 m_sent_interrupt_signo);1710 }1711 } else {1712 // We've requested that the process stop anew; if we had recorded this1713 // requested stop as being in place when we resumed (& therefore would1714 // throw it away), clear that.1715 m_auto_resume_signo = 0;1716 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Interrupt() - previously "1717 "sent an interrupt signal %i that hasn't "1718 "been received yet, interrupt aborted",1719 m_sent_interrupt_signo);1720 }1721 } else {1722 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Interrupt() - process already "1723 "stopped, no interrupt sent");1724 }1725 return false;1726}1727 1728bool MachProcess::Signal(int signal, const struct timespec *timeout_abstime) {1729 DNBLogThreadedIf(LOG_PROCESS,1730 "MachProcess::Signal (signal = %d, timeout = %p)", signal,1731 static_cast<const void *>(timeout_abstime));1732 nub_state_t state = GetState();1733 if (::kill(ProcessID(), signal) == 0) {1734 // If we were running and we have a timeout, wait for the signal to stop1735 if (IsRunning(state) && timeout_abstime) {1736 DNBLogThreadedIf(LOG_PROCESS,1737 "MachProcess::Signal (signal = %d, timeout "1738 "= %p) waiting for signal to stop "1739 "process...",1740 signal, static_cast<const void *>(timeout_abstime));1741 m_private_events.WaitForSetEvents(eEventProcessStoppedStateChanged,1742 timeout_abstime);1743 state = GetState();1744 DNBLogThreadedIf(1745 LOG_PROCESS,1746 "MachProcess::Signal (signal = %d, timeout = %p) state = %s", signal,1747 static_cast<const void *>(timeout_abstime), DNBStateAsString(state));1748 return !IsRunning(state);1749 }1750 DNBLogThreadedIf(1751 LOG_PROCESS,1752 "MachProcess::Signal (signal = %d, timeout = %p) not waiting...",1753 signal, static_cast<const void *>(timeout_abstime));1754 return true;1755 }1756 DNBError err(errno, DNBError::POSIX);1757 err.LogThreadedIfError("kill (pid = %d, signo = %i)", ProcessID(), signal);1758 return false;1759}1760 1761bool MachProcess::SendEvent(const char *event, DNBError &send_err) {1762 DNBLogThreadedIf(LOG_PROCESS,1763 "MachProcess::SendEvent (event = %s) to pid: %d", event,1764 m_pid);1765 if (m_pid == INVALID_NUB_PROCESS)1766 return false;1767// FIXME: Shouldn't we use the launch flavor we were started with?1768#if defined(WITH_FBS) || defined(WITH_BKS)1769 return BoardServiceSendEvent(event, send_err);1770#endif1771 return true;1772}1773 1774nub_state_t MachProcess::DoSIGSTOP(bool clear_bps_and_wps, bool allow_running,1775 uint32_t *thread_idx_ptr) {1776 nub_state_t state = GetState();1777 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::DoSIGSTOP() state = %s",1778 DNBStateAsString(state));1779 1780 if (!IsRunning(state)) {1781 if (clear_bps_and_wps) {1782 DisableAllBreakpoints(true);1783 DisableAllWatchpoints(true);1784 clear_bps_and_wps = false;1785 }1786 1787 // If we already have a thread stopped due to a SIGSTOP, we don't have1788 // to do anything...1789 uint32_t thread_idx =1790 m_thread_list.GetThreadIndexForThreadStoppedWithSignal(SIGSTOP);1791 if (thread_idx_ptr)1792 *thread_idx_ptr = thread_idx;1793 if (thread_idx != UINT32_MAX)1794 return GetState();1795 1796 // No threads were stopped with a SIGSTOP, we need to run and halt the1797 // process with a signal1798 DNBLogThreadedIf(LOG_PROCESS,1799 "MachProcess::DoSIGSTOP() state = %s -- resuming process",1800 DNBStateAsString(state));1801 if (allow_running)1802 m_thread_actions = DNBThreadResumeActions(eStateRunning, 0);1803 else1804 m_thread_actions = DNBThreadResumeActions(eStateSuspended, 0);1805 1806 PrivateResume();1807 1808 // Reset the event that says we were indeed running1809 m_events.ResetEvents(eEventProcessRunningStateChanged);1810 state = GetState();1811 }1812 1813 // We need to be stopped in order to be able to detach, so we need1814 // to send ourselves a SIGSTOP1815 1816 DNBLogThreadedIf(LOG_PROCESS,1817 "MachProcess::DoSIGSTOP() state = %s -- sending SIGSTOP",1818 DNBStateAsString(state));1819 struct timespec sigstop_timeout;1820 DNBTimer::OffsetTimeOfDay(&sigstop_timeout, 2, 0);1821 Signal(SIGSTOP, &sigstop_timeout);1822 if (clear_bps_and_wps) {1823 DisableAllBreakpoints(true);1824 DisableAllWatchpoints(true);1825 // clear_bps_and_wps = false;1826 }1827 uint32_t thread_idx =1828 m_thread_list.GetThreadIndexForThreadStoppedWithSignal(SIGSTOP);1829 if (thread_idx_ptr)1830 *thread_idx_ptr = thread_idx;1831 return GetState();1832}1833 1834bool MachProcess::Detach() {1835 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach()");1836 1837 uint32_t thread_idx = UINT32_MAX;1838 nub_state_t state = DoSIGSTOP(true, true, &thread_idx);1839 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::Detach() DoSIGSTOP() returned %s",1840 DNBStateAsString(state));1841 1842 {1843 m_thread_actions.Clear();1844 m_activities.Clear();1845 DNBThreadResumeAction thread_action;1846 thread_action.tid = m_thread_list.ThreadIDAtIndex(thread_idx);1847 thread_action.state = eStateRunning;1848 thread_action.signal = -1;1849 thread_action.addr = INVALID_NUB_ADDRESS;1850 1851 m_thread_actions.Append(thread_action);1852 m_thread_actions.SetDefaultThreadActionIfNeeded(eStateRunning, 0);1853 1854 std::lock_guard<std::recursive_mutex> guard(m_exception_and_signal_mutex);1855 1856 ReplyToAllExceptions();1857 }1858 1859 m_task.ShutDownExceptionThread();1860 1861 // Detach from our process1862 errno = 0;1863 nub_process_t pid = m_pid;1864 int ret = ::ptrace(PT_DETACH, pid, (caddr_t)1, 0);1865 DNBError err(errno, DNBError::POSIX);1866 if (DNBLogCheckLogBit(LOG_PROCESS) || err.Fail() || (ret != 0))1867 err.LogThreaded("::ptrace (PT_DETACH, %u, (caddr_t)1, 0)", pid);1868 1869 // Resume our task1870 m_task.Resume();1871 1872 // NULL our task out as we have already restored all exception ports1873 m_task.Clear();1874 m_platform = 0;1875 1876 // Clear out any notion of the process we once were1877 const bool detaching = true;1878 Clear(detaching);1879 1880 SetState(eStateDetached);1881 1882 return true;1883}1884 1885//----------------------------------------------------------------------1886// ReadMemory from the MachProcess level will always remove any software1887// breakpoints from the memory buffer before returning. If you wish to1888// read memory and see those traps, read from the MachTask1889// (m_task.ReadMemory()) as that version will give you what is actually1890// in inferior memory.1891//----------------------------------------------------------------------1892nub_size_t MachProcess::ReadMemory(nub_addr_t addr, nub_size_t size,1893 void *buf) {1894 // We need to remove any current software traps (enabled software1895 // breakpoints) that we may have placed in our tasks memory.1896 1897 // First just read the memory as is1898 nub_size_t bytes_read = m_task.ReadMemory(addr, size, buf);1899 1900 // Then place any opcodes that fall into this range back into the buffer1901 // before we return this to callers.1902 if (bytes_read > 0)1903 m_breakpoints.RemoveTrapsFromBuffer(addr, bytes_read, buf);1904 return bytes_read;1905}1906 1907//----------------------------------------------------------------------1908// WriteMemory from the MachProcess level will always write memory around1909// any software breakpoints. Any software breakpoints will have their1910// opcodes modified if they are enabled. Any memory that doesn't overlap1911// with software breakpoints will be written to. If you wish to write to1912// inferior memory without this interference, then write to the MachTask1913// (m_task.WriteMemory()) as that version will always modify inferior1914// memory.1915//----------------------------------------------------------------------1916nub_size_t MachProcess::WriteMemory(nub_addr_t addr, nub_size_t size,1917 const void *buf) {1918 // We need to write any data that would go where any current software traps1919 // (enabled software breakpoints) any software traps (breakpoints) that we1920 // may have placed in our tasks memory.1921 1922 std::vector<DNBBreakpoint *> bps;1923 1924 const size_t num_bps =1925 m_breakpoints.FindBreakpointsThatOverlapRange(addr, size, bps);1926 if (num_bps == 0)1927 return m_task.WriteMemory(addr, size, buf);1928 1929 nub_size_t bytes_written = 0;1930 nub_addr_t intersect_addr;1931 nub_size_t intersect_size;1932 nub_size_t opcode_offset;1933 const uint8_t *ubuf = (const uint8_t *)buf;1934 1935 for (size_t i = 0; i < num_bps; ++i) {1936 DNBBreakpoint *bp = bps[i];1937 1938 const bool intersects = bp->IntersectsRange(1939 addr, size, &intersect_addr, &intersect_size, &opcode_offset);1940 UNUSED_IF_ASSERT_DISABLED(intersects);1941 assert(intersects);1942 assert(addr <= intersect_addr && intersect_addr < addr + size);1943 assert(addr < intersect_addr + intersect_size &&1944 intersect_addr + intersect_size <= addr + size);1945 assert(opcode_offset + intersect_size <= bp->ByteSize());1946 1947 // Check for bytes before this breakpoint1948 const nub_addr_t curr_addr = addr + bytes_written;1949 if (intersect_addr > curr_addr) {1950 // There are some bytes before this breakpoint that we need to1951 // just write to memory1952 nub_size_t curr_size = intersect_addr - curr_addr;1953 nub_size_t curr_bytes_written =1954 m_task.WriteMemory(curr_addr, curr_size, ubuf + bytes_written);1955 bytes_written += curr_bytes_written;1956 if (curr_bytes_written != curr_size) {1957 // We weren't able to write all of the requested bytes, we1958 // are done looping and will return the number of bytes that1959 // we have written so far.1960 break;1961 }1962 }1963 1964 // Now write any bytes that would cover up any software breakpoints1965 // directly into the breakpoint opcode buffer1966 ::memcpy(bp->SavedOpcodeBytes() + opcode_offset, ubuf + bytes_written,1967 intersect_size);1968 bytes_written += intersect_size;1969 }1970 1971 // Write any remaining bytes after the last breakpoint if we have any left1972 if (bytes_written < size)1973 bytes_written += m_task.WriteMemory(1974 addr + bytes_written, size - bytes_written, ubuf + bytes_written);1975 1976 return bytes_written;1977}1978 1979void MachProcess::ReplyToAllExceptions() {1980 std::lock_guard<std::recursive_mutex> guard(m_exception_and_signal_mutex);1981 if (!m_exception_messages.empty()) {1982 MachException::Message::iterator pos;1983 MachException::Message::iterator begin = m_exception_messages.begin();1984 MachException::Message::iterator end = m_exception_messages.end();1985 for (pos = begin; pos != end; ++pos) {1986 DNBLogThreadedIf(LOG_EXCEPTIONS, "Replying to exception %u...",1987 (uint32_t)std::distance(begin, pos));1988 int thread_reply_signal = 0;1989 1990 nub_thread_t tid =1991 m_thread_list.GetThreadIDByMachPortNumber(pos->state.thread_port);1992 const DNBThreadResumeAction *action = NULL;1993 if (tid != INVALID_NUB_THREAD) {1994 action = m_thread_actions.GetActionForThread(tid, false);1995 }1996 1997 if (action) {1998 thread_reply_signal = action->signal;1999 if (thread_reply_signal)2000 m_thread_actions.SetSignalHandledForThread(tid);2001 }2002 2003 DNBError err(pos->Reply(this, thread_reply_signal));2004 if (DNBLogCheckLogBit(LOG_EXCEPTIONS))2005 err.LogThreadedIfError("Error replying to exception");2006 }2007 2008 // Erase all exception message as we should have used and replied2009 // to them all already.2010 m_exception_messages.clear();2011 }2012}2013void MachProcess::PrivateResume() {2014 std::lock_guard<std::recursive_mutex> guard(m_exception_and_signal_mutex);2015 2016 m_auto_resume_signo = m_sent_interrupt_signo;2017 if (m_auto_resume_signo)2018 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::PrivateResume() - task 0x%x "2019 "resuming (with unhandled interrupt signal "2020 "%i)...",2021 m_task.TaskPort(), m_auto_resume_signo);2022 else2023 DNBLogThreadedIf(LOG_PROCESS,2024 "MachProcess::PrivateResume() - task 0x%x resuming...",2025 m_task.TaskPort());2026 2027 ReplyToAllExceptions();2028 // bool stepOverBreakInstruction = step;2029 2030 // Let the thread prepare to resume and see if any threads want us to2031 // step over a breakpoint instruction (ProcessWillResume will modify2032 // the value of stepOverBreakInstruction).2033 m_thread_list.ProcessWillResume(this, m_thread_actions);2034 2035 // Set our state accordingly2036 if (m_thread_actions.NumActionsWithState(eStateStepping))2037 SetState(eStateStepping);2038 else2039 SetState(eStateRunning);2040 2041 // Now resume our task.2042 m_task.Resume();2043}2044 2045DNBBreakpoint *MachProcess::CreateBreakpoint(nub_addr_t addr, nub_size_t length,2046 bool hardware) {2047 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::CreateBreakpoint ( addr = "2048 "0x%8.8llx, length = %llu, hardware = %i)",2049 (uint64_t)addr, (uint64_t)length, hardware);2050 2051 DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr);2052 if (bp)2053 bp->Retain();2054 else2055 bp = m_breakpoints.Add(addr, length, hardware);2056 2057 if (EnableBreakpoint(addr)) {2058 DNBLogThreadedIf(LOG_BREAKPOINTS,2059 "MachProcess::CreateBreakpoint ( addr = "2060 "0x%8.8llx, length = %llu) => %p",2061 (uint64_t)addr, (uint64_t)length, static_cast<void *>(bp));2062 return bp;2063 } else if (bp->Release() == 0) {2064 m_breakpoints.Remove(addr);2065 }2066 // We failed to enable the breakpoint2067 return NULL;2068}2069 2070DNBBreakpoint *MachProcess::CreateWatchpoint(nub_addr_t addr, nub_size_t length,2071 uint32_t watch_flags,2072 bool hardware) {2073 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = "2074 "0x%8.8llx, length = %llu, flags = "2075 "0x%8.8x, hardware = %i)",2076 (uint64_t)addr, (uint64_t)length, watch_flags, hardware);2077 2078 DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr);2079 // since the Z packets only send an address, we can only have one watchpoint2080 // at2081 // an address. If there is already one, we must refuse to create another2082 // watchpoint2083 if (wp)2084 return NULL;2085 2086 wp = m_watchpoints.Add(addr, length, hardware);2087 wp->SetIsWatchpoint(watch_flags);2088 2089 if (EnableWatchpoint(addr)) {2090 DNBLogThreadedIf(LOG_WATCHPOINTS,2091 "MachProcess::CreateWatchpoint ( addr = "2092 "0x%8.8llx, length = %llu) => %p",2093 (uint64_t)addr, (uint64_t)length, static_cast<void *>(wp));2094 return wp;2095 } else {2096 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::CreateWatchpoint ( addr = "2097 "0x%8.8llx, length = %llu) => FAILED",2098 (uint64_t)addr, (uint64_t)length);2099 m_watchpoints.Remove(addr);2100 }2101 // We failed to enable the watchpoint2102 return NULL;2103}2104 2105void MachProcess::DisableAllBreakpoints(bool remove) {2106 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::%s (remove = %d )",2107 __FUNCTION__, remove);2108 2109 m_breakpoints.DisableAllBreakpoints(this);2110 2111 if (remove)2112 m_breakpoints.RemoveDisabled();2113}2114 2115void MachProcess::DisableAllWatchpoints(bool remove) {2116 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::%s (remove = %d )",2117 __FUNCTION__, remove);2118 2119 m_watchpoints.DisableAllWatchpoints(this);2120 2121 if (remove)2122 m_watchpoints.RemoveDisabled();2123}2124 2125bool MachProcess::DisableBreakpoint(nub_addr_t addr, bool remove) {2126 DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr);2127 if (bp) {2128 // After "exec" we might end up with a bunch of breakpoints that were2129 // disabled2130 // manually, just ignore them2131 if (!bp->IsEnabled()) {2132 // Breakpoint might have been disabled by an exec2133 if (remove && bp->Release() == 0) {2134 m_thread_list.NotifyBreakpointChanged(bp);2135 m_breakpoints.Remove(addr);2136 }2137 return true;2138 }2139 2140 // We have multiple references to this breakpoint, decrement the ref count2141 // and if it isn't zero, then return true;2142 if (remove && bp->Release() > 0)2143 return true;2144 2145 DNBLogThreadedIf(2146 LOG_BREAKPOINTS | LOG_VERBOSE,2147 "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = %d )",2148 (uint64_t)addr, remove);2149 2150 if (bp->IsHardware()) {2151 bool hw_disable_result = m_thread_list.DisableHardwareBreakpoint(bp);2152 2153 if (hw_disable_result) {2154 bp->SetEnabled(false);2155 // Let the thread list know that a breakpoint has been modified2156 if (remove) {2157 m_thread_list.NotifyBreakpointChanged(bp);2158 m_breakpoints.Remove(addr);2159 }2160 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::DisableBreakpoint ( "2161 "addr = 0x%8.8llx, remove = %d ) "2162 "(hardware) => success",2163 (uint64_t)addr, remove);2164 return true;2165 }2166 2167 return false;2168 }2169 2170 const nub_size_t break_op_size = bp->ByteSize();2171 assert(break_op_size > 0);2172 const uint8_t *const break_op =2173 DNBArchProtocol::GetBreakpointOpcode(bp->ByteSize());2174 if (break_op_size > 0) {2175 // Clear a software breakpoint instruction2176 uint8_t curr_break_op[break_op_size];2177 bool break_op_found = false;2178 2179 // Read the breakpoint opcode2180 if (m_task.ReadMemory(addr, break_op_size, curr_break_op) ==2181 break_op_size) {2182 bool verify = false;2183 if (bp->IsEnabled()) {2184 // Make sure a breakpoint opcode exists at this address2185 if (memcmp(curr_break_op, break_op, break_op_size) == 0) {2186 break_op_found = true;2187 // We found a valid breakpoint opcode at this address, now restore2188 // the saved opcode.2189 if (m_task.WriteMemory(addr, break_op_size,2190 bp->SavedOpcodeBytes()) == break_op_size) {2191 verify = true;2192 } else {2193 DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, "2194 "remove = %d ) memory write failed when restoring "2195 "original opcode",2196 (uint64_t)addr, remove);2197 }2198 } else {2199 DNBLogWarning("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, "2200 "remove = %d ) expected a breakpoint opcode but "2201 "didn't find one.",2202 (uint64_t)addr, remove);2203 // Set verify to true and so we can check if the original opcode has2204 // already been restored2205 verify = true;2206 }2207 } else {2208 DNBLogThreadedIf(LOG_BREAKPOINTS | LOG_VERBOSE,2209 "MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, "2210 "remove = %d ) is not enabled",2211 (uint64_t)addr, remove);2212 // Set verify to true and so we can check if the original opcode is2213 // there2214 verify = true;2215 }2216 2217 if (verify) {2218 uint8_t verify_opcode[break_op_size];2219 // Verify that our original opcode made it back to the inferior2220 if (m_task.ReadMemory(addr, break_op_size, verify_opcode) ==2221 break_op_size) {2222 // compare the memory we just read with the original opcode2223 if (memcmp(bp->SavedOpcodeBytes(), verify_opcode, break_op_size) ==2224 0) {2225 // SUCCESS2226 bp->SetEnabled(false);2227 // Let the thread list know that a breakpoint has been modified2228 if (remove && bp->Release() == 0) {2229 m_thread_list.NotifyBreakpointChanged(bp);2230 m_breakpoints.Remove(addr);2231 }2232 DNBLogThreadedIf(LOG_BREAKPOINTS,2233 "MachProcess::DisableBreakpoint ( addr = "2234 "0x%8.8llx, remove = %d ) => success",2235 (uint64_t)addr, remove);2236 return true;2237 } else {2238 if (break_op_found)2239 DNBLogError("MachProcess::DisableBreakpoint ( addr = "2240 "0x%8.8llx, remove = %d ) : failed to restore "2241 "original opcode",2242 (uint64_t)addr, remove);2243 else2244 DNBLogError("MachProcess::DisableBreakpoint ( addr = "2245 "0x%8.8llx, remove = %d ) : opcode changed",2246 (uint64_t)addr, remove);2247 }2248 } else {2249 DNBLogWarning("MachProcess::DisableBreakpoint: unable to disable "2250 "breakpoint 0x%8.8llx",2251 (uint64_t)addr);2252 }2253 }2254 } else {2255 DNBLogWarning("MachProcess::DisableBreakpoint: unable to read memory "2256 "at 0x%8.8llx",2257 (uint64_t)addr);2258 }2259 }2260 } else {2261 DNBLogError("MachProcess::DisableBreakpoint ( addr = 0x%8.8llx, remove = "2262 "%d ) invalid breakpoint address",2263 (uint64_t)addr, remove);2264 }2265 return false;2266}2267 2268bool MachProcess::DisableWatchpoint(nub_addr_t addr, bool remove) {2269 DNBLogThreadedIf(LOG_WATCHPOINTS,2270 "MachProcess::%s(addr = 0x%8.8llx, remove = %d)",2271 __FUNCTION__, (uint64_t)addr, remove);2272 DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr);2273 if (wp) {2274 // If we have multiple references to a watchpoint, removing the watchpoint2275 // shouldn't clear it2276 if (remove && wp->Release() > 0)2277 return true;2278 2279 nub_addr_t addr = wp->Address();2280 DNBLogThreadedIf(2281 LOG_WATCHPOINTS,2282 "MachProcess::DisableWatchpoint ( addr = 0x%8.8llx, remove = %d )",2283 (uint64_t)addr, remove);2284 2285 if (wp->IsHardware()) {2286 bool hw_disable_result = m_thread_list.DisableHardwareWatchpoint(wp);2287 2288 if (hw_disable_result) {2289 wp->SetEnabled(false);2290 if (remove)2291 m_watchpoints.Remove(addr);2292 DNBLogThreadedIf(LOG_WATCHPOINTS, "MachProcess::Disablewatchpoint ( "2293 "addr = 0x%8.8llx, remove = %d ) "2294 "(hardware) => success",2295 (uint64_t)addr, remove);2296 return true;2297 }2298 }2299 2300 // TODO: clear software watchpoints if we implement them2301 } else {2302 DNBLogError("MachProcess::DisableWatchpoint ( addr = 0x%8.8llx, remove = "2303 "%d ) invalid watchpoint ID",2304 (uint64_t)addr, remove);2305 }2306 return false;2307}2308 2309uint32_t MachProcess::GetNumSupportedHardwareWatchpoints() const {2310 return m_thread_list.NumSupportedHardwareWatchpoints();2311}2312 2313bool MachProcess::EnableBreakpoint(nub_addr_t addr) {2314 DNBLogThreadedIf(LOG_BREAKPOINTS,2315 "MachProcess::EnableBreakpoint ( addr = 0x%8.8llx )",2316 (uint64_t)addr);2317 DNBBreakpoint *bp = m_breakpoints.FindByAddress(addr);2318 if (bp) {2319 if (bp->IsEnabled()) {2320 DNBLogWarning("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): "2321 "breakpoint already enabled.",2322 (uint64_t)addr);2323 return true;2324 } else {2325 if (bp->HardwarePreferred()) {2326 bp->SetHardwareIndex(m_thread_list.EnableHardwareBreakpoint(bp));2327 if (bp->IsHardware()) {2328 bp->SetEnabled(true);2329 return true;2330 }2331 }2332 2333 const nub_size_t break_op_size = bp->ByteSize();2334 assert(break_op_size != 0);2335 const uint8_t *const break_op =2336 DNBArchProtocol::GetBreakpointOpcode(break_op_size);2337 if (break_op_size > 0) {2338 // Save the original opcode by reading it2339 if (m_task.ReadMemory(addr, break_op_size, bp->SavedOpcodeBytes()) ==2340 break_op_size) {2341 // Write a software breakpoint in place of the original opcode2342 if (m_task.WriteMemory(addr, break_op_size, break_op) ==2343 break_op_size) {2344 uint8_t verify_break_op[4];2345 if (m_task.ReadMemory(addr, break_op_size, verify_break_op) ==2346 break_op_size) {2347 if (memcmp(break_op, verify_break_op, break_op_size) == 0) {2348 bp->SetEnabled(true);2349 // Let the thread list know that a breakpoint has been modified2350 m_thread_list.NotifyBreakpointChanged(bp);2351 DNBLogThreadedIf(LOG_BREAKPOINTS, "MachProcess::"2352 "EnableBreakpoint ( addr = "2353 "0x%8.8llx ) : SUCCESS.",2354 (uint64_t)addr);2355 return true;2356 } else {2357 DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx "2358 "): breakpoint opcode verification failed.",2359 (uint64_t)addr);2360 }2361 } else {2362 DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): "2363 "unable to read memory to verify breakpoint opcode.",2364 (uint64_t)addr);2365 }2366 } else {2367 DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): "2368 "unable to write breakpoint opcode to memory.",2369 (uint64_t)addr);2370 }2371 } else {2372 DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ): "2373 "unable to read memory at breakpoint address.",2374 (uint64_t)addr);2375 }2376 } else {2377 DNBLogError("MachProcess::EnableBreakpoint ( addr = 0x%8.8llx ) no "2378 "software breakpoint opcode for current architecture.",2379 (uint64_t)addr);2380 }2381 }2382 }2383 return false;2384}2385 2386bool MachProcess::EnableWatchpoint(nub_addr_t addr) {2387 DNBLogThreadedIf(LOG_WATCHPOINTS,2388 "MachProcess::EnableWatchpoint(addr = 0x%8.8llx)",2389 (uint64_t)addr);2390 DNBBreakpoint *wp = m_watchpoints.FindByAddress(addr);2391 if (wp) {2392 nub_addr_t addr = wp->Address();2393 if (wp->IsEnabled()) {2394 DNBLogWarning("MachProcess::EnableWatchpoint(addr = 0x%8.8llx): "2395 "watchpoint already enabled.",2396 (uint64_t)addr);2397 return true;2398 } else {2399 // Currently only try and set hardware watchpoints.2400 wp->SetHardwareIndex(m_thread_list.EnableHardwareWatchpoint(wp));2401 if (wp->IsHardware()) {2402 wp->SetEnabled(true);2403 return true;2404 }2405 // TODO: Add software watchpoints by doing page protection tricks.2406 }2407 }2408 return false;2409}2410 2411// Called by the exception thread when an exception has been received from2412// our process. The exception message is completely filled and the exception2413// data has already been copied.2414void MachProcess::ExceptionMessageReceived(2415 const MachException::Message &exceptionMessage) {2416 std::lock_guard<std::recursive_mutex> guard(m_exception_and_signal_mutex);2417 2418 if (m_exception_messages.empty())2419 m_task.Suspend();2420 2421 DNBLogThreadedIf(LOG_EXCEPTIONS, "MachProcess::ExceptionMessageReceived ( )");2422 2423 // Use a locker to automatically unlock our mutex in case of exceptions2424 // Add the exception to our internal exception stack2425 m_exception_messages.push_back(exceptionMessage);2426}2427 2428task_t MachProcess::ExceptionMessageBundleComplete() {2429 // We have a complete bundle of exceptions for our child process.2430 std::lock_guard<std::recursive_mutex> guard(m_exception_and_signal_mutex);2431 DNBLogThreadedIf(LOG_EXCEPTIONS, "%s: %llu exception messages.",2432 __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size());2433 bool auto_resume = false;2434 if (!m_exception_messages.empty()) {2435 m_did_exec = false;2436 // First check for any SIGTRAP and make sure we didn't exec2437 const task_t task = m_task.TaskPort();2438 size_t i;2439 if (m_pid != 0) {2440 bool received_interrupt = false;2441 uint32_t num_task_exceptions = 0;2442 for (i = 0; i < m_exception_messages.size(); ++i) {2443 if (m_exception_messages[i].state.task_port == task) {2444 ++num_task_exceptions;2445 const int signo = m_exception_messages[i].state.SoftSignal();2446 if (signo == SIGTRAP) {2447 // SIGTRAP could mean that we exec'ed. We need to check the2448 // dyld all_image_infos.infoArray to see if it is NULL and if2449 // so, say that we exec'ed.2450 const nub_addr_t aii_addr = GetDYLDAllImageInfosAddress();2451 if (aii_addr != INVALID_NUB_ADDRESS) {2452 const nub_addr_t info_array_count_addr = aii_addr + 4;2453 uint32_t info_array_count = 0;2454 if (m_task.ReadMemory(info_array_count_addr, 4,2455 &info_array_count) == 4) {2456 if (info_array_count == 0) {2457 m_did_exec = true;2458 // Force the task port to update itself in case the task port2459 // changed after exec2460 DNBError err;2461 const task_t old_task = m_task.TaskPort();2462 const task_t new_task =2463 m_task.TaskPortForProcessID(err, true);2464 if (old_task != new_task)2465 DNBLogThreadedIf(2466 LOG_PROCESS,2467 "exec: task changed from 0x%4.4x to 0x%4.4x", old_task,2468 new_task);2469 }2470 } else {2471 DNBLog("error: failed to read all_image_infos.infoArrayCount "2472 "from 0x%8.8llx",2473 (uint64_t)info_array_count_addr);2474 }2475 }2476 break;2477 } else if (m_sent_interrupt_signo != 0 &&2478 signo == m_sent_interrupt_signo) {2479 received_interrupt = true;2480 }2481 }2482 }2483 2484 if (m_did_exec) {2485 cpu_type_t process_cpu_type =2486 MachProcess::GetCPUTypeForLocalProcess(m_pid);2487 if (m_cpu_type != process_cpu_type) {2488 DNBLog("arch changed from 0x%8.8x to 0x%8.8x", m_cpu_type,2489 process_cpu_type);2490 m_cpu_type = process_cpu_type;2491 DNBArchProtocol::SetArchitecture(process_cpu_type);2492 }2493 m_thread_list.Clear();2494 m_activities.Clear();2495 m_breakpoints.DisableAll();2496 m_task.ClearAllocations();2497 }2498 2499 if (m_sent_interrupt_signo != 0) {2500 if (received_interrupt) {2501 DNBLogThreadedIf(LOG_PROCESS,2502 "MachProcess::ExceptionMessageBundleComplete(): "2503 "process successfully interrupted with signal %i",2504 m_sent_interrupt_signo);2505 2506 // Mark that we received the interrupt signal2507 m_sent_interrupt_signo = 0;2508 // Not check if we had a case where:2509 // 1 - We called MachProcess::Interrupt() but we stopped for another2510 // reason2511 // 2 - We called MachProcess::Resume() (but still haven't gotten the2512 // interrupt signal)2513 // 3 - We are now incorrectly stopped because we are handling the2514 // interrupt signal we missed2515 // 4 - We might need to resume if we stopped only with the interrupt2516 // signal that we never handled2517 if (m_auto_resume_signo != 0) {2518 // Only auto_resume if we stopped with _only_ the interrupt signal2519 if (num_task_exceptions == 1) {2520 auto_resume = true;2521 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::"2522 "ExceptionMessageBundleComplete(): "2523 "auto resuming due to unhandled "2524 "interrupt signal %i",2525 m_auto_resume_signo);2526 }2527 m_auto_resume_signo = 0;2528 }2529 } else {2530 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::"2531 "ExceptionMessageBundleComplete(): "2532 "didn't get signal %i after "2533 "MachProcess::Interrupt()",2534 m_sent_interrupt_signo);2535 }2536 }2537 }2538 2539 // Let all threads recover from stopping and do any clean up based2540 // on the previous thread state (if any).2541 m_thread_list.ProcessDidStop(this);2542 m_activities.Clear();2543 2544 // Let each thread know of any exceptions2545 for (i = 0; i < m_exception_messages.size(); ++i) {2546 // Let the thread list figure use the MachProcess to forward all2547 // exceptions2548 // on down to each thread.2549 if (m_exception_messages[i].state.task_port == task)2550 m_thread_list.NotifyException(m_exception_messages[i].state);2551 if (DNBLogCheckLogBit(LOG_EXCEPTIONS))2552 m_exception_messages[i].Dump();2553 }2554 2555 if (DNBLogCheckLogBit(LOG_THREAD))2556 m_thread_list.Dump();2557 2558 bool step_more = false;2559 if (m_thread_list.ShouldStop(step_more) && !auto_resume) {2560 // Wait for the eEventProcessRunningStateChanged event to be reset2561 // before changing state to stopped to avoid race condition with2562 // very fast start/stops2563 struct timespec timeout;2564 // DNBTimer::OffsetTimeOfDay(&timeout, 0, 250 * 1000); // Wait for 2502565 // ms2566 DNBTimer::OffsetTimeOfDay(&timeout, 1, 0); // Wait for 250 ms2567 m_events.WaitForEventsToReset(eEventProcessRunningStateChanged, &timeout);2568 SetState(eStateStopped);2569 } else {2570 // Resume without checking our current state.2571 PrivateResume();2572 }2573 } else {2574 DNBLogThreadedIf(2575 LOG_EXCEPTIONS, "%s empty exception messages bundle (%llu exceptions).",2576 __PRETTY_FUNCTION__, (uint64_t)m_exception_messages.size());2577 }2578 return m_task.TaskPort();2579}2580 2581nub_size_t2582MachProcess::CopyImageInfos(struct DNBExecutableImageInfo **image_infos,2583 bool only_changed) {2584 if (m_image_infos_callback != NULL)2585 return m_image_infos_callback(ProcessID(), image_infos, only_changed,2586 m_image_infos_baton);2587 return 0;2588}2589 2590void MachProcess::SharedLibrariesUpdated() {2591 uint32_t event_bits = eEventSharedLibsStateChange;2592 // Set the shared library event bit to let clients know of shared library2593 // changes2594 m_events.SetEvents(event_bits);2595 // Wait for the event bit to reset if a reset ACK is requested2596 m_events.WaitForResetAck(event_bits);2597}2598 2599void MachProcess::SetExitInfo(const char *info) {2600 if (info && info[0]) {2601 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s(\"%s\")", __FUNCTION__,2602 info);2603 m_exit_info.assign(info);2604 } else {2605 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s(NULL)", __FUNCTION__);2606 m_exit_info.clear();2607 }2608}2609 2610void MachProcess::AppendSTDOUT(char *s, size_t len) {2611 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (<%llu> %s) ...", __FUNCTION__,2612 (uint64_t)len, s);2613 std::lock_guard<std::recursive_mutex> guard(m_stdio_mutex);2614 m_stdout_data.append(s, len);2615 m_events.SetEvents(eEventStdioAvailable);2616 2617 // Wait for the event bit to reset if a reset ACK is requested2618 m_events.WaitForResetAck(eEventStdioAvailable);2619}2620 2621size_t MachProcess::GetAvailableSTDOUT(char *buf, size_t buf_size) {2622 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__,2623 static_cast<void *>(buf), (uint64_t)buf_size);2624 std::lock_guard<std::recursive_mutex> guard(m_stdio_mutex);2625 size_t bytes_available = m_stdout_data.size();2626 if (bytes_available > 0) {2627 if (bytes_available > buf_size) {2628 memcpy(buf, m_stdout_data.data(), buf_size);2629 m_stdout_data.erase(0, buf_size);2630 bytes_available = buf_size;2631 } else {2632 memcpy(buf, m_stdout_data.data(), bytes_available);2633 m_stdout_data.clear();2634 }2635 }2636 return bytes_available;2637}2638 2639nub_addr_t MachProcess::GetDYLDAllImageInfosAddress() {2640 DNBError err;2641 return m_task.GetDYLDAllImageInfosAddress(err);2642}2643 2644/// From dyld SPI header dyld_process_info.h2645struct dyld_process_state_info {2646 uint64_t timestamp;2647 uint32_t imageCount;2648 uint32_t initialImageCount;2649 // one of dyld_process_state_* values2650 uint8_t dyldState;2651};2652enum {2653 dyld_process_state_not_started = 0x00,2654 dyld_process_state_dyld_initialized = 0x10,2655 dyld_process_state_terminated_before_inits = 0x20,2656 dyld_process_state_libSystem_initialized = 0x30,2657 dyld_process_state_running_initializers = 0x40,2658 dyld_process_state_program_running = 0x50,2659 dyld_process_state_dyld_terminated = 0x602660};2661 2662JSONGenerator::ObjectSP MachProcess::GetDyldProcessState() {2663 JSONGenerator::DictionarySP reply_sp(new JSONGenerator::Dictionary());2664 if (!m_dyld_process_info_get_state) {2665 reply_sp->AddStringItem("error",2666 "_dyld_process_info_get_state unavailable");2667 return reply_sp;2668 }2669 if (!m_dyld_process_info_create) {2670 reply_sp->AddStringItem("error", "_dyld_process_info_create unavailable");2671 return reply_sp;2672 }2673 2674 kern_return_t kern_ret;2675 dyld_process_info info =2676 m_dyld_process_info_create(m_task.TaskPort(), 0, &kern_ret);2677 if (!info || kern_ret != KERN_SUCCESS) {2678 reply_sp->AddStringItem(2679 "error", "Unable to create dyld_process_info for inferior task");2680 return reply_sp;2681 }2682 2683 struct dyld_process_state_info state_info;2684 m_dyld_process_info_get_state(info, &state_info);2685 reply_sp->AddIntegerItem("process_state_value", state_info.dyldState);2686 switch (state_info.dyldState) {2687 case dyld_process_state_not_started:2688 reply_sp->AddStringItem("process_state string",2689 "dyld_process_state_not_started");2690 break;2691 case dyld_process_state_dyld_initialized:2692 reply_sp->AddStringItem("process_state string",2693 "dyld_process_state_dyld_initialized");2694 break;2695 case dyld_process_state_terminated_before_inits:2696 reply_sp->AddStringItem("process_state string",2697 "dyld_process_state_terminated_before_inits");2698 break;2699 case dyld_process_state_libSystem_initialized:2700 reply_sp->AddStringItem("process_state string",2701 "dyld_process_state_libSystem_initialized");2702 break;2703 case dyld_process_state_running_initializers:2704 reply_sp->AddStringItem("process_state string",2705 "dyld_process_state_running_initializers");2706 break;2707 case dyld_process_state_program_running:2708 reply_sp->AddStringItem("process_state string",2709 "dyld_process_state_program_running");2710 break;2711 case dyld_process_state_dyld_terminated:2712 reply_sp->AddStringItem("process_state string",2713 "dyld_process_state_dyld_terminated");2714 break;2715 };2716 2717 m_dyld_process_info_release(info);2718 2719 return reply_sp;2720}2721 2722size_t MachProcess::GetAvailableSTDERR(char *buf, size_t buf_size) { return 0; }2723 2724void *MachProcess::STDIOThread(void *arg) {2725 MachProcess *proc = (MachProcess *)arg;2726 DNBLogThreadedIf(LOG_PROCESS,2727 "MachProcess::%s ( arg = %p ) thread starting...",2728 __FUNCTION__, arg);2729 2730#if defined(__APPLE__)2731 pthread_setname_np("stdio monitoring thread");2732#endif2733 2734 // We start use a base and more options so we can control if we2735 // are currently using a timeout on the mach_msg. We do this to get a2736 // bunch of related exceptions on our exception port so we can process2737 // then together. When we have multiple threads, we can get an exception2738 // per thread and they will come in consecutively. The main thread loop2739 // will start by calling mach_msg to without having the MACH_RCV_TIMEOUT2740 // flag set in the options, so we will wait forever for an exception on2741 // our exception port. After we get one exception, we then will use the2742 // MACH_RCV_TIMEOUT option with a zero timeout to grab all other current2743 // exceptions for our process. After we have received the last pending2744 // exception, we will get a timeout which enables us to then notify2745 // our main thread that we have an exception bundle available. We then wait2746 // for the main thread to tell this exception thread to start trying to get2747 // exceptions messages again and we start again with a mach_msg read with2748 // infinite timeout.2749 DNBError err;2750 int stdout_fd = proc->GetStdoutFileDescriptor();2751 int stderr_fd = proc->GetStderrFileDescriptor();2752 if (stdout_fd == stderr_fd)2753 stderr_fd = -1;2754 2755 while (stdout_fd >= 0 || stderr_fd >= 0) {2756 ::pthread_testcancel();2757 2758 fd_set read_fds;2759 FD_ZERO(&read_fds);2760 if (stdout_fd >= 0)2761 FD_SET(stdout_fd, &read_fds);2762 if (stderr_fd >= 0)2763 FD_SET(stderr_fd, &read_fds);2764 int nfds = std::max<int>(stdout_fd, stderr_fd) + 1;2765 2766 int num_set_fds = select(nfds, &read_fds, NULL, NULL, NULL);2767 DNBLogThreadedIf(LOG_PROCESS,2768 "select (nfds, &read_fds, NULL, NULL, NULL) => %d",2769 num_set_fds);2770 2771 if (num_set_fds < 0) {2772 int select_errno = errno;2773 if (DNBLogCheckLogBit(LOG_PROCESS)) {2774 err.SetError(select_errno, DNBError::POSIX);2775 err.LogThreadedIfError(2776 "select (nfds, &read_fds, NULL, NULL, NULL) => %d", num_set_fds);2777 }2778 2779 switch (select_errno) {2780 case EAGAIN: // The kernel was (perhaps temporarily) unable to allocate2781 // the requested number of file descriptors, or we have2782 // non-blocking IO2783 break;2784 case EBADF: // One of the descriptor sets specified an invalid descriptor.2785 return NULL;2786 break;2787 case EINTR: // A signal was delivered before the time limit expired and2788 // before any of the selected events occurred.2789 case EINVAL: // The specified time limit is invalid. One of its components2790 // is negative or too large.2791 default: // Other unknown error2792 break;2793 }2794 } else if (num_set_fds == 0) {2795 } else {2796 char s[1024];2797 s[sizeof(s) - 1] = '\0'; // Ensure we have NULL termination2798 ssize_t bytes_read = 0;2799 if (stdout_fd >= 0 && FD_ISSET(stdout_fd, &read_fds)) {2800 do {2801 bytes_read = ::read(stdout_fd, s, sizeof(s) - 1);2802 if (bytes_read < 0) {2803 int read_errno = errno;2804 DNBLogThreadedIf(LOG_PROCESS,2805 "read (stdout_fd, ) => %zd errno: %d (%s)",2806 bytes_read, read_errno, strerror(read_errno));2807 } else if (bytes_read == 0) {2808 // EOF...2809 DNBLogThreadedIf(2810 LOG_PROCESS,2811 "read (stdout_fd, ) => %zd (reached EOF for child STDOUT)",2812 bytes_read);2813 stdout_fd = -1;2814 } else if (bytes_read > 0) {2815 proc->AppendSTDOUT(s, bytes_read);2816 }2817 2818 } while (bytes_read > 0);2819 }2820 2821 if (stderr_fd >= 0 && FD_ISSET(stderr_fd, &read_fds)) {2822 do {2823 bytes_read = ::read(stderr_fd, s, sizeof(s) - 1);2824 if (bytes_read < 0) {2825 int read_errno = errno;2826 DNBLogThreadedIf(LOG_PROCESS,2827 "read (stderr_fd, ) => %zd errno: %d (%s)",2828 bytes_read, read_errno, strerror(read_errno));2829 } else if (bytes_read == 0) {2830 // EOF...2831 DNBLogThreadedIf(2832 LOG_PROCESS,2833 "read (stderr_fd, ) => %zd (reached EOF for child STDERR)",2834 bytes_read);2835 stderr_fd = -1;2836 } else if (bytes_read > 0) {2837 proc->AppendSTDOUT(s, bytes_read);2838 }2839 2840 } while (bytes_read > 0);2841 }2842 }2843 }2844 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%p): thread exiting...",2845 __FUNCTION__, arg);2846 return NULL;2847}2848 2849void MachProcess::SignalAsyncProfileData(const char *info) {2850 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (%s) ...", __FUNCTION__, info);2851 std::lock_guard<std::recursive_mutex> guard(m_profile_data_mutex);2852 m_profile_data.push_back(info);2853 m_events.SetEvents(eEventProfileDataAvailable);2854 2855 // Wait for the event bit to reset if a reset ACK is requested2856 m_events.WaitForResetAck(eEventProfileDataAvailable);2857}2858 2859size_t MachProcess::GetAsyncProfileData(char *buf, size_t buf_size) {2860 DNBLogThreadedIf(LOG_PROCESS, "MachProcess::%s (&%p[%llu]) ...", __FUNCTION__,2861 static_cast<void *>(buf), (uint64_t)buf_size);2862 std::lock_guard<std::recursive_mutex> guard(m_profile_data_mutex);2863 if (m_profile_data.empty())2864 return 0;2865 2866 size_t bytes_available = m_profile_data.front().size();2867 if (bytes_available > 0) {2868 if (bytes_available > buf_size) {2869 memcpy(buf, m_profile_data.front().data(), buf_size);2870 m_profile_data.front().erase(0, buf_size);2871 bytes_available = buf_size;2872 } else {2873 memcpy(buf, m_profile_data.front().data(), bytes_available);2874 m_profile_data.erase(m_profile_data.begin());2875 }2876 }2877 return bytes_available;2878}2879 2880void *MachProcess::ProfileThread(void *arg) {2881 MachProcess *proc = (MachProcess *)arg;2882 DNBLogThreadedIf(LOG_PROCESS,2883 "MachProcess::%s ( arg = %p ) thread starting...",2884 __FUNCTION__, arg);2885 2886#if defined(__APPLE__)2887 pthread_setname_np("performance profiling thread");2888#endif2889 2890 while (proc->IsProfilingEnabled()) {2891 nub_state_t state = proc->GetState();2892 if (state == eStateRunning) {2893 std::string data =2894 proc->Task().GetProfileData(proc->GetProfileScanType());2895 if (!data.empty()) {2896 proc->SignalAsyncProfileData(data.c_str());2897 }2898 } else if ((state == eStateUnloaded) || (state == eStateDetached) ||2899 (state == eStateUnloaded)) {2900 // Done. Get out of this thread.2901 break;2902 }2903 timespec ts;2904 {2905 using namespace std::chrono;2906 std::chrono::microseconds dur(proc->ProfileInterval());2907 const auto dur_secs = duration_cast<seconds>(dur);2908 const auto dur_usecs = dur % std::chrono::seconds(1);2909 DNBTimer::OffsetTimeOfDay(&ts, dur_secs.count(), 2910 dur_usecs.count());2911 }2912 uint32_t bits_set = 2913 proc->m_profile_events.WaitForSetEvents(eMachProcessProfileCancel, &ts);2914 // If we got bits back, we were told to exit. Do so.2915 if (bits_set & eMachProcessProfileCancel)2916 break;2917 }2918 return NULL;2919}2920 2921pid_t MachProcess::AttachForDebug(2922 pid_t pid, 2923 const RNBContext::IgnoredExceptions &ignored_exceptions, 2924 char *err_str,2925 size_t err_len) {2926 // Clear out and clean up from any current state2927 Clear();2928 if (pid != 0) {2929 DNBError err;2930 // Make sure the process exists...2931 if (::getpgid(pid) < 0) {2932 err.SetErrorToErrno();2933 const char *err_cstr = err.AsString();2934 ::snprintf(err_str, err_len, "%s",2935 err_cstr ? err_cstr : "No such process");2936 DNBLogError ("MachProcess::AttachForDebug pid %d does not exist", pid);2937 return INVALID_NUB_PROCESS;2938 }2939 2940 SetState(eStateAttaching);2941 m_pid = pid;2942 if (!m_task.StartExceptionThread(ignored_exceptions, err)) {2943 const char *err_cstr = err.AsString();2944 ::snprintf(err_str, err_len, "%s",2945 err_cstr ? err_cstr : "unable to start the exception thread");2946 DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", pid);2947 DNBLogError(2948 "[LaunchAttach] END (%d) MachProcess::AttachForDebug failed to start "2949 "exception thread attaching to pid %i: %s",2950 getpid(), pid, err_str);2951 m_pid = INVALID_NUB_PROCESS;2952 return INVALID_NUB_PROCESS;2953 }2954 2955 DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...", getpid(),2956 pid);2957 errno = 0;2958 int ptrace_result = ::ptrace(PT_ATTACHEXC, pid, 0, 0);2959 int ptrace_errno = errno;2960 DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d",2961 getpid(), pid, ptrace_result);2962 if (ptrace_result != 0) {2963 err.SetError(ptrace_errno);2964 DNBLogError("MachProcess::AttachForDebug failed to ptrace(PT_ATTACHEXC) "2965 "pid %i: %s",2966 pid, err.AsString());2967 } else {2968 err.Clear();2969 }2970 2971 if (err.Success()) {2972 m_flags |= eMachProcessFlagsAttached;2973 DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", pid);2974 return m_pid;2975 } else {2976 ::snprintf(err_str, err_len, "%s", err.AsString());2977 DNBLogError(2978 "[LaunchAttach] (%d) MachProcess::AttachForDebug error: failed to "2979 "attach to pid %d",2980 getpid(), pid);2981 2982 if (ProcessIsBeingDebugged(pid)) {2983 nub_process_t ppid = GetParentProcessID(pid);2984 if (ppid == getpid()) {2985 snprintf(err_str, err_len,2986 "%s - Failed to attach to pid %d, AttachForDebug() "2987 "unable to ptrace(PT_ATTACHEXC)",2988 err.AsString(), m_pid);2989 } else {2990 snprintf(err_str, err_len,2991 "%s - process %d is already being debugged by pid %d",2992 err.AsString(), pid, ppid);2993 DNBLogError(2994 "[LaunchAttach] (%d) MachProcess::AttachForDebug pid %d is "2995 "already being debugged by pid %d",2996 getpid(), pid, ppid);2997 }2998 }2999 }3000 }3001 return INVALID_NUB_PROCESS;3002}3003 3004Genealogy::ThreadActivitySP3005MachProcess::GetGenealogyInfoForThread(nub_thread_t tid, bool &timed_out) {3006 return m_activities.GetGenealogyInfoForThread(m_pid, tid, m_thread_list,3007 m_task.TaskPort(), timed_out);3008}3009 3010Genealogy::ProcessExecutableInfoSP3011MachProcess::GetGenealogyImageInfo(size_t idx) {3012 return m_activities.GetProcessExecutableInfosAtIndex(idx);3013}3014 3015bool MachProcess::GetOSVersionNumbers(uint64_t *major, uint64_t *minor,3016 uint64_t *patch) {3017 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];3018 3019 NSOperatingSystemVersion vers =3020 [[NSProcessInfo processInfo] operatingSystemVersion];3021 if (major)3022 *major = vers.majorVersion;3023 if (minor)3024 *minor = vers.minorVersion;3025 if (patch)3026 *patch = vers.patchVersion;3027 3028 [pool drain];3029 3030 return true;3031}3032 3033std::string MachProcess::GetMacCatalystVersionString() {3034 @autoreleasepool {3035 NSDictionary *version_info =3036 [NSDictionary dictionaryWithContentsOfFile:3037 @"/System/Library/CoreServices/SystemVersion.plist"];3038 NSString *version_value = [version_info objectForKey: @"iOSSupportVersion"];3039 if (const char *version_str = [version_value UTF8String])3040 return version_str;3041 }3042 return {};3043}3044 3045nub_process_t MachProcess::GetParentProcessID(nub_process_t child_pid) {3046 struct proc_bsdshortinfo proc;3047 if (proc_pidinfo(child_pid, PROC_PIDT_SHORTBSDINFO, 0, &proc,3048 PROC_PIDT_SHORTBSDINFO_SIZE) == sizeof(proc)) {3049 return proc.pbsi_ppid;3050 }3051 return INVALID_NUB_PROCESS;3052}3053 3054bool MachProcess::ProcessIsBeingDebugged(nub_process_t pid) {3055 struct kinfo_proc kinfo;3056 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};3057 size_t len = sizeof(struct kinfo_proc);3058 if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), &kinfo, &len, NULL, 0) == 0 &&3059 (kinfo.kp_proc.p_flag & P_TRACED))3060 return true;3061 else3062 return false;3063}3064 3065#if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS)3066/// Get the app bundle from the given path. Returns the empty string if the3067/// path doesn't appear to be an app bundle.3068static std::string GetAppBundle(std::string path) {3069 auto pos = path.rfind(".app");3070 // Path doesn't contain `.app`.3071 if (pos == std::string::npos)3072 return {};3073 // Path has `.app` extension.3074 if (pos == path.size() - 4)3075 return path.substr(0, pos + 4);3076 3077 // Look for `.app` before a path separator.3078 do {3079 if (path[pos + 4] == '/')3080 return path.substr(0, pos + 4);3081 path = path.substr(0, pos);3082 pos = path.rfind(".app");3083 } while (pos != std::string::npos);3084 3085 return {};3086}3087#endif3088 3089// Do the process specific setup for attach. If this returns NULL, then there's3090// no3091// platform specific stuff to be done to wait for the attach. If you get3092// non-null,3093// pass that token to the CheckForProcess method, and then to3094// CleanupAfterAttach.3095 3096// Call PrepareForAttach before attaching to a process that has not yet3097// launched3098// This returns a token that can be passed to CheckForProcess, and to3099// CleanupAfterAttach.3100// You should call CleanupAfterAttach to free the token, and do whatever other3101// cleanup seems good.3102 3103const void *MachProcess::PrepareForAttach(const char *path,3104 nub_launch_flavor_t launch_flavor,3105 bool waitfor, DNBError &attach_err) {3106#if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS)3107 // Tell SpringBoard to halt the next launch of this application on startup.3108 3109 if (!waitfor)3110 return NULL;3111 3112 std::string app_bundle_path = GetAppBundle(path);3113 if (app_bundle_path.empty()) {3114 DNBLogThreadedIf(3115 LOG_PROCESS,3116 "MachProcess::PrepareForAttach(): path '%s' doesn't contain .app, "3117 "we can't tell springboard to wait for launch...",3118 path);3119 return NULL;3120 }3121 3122#if defined(WITH_FBS)3123 if (launch_flavor == eLaunchFlavorDefault)3124 launch_flavor = eLaunchFlavorFBS;3125 if (launch_flavor != eLaunchFlavorFBS)3126 return NULL;3127#elif defined(WITH_BKS)3128 if (launch_flavor == eLaunchFlavorDefault)3129 launch_flavor = eLaunchFlavorBKS;3130 if (launch_flavor != eLaunchFlavorBKS)3131 return NULL;3132#elif defined(WITH_SPRINGBOARD)3133 if (launch_flavor == eLaunchFlavorDefault)3134 launch_flavor = eLaunchFlavorSpringBoard;3135 if (launch_flavor != eLaunchFlavorSpringBoard)3136 return NULL;3137#endif3138 3139 CFStringRef bundleIDCFStr =3140 CopyBundleIDForPath(app_bundle_path.c_str(), attach_err);3141 std::string bundleIDStr;3142 CFString::UTF8(bundleIDCFStr, bundleIDStr);3143 DNBLogThreadedIf(LOG_PROCESS,3144 "CopyBundleIDForPath (%s, err_str) returned @\"%s\"",3145 app_bundle_path.c_str(), bundleIDStr.c_str());3146 3147 if (bundleIDCFStr == NULL) {3148 return NULL;3149 }3150 3151#if defined(WITH_FBS)3152 if (launch_flavor == eLaunchFlavorFBS) {3153 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];3154 3155 NSString *stdio_path = nil;3156 NSFileManager *file_manager = [NSFileManager defaultManager];3157 const char *null_path = "/dev/null";3158 stdio_path =3159 [file_manager stringWithFileSystemRepresentation:null_path3160 length:strlen(null_path)];3161 3162 NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];3163 NSMutableDictionary *options = [NSMutableDictionary dictionary];3164 3165 DNBLogThreadedIf(LOG_PROCESS, "Calling BKSSystemService openApplication: "3166 "@\"%s\",options include stdio path: \"%s\", "3167 "BKSDebugOptionKeyDebugOnNextLaunch & "3168 "BKSDebugOptionKeyWaitForDebugger )",3169 bundleIDStr.c_str(), null_path);3170 3171 [debug_options setObject:stdio_path3172 forKey:FBSDebugOptionKeyStandardOutPath];3173 [debug_options setObject:stdio_path3174 forKey:FBSDebugOptionKeyStandardErrorPath];3175 [debug_options setObject:[NSNumber numberWithBool:YES]3176 forKey:FBSDebugOptionKeyWaitForDebugger];3177 [debug_options setObject:[NSNumber numberWithBool:YES]3178 forKey:FBSDebugOptionKeyDebugOnNextLaunch];3179 3180 [options setObject:debug_options3181 forKey:FBSOpenApplicationOptionKeyDebuggingOptions];3182 3183 FBSSystemService *system_service = [[FBSSystemService alloc] init];3184 3185 mach_port_t client_port = [system_service createClientPort];3186 __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);3187 __block FBSOpenApplicationErrorCode attach_error_code =3188 FBSOpenApplicationErrorCodeNone;3189 3190 NSString *bundleIDNSStr = (NSString *)bundleIDCFStr;3191 3192 DNBLog("[LaunchAttach] START (%d) requesting FBS launch of app with bundle "3193 "ID '%s'",3194 getpid(), bundleIDStr.c_str());3195 [system_service openApplication:bundleIDNSStr3196 options:options3197 clientPort:client_port3198 withResult:^(NSError *error) {3199 // The system service will cleanup the client port we3200 // created for us.3201 if (error)3202 attach_error_code =3203 (FBSOpenApplicationErrorCode)[error code];3204 3205 [system_service release];3206 dispatch_semaphore_signal(semaphore);3207 }];3208 3209 const uint32_t timeout_secs = 9;3210 3211 dispatch_time_t timeout =3212 dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC);3213 3214 long success = dispatch_semaphore_wait(semaphore, timeout) == 0;3215 3216 if (!success) {3217 DNBLogError("timed out trying to launch %s.", bundleIDStr.c_str());3218 attach_err.SetErrorString(3219 "debugserver timed out waiting for openApplication to complete.");3220 attach_err.SetError(OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic);3221 } else if (attach_error_code != FBSOpenApplicationErrorCodeNone) {3222 std::string empty_str;3223 SetFBSError(attach_error_code, empty_str, attach_err);3224 DNBLogError("unable to launch the application with CFBundleIdentifier "3225 "'%s' bks_error = %ld",3226 bundleIDStr.c_str(), (NSInteger)attach_error_code);3227 }3228 dispatch_release(semaphore);3229 [pool drain];3230 }3231#endif3232#if defined(WITH_BKS)3233 if (launch_flavor == eLaunchFlavorBKS) {3234 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];3235 3236 NSString *stdio_path = nil;3237 NSFileManager *file_manager = [NSFileManager defaultManager];3238 const char *null_path = "/dev/null";3239 stdio_path =3240 [file_manager stringWithFileSystemRepresentation:null_path3241 length:strlen(null_path)];3242 3243 NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];3244 NSMutableDictionary *options = [NSMutableDictionary dictionary];3245 3246 DNBLogThreadedIf(LOG_PROCESS, "Calling BKSSystemService openApplication: "3247 "@\"%s\",options include stdio path: \"%s\", "3248 "BKSDebugOptionKeyDebugOnNextLaunch & "3249 "BKSDebugOptionKeyWaitForDebugger )",3250 bundleIDStr.c_str(), null_path);3251 3252 [debug_options setObject:stdio_path3253 forKey:BKSDebugOptionKeyStandardOutPath];3254 [debug_options setObject:stdio_path3255 forKey:BKSDebugOptionKeyStandardErrorPath];3256 [debug_options setObject:[NSNumber numberWithBool:YES]3257 forKey:BKSDebugOptionKeyWaitForDebugger];3258 [debug_options setObject:[NSNumber numberWithBool:YES]3259 forKey:BKSDebugOptionKeyDebugOnNextLaunch];3260 3261 [options setObject:debug_options3262 forKey:BKSOpenApplicationOptionKeyDebuggingOptions];3263 3264 BKSSystemService *system_service = [[BKSSystemService alloc] init];3265 3266 mach_port_t client_port = [system_service createClientPort];3267 __block dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);3268 __block BKSOpenApplicationErrorCode attach_error_code =3269 BKSOpenApplicationErrorCodeNone;3270 3271 NSString *bundleIDNSStr = (NSString *)bundleIDCFStr;3272 3273 DNBLog("[LaunchAttach] START (%d) requesting BKS launch of app with bundle "3274 "ID '%s'",3275 getpid(), bundleIDStr.c_str());3276 [system_service openApplication:bundleIDNSStr3277 options:options3278 clientPort:client_port3279 withResult:^(NSError *error) {3280 // The system service will cleanup the client port we3281 // created for us.3282 if (error)3283 attach_error_code =3284 (BKSOpenApplicationErrorCode)[error code];3285 3286 [system_service release];3287 dispatch_semaphore_signal(semaphore);3288 }];3289 3290 const uint32_t timeout_secs = 9;3291 3292 dispatch_time_t timeout =3293 dispatch_time(DISPATCH_TIME_NOW, timeout_secs * NSEC_PER_SEC);3294 3295 long success = dispatch_semaphore_wait(semaphore, timeout) == 0;3296 3297 if (!success) {3298 DNBLogError("timed out trying to launch %s.", bundleIDStr.c_str());3299 attach_err.SetErrorString(3300 "debugserver timed out waiting for openApplication to complete.");3301 attach_err.SetError(OPEN_APPLICATION_TIMEOUT_ERROR, DNBError::Generic);3302 } else if (attach_error_code != BKSOpenApplicationErrorCodeNone) {3303 std::string empty_str;3304 SetBKSError(attach_error_code, empty_str, attach_err);3305 DNBLogError("unable to launch the application with CFBundleIdentifier "3306 "'%s' bks_error = %d",3307 bundleIDStr.c_str(), attach_error_code);3308 }3309 dispatch_release(semaphore);3310 [pool drain];3311 }3312#endif3313 3314#if defined(WITH_SPRINGBOARD)3315 if (launch_flavor == eLaunchFlavorSpringBoard) {3316 SBSApplicationLaunchError sbs_error = 0;3317 3318 const char *stdout_err = "/dev/null";3319 CFString stdio_path;3320 stdio_path.SetFileSystemRepresentation(stdout_err);3321 3322 DNBLogThreadedIf(LOG_PROCESS, "SBSLaunchApplicationForDebugging ( @\"%s\" "3323 ", NULL, NULL, NULL, @\"%s\", @\"%s\", "3324 "SBSApplicationDebugOnNextLaunch | "3325 "SBSApplicationLaunchWaitForDebugger )",3326 bundleIDStr.c_str(), stdout_err, stdout_err);3327 3328 DNBLog("[LaunchAttach] START (%d) requesting SpringBoard launch of app "3329 "with bundle "3330 "ID '%s'",3331 getpid(), bundleIDStr.c_str());3332 sbs_error = SBSLaunchApplicationForDebugging(3333 bundleIDCFStr,3334 (CFURLRef)NULL, // openURL3335 NULL, // launch_argv.get(),3336 NULL, // launch_envp.get(), // CFDictionaryRef environment3337 stdio_path.get(), stdio_path.get(),3338 SBSApplicationDebugOnNextLaunch | SBSApplicationLaunchWaitForDebugger);3339 3340 if (sbs_error != SBSApplicationLaunchErrorSuccess) {3341 attach_err.SetError(sbs_error, DNBError::SpringBoard);3342 return NULL;3343 }3344 }3345#endif // WITH_SPRINGBOARD3346 3347 DNBLogThreadedIf(LOG_PROCESS, "Successfully set DebugOnNextLaunch.");3348 return bundleIDCFStr;3349#else // !(defined (WITH_SPRINGBOARD) || defined (WITH_BKS) || defined3350 // (WITH_FBS))3351 return NULL;3352#endif3353}3354 3355// Pass in the token you got from PrepareForAttach. If there is a process3356// for that token, then the pid will be returned, otherwise INVALID_NUB_PROCESS3357// will be returned.3358 3359nub_process_t MachProcess::CheckForProcess(const void *attach_token,3360 nub_launch_flavor_t launch_flavor) {3361 if (attach_token == NULL)3362 return INVALID_NUB_PROCESS;3363 3364#if defined(WITH_FBS)3365 if (launch_flavor == eLaunchFlavorFBS) {3366 NSString *bundleIDNSStr = (NSString *)attach_token;3367 FBSSystemService *systemService = [[FBSSystemService alloc] init];3368 pid_t pid = [systemService pidForApplication:bundleIDNSStr];3369 [systemService release];3370 if (pid == 0)3371 return INVALID_NUB_PROCESS;3372 else3373 return pid;3374 }3375#endif3376 3377#if defined(WITH_BKS)3378 if (launch_flavor == eLaunchFlavorBKS) {3379 NSString *bundleIDNSStr = (NSString *)attach_token;3380 BKSSystemService *systemService = [[BKSSystemService alloc] init];3381 pid_t pid = [systemService pidForApplication:bundleIDNSStr];3382 [systemService release];3383 if (pid == 0)3384 return INVALID_NUB_PROCESS;3385 else3386 return pid;3387 }3388#endif3389 3390#if defined(WITH_SPRINGBOARD)3391 if (launch_flavor == eLaunchFlavorSpringBoard) {3392 CFStringRef bundleIDCFStr = (CFStringRef)attach_token;3393 Boolean got_it;3394 nub_process_t attach_pid;3395 got_it = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &attach_pid);3396 if (got_it)3397 return attach_pid;3398 else3399 return INVALID_NUB_PROCESS;3400 }3401#endif3402 return INVALID_NUB_PROCESS;3403}3404 3405// Call this to clean up after you have either attached or given up on the3406// attach.3407// Pass true for success if you have attached, false if you have not.3408// The token will also be freed at this point, so you can't use it after calling3409// this method.3410 3411void MachProcess::CleanupAfterAttach(const void *attach_token,3412 nub_launch_flavor_t launch_flavor,3413 bool success, DNBError &err_str) {3414 if (attach_token == NULL)3415 return;3416 3417#if defined(WITH_FBS)3418 if (launch_flavor == eLaunchFlavorFBS) {3419 if (!success) {3420 FBSCleanupAfterAttach(attach_token, err_str);3421 }3422 CFRelease((CFStringRef)attach_token);3423 }3424#endif3425 3426#if defined(WITH_BKS)3427 3428 if (launch_flavor == eLaunchFlavorBKS) {3429 if (!success) {3430 BKSCleanupAfterAttach(attach_token, err_str);3431 }3432 CFRelease((CFStringRef)attach_token);3433 }3434#endif3435 3436#if defined(WITH_SPRINGBOARD)3437 // Tell SpringBoard to cancel the debug on next launch of this application3438 // if we failed to attach3439 if (launch_flavor == eMachProcessFlagsUsingSpringBoard) {3440 if (!success) {3441 SBSApplicationLaunchError sbs_error = 0;3442 CFStringRef bundleIDCFStr = (CFStringRef)attach_token;3443 3444 sbs_error = SBSLaunchApplicationForDebugging(3445 bundleIDCFStr, (CFURLRef)NULL, NULL, NULL, NULL, NULL,3446 SBSApplicationCancelDebugOnNextLaunch);3447 3448 if (sbs_error != SBSApplicationLaunchErrorSuccess) {3449 err_str.SetError(sbs_error, DNBError::SpringBoard);3450 return;3451 }3452 }3453 3454 CFRelease((CFStringRef)attach_token);3455 }3456#endif3457}3458 3459pid_t MachProcess::LaunchForDebug(3460 const char *path, char const *argv[], char const *envp[],3461 const char *working_directory, // NULL => don't change, non-NULL => set3462 // working directory for inferior to this3463 const char *stdin_path, const char *stdout_path, const char *stderr_path,3464 bool no_stdio, nub_launch_flavor_t launch_flavor, int disable_aslr,3465 const char *event_data, 3466 const RNBContext::IgnoredExceptions &ignored_exceptions, 3467 DNBError &launch_err) {3468 // Clear out and clean up from any current state3469 Clear();3470 3471 DNBLogThreadedIf(LOG_PROCESS,3472 "%s( path = '%s', argv = %p, envp = %p, "3473 "launch_flavor = %u, disable_aslr = %d )",3474 __FUNCTION__, path, static_cast<const void *>(argv),3475 static_cast<const void *>(envp), launch_flavor,3476 disable_aslr);3477 3478 // Fork a child process for debugging3479 SetState(eStateLaunching);3480 3481 switch (launch_flavor) {3482 case eLaunchFlavorForkExec:3483 m_pid = MachProcess::ForkChildForPTraceDebugging(path, argv, envp, this,3484 launch_err);3485 break;3486#ifdef WITH_FBS3487 case eLaunchFlavorFBS: {3488 std::string app_bundle_path = GetAppBundle(path);3489 if (!app_bundle_path.empty()) {3490 m_flags |= (eMachProcessFlagsUsingFBS | eMachProcessFlagsBoardCalculated);3491 if (BoardServiceLaunchForDebug(app_bundle_path.c_str(), argv, envp,3492 no_stdio, disable_aslr, event_data,3493 ignored_exceptions, launch_err) != 0)3494 return m_pid; // A successful SBLaunchForDebug() returns and assigns a3495 // non-zero m_pid.3496 }3497 DNBLog("Failed to launch '%s' with FBS", app_bundle_path.c_str());3498 } break;3499#endif3500#ifdef WITH_BKS3501 case eLaunchFlavorBKS: {3502 std::string app_bundle_path = GetAppBundle(path);3503 if (!app_bundle_path.empty()) {3504 m_flags |= (eMachProcessFlagsUsingBKS | eMachProcessFlagsBoardCalculated);3505 if (BoardServiceLaunchForDebug(app_bundle_path.c_str(), argv, envp,3506 no_stdio, disable_aslr, event_data,3507 ignored_exceptions, launch_err) != 0)3508 return m_pid; // A successful SBLaunchForDebug() returns and assigns a3509 // non-zero m_pid.3510 }3511 DNBLog("Failed to launch '%s' with BKS", app_bundle_path.c_str());3512 } break;3513#endif3514#ifdef WITH_SPRINGBOARD3515 case eLaunchFlavorSpringBoard: {3516 std::string app_bundle_path = GetAppBundle(path);3517 if (!app_bundle_path.empty()) {3518 if (SBLaunchForDebug(app_bundle_path.c_str(), argv, envp, no_stdio,3519 disable_aslr, ignored_exceptions, launch_err) != 0)3520 return m_pid; // A successful SBLaunchForDebug() returns and assigns a3521 // non-zero m_pid.3522 }3523 DNBLog("Failed to launch '%s' with SpringBoard", app_bundle_path.c_str());3524 } break;3525 3526#endif3527 3528 case eLaunchFlavorPosixSpawn:3529 m_pid = MachProcess::PosixSpawnChildForPTraceDebugging(3530 path, DNBArchProtocol::GetCPUType(), DNBArchProtocol::GetCPUSubType(),3531 argv, envp, working_directory, stdin_path, stdout_path, stderr_path,3532 no_stdio, this, disable_aslr, launch_err);3533 break;3534 3535 default:3536 DNBLog("Failed to launch: invalid launch flavor: %d", launch_flavor);3537 launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);3538 return INVALID_NUB_PROCESS;3539 }3540 3541 if (m_pid == INVALID_NUB_PROCESS) {3542 // If we don't have a valid process ID and no one has set the error,3543 // then return a generic error3544 if (launch_err.Success())3545 launch_err.SetError(NUB_GENERIC_ERROR, DNBError::Generic);3546 } else {3547 m_path = path;3548 size_t i;3549 char const *arg;3550 for (i = 0; (arg = argv[i]) != NULL; i++)3551 m_args.push_back(arg);3552 3553 m_task.StartExceptionThread(ignored_exceptions, launch_err);3554 if (launch_err.Fail()) {3555 if (launch_err.AsString() == NULL)3556 launch_err.SetErrorString("unable to start the exception thread");3557 DNBLog("Could not get inferior's Mach exception port, sending ptrace "3558 "PT_KILL and exiting.");3559 ::ptrace(PT_KILL, m_pid, 0, 0);3560 m_pid = INVALID_NUB_PROCESS;3561 return INVALID_NUB_PROCESS;3562 }3563 3564 StartSTDIOThread();3565 3566 if (launch_flavor == eLaunchFlavorPosixSpawn) {3567 3568 SetState(eStateAttaching);3569 errno = 0;3570 DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...",3571 getpid(), m_pid);3572 int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0);3573 int ptrace_errno = errno;3574 DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d",3575 getpid(), m_pid, err);3576 if (err == 0) {3577 m_flags |= eMachProcessFlagsAttached;3578 DNBLogThreadedIf(LOG_PROCESS, "successfully spawned pid %d", m_pid);3579 launch_err.Clear();3580 } else {3581 SetState(eStateExited);3582 DNBError ptrace_err(ptrace_errno, DNBError::POSIX);3583 DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to spawned pid "3584 "%d (err = %i, errno = %i (%s))",3585 m_pid, err, ptrace_err.Status(),3586 ptrace_err.AsString());3587 char err_msg[PATH_MAX];3588 3589 snprintf(err_msg, sizeof(err_msg),3590 "Failed to attach to pid %d, LaunchForDebug() unable to "3591 "ptrace(PT_ATTACHEXC)",3592 m_pid);3593 launch_err.SetErrorString(err_msg);3594 }3595 } else {3596 launch_err.Clear();3597 }3598 }3599 return m_pid;3600}3601 3602pid_t MachProcess::PosixSpawnChildForPTraceDebugging(3603 const char *path, cpu_type_t cpu_type, cpu_subtype_t cpu_subtype,3604 char const *argv[], char const *envp[], const char *working_directory,3605 const char *stdin_path, const char *stdout_path, const char *stderr_path,3606 bool no_stdio, MachProcess *process, int disable_aslr, DNBError &err) {3607 posix_spawnattr_t attr;3608 short flags;3609 DNBLogThreadedIf(LOG_PROCESS,3610 "%s ( path='%s', argv=%p, envp=%p, "3611 "working_dir=%s, stdin=%s, stdout=%s "3612 "stderr=%s, no-stdio=%i)",3613 __FUNCTION__, path, static_cast<const void *>(argv),3614 static_cast<const void *>(envp), working_directory,3615 stdin_path, stdout_path, stderr_path, no_stdio);3616 3617 err.SetError(::posix_spawnattr_init(&attr), DNBError::POSIX);3618 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3619 err.LogThreaded("::posix_spawnattr_init ( &attr )");3620 if (err.Fail())3621 return INVALID_NUB_PROCESS;3622 3623 flags = POSIX_SPAWN_START_SUSPENDED | POSIX_SPAWN_SETSIGDEF |3624 POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETPGROUP;3625 if (disable_aslr)3626 flags |= _POSIX_SPAWN_DISABLE_ASLR;3627 3628 sigset_t no_signals;3629 sigset_t all_signals;3630 sigemptyset(&no_signals);3631 sigfillset(&all_signals);3632 ::posix_spawnattr_setsigmask(&attr, &no_signals);3633 ::posix_spawnattr_setsigdefault(&attr, &all_signals);3634 3635 err.SetError(::posix_spawnattr_setflags(&attr, flags), DNBError::POSIX);3636 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3637 err.LogThreaded(3638 "::posix_spawnattr_setflags ( &attr, POSIX_SPAWN_START_SUSPENDED%s )",3639 flags & _POSIX_SPAWN_DISABLE_ASLR ? " | _POSIX_SPAWN_DISABLE_ASLR"3640 : "");3641 if (err.Fail())3642 return INVALID_NUB_PROCESS;3643 3644// Don't do this on SnowLeopard, _sometimes_ the TASK_BASIC_INFO will fail3645// and we will fail to continue with our process...3646 3647// On SnowLeopard we should set "DYLD_NO_PIE" in the inferior environment....3648 3649 if (cpu_type != 0) {3650 size_t ocount = 0;3651 bool slice_preference_set = false;3652 3653 if (cpu_subtype != 0) {3654 typedef int (*posix_spawnattr_setarchpref_np_t)(3655 posix_spawnattr_t *, size_t, cpu_type_t *, cpu_subtype_t *, size_t *);3656 posix_spawnattr_setarchpref_np_t posix_spawnattr_setarchpref_np_fn =3657 (posix_spawnattr_setarchpref_np_t)dlsym(3658 RTLD_DEFAULT, "posix_spawnattr_setarchpref_np");3659 if (posix_spawnattr_setarchpref_np_fn) {3660 err.SetError((*posix_spawnattr_setarchpref_np_fn)(3661 &attr, 1, &cpu_type, &cpu_subtype, &ocount));3662 slice_preference_set = err.Success();3663 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3664 err.LogThreaded(3665 "::posix_spawnattr_setarchpref_np ( &attr, 1, cpu_type = "3666 "0x%8.8x, cpu_subtype = 0x%8.8x, count => %llu )",3667 cpu_type, cpu_subtype, (uint64_t)ocount);3668 if (err.Fail() != 0 || ocount != 1)3669 return INVALID_NUB_PROCESS;3670 }3671 }3672 3673 if (!slice_preference_set) {3674 err.SetError(3675 ::posix_spawnattr_setbinpref_np(&attr, 1, &cpu_type, &ocount),3676 DNBError::POSIX);3677 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3678 err.LogThreaded(3679 "::posix_spawnattr_setbinpref_np ( &attr, 1, cpu_type = "3680 "0x%8.8x, count => %llu )",3681 cpu_type, (uint64_t)ocount);3682 3683 if (err.Fail() != 0 || ocount != 1)3684 return INVALID_NUB_PROCESS;3685 }3686 }3687 3688 PseudoTerminal pty;3689 3690 posix_spawn_file_actions_t file_actions;3691 err.SetError(::posix_spawn_file_actions_init(&file_actions), DNBError::POSIX);3692 int file_actions_valid = err.Success();3693 if (!file_actions_valid || DNBLogCheckLogBit(LOG_PROCESS))3694 err.LogThreaded("::posix_spawn_file_actions_init ( &file_actions )");3695 int pty_error = -1;3696 pid_t pid = INVALID_NUB_PROCESS;3697 if (file_actions_valid) {3698 if (stdin_path == NULL && stdout_path == NULL && stderr_path == NULL &&3699 !no_stdio) {3700 pty_error = pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY);3701 if (pty_error == PseudoTerminal::success) {3702 stdin_path = stdout_path = stderr_path = pty.SecondaryName();3703 }3704 }3705 3706 // if no_stdio or std paths not supplied, then route to "/dev/null".3707 if (no_stdio || stdin_path == NULL || stdin_path[0] == '\0')3708 stdin_path = "/dev/null";3709 if (no_stdio || stdout_path == NULL || stdout_path[0] == '\0')3710 stdout_path = "/dev/null";3711 if (no_stdio || stderr_path == NULL || stderr_path[0] == '\0')3712 stderr_path = "/dev/null";3713 3714 err.SetError(::posix_spawn_file_actions_addopen(&file_actions, STDIN_FILENO,3715 stdin_path,3716 O_RDONLY | O_NOCTTY, 0),3717 DNBError::POSIX);3718 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3719 err.LogThreaded("::posix_spawn_file_actions_addopen (&file_actions, "3720 "filedes=STDIN_FILENO, path='%s')",3721 stdin_path);3722 3723 err.SetError(::posix_spawn_file_actions_addopen(3724 &file_actions, STDOUT_FILENO, stdout_path,3725 O_WRONLY | O_NOCTTY | O_CREAT, 0640),3726 DNBError::POSIX);3727 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3728 err.LogThreaded("::posix_spawn_file_actions_addopen (&file_actions, "3729 "filedes=STDOUT_FILENO, path='%s')",3730 stdout_path);3731 3732 err.SetError(::posix_spawn_file_actions_addopen(3733 &file_actions, STDERR_FILENO, stderr_path,3734 O_WRONLY | O_NOCTTY | O_CREAT, 0640),3735 DNBError::POSIX);3736 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3737 err.LogThreaded("::posix_spawn_file_actions_addopen (&file_actions, "3738 "filedes=STDERR_FILENO, path='%s')",3739 stderr_path);3740 3741 // TODO: Verify if we can set the working directory back immediately3742 // after the posix_spawnp call without creating a race condition???3743 if (working_directory)3744 ::chdir(working_directory);3745 3746 err.SetError(::posix_spawnp(&pid, path, &file_actions, &attr,3747 const_cast<char *const *>(argv),3748 const_cast<char *const *>(envp)),3749 DNBError::POSIX);3750 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3751 err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = "3752 "%p, attr = %p, argv = %p, envp = %p )",3753 pid, path, &file_actions, &attr, argv, envp);3754 } else {3755 // TODO: Verify if we can set the working directory back immediately3756 // after the posix_spawnp call without creating a race condition???3757 if (working_directory)3758 ::chdir(working_directory);3759 3760 err.SetError(::posix_spawnp(&pid, path, NULL, &attr,3761 const_cast<char *const *>(argv),3762 const_cast<char *const *>(envp)),3763 DNBError::POSIX);3764 if (err.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3765 err.LogThreaded("::posix_spawnp ( pid => %i, path = '%s', file_actions = "3766 "%p, attr = %p, argv = %p, envp = %p )",3767 pid, path, NULL, &attr, argv, envp);3768 }3769 3770 // We have seen some cases where posix_spawnp was returning a valid3771 // looking pid even when an error was returned, so clear it out3772 if (err.Fail())3773 pid = INVALID_NUB_PROCESS;3774 3775 if (pty_error == 0) {3776 if (process != NULL) {3777 int primary_fd = pty.ReleasePrimaryFD();3778 process->SetChildFileDescriptors(primary_fd, primary_fd, primary_fd);3779 }3780 }3781 ::posix_spawnattr_destroy(&attr);3782 3783 if (pid != INVALID_NUB_PROCESS) {3784 cpu_type_t pid_cpu_type = MachProcess::GetCPUTypeForLocalProcess(pid);3785 DNBLogThreadedIf(LOG_PROCESS,3786 "MachProcess::%s ( ) pid=%i, cpu_type=0x%8.8x",3787 __FUNCTION__, pid, pid_cpu_type);3788 if (pid_cpu_type)3789 DNBArchProtocol::SetArchitecture(pid_cpu_type);3790 }3791 3792 if (file_actions_valid) {3793 DNBError err2;3794 err2.SetError(::posix_spawn_file_actions_destroy(&file_actions),3795 DNBError::POSIX);3796 if (err2.Fail() || DNBLogCheckLogBit(LOG_PROCESS))3797 err2.LogThreaded("::posix_spawn_file_actions_destroy ( &file_actions )");3798 }3799 3800 return pid;3801}3802 3803uint32_t MachProcess::GetCPUTypeForLocalProcess(pid_t pid) {3804 int mib[CTL_MAXNAME] = {3805 0,3806 };3807 size_t len = CTL_MAXNAME;3808 if (::sysctlnametomib("sysctl.proc_cputype", mib, &len))3809 return 0;3810 3811 mib[len] = pid;3812 len++;3813 3814 cpu_type_t cpu;3815 size_t cpu_len = sizeof(cpu);3816 if (::sysctl(mib, static_cast<u_int>(len), &cpu, &cpu_len, 0, 0))3817 cpu = 0;3818 return cpu;3819}3820 3821pid_t MachProcess::ForkChildForPTraceDebugging(const char *path,3822 char const *argv[],3823 char const *envp[],3824 MachProcess *process,3825 DNBError &launch_err) {3826 PseudoTerminal::Status pty_error = PseudoTerminal::success;3827 3828 // Use a fork that ties the child process's stdin/out/err to a pseudo3829 // terminal so we can read it in our MachProcess::STDIOThread3830 // as unbuffered io.3831 PseudoTerminal pty;3832 pid_t pid = pty.Fork(pty_error);3833 3834 if (pid < 0) {3835 //--------------------------------------------------------------3836 // Status during fork.3837 //--------------------------------------------------------------3838 return pid;3839 } else if (pid == 0) {3840 //--------------------------------------------------------------3841 // Child process3842 //--------------------------------------------------------------3843 ::ptrace(PT_TRACE_ME, 0, 0, 0); // Debug this process3844 ::ptrace(PT_SIGEXC, 0, 0, 0); // Get BSD signals as mach exceptions3845 3846 // If our parent is setgid, lets make sure we don't inherit those3847 // extra powers due to nepotism.3848 if (::setgid(getgid()) == 0) {3849 3850 // Let the child have its own process group. We need to execute3851 // this call in both the child and parent to avoid a race condition3852 // between the two processes.3853 ::setpgid(0, 0); // Set the child process group to match its pid3854 3855 // Sleep a bit to before the exec call3856 ::sleep(1);3857 3858 // Turn this process into3859 ::execv(path, const_cast<char *const *>(argv));3860 }3861 // Exit with error code. Child process should have taken3862 // over in above exec call and if the exec fails it will3863 // exit the child process below.3864 ::exit(127);3865 } else {3866 //--------------------------------------------------------------3867 // Parent process3868 //--------------------------------------------------------------3869 // Let the child have its own process group. We need to execute3870 // this call in both the child and parent to avoid a race condition3871 // between the two processes.3872 ::setpgid(pid, pid); // Set the child process group to match its pid3873 3874 if (process != NULL) {3875 // Release our primary pty file descriptor so the pty class doesn't3876 // close it and so we can continue to use it in our STDIO thread3877 int primary_fd = pty.ReleasePrimaryFD();3878 process->SetChildFileDescriptors(primary_fd, primary_fd, primary_fd);3879 }3880 }3881 return pid;3882}3883 3884#if defined(WITH_SPRINGBOARD) || defined(WITH_BKS) || defined(WITH_FBS)3885// This returns a CFRetained pointer to the Bundle ID for app_bundle_path,3886// or NULL if there was some problem getting the bundle id.3887static CFStringRef CopyBundleIDForPath(const char *app_bundle_path,3888 DNBError &err_str) {3889 CFBundle bundle(app_bundle_path);3890 CFStringRef bundleIDCFStr = bundle.GetIdentifier();3891 std::string bundleID;3892 if (CFString::UTF8(bundleIDCFStr, bundleID) == NULL) {3893 struct stat app_bundle_stat;3894 char err_msg[PATH_MAX];3895 3896 if (::stat(app_bundle_path, &app_bundle_stat) < 0) {3897 err_str.SetError(errno, DNBError::POSIX);3898 snprintf(err_msg, sizeof(err_msg), "%s: \"%s\"", err_str.AsString(),3899 app_bundle_path);3900 err_str.SetErrorString(err_msg);3901 DNBLogThreadedIf(LOG_PROCESS, "%s() error: %s", __FUNCTION__, err_msg);3902 } else {3903 err_str.SetError(-1, DNBError::Generic);3904 snprintf(err_msg, sizeof(err_msg),3905 "failed to extract CFBundleIdentifier from %s", app_bundle_path);3906 err_str.SetErrorString(err_msg);3907 DNBLogThreadedIf(3908 LOG_PROCESS,3909 "%s() error: failed to extract CFBundleIdentifier from '%s'",3910 __FUNCTION__, app_bundle_path);3911 }3912 return NULL;3913 }3914 3915 DNBLogThreadedIf(LOG_PROCESS, "%s() extracted CFBundleIdentifier: %s",3916 __FUNCTION__, bundleID.c_str());3917 CFRetain(bundleIDCFStr);3918 3919 return bundleIDCFStr;3920}3921#endif // #if defined (WITH_SPRINGBOARD) || defined (WITH_BKS) || defined3922 // (WITH_FBS)3923#ifdef WITH_SPRINGBOARD3924 3925pid_t MachProcess::SBLaunchForDebug(const char *path, char const *argv[],3926 char const *envp[], bool no_stdio,3927 bool disable_aslr, 3928 const RNBContext::IgnoredExceptions 3929 &ignored_exceptions,3930 DNBError &launch_err) {3931 // Clear out and clean up from any current state3932 Clear();3933 3934 DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path);3935 3936 // Fork a child process for debugging3937 SetState(eStateLaunching);3938 m_pid = MachProcess::SBForkChildForPTraceDebugging(path, argv, envp, no_stdio,3939 this, launch_err);3940 if (m_pid != 0) {3941 m_path = path;3942 size_t i;3943 char const *arg;3944 for (i = 0; (arg = argv[i]) != NULL; i++)3945 m_args.push_back(arg);3946 m_task.StartExceptionThread(ignored_exceptions, launch_err);3947 3948 if (launch_err.Fail()) {3949 if (launch_err.AsString() == NULL)3950 launch_err.SetErrorString("unable to start the exception thread");3951 DNBLog("Could not get inferior's Mach exception port, sending ptrace "3952 "PT_KILL and exiting.");3953 ::ptrace(PT_KILL, m_pid, 0, 0);3954 m_pid = INVALID_NUB_PROCESS;3955 return INVALID_NUB_PROCESS;3956 }3957 3958 StartSTDIOThread();3959 SetState(eStateAttaching);3960 DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...", getpid(),3961 m_pid);3962 int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0);3963 DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d",3964 getpid(), m_pid, err);3965 if (err == 0) {3966 m_flags |= eMachProcessFlagsAttached;3967 DNBLogThreadedIf(LOG_PROCESS, "successfully attached to pid %d", m_pid);3968 } else {3969 launch_err.SetErrorString(3970 "Failed to attach to pid %d, SBLaunchForDebug() unable to "3971 "ptrace(PT_ATTACHEXC)",3972 m_pid);3973 SetState(eStateExited);3974 DNBLogThreadedIf(LOG_PROCESS, "error: failed to attach to pid %d", m_pid);3975 }3976 }3977 return m_pid;3978}3979 3980#include <servers/bootstrap.h>3981 3982pid_t MachProcess::SBForkChildForPTraceDebugging(3983 const char *app_bundle_path, char const *argv[], char const *envp[],3984 bool no_stdio, MachProcess *process, DNBError &launch_err) {3985 DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__,3986 app_bundle_path, process);3987 CFAllocatorRef alloc = kCFAllocatorDefault;3988 3989 if (argv[0] == NULL)3990 return INVALID_NUB_PROCESS;3991 3992 size_t argc = 0;3993 // Count the number of arguments3994 while (argv[argc] != NULL)3995 argc++;3996 3997 // Enumerate the arguments3998 size_t first_launch_arg_idx = 1;3999 CFReleaser<CFMutableArrayRef> launch_argv;4000 4001 if (argv[first_launch_arg_idx]) {4002 size_t launch_argc = argc > 0 ? argc - 1 : 0;4003 launch_argv.reset(4004 ::CFArrayCreateMutable(alloc, launch_argc, &kCFTypeArrayCallBacks));4005 size_t i;4006 char const *arg;4007 CFString launch_arg;4008 for (i = first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL);4009 i++) {4010 launch_arg.reset(4011 ::CFStringCreateWithCString(alloc, arg, kCFStringEncodingUTF8));4012 if (launch_arg.get() != NULL)4013 CFArrayAppendValue(launch_argv.get(), launch_arg.get());4014 else4015 break;4016 }4017 }4018 4019 // Next fill in the arguments dictionary. Note, the envp array is of the form4020 // Variable=value but SpringBoard wants a CF dictionary. So we have to4021 // convert4022 // this here.4023 4024 CFReleaser<CFMutableDictionaryRef> launch_envp;4025 4026 if (envp[0]) {4027 launch_envp.reset(4028 ::CFDictionaryCreateMutable(alloc, 0, &kCFTypeDictionaryKeyCallBacks,4029 &kCFTypeDictionaryValueCallBacks));4030 const char *value;4031 int name_len;4032 CFString name_string, value_string;4033 4034 for (int i = 0; envp[i] != NULL; i++) {4035 value = strstr(envp[i], "=");4036 4037 // If the name field is empty or there's no =, skip it. Somebody's4038 // messing with us.4039 if (value == NULL || value == envp[i])4040 continue;4041 4042 name_len = value - envp[i];4043 4044 // Now move value over the "="4045 value++;4046 4047 name_string.reset(4048 ::CFStringCreateWithBytes(alloc, (const UInt8 *)envp[i], name_len,4049 kCFStringEncodingUTF8, false));4050 value_string.reset(4051 ::CFStringCreateWithCString(alloc, value, kCFStringEncodingUTF8));4052 CFDictionarySetValue(launch_envp.get(), name_string.get(),4053 value_string.get());4054 }4055 }4056 4057 CFString stdio_path;4058 4059 PseudoTerminal pty;4060 if (!no_stdio) {4061 PseudoTerminal::Status pty_err =4062 pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY);4063 if (pty_err == PseudoTerminal::success) {4064 const char *secondary_name = pty.SecondaryName();4065 DNBLogThreadedIf(LOG_PROCESS,4066 "%s() successfully opened primary pty, secondary is %s",4067 __FUNCTION__, secondary_name);4068 if (secondary_name && secondary_name[0]) {4069 ::chmod(secondary_name, S_IRWXU | S_IRWXG | S_IRWXO);4070 stdio_path.SetFileSystemRepresentation(secondary_name);4071 }4072 }4073 }4074 4075 if (stdio_path.get() == NULL) {4076 stdio_path.SetFileSystemRepresentation("/dev/null");4077 }4078 4079 CFStringRef bundleIDCFStr = CopyBundleIDForPath(app_bundle_path, launch_err);4080 if (bundleIDCFStr == NULL)4081 return INVALID_NUB_PROCESS;4082 4083 // This is just for logging:4084 std::string bundleID;4085 CFString::UTF8(bundleIDCFStr, bundleID);4086 4087 DNBLogThreadedIf(LOG_PROCESS, "%s() serialized launch arg array",4088 __FUNCTION__);4089 4090 // Find SpringBoard4091 SBSApplicationLaunchError sbs_error = 0;4092 sbs_error = SBSLaunchApplicationForDebugging(4093 bundleIDCFStr,4094 (CFURLRef)NULL, // openURL4095 launch_argv.get(),4096 launch_envp.get(), // CFDictionaryRef environment4097 stdio_path.get(), stdio_path.get(),4098 SBSApplicationLaunchWaitForDebugger | SBSApplicationLaunchUnlockDevice);4099 4100 launch_err.SetError(sbs_error, DNBError::SpringBoard);4101 4102 if (sbs_error == SBSApplicationLaunchErrorSuccess) {4103 static const useconds_t pid_poll_interval = 200000;4104 static const useconds_t pid_poll_timeout = 30000000;4105 4106 useconds_t pid_poll_total = 0;4107 4108 nub_process_t pid = INVALID_NUB_PROCESS;4109 Boolean pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);4110 // Poll until the process is running, as long as we are getting valid4111 // responses and the timeout hasn't expired4112 // A return PID of 0 means the process is not running, which may be because4113 // it hasn't been (asynchronously) started4114 // yet, or that it died very quickly (if you weren't using waitForDebugger).4115 while (!pid_found && pid_poll_total < pid_poll_timeout) {4116 usleep(pid_poll_interval);4117 pid_poll_total += pid_poll_interval;4118 DNBLogThreadedIf(LOG_PROCESS,4119 "%s() polling Springboard for pid for %s...",4120 __FUNCTION__, bundleID.c_str());4121 pid_found = SBSProcessIDForDisplayIdentifier(bundleIDCFStr, &pid);4122 }4123 4124 CFRelease(bundleIDCFStr);4125 if (pid_found) {4126 if (process != NULL) {4127 // Release our primary pty file descriptor so the pty class doesn't4128 // close it and so we can continue to use it in our STDIO thread4129 int primary_fd = pty.ReleasePrimaryFD();4130 process->SetChildFileDescriptors(primary_fd, primary_fd, primary_fd);4131 }4132 DNBLogThreadedIf(LOG_PROCESS, "%s() => pid = %4.4x", __FUNCTION__, pid);4133 } else {4134 DNBLogError("failed to lookup the process ID for CFBundleIdentifier %s.",4135 bundleID.c_str());4136 }4137 return pid;4138 }4139 4140 DNBLogError("unable to launch the application with CFBundleIdentifier '%s' "4141 "sbs_error = %u",4142 bundleID.c_str(), sbs_error);4143 return INVALID_NUB_PROCESS;4144}4145 4146#endif // #ifdef WITH_SPRINGBOARD4147 4148#if defined(WITH_BKS) || defined(WITH_FBS)4149pid_t MachProcess::BoardServiceLaunchForDebug(4150 const char *path, char const *argv[], char const *envp[], bool no_stdio,4151 bool disable_aslr, const char *event_data, 4152 const RNBContext::IgnoredExceptions &ignored_exceptions,4153 DNBError &launch_err) {4154 DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv)", __FUNCTION__, path);4155 4156 // Fork a child process for debugging4157 SetState(eStateLaunching);4158 m_pid = BoardServiceForkChildForPTraceDebugging(4159 path, argv, envp, no_stdio, disable_aslr, event_data, launch_err);4160 if (m_pid != 0) {4161 m_path = path;4162 size_t i;4163 char const *arg;4164 for (i = 0; (arg = argv[i]) != NULL; i++)4165 m_args.push_back(arg);4166 m_task.StartExceptionThread(ignored_exceptions, launch_err);4167 4168 if (launch_err.Fail()) {4169 if (launch_err.AsString() == NULL)4170 launch_err.SetErrorString("unable to start the exception thread");4171 DNBLog("[LaunchAttach] END (%d) Could not get inferior's Mach exception "4172 "port, "4173 "sending ptrace "4174 "PT_KILL to pid %i and exiting.",4175 getpid(), m_pid);4176 ::ptrace(PT_KILL, m_pid, 0, 0);4177 m_pid = INVALID_NUB_PROCESS;4178 return INVALID_NUB_PROCESS;4179 }4180 4181 StartSTDIOThread();4182 SetState(eStateAttaching);4183 DNBLog("[LaunchAttach] (%d) About to ptrace(PT_ATTACHEXC, %d)...", getpid(),4184 m_pid);4185 int err = ::ptrace(PT_ATTACHEXC, m_pid, 0, 0);4186 DNBLog("[LaunchAttach] (%d) Completed ptrace(PT_ATTACHEXC, %d) == %d",4187 getpid(), m_pid, err);4188 if (err == 0) {4189 m_flags |= eMachProcessFlagsAttached;4190 DNBLog("[LaunchAttach] successfully attached to pid %d", m_pid);4191 } else {4192 std::string errmsg = "Failed to attach to pid ";4193 errmsg += std::to_string(m_pid);4194 errmsg += ", BoardServiceLaunchForDebug() unable to ptrace(PT_ATTACHEXC)";4195 launch_err.SetErrorString(errmsg.c_str());4196 SetState(eStateExited);4197 DNBLog("[LaunchAttach] END (%d) error: failed to attach to pid %d",4198 getpid(), m_pid);4199 }4200 }4201 return m_pid;4202}4203 4204pid_t MachProcess::BoardServiceForkChildForPTraceDebugging(4205 const char *app_bundle_path, char const *argv[], char const *envp[],4206 bool no_stdio, bool disable_aslr, const char *event_data,4207 DNBError &launch_err) {4208 if (argv[0] == NULL)4209 return INVALID_NUB_PROCESS;4210 4211 DNBLogThreadedIf(LOG_PROCESS, "%s( '%s', argv, %p)", __FUNCTION__,4212 app_bundle_path, this);4213 4214 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];4215 4216 size_t argc = 0;4217 // Count the number of arguments4218 while (argv[argc] != NULL)4219 argc++;4220 4221 // Enumerate the arguments4222 size_t first_launch_arg_idx = 1;4223 4224 NSMutableArray *launch_argv = nil;4225 4226 if (argv[first_launch_arg_idx]) {4227 size_t launch_argc = argc > 0 ? argc - 1 : 0;4228 launch_argv = [NSMutableArray arrayWithCapacity:launch_argc];4229 size_t i;4230 char const *arg;4231 NSString *launch_arg;4232 for (i = first_launch_arg_idx; (i < argc) && ((arg = argv[i]) != NULL);4233 i++) {4234 launch_arg = [NSString stringWithUTF8String:arg];4235 // FIXME: Should we silently eat an argument that we can't convert into a4236 // UTF8 string?4237 if (launch_arg != nil)4238 [launch_argv addObject:launch_arg];4239 else4240 break;4241 }4242 }4243 4244 NSMutableDictionary *launch_envp = nil;4245 if (envp[0]) {4246 launch_envp = [[NSMutableDictionary alloc] init];4247 const char *value;4248 int name_len;4249 NSString *name_string, *value_string;4250 4251 for (int i = 0; envp[i] != NULL; i++) {4252 value = strstr(envp[i], "=");4253 4254 // If the name field is empty or there's no =, skip it. Somebody's4255 // messing with us.4256 if (value == NULL || value == envp[i])4257 continue;4258 4259 name_len = value - envp[i];4260 4261 // Now move value over the "="4262 value++;4263 name_string = [[NSString alloc] initWithBytes:envp[i]4264 length:name_len4265 encoding:NSUTF8StringEncoding];4266 value_string = [NSString stringWithUTF8String:value];4267 [launch_envp setObject:value_string forKey:name_string];4268 }4269 }4270 4271 NSString *stdio_path = nil;4272 NSFileManager *file_manager = [NSFileManager defaultManager];4273 4274 PseudoTerminal pty;4275 if (!no_stdio) {4276 PseudoTerminal::Status pty_err =4277 pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY);4278 if (pty_err == PseudoTerminal::success) {4279 const char *secondary_name = pty.SecondaryName();4280 DNBLogThreadedIf(LOG_PROCESS,4281 "%s() successfully opened primary pty, secondary is %s",4282 __FUNCTION__, secondary_name);4283 if (secondary_name && secondary_name[0]) {4284 ::chmod(secondary_name, S_IRWXU | S_IRWXG | S_IRWXO);4285 stdio_path = [file_manager4286 stringWithFileSystemRepresentation:secondary_name4287 length:strlen(secondary_name)];4288 }4289 }4290 }4291 4292 if (stdio_path == nil) {4293 const char *null_path = "/dev/null";4294 stdio_path =4295 [file_manager stringWithFileSystemRepresentation:null_path4296 length:strlen(null_path)];4297 }4298 4299 CFStringRef bundleIDCFStr = CopyBundleIDForPath(app_bundle_path, launch_err);4300 if (bundleIDCFStr == NULL) {4301 [pool drain];4302 return INVALID_NUB_PROCESS;4303 }4304 4305 // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use4306 // toll-free bridging here:4307 NSString *bundleIDNSStr = (NSString *)bundleIDCFStr;4308 4309 // Okay, now let's assemble all these goodies into the BackBoardServices4310 // options mega-dictionary:4311 4312 NSMutableDictionary *options = nullptr;4313 pid_t return_pid = INVALID_NUB_PROCESS;4314 bool success = false;4315 4316#ifdef WITH_BKS4317 if (ProcessUsingBackBoard()) {4318 options =4319 BKSCreateOptionsDictionary(app_bundle_path, launch_argv, launch_envp,4320 stdio_path, disable_aslr, event_data);4321 success = BKSCallOpenApplicationFunction(bundleIDNSStr, options, launch_err,4322 &return_pid);4323 }4324#endif4325#ifdef WITH_FBS4326 if (ProcessUsingFrontBoard()) {4327 options =4328 FBSCreateOptionsDictionary(app_bundle_path, launch_argv, launch_envp,4329 stdio_path, disable_aslr, event_data);4330 success = FBSCallOpenApplicationFunction(bundleIDNSStr, options, launch_err,4331 &return_pid);4332 }4333#endif4334 4335 if (success) {4336 int primary_fd = pty.ReleasePrimaryFD();4337 SetChildFileDescriptors(primary_fd, primary_fd, primary_fd);4338 CFString::UTF8(bundleIDCFStr, m_bundle_id);4339 }4340 4341 [pool drain];4342 4343 return return_pid;4344}4345 4346bool MachProcess::BoardServiceSendEvent(const char *event_data,4347 DNBError &send_err) {4348 bool return_value = true;4349 4350 if (event_data == NULL || *event_data == '\0') {4351 DNBLogError("SendEvent called with NULL event data.");4352 send_err.SetErrorString("SendEvent called with empty event data");4353 return false;4354 }4355 4356 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];4357 4358 if (strcmp(event_data, "BackgroundApplication") == 0) {4359// This is an event I cooked up. What you actually do is foreground the system4360// app, so:4361#ifdef WITH_BKS4362 if (ProcessUsingBackBoard()) {4363 return_value = BKSCallOpenApplicationFunction(nil, nil, send_err, NULL);4364 }4365#endif4366#ifdef WITH_FBS4367 if (ProcessUsingFrontBoard()) {4368 return_value = FBSCallOpenApplicationFunction(nil, nil, send_err, NULL);4369 }4370#endif4371 if (!return_value) {4372 DNBLogError("Failed to background application, error: %s.",4373 send_err.AsString());4374 }4375 } else {4376 if (m_bundle_id.empty()) {4377 // See if we can figure out the bundle ID for this PID:4378 4379 DNBLogError(4380 "Tried to send event \"%s\" to a process that has no bundle ID.",4381 event_data);4382 return false;4383 }4384 4385 NSString *bundleIDNSStr =4386 [NSString stringWithUTF8String:m_bundle_id.c_str()];4387 4388 NSMutableDictionary *options = [NSMutableDictionary dictionary];4389 4390#ifdef WITH_BKS4391 if (ProcessUsingBackBoard()) {4392 if (!BKSAddEventDataToOptions(options, event_data, send_err)) {4393 [pool drain];4394 return false;4395 }4396 return_value = BKSCallOpenApplicationFunction(bundleIDNSStr, options,4397 send_err, NULL);4398 DNBLogThreadedIf(LOG_PROCESS,4399 "Called BKSCallOpenApplicationFunction to send event.");4400 }4401#endif4402#ifdef WITH_FBS4403 if (ProcessUsingFrontBoard()) {4404 if (!FBSAddEventDataToOptions(options, event_data, send_err)) {4405 [pool drain];4406 return false;4407 }4408 return_value = FBSCallOpenApplicationFunction(bundleIDNSStr, options,4409 send_err, NULL);4410 DNBLogThreadedIf(LOG_PROCESS,4411 "Called FBSCallOpenApplicationFunction to send event.");4412 }4413#endif4414 4415 if (!return_value) {4416 DNBLogError("Failed to send event: %s, error: %s.", event_data,4417 send_err.AsString());4418 }4419 }4420 4421 [pool drain];4422 return return_value;4423}4424#endif // defined(WITH_BKS) || defined (WITH_FBS)4425 4426#ifdef WITH_BKS4427void MachProcess::BKSCleanupAfterAttach(const void *attach_token,4428 DNBError &err_str) {4429 bool success;4430 4431 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];4432 4433 // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use4434 // toll-free bridging here:4435 NSString *bundleIDNSStr = (NSString *)attach_token;4436 4437 // Okay, now let's assemble all these goodies into the BackBoardServices4438 // options mega-dictionary:4439 4440 // First we have the debug sub-dictionary:4441 NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];4442 [debug_options setObject:[NSNumber numberWithBool:YES]4443 forKey:BKSDebugOptionKeyCancelDebugOnNextLaunch];4444 4445 // That will go in the overall dictionary:4446 4447 NSMutableDictionary *options = [NSMutableDictionary dictionary];4448 [options setObject:debug_options4449 forKey:BKSOpenApplicationOptionKeyDebuggingOptions];4450 4451 success =4452 BKSCallOpenApplicationFunction(bundleIDNSStr, options, err_str, NULL);4453 4454 if (!success) {4455 DNBLogError("error trying to cancel debug on next launch for %s: %s",4456 [bundleIDNSStr UTF8String], err_str.AsString());4457 }4458 4459 [pool drain];4460}4461#endif // WITH_BKS4462 4463#ifdef WITH_FBS4464void MachProcess::FBSCleanupAfterAttach(const void *attach_token,4465 DNBError &err_str) {4466 bool success;4467 4468 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];4469 4470 // Instead of rewriting CopyBundleIDForPath for NSStrings, we'll just use4471 // toll-free bridging here:4472 NSString *bundleIDNSStr = (NSString *)attach_token;4473 4474 // Okay, now let's assemble all these goodies into the BackBoardServices4475 // options mega-dictionary:4476 4477 // First we have the debug sub-dictionary:4478 NSMutableDictionary *debug_options = [NSMutableDictionary dictionary];4479 [debug_options setObject:[NSNumber numberWithBool:YES]4480 forKey:FBSDebugOptionKeyCancelDebugOnNextLaunch];4481 4482 // That will go in the overall dictionary:4483 4484 NSMutableDictionary *options = [NSMutableDictionary dictionary];4485 [options setObject:debug_options4486 forKey:FBSOpenApplicationOptionKeyDebuggingOptions];4487 4488 success =4489 FBSCallOpenApplicationFunction(bundleIDNSStr, options, err_str, NULL);4490 4491 if (!success) {4492 DNBLogError("error trying to cancel debug on next launch for %s: %s",4493 [bundleIDNSStr UTF8String], err_str.AsString());4494 }4495 4496 [pool drain];4497}4498#endif // WITH_FBS4499 4500 4501void MachProcess::CalculateBoardStatus()4502{4503 if (m_flags & eMachProcessFlagsBoardCalculated)4504 return;4505 if (m_pid == 0)4506 return;4507 4508#if defined (WITH_FBS) || defined (WITH_BKS)4509 bool found_app_flavor = false;4510#endif4511 4512#if defined(WITH_FBS)4513 if (!found_app_flavor && IsFBSProcess(m_pid)) {4514 found_app_flavor = true;4515 m_flags |= eMachProcessFlagsUsingFBS;4516 }4517#endif4518#if defined(WITH_BKS)4519 if (!found_app_flavor && IsBKSProcess(m_pid)) {4520 found_app_flavor = true;4521 m_flags |= eMachProcessFlagsUsingBKS;4522 }4523#endif4524 4525 m_flags |= eMachProcessFlagsBoardCalculated;4526}4527 4528bool MachProcess::ProcessUsingBackBoard() {4529 CalculateBoardStatus();4530 return (m_flags & eMachProcessFlagsUsingBKS) != 0;4531}4532 4533bool MachProcess::ProcessUsingFrontBoard() {4534 CalculateBoardStatus();4535 return (m_flags & eMachProcessFlagsUsingFBS) != 0;4536}4537 4538int MachProcess::GetInferiorAddrSize(pid_t pid) {4539 int pointer_size = 8;4540 int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};4541 struct kinfo_proc processInfo;4542 size_t bufsize = sizeof(processInfo);4543 if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize,4544 NULL, 0) == 0 &&4545 bufsize > 0) {4546 if ((processInfo.kp_proc.p_flag & P_LP64) == 0)4547 pointer_size = 4;4548 }4549 return pointer_size;4550}4551