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