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