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