DNB.cpp revision 452bf613496c7290c6b7a1a1eb28efbce63fd3b9
1//===-- DNB.cpp -------------------------------------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// Created by Greg Clayton on 3/23/07. 11// 12//===----------------------------------------------------------------------===// 13 14#include "DNB.h" 15#include <signal.h> 16#include <stdio.h> 17#include <stdlib.h> 18#include <sys/resource.h> 19#include <sys/stat.h> 20#include <sys/types.h> 21#include <sys/wait.h> 22#include <unistd.h> 23#include <sys/sysctl.h> 24#include <map> 25#include <vector> 26 27#include "MacOSX/MachProcess.h" 28#include "MacOSX/MachTask.h" 29#include "CFString.h" 30#include "DNBLog.h" 31#include "DNBDataRef.h" 32#include "DNBThreadResumeActions.h" 33#include "DNBTimer.h" 34 35typedef std::tr1::shared_ptr<MachProcess> MachProcessSP; 36typedef std::map<nub_process_t, MachProcessSP> ProcessMap; 37typedef ProcessMap::iterator ProcessMapIter; 38typedef ProcessMap::const_iterator ProcessMapConstIter; 39 40static size_t GetAllInfos (std::vector<struct kinfo_proc>& proc_infos); 41static size_t GetAllInfosMatchingName (const char *process_name, std::vector<struct kinfo_proc>& matching_proc_infos); 42 43//---------------------------------------------------------------------- 44// A Thread safe singleton to get a process map pointer. 45// 46// Returns a pointer to the existing process map, or a pointer to a 47// newly created process map if CAN_CREATE is non-zero. 48//---------------------------------------------------------------------- 49static ProcessMap* 50GetProcessMap(bool can_create) 51{ 52 static ProcessMap* g_process_map_ptr = NULL; 53 54 if (can_create && g_process_map_ptr == NULL) 55 { 56 static pthread_mutex_t g_process_map_mutex = PTHREAD_MUTEX_INITIALIZER; 57 PTHREAD_MUTEX_LOCKER (locker, &g_process_map_mutex); 58 if (g_process_map_ptr == NULL) 59 g_process_map_ptr = new ProcessMap; 60 } 61 return g_process_map_ptr; 62} 63 64//---------------------------------------------------------------------- 65// Add PID to the shared process pointer map. 66// 67// Return non-zero value if we succeed in adding the process to the map. 68// The only time this should fail is if we run out of memory and can't 69// allocate a ProcessMap. 70//---------------------------------------------------------------------- 71static nub_bool_t 72AddProcessToMap (nub_process_t pid, MachProcessSP& procSP) 73{ 74 ProcessMap* process_map = GetProcessMap(true); 75 if (process_map) 76 { 77 process_map->insert(std::make_pair(pid, procSP)); 78 return true; 79 } 80 return false; 81} 82 83//---------------------------------------------------------------------- 84// Remove the shared pointer for PID from the process map. 85// 86// Returns the number of items removed from the process map. 87//---------------------------------------------------------------------- 88static size_t 89RemoveProcessFromMap (nub_process_t pid) 90{ 91 ProcessMap* process_map = GetProcessMap(false); 92 if (process_map) 93 { 94 return process_map->erase(pid); 95 } 96 return 0; 97} 98 99//---------------------------------------------------------------------- 100// Get the shared pointer for PID from the existing process map. 101// 102// Returns true if we successfully find a shared pointer to a 103// MachProcess object. 104//---------------------------------------------------------------------- 105static nub_bool_t 106GetProcessSP (nub_process_t pid, MachProcessSP& procSP) 107{ 108 ProcessMap* process_map = GetProcessMap(false); 109 if (process_map != NULL) 110 { 111 ProcessMapIter pos = process_map->find(pid); 112 if (pos != process_map->end()) 113 { 114 procSP = pos->second; 115 return true; 116 } 117 } 118 procSP.reset(); 119 return false; 120} 121 122 123static void * 124waitpid_thread (void *arg) 125{ 126 const pid_t pid = (pid_t)(intptr_t)arg; 127 int status; 128 while (1) 129 { 130 pid_t child_pid = waitpid(pid, &status, 0); 131 DNBLogThreadedIf(LOG_PROCESS, "waitpid_process_thread (): waitpid (pid = %i, &status, 0) => %i, status = %i, errno = %i", pid, child_pid, status, errno); 132 133 if (child_pid < 0) 134 { 135 if (errno == EINTR) 136 continue; 137 break; 138 } 139 else 140 { 141 if (WIFSTOPPED(status)) 142 { 143 continue; 144 } 145 else// if (WIFEXITED(status) || WIFSIGNALED(status)) 146 { 147 DNBLogThreadedIf(LOG_PROCESS, "waitpid_process_thread (): setting exit status for pid = %i to %i", child_pid, status); 148 DNBProcessSetExitStatus (child_pid, status); 149 return NULL; 150 } 151 } 152 } 153 154 // We should never exit as long as our child process is alive, so if we 155 // do something else went wrong and we should exit... 156 DNBLogThreadedIf(LOG_PROCESS, "waitpid_process_thread (): main loop exited, setting exit status to an invalid value (-1) for pid %i", pid); 157 DNBProcessSetExitStatus (pid, -1); 158 return NULL; 159} 160 161static bool 162spawn_waitpid_thread (pid_t pid) 163{ 164 pthread_t thread = THREAD_NULL; 165 ::pthread_create (&thread, NULL, waitpid_thread, (void *)(intptr_t)pid); 166 if (thread != THREAD_NULL) 167 { 168 ::pthread_detach (thread); 169 return true; 170 } 171 return false; 172} 173 174nub_process_t 175DNBProcessLaunch (const char *path, 176 char const *argv[], 177 const char *envp[], 178 const char *stdio_path, 179 nub_launch_flavor_t launch_flavor, 180 int disable_aslr, 181 char *err_str, 182 size_t err_len) 183{ 184 DNBLogThreadedIf(LOG_PROCESS, "%s ( path='%s', argv = %p, envp = %p, launch_flavor = %u, disable_aslr = %d, err = %p, err_len = %zu) called...", __FUNCTION__, path, argv, envp, launch_flavor, disable_aslr, err_str, err_len); 185 186 if (err_str && err_len > 0) 187 err_str[0] = '\0'; 188 struct stat path_stat; 189 if (::stat(path, &path_stat) == -1) 190 { 191 char stat_error[256]; 192 ::strerror_r (errno, stat_error, sizeof(stat_error)); 193 snprintf(err_str, err_len, "%s (%s)", stat_error, path); 194 return INVALID_NUB_PROCESS; 195 } 196 197 MachProcessSP processSP (new MachProcess); 198 if (processSP.get()) 199 { 200 DNBError launch_err; 201 pid_t pid = processSP->LaunchForDebug(path, argv, envp, stdio_path, launch_flavor, disable_aslr, launch_err); 202 if (err_str) 203 { 204 *err_str = '\0'; 205 if (launch_err.Fail()) 206 { 207 const char *launch_err_str = launch_err.AsString(); 208 if (launch_err_str) 209 { 210 strncpy(err_str, launch_err_str, err_len-1); 211 err_str[err_len-1] = '\0'; // Make sure the error string is terminated 212 } 213 } 214 } 215 216 DNBLogThreadedIf(LOG_PROCESS, "(DebugNub) new pid is %d...", pid); 217 218 if (pid != INVALID_NUB_PROCESS) 219 { 220 // Spawn a thread to reap our child inferior process... 221 spawn_waitpid_thread (pid); 222 223 if (processSP->Task().TaskPortForProcessID (launch_err) == TASK_NULL) 224 { 225 // We failed to get the task for our process ID which is bad. 226 if (err_str && err_len > 0) 227 { 228 if (launch_err.AsString()) 229 { 230 ::snprintf (err_str, err_len, "failed to get the task for process %i (%s)", pid, launch_err.AsString()); 231 } 232 else 233 { 234 ::snprintf (err_str, err_len, "failed to get the task for process %i", pid); 235 } 236 } 237 } 238 else 239 { 240 assert(AddProcessToMap(pid, processSP)); 241 return pid; 242 } 243 } 244 } 245 return INVALID_NUB_PROCESS; 246} 247 248nub_process_t 249DNBProcessAttachByName (const char *name, struct timespec *timeout, char *err_str, size_t err_len) 250{ 251 if (err_str && err_len > 0) 252 err_str[0] = '\0'; 253 std::vector<struct kinfo_proc> matching_proc_infos; 254 size_t num_matching_proc_infos = GetAllInfosMatchingName(name, matching_proc_infos); 255 if (num_matching_proc_infos == 0) 256 { 257 DNBLogError ("error: no processes match '%s'\n", name); 258 return INVALID_NUB_PROCESS; 259 } 260 else if (num_matching_proc_infos > 1) 261 { 262 DNBLogError ("error: %u processes match '%s':\n", num_matching_proc_infos, name); 263 size_t i; 264 for (i=0; i<num_matching_proc_infos; ++i) 265 DNBLogError ("%6u - %s\n", matching_proc_infos[i].kp_proc.p_pid, matching_proc_infos[i].kp_proc.p_comm); 266 return INVALID_NUB_PROCESS; 267 } 268 else 269 { 270 return DNBProcessAttach (matching_proc_infos[0].kp_proc.p_pid, timeout, err_str, err_len); 271 } 272} 273 274nub_process_t 275DNBProcessAttach (nub_process_t attach_pid, struct timespec *timeout, char *err_str, size_t err_len) 276{ 277 if (err_str && err_len > 0) 278 err_str[0] = '\0'; 279 280 pid_t pid; 281 MachProcessSP processSP(new MachProcess); 282 if (processSP.get()) 283 { 284 DNBLogThreadedIf(LOG_PROCESS, "(DebugNub) attaching to pid %d...", attach_pid); 285 pid = processSP->AttachForDebug (attach_pid, err_str, err_len); 286 287 if (pid != INVALID_NUB_PROCESS) 288 { 289 assert(AddProcessToMap(pid, processSP)); 290 spawn_waitpid_thread(pid); 291 } 292 } 293 294 while (pid != INVALID_NUB_PROCESS) 295 { 296 // Wait for process to start up and hit entry point 297 DNBLogThreadedIf (LOG_PROCESS, "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged " 298 "| eEventProcessStoppedStateChanged, true, INFINITE)...", 299 __FUNCTION__, pid); 300 nub_event_t set_events = DNBProcessWaitForEvents (pid, 301 eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, 302 true, timeout); 303 DNBLogThreadedIf (LOG_PROCESS, "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged " 304 "| eEventProcessStoppedStateChanged, true, INFINITE) => 0x%8.8x", 305 __FUNCTION__, pid, set_events); 306 307 if (set_events == 0) 308 { 309 if (err_str && err_len > 0) 310 snprintf(err_str, err_len, "operation timed out"); 311 pid = INVALID_NUB_PROCESS; 312 } 313 else 314 { 315 if (set_events & (eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged)) 316 { 317 nub_state_t pid_state = DNBProcessGetState (pid); 318 DNBLogThreadedIf (LOG_PROCESS, "%s process %4.4x state changed (eEventProcessStateChanged): %s", 319 __FUNCTION__, pid, DNBStateAsString(pid_state)); 320 321 switch (pid_state) 322 { 323 default: 324 case eStateInvalid: 325 case eStateUnloaded: 326 case eStateAttaching: 327 case eStateLaunching: 328 case eStateSuspended: 329 break; // Ignore 330 331 case eStateRunning: 332 case eStateStepping: 333 // Still waiting to stop at entry point... 334 break; 335 336 case eStateStopped: 337 case eStateCrashed: 338 return pid; 339 case eStateDetached: 340 case eStateExited: 341 if (err_str && err_len > 0) 342 snprintf(err_str, err_len, "process exited"); 343 return INVALID_NUB_PROCESS; 344 } 345 } 346 347 DNBProcessResetEvents(pid, set_events); 348 } 349 } 350 351 return INVALID_NUB_PROCESS; 352} 353 354static size_t 355GetAllInfos(std::vector<struct kinfo_proc>& proc_infos) 356{ 357 size_t size; 358 int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL }; 359 u_int namelen = sizeof(name)/sizeof(int); 360 int err; 361 362 // Try to find out how many processes are around so we can 363 // size the buffer appropriately. sysctl's man page specifically suggests 364 // this approach, and says it returns a bit larger size than needed to 365 // handle any new processes created between then and now. 366 367 err = ::sysctl (name, namelen, NULL, &size, NULL, 0); 368 369 if ((err < 0) && (err != ENOMEM)) 370 { 371 proc_infos.clear(); 372 perror("sysctl (mib, miblen, NULL, &num_processes, NULL, 0)"); 373 return 0; 374 } 375 376 377 // Increase the size of the buffer by a few processes in case more have 378 // been spawned 379 proc_infos.resize (size / sizeof(struct kinfo_proc)); 380 size = proc_infos.size() * sizeof(struct kinfo_proc); // Make sure we don't exceed our resize... 381 err = ::sysctl (name, namelen, &proc_infos[0], &size, NULL, 0); 382 if (err < 0) 383 { 384 proc_infos.clear(); 385 return 0; 386 } 387 388 // Trim down our array to fit what we actually got back 389 proc_infos.resize(size / sizeof(struct kinfo_proc)); 390 return proc_infos.size(); 391} 392 393 394static size_t 395GetAllInfosMatchingName(const char *full_process_name, std::vector<struct kinfo_proc>& matching_proc_infos) 396{ 397 398 matching_proc_infos.clear(); 399 if (full_process_name && full_process_name[0]) 400 { 401 // We only get the process name, not the full path, from the proc_info. So just take the 402 // base name of the process name... 403 const char *process_name; 404 process_name = strrchr (full_process_name, '/'); 405 if (process_name == NULL) 406 process_name = full_process_name; 407 else 408 process_name++; 409 410 std::vector<struct kinfo_proc> proc_infos; 411 const size_t num_proc_infos = GetAllInfos(proc_infos); 412 if (num_proc_infos > 0) 413 { 414 uint32_t i; 415 for (i=0; i<num_proc_infos; i++) 416 { 417 // Skip zombie processes and processes with unset status 418 if (proc_infos[i].kp_proc.p_stat == 0 || proc_infos[i].kp_proc.p_stat == SZOMB) 419 continue; 420 421 // Check for process by name. We only check the first MAXCOMLEN 422 // chars as that is all that kp_proc.p_comm holds. 423 if (::strncasecmp(proc_infos[i].kp_proc.p_comm, process_name, MAXCOMLEN) == 0) 424 { 425 // We found a matching process, add it to our list 426 matching_proc_infos.push_back(proc_infos[i]); 427 } 428 } 429 } 430 } 431 // return the newly added matches. 432 return matching_proc_infos.size(); 433} 434 435nub_process_t 436DNBProcessAttachWait (const char *waitfor_process_name, nub_launch_flavor_t launch_flavor, 437 struct timespec *timeout_abstime, useconds_t waitfor_interval, 438 char *err_str, size_t err_len, 439 DNBShouldCancelCallback should_cancel_callback, 440 void *callback_data) 441{ 442 DNBError prepare_error; 443 std::vector<struct kinfo_proc> exclude_proc_infos; 444 size_t num_exclude_proc_infos; 445 446 // If the PrepareForAttach returns a valid token, use MachProcess to check 447 // for the process, otherwise scan the process table. 448 449 const void *attach_token = MachProcess::PrepareForAttach (waitfor_process_name, launch_flavor, true, prepare_error); 450 451 if (prepare_error.Fail()) 452 { 453 DNBLogError ("Error in PrepareForAttach: %s", prepare_error.AsString()); 454 return INVALID_NUB_PROCESS; 455 } 456 457 if (attach_token == NULL) 458 num_exclude_proc_infos = GetAllInfosMatchingName (waitfor_process_name, exclude_proc_infos); 459 460 DNBLogThreadedIf (LOG_PROCESS, "Waiting for '%s' to appear...\n", waitfor_process_name); 461 462 // Loop and try to find the process by name 463 nub_process_t waitfor_pid = INVALID_NUB_PROCESS; 464 465 while (waitfor_pid == INVALID_NUB_PROCESS) 466 { 467 if (attach_token != NULL) 468 { 469 nub_process_t pid; 470 pid = MachProcess::CheckForProcess(attach_token); 471 if (pid != INVALID_NUB_PROCESS) 472 { 473 waitfor_pid = pid; 474 break; 475 } 476 } 477 else 478 { 479 480 // Get the current process list, and check for matches that 481 // aren't in our original list. If anyone wants to attach 482 // to an existing process by name, they should do it with 483 // --attach=PROCNAME. Else we will wait for the first matching 484 // process that wasn't in our exclusion list. 485 std::vector<struct kinfo_proc> proc_infos; 486 const size_t num_proc_infos = GetAllInfosMatchingName (waitfor_process_name, proc_infos); 487 for (size_t i=0; i<num_proc_infos; i++) 488 { 489 nub_process_t curr_pid = proc_infos[i].kp_proc.p_pid; 490 for (size_t j=0; j<num_exclude_proc_infos; j++) 491 { 492 if (curr_pid == exclude_proc_infos[j].kp_proc.p_pid) 493 { 494 // This process was in our exclusion list, don't use it. 495 curr_pid = INVALID_NUB_PROCESS; 496 break; 497 } 498 } 499 500 // If we didn't find CURR_PID in our exclusion list, then use it. 501 if (curr_pid != INVALID_NUB_PROCESS) 502 { 503 // We found our process! 504 waitfor_pid = curr_pid; 505 break; 506 } 507 } 508 } 509 510 // If we haven't found our process yet, check for a timeout 511 // and then sleep for a bit until we poll again. 512 if (waitfor_pid == INVALID_NUB_PROCESS) 513 { 514 if (timeout_abstime != NULL) 515 { 516 // Check to see if we have a waitfor-duration option that 517 // has timed out? 518 if (DNBTimer::TimeOfDayLaterThan(*timeout_abstime)) 519 { 520 if (err_str && err_len > 0) 521 snprintf(err_str, err_len, "operation timed out"); 522 DNBLogError ("error: waiting for process '%s' timed out.\n", waitfor_process_name); 523 return INVALID_NUB_PROCESS; 524 } 525 } 526 527 // Call the should cancel callback as well... 528 529 if (should_cancel_callback != NULL 530 && should_cancel_callback (callback_data)) 531 { 532 DNBLogThreadedIf (LOG_PROCESS, "DNBProcessAttachWait cancelled by should_cancel callback."); 533 waitfor_pid = INVALID_NUB_PROCESS; 534 break; 535 } 536 537 ::usleep (waitfor_interval); // Sleep for WAITFOR_INTERVAL, then poll again 538 } 539 } 540 541 if (waitfor_pid != INVALID_NUB_PROCESS) 542 { 543 DNBLogThreadedIf (LOG_PROCESS, "Attaching to %s with pid %i...\n", waitfor_process_name, waitfor_pid); 544 waitfor_pid = DNBProcessAttach (waitfor_pid, timeout_abstime, err_str, err_len); 545 } 546 547 bool success = waitfor_pid != INVALID_NUB_PROCESS; 548 MachProcess::CleanupAfterAttach (attach_token, success, prepare_error); 549 550 return waitfor_pid; 551} 552 553nub_bool_t 554DNBProcessDetach (nub_process_t pid) 555{ 556 MachProcessSP procSP; 557 if (GetProcessSP (pid, procSP)) 558 { 559 return procSP->Detach(); 560 } 561 return false; 562} 563 564nub_bool_t 565DNBProcessKill (nub_process_t pid) 566{ 567 MachProcessSP procSP; 568 if (GetProcessSP (pid, procSP)) 569 { 570 return procSP->Kill (); 571 } 572 return false; 573} 574 575nub_bool_t 576DNBProcessSignal (nub_process_t pid, int signal) 577{ 578 MachProcessSP procSP; 579 if (GetProcessSP (pid, procSP)) 580 { 581 return procSP->Signal (signal); 582 } 583 return false; 584} 585 586 587nub_bool_t 588DNBProcessIsAlive (nub_process_t pid) 589{ 590 MachProcessSP procSP; 591 if (GetProcessSP (pid, procSP)) 592 { 593 return MachTask::IsValid (procSP->Task().TaskPort()); 594 } 595 return eStateInvalid; 596} 597 598//---------------------------------------------------------------------- 599// Process and Thread state information 600//---------------------------------------------------------------------- 601nub_state_t 602DNBProcessGetState (nub_process_t pid) 603{ 604 MachProcessSP procSP; 605 if (GetProcessSP (pid, procSP)) 606 { 607 return procSP->GetState(); 608 } 609 return eStateInvalid; 610} 611 612//---------------------------------------------------------------------- 613// Process and Thread state information 614//---------------------------------------------------------------------- 615nub_bool_t 616DNBProcessGetExitStatus (nub_process_t pid, int* status) 617{ 618 MachProcessSP procSP; 619 if (GetProcessSP (pid, procSP)) 620 { 621 return procSP->GetExitStatus(status); 622 } 623 return false; 624} 625 626nub_bool_t 627DNBProcessSetExitStatus (nub_process_t pid, int status) 628{ 629 MachProcessSP procSP; 630 if (GetProcessSP (pid, procSP)) 631 { 632 procSP->SetExitStatus(status); 633 return true; 634 } 635 return false; 636} 637 638 639const char * 640DNBThreadGetName (nub_process_t pid, nub_thread_t tid) 641{ 642 MachProcessSP procSP; 643 if (GetProcessSP (pid, procSP)) 644 return procSP->ThreadGetName(tid); 645 return NULL; 646} 647 648 649nub_bool_t 650DNBThreadGetIdentifierInfo (nub_process_t pid, nub_thread_t tid, thread_identifier_info_data_t *ident_info) 651{ 652 MachProcessSP procSP; 653 if (GetProcessSP (pid, procSP)) 654 return procSP->GetThreadList().GetIdentifierInfo(tid, ident_info); 655 return false; 656} 657 658nub_state_t 659DNBThreadGetState (nub_process_t pid, nub_thread_t tid) 660{ 661 MachProcessSP procSP; 662 if (GetProcessSP (pid, procSP)) 663 { 664 return procSP->ThreadGetState(tid); 665 } 666 return eStateInvalid; 667} 668 669const char * 670DNBStateAsString(nub_state_t state) 671{ 672 switch (state) 673 { 674 case eStateUnloaded: return "Unloaded"; 675 case eStateAttaching: return "Attaching"; 676 case eStateLaunching: return "Launching"; 677 case eStateStopped: return "Stopped"; 678 case eStateRunning: return "Running"; 679 case eStateStepping: return "Stepping"; 680 case eStateCrashed: return "Crashed"; 681 case eStateDetached: return "Detached"; 682 case eStateExited: return "Exited"; 683 case eStateSuspended: return "Suspended"; 684 } 685 return "nub_state_t ???"; 686} 687 688const char * 689DNBProcessGetExecutablePath (nub_process_t pid) 690{ 691 MachProcessSP procSP; 692 if (GetProcessSP (pid, procSP)) 693 { 694 return procSP->Path(); 695 } 696 return NULL; 697} 698 699nub_size_t 700DNBProcessGetArgumentCount (nub_process_t pid) 701{ 702 MachProcessSP procSP; 703 if (GetProcessSP (pid, procSP)) 704 { 705 return procSP->ArgumentCount(); 706 } 707 return 0; 708} 709 710const char * 711DNBProcessGetArgumentAtIndex (nub_process_t pid, nub_size_t idx) 712{ 713 MachProcessSP procSP; 714 if (GetProcessSP (pid, procSP)) 715 { 716 return procSP->ArgumentAtIndex (idx); 717 } 718 return NULL; 719} 720 721 722//---------------------------------------------------------------------- 723// Execution control 724//---------------------------------------------------------------------- 725nub_bool_t 726DNBProcessResume (nub_process_t pid, const DNBThreadResumeAction *actions, size_t num_actions) 727{ 728 DNBLogThreadedIf(LOG_PROCESS, "%s(pid = %4.4x)", __FUNCTION__, pid); 729 MachProcessSP procSP; 730 if (GetProcessSP (pid, procSP)) 731 { 732 DNBThreadResumeActions thread_actions (actions, num_actions); 733 734 // Below we add a default thread plan just in case one wasn't 735 // provided so all threads always know what they were supposed to do 736 if (thread_actions.IsEmpty()) 737 { 738 // No thread plans were given, so the default it to run all threads 739 thread_actions.SetDefaultThreadActionIfNeeded (eStateRunning, 0); 740 } 741 else 742 { 743 // Some thread plans were given which means anything that wasn't 744 // specified should remain stopped. 745 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0); 746 } 747 return procSP->Resume (thread_actions); 748 } 749 return false; 750} 751 752nub_bool_t 753DNBProcessHalt (nub_process_t pid) 754{ 755 DNBLogThreadedIf(LOG_PROCESS, "%s(pid = %4.4x)", __FUNCTION__, pid); 756 MachProcessSP procSP; 757 if (GetProcessSP (pid, procSP)) 758 return procSP->Signal (SIGSTOP); 759 return false; 760} 761// 762//nub_bool_t 763//DNBThreadResume (nub_process_t pid, nub_thread_t tid, nub_bool_t step) 764//{ 765// DNBLogThreadedIf(LOG_THREAD, "%s(pid = %4.4x, tid = %4.4x, step = %u)", __FUNCTION__, pid, tid, (uint32_t)step); 766// MachProcessSP procSP; 767// if (GetProcessSP (pid, procSP)) 768// { 769// return procSP->Resume(tid, step, 0); 770// } 771// return false; 772//} 773// 774//nub_bool_t 775//DNBThreadResumeWithSignal (nub_process_t pid, nub_thread_t tid, nub_bool_t step, int signal) 776//{ 777// DNBLogThreadedIf(LOG_THREAD, "%s(pid = %4.4x, tid = %4.4x, step = %u, signal = %i)", __FUNCTION__, pid, tid, (uint32_t)step, signal); 778// MachProcessSP procSP; 779// if (GetProcessSP (pid, procSP)) 780// { 781// return procSP->Resume(tid, step, signal); 782// } 783// return false; 784//} 785 786nub_event_t 787DNBProcessWaitForEvents (nub_process_t pid, nub_event_t event_mask, bool wait_for_set, struct timespec* timeout) 788{ 789 nub_event_t result = 0; 790 MachProcessSP procSP; 791 if (GetProcessSP (pid, procSP)) 792 { 793 if (wait_for_set) 794 result = procSP->Events().WaitForSetEvents(event_mask, timeout); 795 else 796 result = procSP->Events().WaitForEventsToReset(event_mask, timeout); 797 } 798 return result; 799} 800 801void 802DNBProcessResetEvents (nub_process_t pid, nub_event_t event_mask) 803{ 804 MachProcessSP procSP; 805 if (GetProcessSP (pid, procSP)) 806 procSP->Events().ResetEvents(event_mask); 807} 808 809void 810DNBProcessInterruptEvents (nub_process_t pid) 811{ 812 MachProcessSP procSP; 813 if (GetProcessSP (pid, procSP)) 814 procSP->Events().SetEvents(eEventProcessAsyncInterrupt); 815} 816 817 818// Breakpoints 819nub_break_t 820DNBBreakpointSet (nub_process_t pid, nub_addr_t addr, nub_size_t size, nub_bool_t hardware) 821{ 822 MachProcessSP procSP; 823 if (GetProcessSP (pid, procSP)) 824 { 825 return procSP->CreateBreakpoint(addr, size, hardware, THREAD_NULL); 826 } 827 return INVALID_NUB_BREAK_ID; 828} 829 830nub_bool_t 831DNBBreakpointClear (nub_process_t pid, nub_break_t breakID) 832{ 833 if (NUB_BREAK_ID_IS_VALID(breakID)) 834 { 835 MachProcessSP procSP; 836 if (GetProcessSP (pid, procSP)) 837 { 838 return procSP->DisableBreakpoint(breakID, true); 839 } 840 } 841 return false; // Failed 842} 843 844nub_ssize_t 845DNBBreakpointGetHitCount (nub_process_t pid, nub_break_t breakID) 846{ 847 if (NUB_BREAK_ID_IS_VALID(breakID)) 848 { 849 MachProcessSP procSP; 850 if (GetProcessSP (pid, procSP)) 851 { 852 DNBBreakpoint *bp = procSP->Breakpoints().FindByID(breakID); 853 if (bp) 854 return bp->GetHitCount(); 855 } 856 } 857 return 0; 858} 859 860nub_ssize_t 861DNBBreakpointGetIgnoreCount (nub_process_t pid, nub_break_t breakID) 862{ 863 if (NUB_BREAK_ID_IS_VALID(breakID)) 864 { 865 MachProcessSP procSP; 866 if (GetProcessSP (pid, procSP)) 867 { 868 DNBBreakpoint *bp = procSP->Breakpoints().FindByID(breakID); 869 if (bp) 870 return bp->GetIgnoreCount(); 871 } 872 } 873 return 0; 874} 875 876nub_bool_t 877DNBBreakpointSetIgnoreCount (nub_process_t pid, nub_break_t breakID, nub_size_t ignore_count) 878{ 879 if (NUB_BREAK_ID_IS_VALID(breakID)) 880 { 881 MachProcessSP procSP; 882 if (GetProcessSP (pid, procSP)) 883 { 884 DNBBreakpoint *bp = procSP->Breakpoints().FindByID(breakID); 885 if (bp) 886 { 887 bp->SetIgnoreCount(ignore_count); 888 return true; 889 } 890 } 891 } 892 return false; 893} 894 895// Set the callback function for a given breakpoint. The callback function will 896// get called as soon as the breakpoint is hit. The function will be called 897// with the process ID, thread ID, breakpoint ID and the baton, and can return 898// 899nub_bool_t 900DNBBreakpointSetCallback (nub_process_t pid, nub_break_t breakID, DNBCallbackBreakpointHit callback, void *baton) 901{ 902 if (NUB_BREAK_ID_IS_VALID(breakID)) 903 { 904 MachProcessSP procSP; 905 if (GetProcessSP (pid, procSP)) 906 { 907 DNBBreakpoint *bp = procSP->Breakpoints().FindByID(breakID); 908 if (bp) 909 { 910 bp->SetCallback(callback, baton); 911 return true; 912 } 913 } 914 } 915 return false; 916} 917 918//---------------------------------------------------------------------- 919// Dump the breakpoints stats for process PID for a breakpoint by ID. 920//---------------------------------------------------------------------- 921void 922DNBBreakpointPrint (nub_process_t pid, nub_break_t breakID) 923{ 924 MachProcessSP procSP; 925 if (GetProcessSP (pid, procSP)) 926 procSP->DumpBreakpoint(breakID); 927} 928 929//---------------------------------------------------------------------- 930// Watchpoints 931//---------------------------------------------------------------------- 932nub_watch_t 933DNBWatchpointSet (nub_process_t pid, nub_addr_t addr, nub_size_t size, uint32_t watch_flags, nub_bool_t hardware) 934{ 935 MachProcessSP procSP; 936 if (GetProcessSP (pid, procSP)) 937 { 938 return procSP->CreateWatchpoint(addr, size, watch_flags, hardware, THREAD_NULL); 939 } 940 return INVALID_NUB_BREAK_ID; 941} 942 943nub_bool_t 944DNBWatchpointClear (nub_process_t pid, nub_watch_t watchID) 945{ 946 if (NUB_BREAK_ID_IS_VALID(watchID)) 947 { 948 MachProcessSP procSP; 949 if (GetProcessSP (pid, procSP)) 950 { 951 return procSP->DisableWatchpoint(watchID, true); 952 } 953 } 954 return false; // Failed 955} 956 957nub_ssize_t 958DNBWatchpointGetHitCount (nub_process_t pid, nub_watch_t watchID) 959{ 960 if (NUB_BREAK_ID_IS_VALID(watchID)) 961 { 962 MachProcessSP procSP; 963 if (GetProcessSP (pid, procSP)) 964 { 965 DNBBreakpoint *bp = procSP->Watchpoints().FindByID(watchID); 966 if (bp) 967 return bp->GetHitCount(); 968 } 969 } 970 return 0; 971} 972 973nub_ssize_t 974DNBWatchpointGetIgnoreCount (nub_process_t pid, nub_watch_t watchID) 975{ 976 if (NUB_BREAK_ID_IS_VALID(watchID)) 977 { 978 MachProcessSP procSP; 979 if (GetProcessSP (pid, procSP)) 980 { 981 DNBBreakpoint *bp = procSP->Watchpoints().FindByID(watchID); 982 if (bp) 983 return bp->GetIgnoreCount(); 984 } 985 } 986 return 0; 987} 988 989nub_bool_t 990DNBWatchpointSetIgnoreCount (nub_process_t pid, nub_watch_t watchID, nub_size_t ignore_count) 991{ 992 if (NUB_BREAK_ID_IS_VALID(watchID)) 993 { 994 MachProcessSP procSP; 995 if (GetProcessSP (pid, procSP)) 996 { 997 DNBBreakpoint *bp = procSP->Watchpoints().FindByID(watchID); 998 if (bp) 999 { 1000 bp->SetIgnoreCount(ignore_count); 1001 return true; 1002 } 1003 } 1004 } 1005 return false; 1006} 1007 1008// Set the callback function for a given watchpoint. The callback function will 1009// get called as soon as the watchpoint is hit. The function will be called 1010// with the process ID, thread ID, watchpoint ID and the baton, and can return 1011// 1012nub_bool_t 1013DNBWatchpointSetCallback (nub_process_t pid, nub_watch_t watchID, DNBCallbackBreakpointHit callback, void *baton) 1014{ 1015 if (NUB_BREAK_ID_IS_VALID(watchID)) 1016 { 1017 MachProcessSP procSP; 1018 if (GetProcessSP (pid, procSP)) 1019 { 1020 DNBBreakpoint *bp = procSP->Watchpoints().FindByID(watchID); 1021 if (bp) 1022 { 1023 bp->SetCallback(callback, baton); 1024 return true; 1025 } 1026 } 1027 } 1028 return false; 1029} 1030 1031//---------------------------------------------------------------------- 1032// Dump the watchpoints stats for process PID for a watchpoint by ID. 1033//---------------------------------------------------------------------- 1034void 1035DNBWatchpointPrint (nub_process_t pid, nub_watch_t watchID) 1036{ 1037 MachProcessSP procSP; 1038 if (GetProcessSP (pid, procSP)) 1039 procSP->DumpWatchpoint(watchID); 1040} 1041 1042//---------------------------------------------------------------------- 1043// Read memory in the address space of process PID. This call will take 1044// care of setting and restoring permissions and breaking up the memory 1045// read into multiple chunks as required. 1046// 1047// RETURNS: number of bytes actually read 1048//---------------------------------------------------------------------- 1049nub_size_t 1050DNBProcessMemoryRead (nub_process_t pid, nub_addr_t addr, nub_size_t size, void *buf) 1051{ 1052 MachProcessSP procSP; 1053 if (GetProcessSP (pid, procSP)) 1054 return procSP->ReadMemory(addr, size, buf); 1055 return 0; 1056} 1057 1058//---------------------------------------------------------------------- 1059// Write memory to the address space of process PID. This call will take 1060// care of setting and restoring permissions and breaking up the memory 1061// write into multiple chunks as required. 1062// 1063// RETURNS: number of bytes actually written 1064//---------------------------------------------------------------------- 1065nub_size_t 1066DNBProcessMemoryWrite (nub_process_t pid, nub_addr_t addr, nub_size_t size, const void *buf) 1067{ 1068 MachProcessSP procSP; 1069 if (GetProcessSP (pid, procSP)) 1070 return procSP->WriteMemory(addr, size, buf); 1071 return 0; 1072} 1073 1074nub_addr_t 1075DNBProcessMemoryAllocate (nub_process_t pid, nub_size_t size, uint32_t permissions) 1076{ 1077 MachProcessSP procSP; 1078 if (GetProcessSP (pid, procSP)) 1079 return procSP->Task().AllocateMemory (size, permissions); 1080 return 0; 1081} 1082 1083nub_bool_t 1084DNBProcessMemoryDeallocate (nub_process_t pid, nub_addr_t addr) 1085{ 1086 MachProcessSP procSP; 1087 if (GetProcessSP (pid, procSP)) 1088 return procSP->Task().DeallocateMemory (addr); 1089 return 0; 1090} 1091 1092 1093//---------------------------------------------------------------------- 1094// Formatted output that uses memory and registers from process and 1095// thread in place of arguments. 1096//---------------------------------------------------------------------- 1097nub_size_t 1098DNBPrintf (nub_process_t pid, nub_thread_t tid, nub_addr_t base_addr, FILE *file, const char *format) 1099{ 1100 if (file == NULL) 1101 return 0; 1102 enum printf_flags 1103 { 1104 alternate_form = (1 << 0), 1105 zero_padding = (1 << 1), 1106 negative_field_width = (1 << 2), 1107 blank_space = (1 << 3), 1108 show_sign = (1 << 4), 1109 show_thousands_separator= (1 << 5), 1110 }; 1111 1112 enum printf_length_modifiers 1113 { 1114 length_mod_h = (1 << 0), 1115 length_mod_hh = (1 << 1), 1116 length_mod_l = (1 << 2), 1117 length_mod_ll = (1 << 3), 1118 length_mod_L = (1 << 4), 1119 length_mod_j = (1 << 5), 1120 length_mod_t = (1 << 6), 1121 length_mod_z = (1 << 7), 1122 length_mod_q = (1 << 8), 1123 }; 1124 1125 nub_addr_t addr = base_addr; 1126 char *end_format = (char*)format + strlen(format); 1127 char *end = NULL; // For strtoXXXX calls; 1128 std::basic_string<uint8_t> buf; 1129 nub_size_t total_bytes_read = 0; 1130 DNBDataRef data; 1131 const char *f; 1132 for (f = format; *f != '\0' && f < end_format; f++) 1133 { 1134 char ch = *f; 1135 switch (ch) 1136 { 1137 case '%': 1138 { 1139 f++; // Skip the '%' character 1140 int min_field_width = 0; 1141 int precision = 0; 1142 uint32_t flags = 0; 1143 uint32_t length_modifiers = 0; 1144 uint32_t byte_size = 0; 1145 uint32_t actual_byte_size = 0; 1146 bool is_string = false; 1147 bool is_register = false; 1148 DNBRegisterValue register_value; 1149 int64_t register_offset = 0; 1150 nub_addr_t register_addr = INVALID_NUB_ADDRESS; 1151 1152 // Create the format string to use for this conversion specification 1153 // so we can remove and mprintf specific flags and formatters. 1154 std::string fprintf_format("%"); 1155 1156 // Decode any flags 1157 switch (*f) 1158 { 1159 case '#': fprintf_format += *f++; flags |= alternate_form; break; 1160 case '0': fprintf_format += *f++; flags |= zero_padding; break; 1161 case '-': fprintf_format += *f++; flags |= negative_field_width; break; 1162 case ' ': fprintf_format += *f++; flags |= blank_space; break; 1163 case '+': fprintf_format += *f++; flags |= show_sign; break; 1164 case ',': fprintf_format += *f++; flags |= show_thousands_separator;break; 1165 case '{': 1166 case '[': 1167 { 1168 // We have a register name specification that can take two forms: 1169 // ${regname} or ${regname+offset} 1170 // The action is to read the register value and add the signed offset 1171 // (if any) and use that as the value to format. 1172 // $[regname] or $[regname+offset] 1173 // The action is to read the register value and add the signed offset 1174 // (if any) and use the result as an address to dereference. The size 1175 // of what is dereferenced is specified by the actual byte size that 1176 // follows the minimum field width and precision (see comments below). 1177 switch (*f) 1178 { 1179 case '{': 1180 case '[': 1181 { 1182 char open_scope_ch = *f; 1183 f++; 1184 const char *reg_name = f; 1185 size_t reg_name_length = strcspn(f, "+-}]"); 1186 if (reg_name_length > 0) 1187 { 1188 std::string register_name(reg_name, reg_name_length); 1189 f += reg_name_length; 1190 register_offset = strtoll(f, &end, 0); 1191 if (f < end) 1192 f = end; 1193 if ((open_scope_ch == '{' && *f != '}') || (open_scope_ch == '[' && *f != ']')) 1194 { 1195 fprintf(file, "error: Invalid register format string. Valid formats are %%{regname} or %%{regname+offset}, %%[regname] or %%[regname+offset]\n"); 1196 return total_bytes_read; 1197 } 1198 else 1199 { 1200 f++; 1201 if (DNBThreadGetRegisterValueByName(pid, tid, REGISTER_SET_ALL, register_name.c_str(), ®ister_value)) 1202 { 1203 // Set the address to dereference using the register value plus the offset 1204 switch (register_value.info.size) 1205 { 1206 default: 1207 case 0: 1208 fprintf (file, "error: unsupported register size of %u.\n", register_value.info.size); 1209 return total_bytes_read; 1210 1211 case 1: register_addr = register_value.value.uint8 + register_offset; break; 1212 case 2: register_addr = register_value.value.uint16 + register_offset; break; 1213 case 4: register_addr = register_value.value.uint32 + register_offset; break; 1214 case 8: register_addr = register_value.value.uint64 + register_offset; break; 1215 case 16: 1216 if (open_scope_ch == '[') 1217 { 1218 fprintf (file, "error: register size (%u) too large for address.\n", register_value.info.size); 1219 return total_bytes_read; 1220 } 1221 break; 1222 } 1223 1224 if (open_scope_ch == '{') 1225 { 1226 byte_size = register_value.info.size; 1227 is_register = true; // value is in a register 1228 1229 } 1230 else 1231 { 1232 addr = register_addr; // Use register value and offset as the address 1233 } 1234 } 1235 else 1236 { 1237 fprintf(file, "error: unable to read register '%s' for process %#.4x and thread %#.4x\n", register_name.c_str(), pid, tid); 1238 return total_bytes_read; 1239 } 1240 } 1241 } 1242 } 1243 break; 1244 1245 default: 1246 fprintf(file, "error: %%$ must be followed by (regname + n) or [regname + n]\n"); 1247 return total_bytes_read; 1248 } 1249 } 1250 break; 1251 } 1252 1253 // Check for a minimum field width 1254 if (isdigit(*f)) 1255 { 1256 min_field_width = strtoul(f, &end, 10); 1257 if (end > f) 1258 { 1259 fprintf_format.append(f, end - f); 1260 f = end; 1261 } 1262 } 1263 1264 1265 // Check for a precision 1266 if (*f == '.') 1267 { 1268 f++; 1269 if (isdigit(*f)) 1270 { 1271 fprintf_format += '.'; 1272 precision = strtoul(f, &end, 10); 1273 if (end > f) 1274 { 1275 fprintf_format.append(f, end - f); 1276 f = end; 1277 } 1278 } 1279 } 1280 1281 1282 // mprintf specific: read the optional actual byte size (abs) 1283 // after the standard minimum field width (mfw) and precision (prec). 1284 // Standard printf calls you can have "mfw.prec" or ".prec", but 1285 // mprintf can have "mfw.prec.abs", ".prec.abs" or "..abs". This is nice 1286 // for strings that may be in a fixed size buffer, but may not use all bytes 1287 // in that buffer for printable characters. 1288 if (*f == '.') 1289 { 1290 f++; 1291 actual_byte_size = strtoul(f, &end, 10); 1292 if (end > f) 1293 { 1294 byte_size = actual_byte_size; 1295 f = end; 1296 } 1297 } 1298 1299 // Decode the length modifiers 1300 switch (*f) 1301 { 1302 case 'h': // h and hh length modifiers 1303 fprintf_format += *f++; 1304 length_modifiers |= length_mod_h; 1305 if (*f == 'h') 1306 { 1307 fprintf_format += *f++; 1308 length_modifiers |= length_mod_hh; 1309 } 1310 break; 1311 1312 case 'l': // l and ll length modifiers 1313 fprintf_format += *f++; 1314 length_modifiers |= length_mod_l; 1315 if (*f == 'h') 1316 { 1317 fprintf_format += *f++; 1318 length_modifiers |= length_mod_ll; 1319 } 1320 break; 1321 1322 case 'L': fprintf_format += *f++; length_modifiers |= length_mod_L; break; 1323 case 'j': fprintf_format += *f++; length_modifiers |= length_mod_j; break; 1324 case 't': fprintf_format += *f++; length_modifiers |= length_mod_t; break; 1325 case 'z': fprintf_format += *f++; length_modifiers |= length_mod_z; break; 1326 case 'q': fprintf_format += *f++; length_modifiers |= length_mod_q; break; 1327 } 1328 1329 // Decode the conversion specifier 1330 switch (*f) 1331 { 1332 case '_': 1333 // mprintf specific format items 1334 { 1335 ++f; // Skip the '_' character 1336 switch (*f) 1337 { 1338 case 'a': // Print the current address 1339 ++f; 1340 fprintf_format += "ll"; 1341 fprintf_format += *f; // actual format to show address with folows the 'a' ("%_ax") 1342 fprintf (file, fprintf_format.c_str(), addr); 1343 break; 1344 case 'o': // offset from base address 1345 ++f; 1346 fprintf_format += "ll"; 1347 fprintf_format += *f; // actual format to show address with folows the 'a' ("%_ox") 1348 fprintf(file, fprintf_format.c_str(), addr - base_addr); 1349 break; 1350 default: 1351 fprintf (file, "error: unsupported mprintf specific format character '%c'.\n", *f); 1352 break; 1353 } 1354 continue; 1355 } 1356 break; 1357 1358 case 'D': 1359 case 'O': 1360 case 'U': 1361 fprintf_format += *f; 1362 if (byte_size == 0) 1363 byte_size = sizeof(long int); 1364 break; 1365 1366 case 'd': 1367 case 'i': 1368 case 'o': 1369 case 'u': 1370 case 'x': 1371 case 'X': 1372 fprintf_format += *f; 1373 if (byte_size == 0) 1374 { 1375 if (length_modifiers & length_mod_hh) 1376 byte_size = sizeof(char); 1377 else if (length_modifiers & length_mod_h) 1378 byte_size = sizeof(short); 1379 if (length_modifiers & length_mod_ll) 1380 byte_size = sizeof(long long); 1381 else if (length_modifiers & length_mod_l) 1382 byte_size = sizeof(long); 1383 else 1384 byte_size = sizeof(int); 1385 } 1386 break; 1387 1388 case 'a': 1389 case 'A': 1390 case 'f': 1391 case 'F': 1392 case 'e': 1393 case 'E': 1394 case 'g': 1395 case 'G': 1396 fprintf_format += *f; 1397 if (byte_size == 0) 1398 { 1399 if (length_modifiers & length_mod_L) 1400 byte_size = sizeof(long double); 1401 else 1402 byte_size = sizeof(double); 1403 } 1404 break; 1405 1406 case 'c': 1407 if ((length_modifiers & length_mod_l) == 0) 1408 { 1409 fprintf_format += *f; 1410 if (byte_size == 0) 1411 byte_size = sizeof(char); 1412 break; 1413 } 1414 // Fall through to 'C' modifier below... 1415 1416 case 'C': 1417 fprintf_format += *f; 1418 if (byte_size == 0) 1419 byte_size = sizeof(wchar_t); 1420 break; 1421 1422 case 's': 1423 fprintf_format += *f; 1424 if (is_register || byte_size == 0) 1425 is_string = 1; 1426 break; 1427 1428 case 'p': 1429 fprintf_format += *f; 1430 if (byte_size == 0) 1431 byte_size = sizeof(void*); 1432 break; 1433 } 1434 1435 if (is_string) 1436 { 1437 std::string mem_string; 1438 const size_t string_buf_len = 4; 1439 char string_buf[string_buf_len+1]; 1440 char *string_buf_end = string_buf + string_buf_len; 1441 string_buf[string_buf_len] = '\0'; 1442 nub_size_t bytes_read; 1443 nub_addr_t str_addr = is_register ? register_addr : addr; 1444 while ((bytes_read = DNBProcessMemoryRead(pid, str_addr, string_buf_len, &string_buf[0])) > 0) 1445 { 1446 // Did we get a NULL termination character yet? 1447 if (strchr(string_buf, '\0') == string_buf_end) 1448 { 1449 // no NULL terminator yet, append as a std::string 1450 mem_string.append(string_buf, string_buf_len); 1451 str_addr += string_buf_len; 1452 } 1453 else 1454 { 1455 // yep 1456 break; 1457 } 1458 } 1459 // Append as a C-string so we don't get the extra NULL 1460 // characters in the temp buffer (since it was resized) 1461 mem_string += string_buf; 1462 size_t mem_string_len = mem_string.size() + 1; 1463 fprintf(file, fprintf_format.c_str(), mem_string.c_str()); 1464 if (mem_string_len > 0) 1465 { 1466 if (!is_register) 1467 { 1468 addr += mem_string_len; 1469 total_bytes_read += mem_string_len; 1470 } 1471 } 1472 else 1473 return total_bytes_read; 1474 } 1475 else 1476 if (byte_size > 0) 1477 { 1478 buf.resize(byte_size); 1479 nub_size_t bytes_read = 0; 1480 if (is_register) 1481 bytes_read = register_value.info.size; 1482 else 1483 bytes_read = DNBProcessMemoryRead(pid, addr, buf.size(), &buf[0]); 1484 if (bytes_read > 0) 1485 { 1486 if (!is_register) 1487 total_bytes_read += bytes_read; 1488 1489 if (bytes_read == byte_size) 1490 { 1491 switch (*f) 1492 { 1493 case 'd': 1494 case 'i': 1495 case 'o': 1496 case 'u': 1497 case 'X': 1498 case 'x': 1499 case 'a': 1500 case 'A': 1501 case 'f': 1502 case 'F': 1503 case 'e': 1504 case 'E': 1505 case 'g': 1506 case 'G': 1507 case 'p': 1508 case 'c': 1509 case 'C': 1510 { 1511 if (is_register) 1512 data.SetData(®ister_value.value.v_uint8[0], register_value.info.size); 1513 else 1514 data.SetData(&buf[0], bytes_read); 1515 DNBDataRef::offset_t data_offset = 0; 1516 if (byte_size <= 4) 1517 { 1518 uint32_t u32 = data.GetMax32(&data_offset, byte_size); 1519 // Show the actual byte width when displaying hex 1520 fprintf(file, fprintf_format.c_str(), u32); 1521 } 1522 else if (byte_size <= 8) 1523 { 1524 uint64_t u64 = data.GetMax64(&data_offset, byte_size); 1525 // Show the actual byte width when displaying hex 1526 fprintf(file, fprintf_format.c_str(), u64); 1527 } 1528 else 1529 { 1530 fprintf(file, "error: integer size not supported, must be 8 bytes or less (%u bytes).\n", byte_size); 1531 } 1532 if (!is_register) 1533 addr += byte_size; 1534 } 1535 break; 1536 1537 case 's': 1538 fprintf(file, fprintf_format.c_str(), buf.c_str()); 1539 addr += byte_size; 1540 break; 1541 1542 default: 1543 fprintf(file, "error: unsupported conversion specifier '%c'.\n", *f); 1544 break; 1545 } 1546 } 1547 } 1548 } 1549 else 1550 return total_bytes_read; 1551 } 1552 break; 1553 1554 case '\\': 1555 { 1556 f++; 1557 switch (*f) 1558 { 1559 case 'e': ch = '\e'; break; 1560 case 'a': ch = '\a'; break; 1561 case 'b': ch = '\b'; break; 1562 case 'f': ch = '\f'; break; 1563 case 'n': ch = '\n'; break; 1564 case 'r': ch = '\r'; break; 1565 case 't': ch = '\t'; break; 1566 case 'v': ch = '\v'; break; 1567 case '\'': ch = '\''; break; 1568 case '\\': ch = '\\'; break; 1569 case '0': 1570 case '1': 1571 case '2': 1572 case '3': 1573 case '4': 1574 case '5': 1575 case '6': 1576 case '7': 1577 ch = strtoul(f, &end, 8); 1578 f = end; 1579 break; 1580 default: 1581 ch = *f; 1582 break; 1583 } 1584 fputc(ch, file); 1585 } 1586 break; 1587 1588 default: 1589 fputc(ch, file); 1590 break; 1591 } 1592 } 1593 return total_bytes_read; 1594} 1595 1596 1597//---------------------------------------------------------------------- 1598// Get the number of threads for the specified process. 1599//---------------------------------------------------------------------- 1600nub_size_t 1601DNBProcessGetNumThreads (nub_process_t pid) 1602{ 1603 MachProcessSP procSP; 1604 if (GetProcessSP (pid, procSP)) 1605 return procSP->GetNumThreads(); 1606 return 0; 1607} 1608 1609//---------------------------------------------------------------------- 1610// Get the thread ID of the current thread. 1611//---------------------------------------------------------------------- 1612nub_thread_t 1613DNBProcessGetCurrentThread (nub_process_t pid) 1614{ 1615 MachProcessSP procSP; 1616 if (GetProcessSP (pid, procSP)) 1617 return procSP->GetCurrentThread(); 1618 return 0; 1619} 1620 1621//---------------------------------------------------------------------- 1622// Change the current thread. 1623//---------------------------------------------------------------------- 1624nub_thread_t 1625DNBProcessSetCurrentThread (nub_process_t pid, nub_thread_t tid) 1626{ 1627 MachProcessSP procSP; 1628 if (GetProcessSP (pid, procSP)) 1629 return procSP->SetCurrentThread (tid); 1630 return INVALID_NUB_THREAD; 1631} 1632 1633 1634//---------------------------------------------------------------------- 1635// Dump a string describing a thread's stop reason to the specified file 1636// handle 1637//---------------------------------------------------------------------- 1638nub_bool_t 1639DNBThreadGetStopReason (nub_process_t pid, nub_thread_t tid, struct DNBThreadStopInfo *stop_info) 1640{ 1641 MachProcessSP procSP; 1642 if (GetProcessSP (pid, procSP)) 1643 return procSP->GetThreadStoppedReason (tid, stop_info); 1644 return false; 1645} 1646 1647//---------------------------------------------------------------------- 1648// Return string description for the specified thread. 1649// 1650// RETURNS: NULL if the thread isn't valid, else a NULL terminated C 1651// string from a static buffer that must be copied prior to subsequent 1652// calls. 1653//---------------------------------------------------------------------- 1654const char * 1655DNBThreadGetInfo (nub_process_t pid, nub_thread_t tid) 1656{ 1657 MachProcessSP procSP; 1658 if (GetProcessSP (pid, procSP)) 1659 return procSP->GetThreadInfo (tid); 1660 return NULL; 1661} 1662 1663//---------------------------------------------------------------------- 1664// Get the thread ID given a thread index. 1665//---------------------------------------------------------------------- 1666nub_thread_t 1667DNBProcessGetThreadAtIndex (nub_process_t pid, size_t thread_idx) 1668{ 1669 MachProcessSP procSP; 1670 if (GetProcessSP (pid, procSP)) 1671 return procSP->GetThreadAtIndex (thread_idx); 1672 return INVALID_NUB_THREAD; 1673} 1674 1675nub_addr_t 1676DNBProcessGetSharedLibraryInfoAddress (nub_process_t pid) 1677{ 1678 MachProcessSP procSP; 1679 DNBError err; 1680 if (GetProcessSP (pid, procSP)) 1681 return procSP->Task().GetDYLDAllImageInfosAddress (err); 1682 return INVALID_NUB_ADDRESS; 1683} 1684 1685 1686nub_bool_t 1687DNBProcessSharedLibrariesUpdated(nub_process_t pid) 1688{ 1689 MachProcessSP procSP; 1690 if (GetProcessSP (pid, procSP)) 1691 { 1692 procSP->SharedLibrariesUpdated (); 1693 return true; 1694 } 1695 return false; 1696} 1697 1698//---------------------------------------------------------------------- 1699// Get the current shared library information for a process. Only return 1700// the shared libraries that have changed since the last shared library 1701// state changed event if only_changed is non-zero. 1702//---------------------------------------------------------------------- 1703nub_size_t 1704DNBProcessGetSharedLibraryInfo (nub_process_t pid, nub_bool_t only_changed, struct DNBExecutableImageInfo **image_infos) 1705{ 1706 MachProcessSP procSP; 1707 if (GetProcessSP (pid, procSP)) 1708 return procSP->CopyImageInfos (image_infos, only_changed); 1709 1710 // If we have no process, then return NULL for the shared library info 1711 // and zero for shared library count 1712 *image_infos = NULL; 1713 return 0; 1714} 1715 1716//---------------------------------------------------------------------- 1717// Get the register set information for a specific thread. 1718//---------------------------------------------------------------------- 1719const DNBRegisterSetInfo * 1720DNBGetRegisterSetInfo (nub_size_t *num_reg_sets) 1721{ 1722 return DNBArch::GetRegisterSetInfo (num_reg_sets); 1723} 1724 1725 1726//---------------------------------------------------------------------- 1727// Read a register value by register set and register index. 1728//---------------------------------------------------------------------- 1729nub_bool_t 1730DNBThreadGetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value) 1731{ 1732 MachProcessSP procSP; 1733 ::bzero (value, sizeof(DNBRegisterValue)); 1734 if (GetProcessSP (pid, procSP)) 1735 { 1736 if (tid != INVALID_NUB_THREAD) 1737 return procSP->GetRegisterValue (tid, set, reg, value); 1738 } 1739 return false; 1740} 1741 1742nub_bool_t 1743DNBThreadSetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value) 1744{ 1745 if (tid != INVALID_NUB_THREAD) 1746 { 1747 MachProcessSP procSP; 1748 if (GetProcessSP (pid, procSP)) 1749 return procSP->SetRegisterValue (tid, set, reg, value); 1750 } 1751 return false; 1752} 1753 1754nub_size_t 1755DNBThreadGetRegisterContext (nub_process_t pid, nub_thread_t tid, void *buf, size_t buf_len) 1756{ 1757 MachProcessSP procSP; 1758 if (GetProcessSP (pid, procSP)) 1759 { 1760 if (tid != INVALID_NUB_THREAD) 1761 return procSP->GetThreadList().GetRegisterContext (tid, buf, buf_len); 1762 } 1763 ::bzero (buf, buf_len); 1764 return 0; 1765 1766} 1767 1768nub_size_t 1769DNBThreadSetRegisterContext (nub_process_t pid, nub_thread_t tid, const void *buf, size_t buf_len) 1770{ 1771 MachProcessSP procSP; 1772 if (GetProcessSP (pid, procSP)) 1773 { 1774 if (tid != INVALID_NUB_THREAD) 1775 return procSP->GetThreadList().SetRegisterContext (tid, buf, buf_len); 1776 } 1777 return 0; 1778} 1779 1780//---------------------------------------------------------------------- 1781// Read a register value by name. 1782//---------------------------------------------------------------------- 1783nub_bool_t 1784DNBThreadGetRegisterValueByName (nub_process_t pid, nub_thread_t tid, uint32_t reg_set, const char *reg_name, DNBRegisterValue *value) 1785{ 1786 MachProcessSP procSP; 1787 ::bzero (value, sizeof(DNBRegisterValue)); 1788 if (GetProcessSP (pid, procSP)) 1789 { 1790 const struct DNBRegisterSetInfo *set_info; 1791 nub_size_t num_reg_sets = 0; 1792 set_info = DNBGetRegisterSetInfo (&num_reg_sets); 1793 if (set_info) 1794 { 1795 uint32_t set = reg_set; 1796 uint32_t reg; 1797 if (set == REGISTER_SET_ALL) 1798 { 1799 for (set = 1; set < num_reg_sets; ++set) 1800 { 1801 for (reg = 0; reg < set_info[set].num_registers; ++reg) 1802 { 1803 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0) 1804 return procSP->GetRegisterValue (tid, set, reg, value); 1805 } 1806 } 1807 } 1808 else 1809 { 1810 for (reg = 0; reg < set_info[set].num_registers; ++reg) 1811 { 1812 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0) 1813 return procSP->GetRegisterValue (tid, set, reg, value); 1814 } 1815 } 1816 } 1817 } 1818 return false; 1819} 1820 1821 1822//---------------------------------------------------------------------- 1823// Read a register set and register number from the register name. 1824//---------------------------------------------------------------------- 1825nub_bool_t 1826DNBGetRegisterInfoByName (const char *reg_name, DNBRegisterInfo* info) 1827{ 1828 const struct DNBRegisterSetInfo *set_info; 1829 nub_size_t num_reg_sets = 0; 1830 set_info = DNBGetRegisterSetInfo (&num_reg_sets); 1831 if (set_info) 1832 { 1833 uint32_t set, reg; 1834 for (set = 1; set < num_reg_sets; ++set) 1835 { 1836 for (reg = 0; reg < set_info[set].num_registers; ++reg) 1837 { 1838 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0) 1839 { 1840 *info = set_info[set].registers[reg]; 1841 return true; 1842 } 1843 } 1844 } 1845 1846 for (set = 1; set < num_reg_sets; ++set) 1847 { 1848 uint32_t reg; 1849 for (reg = 0; reg < set_info[set].num_registers; ++reg) 1850 { 1851 if (set_info[set].registers[reg].alt == NULL) 1852 continue; 1853 1854 if (strcasecmp(reg_name, set_info[set].registers[reg].alt) == 0) 1855 { 1856 *info = set_info[set].registers[reg]; 1857 return true; 1858 } 1859 } 1860 } 1861 } 1862 1863 ::bzero (info, sizeof(DNBRegisterInfo)); 1864 return false; 1865} 1866 1867 1868//---------------------------------------------------------------------- 1869// Set the name to address callback function that this nub can use 1870// for any name to address lookups that are needed. 1871//---------------------------------------------------------------------- 1872nub_bool_t 1873DNBProcessSetNameToAddressCallback (nub_process_t pid, DNBCallbackNameToAddress callback, void *baton) 1874{ 1875 MachProcessSP procSP; 1876 if (GetProcessSP (pid, procSP)) 1877 { 1878 procSP->SetNameToAddressCallback (callback, baton); 1879 return true; 1880 } 1881 return false; 1882} 1883 1884 1885//---------------------------------------------------------------------- 1886// Set the name to address callback function that this nub can use 1887// for any name to address lookups that are needed. 1888//---------------------------------------------------------------------- 1889nub_bool_t 1890DNBProcessSetSharedLibraryInfoCallback (nub_process_t pid, DNBCallbackCopyExecutableImageInfos callback, void *baton) 1891{ 1892 MachProcessSP procSP; 1893 if (GetProcessSP (pid, procSP)) 1894 { 1895 procSP->SetSharedLibraryInfoCallback (callback, baton); 1896 return true; 1897 } 1898 return false; 1899} 1900 1901nub_addr_t 1902DNBProcessLookupAddress (nub_process_t pid, const char *name, const char *shlib) 1903{ 1904 MachProcessSP procSP; 1905 if (GetProcessSP (pid, procSP)) 1906 { 1907 return procSP->LookupSymbol (name, shlib); 1908 } 1909 return INVALID_NUB_ADDRESS; 1910} 1911 1912 1913nub_size_t 1914DNBProcessGetAvailableSTDOUT (nub_process_t pid, char *buf, nub_size_t buf_size) 1915{ 1916 MachProcessSP procSP; 1917 if (GetProcessSP (pid, procSP)) 1918 return procSP->GetAvailableSTDOUT (buf, buf_size); 1919 return 0; 1920} 1921 1922nub_size_t 1923DNBProcessGetAvailableSTDERR (nub_process_t pid, char *buf, nub_size_t buf_size) 1924{ 1925 MachProcessSP procSP; 1926 if (GetProcessSP (pid, procSP)) 1927 return procSP->GetAvailableSTDERR (buf, buf_size); 1928 return 0; 1929} 1930 1931nub_size_t 1932DNBProcessGetStopCount (nub_process_t pid) 1933{ 1934 MachProcessSP procSP; 1935 if (GetProcessSP (pid, procSP)) 1936 return procSP->StopCount(); 1937 return 0; 1938} 1939 1940nub_bool_t 1941DNBResolveExecutablePath (const char *path, char *resolved_path, size_t resolved_path_size) 1942{ 1943 if (path == NULL || path[0] == '\0') 1944 return false; 1945 1946 char max_path[PATH_MAX]; 1947 std::string result; 1948 CFString::GlobPath(path, result); 1949 1950 if (result.empty()) 1951 result = path; 1952 1953 if (realpath(path, max_path)) 1954 { 1955 // Found the path relatively... 1956 ::strncpy(resolved_path, max_path, resolved_path_size); 1957 return strlen(resolved_path) + 1 < resolved_path_size; 1958 } 1959 else 1960 { 1961 // Not a relative path, check the PATH environment variable if the 1962 const char *PATH = getenv("PATH"); 1963 if (PATH) 1964 { 1965 const char *curr_path_start = PATH; 1966 const char *curr_path_end; 1967 while (curr_path_start && *curr_path_start) 1968 { 1969 curr_path_end = strchr(curr_path_start, ':'); 1970 if (curr_path_end == NULL) 1971 { 1972 result.assign(curr_path_start); 1973 curr_path_start = NULL; 1974 } 1975 else if (curr_path_end > curr_path_start) 1976 { 1977 size_t len = curr_path_end - curr_path_start; 1978 result.assign(curr_path_start, len); 1979 curr_path_start += len + 1; 1980 } 1981 else 1982 break; 1983 1984 result += '/'; 1985 result += path; 1986 struct stat s; 1987 if (stat(result.c_str(), &s) == 0) 1988 { 1989 ::strncpy(resolved_path, result.c_str(), resolved_path_size); 1990 return result.size() + 1 < resolved_path_size; 1991 } 1992 } 1993 } 1994 } 1995 return false; 1996} 1997 1998