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