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