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