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