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