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