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