blob: f9cab2ff665492e32c3c6ba3638495aa9b670b4d [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 Molenda36a216e2014-07-24 01:36:24 +000029#if defined (__APPLE__)
30#include <pthread.h>
31#include <sched.h>
32#endif
33
Jason Molendaa3329782014-03-29 18:54:20 +000034#define TRY_KQUEUE 1
35
36#ifdef TRY_KQUEUE
37 #include <sys/event.h>
38 #include <sys/time.h>
39 #ifdef NOTE_EXIT_DETAIL
40 #define USE_KQUEUE
41 #endif
42#endif
43
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044#include "MacOSX/MachProcess.h"
45#include "MacOSX/MachTask.h"
Jason Molenda705b1802014-06-13 02:37:02 +000046#include "MacOSX/Genealogy.h"
47#include "MacOSX/ThreadInfo.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000048#include "CFString.h"
49#include "DNBLog.h"
50#include "DNBDataRef.h"
51#include "DNBThreadResumeActions.h"
52#include "DNBTimer.h"
Greg Clayton48baf7a2012-10-31 21:44:39 +000053#include "CFBundle.h"
54
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055
Greg Clayton7b0992d2013-04-18 22:45:39 +000056typedef std::shared_ptr<MachProcess> MachProcessSP;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057typedef std::map<nub_process_t, MachProcessSP> ProcessMap;
58typedef ProcessMap::iterator ProcessMapIter;
59typedef ProcessMap::const_iterator ProcessMapConstIter;
60
Greg Clayton9eb4e032012-11-06 23:36:26 +000061size_t GetAllInfos (std::vector<struct kinfo_proc>& proc_infos);
62static size_t GetAllInfosMatchingName (const char *process_name, std::vector<struct kinfo_proc>& matching_proc_infos);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000063
64//----------------------------------------------------------------------
65// A Thread safe singleton to get a process map pointer.
66//
67// Returns a pointer to the existing process map, or a pointer to a
68// newly created process map if CAN_CREATE is non-zero.
69//----------------------------------------------------------------------
70static ProcessMap*
71GetProcessMap(bool can_create)
72{
73 static ProcessMap* g_process_map_ptr = NULL;
74
75 if (can_create && g_process_map_ptr == NULL)
76 {
77 static pthread_mutex_t g_process_map_mutex = PTHREAD_MUTEX_INITIALIZER;
78 PTHREAD_MUTEX_LOCKER (locker, &g_process_map_mutex);
79 if (g_process_map_ptr == NULL)
80 g_process_map_ptr = new ProcessMap;
81 }
82 return g_process_map_ptr;
83}
84
85//----------------------------------------------------------------------
86// Add PID to the shared process pointer map.
87//
88// Return non-zero value if we succeed in adding the process to the map.
89// The only time this should fail is if we run out of memory and can't
90// allocate a ProcessMap.
91//----------------------------------------------------------------------
92static nub_bool_t
93AddProcessToMap (nub_process_t pid, MachProcessSP& procSP)
94{
95 ProcessMap* process_map = GetProcessMap(true);
96 if (process_map)
97 {
98 process_map->insert(std::make_pair(pid, procSP));
99 return true;
100 }
101 return false;
102}
103
104//----------------------------------------------------------------------
105// Remove the shared pointer for PID from the process map.
106//
107// Returns the number of items removed from the process map.
108//----------------------------------------------------------------------
Greg Claytonee2ed522015-03-09 19:45:23 +0000109//static size_t
110//RemoveProcessFromMap (nub_process_t pid)
111//{
112// ProcessMap* process_map = GetProcessMap(false);
113// if (process_map)
114// {
115// return process_map->erase(pid);
116// }
117// return 0;
118//}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000119
120//----------------------------------------------------------------------
121// Get the shared pointer for PID from the existing process map.
122//
123// Returns true if we successfully find a shared pointer to a
124// MachProcess object.
125//----------------------------------------------------------------------
126static nub_bool_t
127GetProcessSP (nub_process_t pid, MachProcessSP& procSP)
128{
129 ProcessMap* process_map = GetProcessMap(false);
130 if (process_map != NULL)
131 {
132 ProcessMapIter pos = process_map->find(pid);
133 if (pos != process_map->end())
134 {
135 procSP = pos->second;
136 return true;
137 }
138 }
139 procSP.reset();
140 return false;
141}
142
Jason Molendaa3329782014-03-29 18:54:20 +0000143#ifdef USE_KQUEUE
144void *
145kqueue_thread (void *arg)
146{
147 int kq_id = (int) (intptr_t) arg;
148
Jason Molenda36a216e2014-07-24 01:36:24 +0000149#if defined (__APPLE__)
150 pthread_setname_np ("kqueue thread");
151#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
152 struct sched_param thread_param;
153 int thread_sched_policy;
154 if (pthread_getschedparam(pthread_self(), &thread_sched_policy, &thread_param) == 0)
155 {
156 thread_param.sched_priority = 47;
157 pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
158 }
159#endif
160#endif
161
Jason Molendaa3329782014-03-29 18:54:20 +0000162 struct kevent death_event;
163 while (1)
164 {
165 int n_events = kevent (kq_id, NULL, 0, &death_event, 1, NULL);
166 if (n_events == -1)
167 {
168 if (errno == EINTR)
169 continue;
170 else
171 {
172 DNBLogError ("kqueue failed with error: (%d): %s", errno, strerror(errno));
173 return NULL;
174 }
175 }
176 else if (death_event.flags & EV_ERROR)
177 {
Greg Claytonee2ed522015-03-09 19:45:23 +0000178 int error_no = static_cast<int>(death_event.data);
179 const char *error_str = strerror(error_no);
Jason Molendaa3329782014-03-29 18:54:20 +0000180 if (error_str == NULL)
181 error_str = "Unknown error";
182 DNBLogError ("Failed to initialize kqueue event: (%d): %s", error_no, error_str );
183 return NULL;
184 }
185 else
186 {
187 int status;
Greg Clayton040c5602014-04-30 20:24:10 +0000188 const pid_t pid = (pid_t)death_event.ident;
189 const pid_t child_pid = waitpid (pid, &status, 0);
Jason Molendaa3329782014-03-29 18:54:20 +0000190
Greg Clayton040c5602014-04-30 20:24:10 +0000191
192 bool exited = false;
193 int signal = 0;
194 int exit_status = 0;
Greg Clayton040c5602014-04-30 20:24:10 +0000195 if (WIFSTOPPED(status))
196 {
197 signal = WSTOPSIG(status);
Greg Clayton040c5602014-04-30 20:24:10 +0000198 DNBLogThreadedIf(LOG_PROCESS, "waitpid (%i) -> STOPPED (signal = %i)", child_pid, signal);
199 }
200 else if (WIFEXITED(status))
201 {
202 exit_status = WEXITSTATUS(status);
Greg Clayton040c5602014-04-30 20:24:10 +0000203 exited = true;
204 DNBLogThreadedIf(LOG_PROCESS, "waitpid (%i) -> EXITED (status = %i)", child_pid, exit_status);
205 }
206 else if (WIFSIGNALED(status))
207 {
208 signal = WTERMSIG(status);
Greg Clayton040c5602014-04-30 20:24:10 +0000209 if (child_pid == abs(pid))
210 {
211 DNBLogThreadedIf(LOG_PROCESS, "waitpid (%i) -> SIGNALED and EXITED (signal = %i)", child_pid, signal);
212 char exit_info[64];
213 ::snprintf (exit_info, sizeof(exit_info), "Terminated due to signal %i", signal);
214 DNBProcessSetExitInfo (child_pid, exit_info);
215 exited = true;
216 exit_status = INT8_MAX;
217 }
218 else
219 {
220 DNBLogThreadedIf(LOG_PROCESS, "waitpid (%i) -> SIGNALED (signal = %i)", child_pid, signal);
221 }
222 }
223
224 if (exited)
225 {
226 if (death_event.data & NOTE_EXIT_MEMORY)
Jim Ingham0c7ebe92014-06-17 21:02:44 +0000227 DNBProcessSetExitInfo (child_pid, "Terminated due to memory issue");
Greg Clayton040c5602014-04-30 20:24:10 +0000228 else if (death_event.data & NOTE_EXIT_DECRYPTFAIL)
229 DNBProcessSetExitInfo (child_pid, "Terminated due to decrypt failure");
230 else if (death_event.data & NOTE_EXIT_CSERROR)
231 DNBProcessSetExitInfo (child_pid, "Terminated due to code signing error");
232
233 DNBLogThreadedIf(LOG_PROCESS, "waitpid_process_thread (): setting exit status for pid = %i to %i", child_pid, exit_status);
234 DNBProcessSetExitStatus (child_pid, status);
235 return NULL;
236 }
Jason Molendaa3329782014-03-29 18:54:20 +0000237 }
238 }
239}
240
241static bool
242spawn_kqueue_thread (pid_t pid)
243{
244 pthread_t thread;
245 int kq_id;
246
247 kq_id = kqueue();
248 if (kq_id == -1)
249 {
250 DNBLogError ("Could not get kqueue for pid = %i.", pid);
251 return false;
252 }
253
254 struct kevent reg_event;
255
Jim Ingham60089242014-06-24 21:51:42 +0000256 EV_SET(&reg_event, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT|NOTE_EXITSTATUS|NOTE_EXIT_DETAIL, 0, NULL);
Jason Molendaa3329782014-03-29 18:54:20 +0000257 // Register the event:
258 int result = kevent (kq_id, &reg_event, 1, NULL, 0, NULL);
259 if (result != 0)
260 {
261 DNBLogError ("Failed to register kqueue NOTE_EXIT event for pid %i, error: %d.", pid, result);
262 return false;
263 }
264
265 int ret = ::pthread_create (&thread, NULL, kqueue_thread, (void *)(intptr_t)kq_id);
266
267 // pthread_create returns 0 if successful
268 if (ret == 0)
269 {
270 ::pthread_detach (thread);
271 return true;
272 }
273 return false;
274}
275#endif // #if USE_KQUEUE
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000276
277static void *
278waitpid_thread (void *arg)
279{
280 const pid_t pid = (pid_t)(intptr_t)arg;
281 int status;
Jason Molenda36a216e2014-07-24 01:36:24 +0000282
283#if defined (__APPLE__)
284 pthread_setname_np ("waitpid thread");
285#if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
286 struct sched_param thread_param;
287 int thread_sched_policy;
288 if (pthread_getschedparam(pthread_self(), &thread_sched_policy, &thread_param) == 0)
289 {
290 thread_param.sched_priority = 47;
291 pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
292 }
293#endif
294#endif
295
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000296 while (1)
297 {
298 pid_t child_pid = waitpid(pid, &status, 0);
Greg Clayton6467ff92013-06-27 00:23:57 +0000299 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 +0000300
301 if (child_pid < 0)
302 {
303 if (errno == EINTR)
304 continue;
305 break;
306 }
307 else
308 {
309 if (WIFSTOPPED(status))
310 {
311 continue;
312 }
313 else// if (WIFEXITED(status) || WIFSIGNALED(status))
314 {
Greg Clayton6467ff92013-06-27 00:23:57 +0000315 DNBLogThreadedIf(LOG_PROCESS, "waitpid_thread (): setting exit status for pid = %i to %i", child_pid, status);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000316 DNBProcessSetExitStatus (child_pid, status);
317 return NULL;
318 }
319 }
320 }
321
322 // We should never exit as long as our child process is alive, so if we
323 // do something else went wrong and we should exit...
Greg Clayton6467ff92013-06-27 00:23:57 +0000324 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 +0000325 DNBProcessSetExitStatus (pid, -1);
326 return NULL;
327}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328static bool
329spawn_waitpid_thread (pid_t pid)
330{
Jason Molendaa3329782014-03-29 18:54:20 +0000331#ifdef USE_KQUEUE
332 bool success = spawn_kqueue_thread (pid);
333 if (success)
334 return true;
335#endif
336
Jason Molenda27148b32013-10-05 02:52:22 +0000337 pthread_t thread;
338 int ret = ::pthread_create (&thread, NULL, waitpid_thread, (void *)(intptr_t)pid);
339 // pthread_create returns 0 if successful
340 if (ret == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000341 {
342 ::pthread_detach (thread);
343 return true;
344 }
345 return false;
346}
347
348nub_process_t
349DNBProcessLaunch (const char *path,
350 char const *argv[],
351 const char *envp[],
Bruce Mitcheneraaa0ba32014-07-08 18:05:41 +0000352 const char *working_directory, // NULL => don't change, non-NULL => set working directory for inferior to this
Greg Clayton6779606a2011-01-22 23:43:18 +0000353 const char *stdin_path,
354 const char *stdout_path,
355 const char *stderr_path,
Caroline Ticef8da8632010-12-03 18:46:09 +0000356 bool no_stdio,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000357 nub_launch_flavor_t launch_flavor,
Greg Claytonf681b942010-08-31 18:35:14 +0000358 int disable_aslr,
Jason Molendaa3329782014-03-29 18:54:20 +0000359 const char *event_data,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000360 char *err_str,
361 size_t err_len)
362{
Greg Clayton43e0af02012-09-18 18:04:04 +0000363 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 +0000364 __FUNCTION__,
365 path,
366 argv,
367 envp,
368 working_directory,
369 stdin_path,
370 stdout_path,
371 stderr_path,
372 no_stdio,
373 launch_flavor,
374 disable_aslr,
375 err_str,
Greg Clayton43e0af02012-09-18 18:04:04 +0000376 (uint64_t)err_len);
Greg Claytonbd82a5d2011-01-23 05:56:20 +0000377
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000378 if (err_str && err_len > 0)
379 err_str[0] = '\0';
380 struct stat path_stat;
381 if (::stat(path, &path_stat) == -1)
382 {
383 char stat_error[256];
384 ::strerror_r (errno, stat_error, sizeof(stat_error));
385 snprintf(err_str, err_len, "%s (%s)", stat_error, path);
386 return INVALID_NUB_PROCESS;
387 }
388
389 MachProcessSP processSP (new MachProcess);
390 if (processSP.get())
391 {
392 DNBError launch_err;
Greg Clayton6779606a2011-01-22 23:43:18 +0000393 pid_t pid = processSP->LaunchForDebug (path,
394 argv,
395 envp,
396 working_directory,
397 stdin_path,
398 stdout_path,
399 stderr_path,
400 no_stdio,
401 launch_flavor,
Jason Molendaa3329782014-03-29 18:54:20 +0000402 disable_aslr,
403 event_data,
Greg Clayton6779606a2011-01-22 23:43:18 +0000404 launch_err);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000405 if (err_str)
406 {
407 *err_str = '\0';
408 if (launch_err.Fail())
409 {
410 const char *launch_err_str = launch_err.AsString();
411 if (launch_err_str)
412 {
413 strncpy(err_str, launch_err_str, err_len-1);
414 err_str[err_len-1] = '\0'; // Make sure the error string is terminated
415 }
416 }
417 }
418
419 DNBLogThreadedIf(LOG_PROCESS, "(DebugNub) new pid is %d...", pid);
420
421 if (pid != INVALID_NUB_PROCESS)
422 {
423 // Spawn a thread to reap our child inferior process...
424 spawn_waitpid_thread (pid);
425
426 if (processSP->Task().TaskPortForProcessID (launch_err) == TASK_NULL)
427 {
428 // We failed to get the task for our process ID which is bad.
Greg Claytonfb640c22012-02-02 19:23:22 +0000429 // Kill our process otherwise it will be stopped at the entry
430 // point and get reparented to someone else and never go away.
Jason Molenda153c8e02013-01-05 06:08:51 +0000431 DNBLog ("Could not get task port for process, sending SIGKILL and exiting.");
Greg Claytonfb640c22012-02-02 19:23:22 +0000432 kill (SIGKILL, pid);
433
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000434 if (err_str && err_len > 0)
435 {
436 if (launch_err.AsString())
437 {
438 ::snprintf (err_str, err_len, "failed to get the task for process %i (%s)", pid, launch_err.AsString());
439 }
440 else
441 {
442 ::snprintf (err_str, err_len, "failed to get the task for process %i", pid);
443 }
444 }
445 }
446 else
447 {
Charles Davisb786e7d2012-02-21 00:53:12 +0000448 bool res = AddProcessToMap(pid, processSP);
449 assert(res && "Couldn't add process to map!");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000450 return pid;
451 }
452 }
453 }
454 return INVALID_NUB_PROCESS;
455}
456
457nub_process_t
458DNBProcessAttachByName (const char *name, struct timespec *timeout, char *err_str, size_t err_len)
459{
460 if (err_str && err_len > 0)
461 err_str[0] = '\0';
462 std::vector<struct kinfo_proc> matching_proc_infos;
463 size_t num_matching_proc_infos = GetAllInfosMatchingName(name, matching_proc_infos);
464 if (num_matching_proc_infos == 0)
465 {
466 DNBLogError ("error: no processes match '%s'\n", name);
467 return INVALID_NUB_PROCESS;
468 }
469 else if (num_matching_proc_infos > 1)
470 {
Greg Clayton43e0af02012-09-18 18:04:04 +0000471 DNBLogError ("error: %llu processes match '%s':\n", (uint64_t)num_matching_proc_infos, name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000472 size_t i;
473 for (i=0; i<num_matching_proc_infos; ++i)
474 DNBLogError ("%6u - %s\n", matching_proc_infos[i].kp_proc.p_pid, matching_proc_infos[i].kp_proc.p_comm);
475 return INVALID_NUB_PROCESS;
476 }
Greg Clayton3af9ea52010-11-18 05:57:03 +0000477
478 return DNBProcessAttach (matching_proc_infos[0].kp_proc.p_pid, timeout, err_str, err_len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000479}
480
481nub_process_t
482DNBProcessAttach (nub_process_t attach_pid, struct timespec *timeout, char *err_str, size_t err_len)
483{
484 if (err_str && err_len > 0)
485 err_str[0] = '\0';
486
Johnny Chen64503c82011-08-11 19:03:44 +0000487 pid_t pid = INVALID_NUB_PROCESS;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000488 MachProcessSP processSP(new MachProcess);
489 if (processSP.get())
490 {
491 DNBLogThreadedIf(LOG_PROCESS, "(DebugNub) attaching to pid %d...", attach_pid);
492 pid = processSP->AttachForDebug (attach_pid, err_str, err_len);
493
494 if (pid != INVALID_NUB_PROCESS)
495 {
Charles Davisb786e7d2012-02-21 00:53:12 +0000496 bool res = AddProcessToMap(pid, processSP);
497 assert(res && "Couldn't add process to map!");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000498 spawn_waitpid_thread(pid);
499 }
500 }
501
502 while (pid != INVALID_NUB_PROCESS)
503 {
504 // Wait for process to start up and hit entry point
Greg Clayton3af9ea52010-11-18 05:57:03 +0000505 DNBLogThreadedIf (LOG_PROCESS,
506 "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, true, INFINITE)...",
507 __FUNCTION__,
508 pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000509 nub_event_t set_events = DNBProcessWaitForEvents (pid,
Greg Clayton3af9ea52010-11-18 05:57:03 +0000510 eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged,
511 true,
512 timeout);
513
514 DNBLogThreadedIf (LOG_PROCESS,
515 "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, true, INFINITE) => 0x%8.8x",
516 __FUNCTION__,
517 pid,
518 set_events);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000519
520 if (set_events == 0)
521 {
522 if (err_str && err_len > 0)
523 snprintf(err_str, err_len, "operation timed out");
524 pid = INVALID_NUB_PROCESS;
525 }
526 else
527 {
528 if (set_events & (eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged))
529 {
530 nub_state_t pid_state = DNBProcessGetState (pid);
531 DNBLogThreadedIf (LOG_PROCESS, "%s process %4.4x state changed (eEventProcessStateChanged): %s",
532 __FUNCTION__, pid, DNBStateAsString(pid_state));
533
534 switch (pid_state)
535 {
Greg Clayton3af9ea52010-11-18 05:57:03 +0000536 default:
537 case eStateInvalid:
538 case eStateUnloaded:
539 case eStateAttaching:
540 case eStateLaunching:
541 case eStateSuspended:
542 break; // Ignore
543
544 case eStateRunning:
545 case eStateStepping:
546 // Still waiting to stop at entry point...
547 break;
548
549 case eStateStopped:
550 case eStateCrashed:
551 return pid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000552
Greg Clayton3af9ea52010-11-18 05:57:03 +0000553 case eStateDetached:
554 case eStateExited:
555 if (err_str && err_len > 0)
556 snprintf(err_str, err_len, "process exited");
557 return INVALID_NUB_PROCESS;
558 }
559 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000560
561 DNBProcessResetEvents(pid, set_events);
562 }
563 }
564
565 return INVALID_NUB_PROCESS;
566}
567
Greg Clayton9eb4e032012-11-06 23:36:26 +0000568size_t
Greg Clayton3af9ea52010-11-18 05:57:03 +0000569GetAllInfos (std::vector<struct kinfo_proc>& proc_infos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000570{
Greg Clayton9eb4e032012-11-06 23:36:26 +0000571 size_t size = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000572 int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL };
Jim Inghamc1fdb882014-06-27 16:02:55 +0000573 u_int namelen = sizeof(name)/sizeof(int);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000574 int err;
575
576 // Try to find out how many processes are around so we can
577 // size the buffer appropriately. sysctl's man page specifically suggests
578 // this approach, and says it returns a bit larger size than needed to
579 // handle any new processes created between then and now.
580
581 err = ::sysctl (name, namelen, NULL, &size, NULL, 0);
582
583 if ((err < 0) && (err != ENOMEM))
584 {
585 proc_infos.clear();
586 perror("sysctl (mib, miblen, NULL, &num_processes, NULL, 0)");
587 return 0;
588 }
589
590
591 // Increase the size of the buffer by a few processes in case more have
592 // been spawned
593 proc_infos.resize (size / sizeof(struct kinfo_proc));
594 size = proc_infos.size() * sizeof(struct kinfo_proc); // Make sure we don't exceed our resize...
595 err = ::sysctl (name, namelen, &proc_infos[0], &size, NULL, 0);
596 if (err < 0)
597 {
598 proc_infos.clear();
599 return 0;
600 }
601
602 // Trim down our array to fit what we actually got back
603 proc_infos.resize(size / sizeof(struct kinfo_proc));
604 return proc_infos.size();
605}
606
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000607static size_t
608GetAllInfosMatchingName(const char *full_process_name, std::vector<struct kinfo_proc>& matching_proc_infos)
609{
610
611 matching_proc_infos.clear();
612 if (full_process_name && full_process_name[0])
613 {
614 // We only get the process name, not the full path, from the proc_info. So just take the
615 // base name of the process name...
616 const char *process_name;
617 process_name = strrchr (full_process_name, '/');
618 if (process_name == NULL)
Greg Clayton7dab2be2012-07-19 02:45:35 +0000619 process_name = full_process_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000620 else
Greg Clayton7dab2be2012-07-19 02:45:35 +0000621 process_name++;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000622
Greg Claytonee2ed522015-03-09 19:45:23 +0000623 const size_t process_name_len = strlen(process_name);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000624 std::vector<struct kinfo_proc> proc_infos;
625 const size_t num_proc_infos = GetAllInfos(proc_infos);
626 if (num_proc_infos > 0)
627 {
628 uint32_t i;
629 for (i=0; i<num_proc_infos; i++)
630 {
631 // Skip zombie processes and processes with unset status
632 if (proc_infos[i].kp_proc.p_stat == 0 || proc_infos[i].kp_proc.p_stat == SZOMB)
633 continue;
634
635 // Check for process by name. We only check the first MAXCOMLEN
636 // chars as that is all that kp_proc.p_comm holds.
Jim Ingham490bccd2012-11-01 01:04:46 +0000637
Greg Clayton7dab2be2012-07-19 02:45:35 +0000638 if (::strncasecmp(process_name, proc_infos[i].kp_proc.p_comm, MAXCOMLEN) == 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 {
Greg Clayton7dab2be2012-07-19 02:45:35 +0000640 if (process_name_len > MAXCOMLEN)
641 {
642 // We found a matching process name whose first MAXCOMLEN
643 // characters match, but there is more to the name than
Jim Ingham490bccd2012-11-01 01:04:46 +0000644 // this. We need to get the full process name. Use proc_pidpath, which will get
645 // us the full path to the executed process.
Greg Clayton7dab2be2012-07-19 02:45:35 +0000646
Jim Ingham490bccd2012-11-01 01:04:46 +0000647 char proc_path_buf[PATH_MAX];
Greg Clayton7dab2be2012-07-19 02:45:35 +0000648
Jim Ingham490bccd2012-11-01 01:04:46 +0000649 int return_val = proc_pidpath (proc_infos[i].kp_proc.p_pid, proc_path_buf, PATH_MAX);
650 if (return_val > 0)
Greg Clayton7dab2be2012-07-19 02:45:35 +0000651 {
Jim Ingham490bccd2012-11-01 01:04:46 +0000652 // Okay, now search backwards from that to see if there is a
653 // slash in the name. Note, even though we got all the args we don't care
654 // because the list data is just a bunch of concatenated null terminated strings
655 // so strrchr will start from the end of argv0.
656
657 const char *argv_basename = strrchr(proc_path_buf, '/');
Greg Clayton7dab2be2012-07-19 02:45:35 +0000658 if (argv_basename)
659 {
660 // Skip the '/'
661 ++argv_basename;
662 }
663 else
664 {
665 // 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 +0000666 argv_basename = proc_path_buf;
Greg Clayton7dab2be2012-07-19 02:45:35 +0000667 }
668
669 if (argv_basename)
670 {
671 if (::strncasecmp(process_name, argv_basename, PATH_MAX) == 0)
672 {
673 matching_proc_infos.push_back(proc_infos[i]);
674 }
675 }
676 }
677 }
678 else
679 {
680 // We found a matching process, add it to our list
Greg Clayton7dab2be2012-07-19 02:45:35 +0000681 matching_proc_infos.push_back(proc_infos[i]);
682 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000683 }
684 }
685 }
686 }
687 // return the newly added matches.
688 return matching_proc_infos.size();
689}
690
691nub_process_t
Greg Clayton19388cf2010-10-18 01:45:30 +0000692DNBProcessAttachWait (const char *waitfor_process_name,
693 nub_launch_flavor_t launch_flavor,
Jim Inghamcd16df92012-07-20 21:37:13 +0000694 bool ignore_existing,
Greg Clayton19388cf2010-10-18 01:45:30 +0000695 struct timespec *timeout_abstime,
696 useconds_t waitfor_interval,
697 char *err_str,
698 size_t err_len,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000699 DNBShouldCancelCallback should_cancel_callback,
700 void *callback_data)
701{
702 DNBError prepare_error;
703 std::vector<struct kinfo_proc> exclude_proc_infos;
704 size_t num_exclude_proc_infos;
705
706 // If the PrepareForAttach returns a valid token, use MachProcess to check
707 // for the process, otherwise scan the process table.
708
709 const void *attach_token = MachProcess::PrepareForAttach (waitfor_process_name, launch_flavor, true, prepare_error);
710
711 if (prepare_error.Fail())
712 {
713 DNBLogError ("Error in PrepareForAttach: %s", prepare_error.AsString());
714 return INVALID_NUB_PROCESS;
715 }
716
717 if (attach_token == NULL)
Jim Inghamcd16df92012-07-20 21:37:13 +0000718 {
719 if (ignore_existing)
720 num_exclude_proc_infos = GetAllInfosMatchingName (waitfor_process_name, exclude_proc_infos);
721 else
722 num_exclude_proc_infos = 0;
723 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000724
725 DNBLogThreadedIf (LOG_PROCESS, "Waiting for '%s' to appear...\n", waitfor_process_name);
726
727 // Loop and try to find the process by name
728 nub_process_t waitfor_pid = INVALID_NUB_PROCESS;
729
730 while (waitfor_pid == INVALID_NUB_PROCESS)
731 {
732 if (attach_token != NULL)
733 {
734 nub_process_t pid;
735 pid = MachProcess::CheckForProcess(attach_token);
736 if (pid != INVALID_NUB_PROCESS)
737 {
738 waitfor_pid = pid;
739 break;
740 }
741 }
742 else
743 {
744
745 // Get the current process list, and check for matches that
746 // aren't in our original list. If anyone wants to attach
747 // to an existing process by name, they should do it with
748 // --attach=PROCNAME. Else we will wait for the first matching
749 // process that wasn't in our exclusion list.
750 std::vector<struct kinfo_proc> proc_infos;
751 const size_t num_proc_infos = GetAllInfosMatchingName (waitfor_process_name, proc_infos);
752 for (size_t i=0; i<num_proc_infos; i++)
753 {
754 nub_process_t curr_pid = proc_infos[i].kp_proc.p_pid;
755 for (size_t j=0; j<num_exclude_proc_infos; j++)
756 {
757 if (curr_pid == exclude_proc_infos[j].kp_proc.p_pid)
758 {
759 // This process was in our exclusion list, don't use it.
760 curr_pid = INVALID_NUB_PROCESS;
761 break;
762 }
763 }
764
765 // If we didn't find CURR_PID in our exclusion list, then use it.
766 if (curr_pid != INVALID_NUB_PROCESS)
767 {
768 // We found our process!
769 waitfor_pid = curr_pid;
770 break;
771 }
772 }
773 }
774
775 // If we haven't found our process yet, check for a timeout
776 // and then sleep for a bit until we poll again.
777 if (waitfor_pid == INVALID_NUB_PROCESS)
778 {
779 if (timeout_abstime != NULL)
780 {
781 // Check to see if we have a waitfor-duration option that
782 // has timed out?
783 if (DNBTimer::TimeOfDayLaterThan(*timeout_abstime))
784 {
785 if (err_str && err_len > 0)
786 snprintf(err_str, err_len, "operation timed out");
787 DNBLogError ("error: waiting for process '%s' timed out.\n", waitfor_process_name);
788 return INVALID_NUB_PROCESS;
789 }
790 }
791
792 // Call the should cancel callback as well...
793
794 if (should_cancel_callback != NULL
795 && should_cancel_callback (callback_data))
796 {
797 DNBLogThreadedIf (LOG_PROCESS, "DNBProcessAttachWait cancelled by should_cancel callback.");
798 waitfor_pid = INVALID_NUB_PROCESS;
799 break;
800 }
801
802 ::usleep (waitfor_interval); // Sleep for WAITFOR_INTERVAL, then poll again
803 }
804 }
805
806 if (waitfor_pid != INVALID_NUB_PROCESS)
807 {
808 DNBLogThreadedIf (LOG_PROCESS, "Attaching to %s with pid %i...\n", waitfor_process_name, waitfor_pid);
809 waitfor_pid = DNBProcessAttach (waitfor_pid, timeout_abstime, err_str, err_len);
810 }
811
812 bool success = waitfor_pid != INVALID_NUB_PROCESS;
813 MachProcess::CleanupAfterAttach (attach_token, success, prepare_error);
814
815 return waitfor_pid;
816}
817
818nub_bool_t
819DNBProcessDetach (nub_process_t pid)
820{
821 MachProcessSP procSP;
822 if (GetProcessSP (pid, procSP))
823 {
Jim Ingham58813182014-02-25 04:53:13 +0000824 const bool remove = true;
825 DNBLogThreaded("Disabling breakpoints and watchpoints, and detaching from %d.", pid);
826 procSP->DisableAllBreakpoints(remove);
827 procSP->DisableAllWatchpoints (remove);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000828 return procSP->Detach();
829 }
830 return false;
831}
832
833nub_bool_t
834DNBProcessKill (nub_process_t pid)
835{
836 MachProcessSP procSP;
837 if (GetProcessSP (pid, procSP))
838 {
839 return procSP->Kill ();
840 }
841 return false;
842}
843
844nub_bool_t
845DNBProcessSignal (nub_process_t pid, int signal)
846{
847 MachProcessSP procSP;
848 if (GetProcessSP (pid, procSP))
849 {
850 return procSP->Signal (signal);
851 }
852 return false;
853}
854
Greg Clayton4296c222014-04-24 19:54:32 +0000855
856nub_bool_t
857DNBProcessInterrupt(nub_process_t pid)
858{
859 MachProcessSP procSP;
860 if (GetProcessSP (pid, procSP))
861 return procSP->Interrupt();
862 return false;
863}
864
Jason Molendaa3329782014-03-29 18:54:20 +0000865nub_bool_t
866DNBProcessSendEvent (nub_process_t pid, const char *event)
867{
868 MachProcessSP procSP;
869 if (GetProcessSP (pid, procSP))
870 {
871 // FIXME: Do something with the error...
872 DNBError send_error;
873 return procSP->SendEvent (event, send_error);
874 }
875 return false;
876}
877
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878
879nub_bool_t
880DNBProcessIsAlive (nub_process_t pid)
881{
882 MachProcessSP procSP;
883 if (GetProcessSP (pid, procSP))
884 {
885 return MachTask::IsValid (procSP->Task().TaskPort());
886 }
887 return eStateInvalid;
888}
889
890//----------------------------------------------------------------------
891// Process and Thread state information
892//----------------------------------------------------------------------
893nub_state_t
894DNBProcessGetState (nub_process_t pid)
895{
896 MachProcessSP procSP;
897 if (GetProcessSP (pid, procSP))
898 {
899 return procSP->GetState();
900 }
901 return eStateInvalid;
902}
903
904//----------------------------------------------------------------------
905// Process and Thread state information
906//----------------------------------------------------------------------
907nub_bool_t
908DNBProcessGetExitStatus (nub_process_t pid, int* status)
909{
910 MachProcessSP procSP;
911 if (GetProcessSP (pid, procSP))
912 {
913 return procSP->GetExitStatus(status);
914 }
915 return false;
916}
917
918nub_bool_t
919DNBProcessSetExitStatus (nub_process_t pid, int status)
920{
921 MachProcessSP procSP;
922 if (GetProcessSP (pid, procSP))
923 {
924 procSP->SetExitStatus(status);
925 return true;
926 }
927 return false;
928}
929
Jason Molendaa3329782014-03-29 18:54:20 +0000930const char *
931DNBProcessGetExitInfo (nub_process_t pid)
932{
933 MachProcessSP procSP;
934 if (GetProcessSP (pid, procSP))
935 {
936 return procSP->GetExitInfo();
937 }
938 return NULL;
939}
940
941nub_bool_t
942DNBProcessSetExitInfo (nub_process_t pid, const char *info)
943{
944 MachProcessSP procSP;
945 if (GetProcessSP (pid, procSP))
946 {
947 procSP->SetExitInfo(info);
948 return true;
949 }
950 return false;
951}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000952
953const char *
954DNBThreadGetName (nub_process_t pid, nub_thread_t tid)
955{
956 MachProcessSP procSP;
957 if (GetProcessSP (pid, procSP))
958 return procSP->ThreadGetName(tid);
959 return NULL;
960}
961
962
963nub_bool_t
964DNBThreadGetIdentifierInfo (nub_process_t pid, nub_thread_t tid, thread_identifier_info_data_t *ident_info)
965{
966 MachProcessSP procSP;
967 if (GetProcessSP (pid, procSP))
968 return procSP->GetThreadList().GetIdentifierInfo(tid, ident_info);
969 return false;
970}
971
972nub_state_t
973DNBThreadGetState (nub_process_t pid, nub_thread_t tid)
974{
975 MachProcessSP procSP;
976 if (GetProcessSP (pid, procSP))
977 {
978 return procSP->ThreadGetState(tid);
979 }
980 return eStateInvalid;
981}
982
983const char *
984DNBStateAsString(nub_state_t state)
985{
986 switch (state)
987 {
Greg Claytoneffe5c92011-05-03 22:09:39 +0000988 case eStateInvalid: return "Invalid";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000989 case eStateUnloaded: return "Unloaded";
990 case eStateAttaching: return "Attaching";
991 case eStateLaunching: return "Launching";
992 case eStateStopped: return "Stopped";
993 case eStateRunning: return "Running";
994 case eStateStepping: return "Stepping";
995 case eStateCrashed: return "Crashed";
996 case eStateDetached: return "Detached";
997 case eStateExited: return "Exited";
998 case eStateSuspended: return "Suspended";
999 }
1000 return "nub_state_t ???";
1001}
1002
Jason Molenda705b1802014-06-13 02:37:02 +00001003Genealogy::ThreadActivitySP
1004DNBGetGenealogyInfoForThread (nub_process_t pid, nub_thread_t tid, bool &timed_out)
1005{
1006 Genealogy::ThreadActivitySP thread_activity_sp;
1007 MachProcessSP procSP;
1008 if (GetProcessSP (pid, procSP))
1009 thread_activity_sp = procSP->GetGenealogyInfoForThread (tid, timed_out);
1010 return thread_activity_sp;
1011}
1012
1013Genealogy::ProcessExecutableInfoSP
1014DNBGetGenealogyImageInfo (nub_process_t pid, size_t idx)
1015{
1016 Genealogy::ProcessExecutableInfoSP image_info_sp;
1017 MachProcessSP procSP;
1018 if (GetProcessSP (pid, procSP))
1019 {
1020 image_info_sp = procSP->GetGenealogyImageInfo (idx);
1021 }
1022 return image_info_sp;
1023}
1024
1025ThreadInfo::QoS
1026DNBGetRequestedQoSForThread (nub_process_t pid, nub_thread_t tid, nub_addr_t tsd, uint64_t dti_qos_class_index)
1027{
1028 MachProcessSP procSP;
1029 if (GetProcessSP (pid, procSP))
1030 {
1031 return procSP->GetRequestedQoS (tid, tsd, dti_qos_class_index);
1032 }
1033 return ThreadInfo::QoS();
1034}
1035
1036nub_addr_t
1037DNBGetPThreadT (nub_process_t pid, nub_thread_t tid)
1038{
1039 MachProcessSP procSP;
1040 if (GetProcessSP (pid, procSP))
1041 {
1042 return procSP->GetPThreadT (tid);
1043 }
1044 return INVALID_NUB_ADDRESS;
1045}
1046
1047nub_addr_t
1048DNBGetDispatchQueueT (nub_process_t pid, nub_thread_t tid)
1049{
1050 MachProcessSP procSP;
1051 if (GetProcessSP (pid, procSP))
1052 {
1053 return procSP->GetDispatchQueueT (tid);
1054 }
1055 return INVALID_NUB_ADDRESS;
1056}
1057
1058nub_addr_t
1059DNBGetTSDAddressForThread (nub_process_t pid, nub_thread_t tid, uint64_t plo_pthread_tsd_base_address_offset, uint64_t plo_pthread_tsd_base_offset, uint64_t plo_pthread_tsd_entry_size)
1060{
1061 MachProcessSP procSP;
1062 if (GetProcessSP (pid, procSP))
1063 {
1064 return procSP->GetTSDAddressForThread (tid, plo_pthread_tsd_base_address_offset, plo_pthread_tsd_base_offset, plo_pthread_tsd_entry_size);
1065 }
1066 return INVALID_NUB_ADDRESS;
1067}
1068
Jason Molenda20ee21b2015-07-10 23:15:22 +00001069JSONGenerator::ObjectSP
1070DNBGetLoadedDynamicLibrariesInfos (nub_process_t pid, nub_addr_t image_list_address, nub_addr_t image_count)
1071{
1072 MachProcessSP procSP;
1073 if (GetProcessSP (pid, procSP))
1074 {
1075 return procSP->GetLoadedDynamicLibrariesInfos (pid, image_list_address, image_count);
1076 }
1077 return JSONGenerator::ObjectSP();
1078}
1079
1080
Jason Molenda705b1802014-06-13 02:37:02 +00001081
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082const char *
1083DNBProcessGetExecutablePath (nub_process_t pid)
1084{
1085 MachProcessSP procSP;
1086 if (GetProcessSP (pid, procSP))
1087 {
1088 return procSP->Path();
1089 }
1090 return NULL;
1091}
1092
1093nub_size_t
1094DNBProcessGetArgumentCount (nub_process_t pid)
1095{
1096 MachProcessSP procSP;
1097 if (GetProcessSP (pid, procSP))
1098 {
1099 return procSP->ArgumentCount();
1100 }
1101 return 0;
1102}
1103
1104const char *
1105DNBProcessGetArgumentAtIndex (nub_process_t pid, nub_size_t idx)
1106{
1107 MachProcessSP procSP;
1108 if (GetProcessSP (pid, procSP))
1109 {
1110 return procSP->ArgumentAtIndex (idx);
1111 }
1112 return NULL;
1113}
1114
1115
1116//----------------------------------------------------------------------
1117// Execution control
1118//----------------------------------------------------------------------
1119nub_bool_t
1120DNBProcessResume (nub_process_t pid, const DNBThreadResumeAction *actions, size_t num_actions)
1121{
1122 DNBLogThreadedIf(LOG_PROCESS, "%s(pid = %4.4x)", __FUNCTION__, pid);
1123 MachProcessSP procSP;
1124 if (GetProcessSP (pid, procSP))
1125 {
1126 DNBThreadResumeActions thread_actions (actions, num_actions);
1127
1128 // Below we add a default thread plan just in case one wasn't
1129 // provided so all threads always know what they were supposed to do
1130 if (thread_actions.IsEmpty())
1131 {
1132 // No thread plans were given, so the default it to run all threads
1133 thread_actions.SetDefaultThreadActionIfNeeded (eStateRunning, 0);
1134 }
1135 else
1136 {
1137 // Some thread plans were given which means anything that wasn't
1138 // specified should remain stopped.
1139 thread_actions.SetDefaultThreadActionIfNeeded (eStateStopped, 0);
1140 }
1141 return procSP->Resume (thread_actions);
1142 }
1143 return false;
1144}
1145
1146nub_bool_t
1147DNBProcessHalt (nub_process_t pid)
1148{
1149 DNBLogThreadedIf(LOG_PROCESS, "%s(pid = %4.4x)", __FUNCTION__, pid);
1150 MachProcessSP procSP;
1151 if (GetProcessSP (pid, procSP))
1152 return procSP->Signal (SIGSTOP);
1153 return false;
1154}
1155//
1156//nub_bool_t
1157//DNBThreadResume (nub_process_t pid, nub_thread_t tid, nub_bool_t step)
1158//{
1159// DNBLogThreadedIf(LOG_THREAD, "%s(pid = %4.4x, tid = %4.4x, step = %u)", __FUNCTION__, pid, tid, (uint32_t)step);
1160// MachProcessSP procSP;
1161// if (GetProcessSP (pid, procSP))
1162// {
1163// return procSP->Resume(tid, step, 0);
1164// }
1165// return false;
1166//}
1167//
1168//nub_bool_t
1169//DNBThreadResumeWithSignal (nub_process_t pid, nub_thread_t tid, nub_bool_t step, int signal)
1170//{
1171// DNBLogThreadedIf(LOG_THREAD, "%s(pid = %4.4x, tid = %4.4x, step = %u, signal = %i)", __FUNCTION__, pid, tid, (uint32_t)step, signal);
1172// MachProcessSP procSP;
1173// if (GetProcessSP (pid, procSP))
1174// {
1175// return procSP->Resume(tid, step, signal);
1176// }
1177// return false;
1178//}
1179
1180nub_event_t
1181DNBProcessWaitForEvents (nub_process_t pid, nub_event_t event_mask, bool wait_for_set, struct timespec* timeout)
1182{
1183 nub_event_t result = 0;
1184 MachProcessSP procSP;
1185 if (GetProcessSP (pid, procSP))
1186 {
1187 if (wait_for_set)
1188 result = procSP->Events().WaitForSetEvents(event_mask, timeout);
1189 else
1190 result = procSP->Events().WaitForEventsToReset(event_mask, timeout);
1191 }
1192 return result;
1193}
1194
1195void
1196DNBProcessResetEvents (nub_process_t pid, nub_event_t event_mask)
1197{
1198 MachProcessSP procSP;
1199 if (GetProcessSP (pid, procSP))
1200 procSP->Events().ResetEvents(event_mask);
1201}
1202
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001203// Breakpoints
Greg Claytond8cf1a12013-06-12 00:46:38 +00001204nub_bool_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001205DNBBreakpointSet (nub_process_t pid, nub_addr_t addr, nub_size_t size, nub_bool_t hardware)
1206{
1207 MachProcessSP procSP;
1208 if (GetProcessSP (pid, procSP))
Greg Claytond8cf1a12013-06-12 00:46:38 +00001209 return procSP->CreateBreakpoint(addr, size, hardware) != NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001210 return false;
1211}
1212
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001213nub_bool_t
Greg Claytond8cf1a12013-06-12 00:46:38 +00001214DNBBreakpointClear (nub_process_t pid, nub_addr_t addr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001215{
1216 MachProcessSP procSP;
1217 if (GetProcessSP (pid, procSP))
Greg Claytond8cf1a12013-06-12 00:46:38 +00001218 return procSP->DisableBreakpoint(addr, true);
1219 return false; // Failed
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001220}
1221
Greg Claytond8cf1a12013-06-12 00:46:38 +00001222
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001223//----------------------------------------------------------------------
1224// Watchpoints
1225//----------------------------------------------------------------------
Greg Claytond8cf1a12013-06-12 00:46:38 +00001226nub_bool_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001227DNBWatchpointSet (nub_process_t pid, nub_addr_t addr, nub_size_t size, uint32_t watch_flags, nub_bool_t hardware)
1228{
1229 MachProcessSP procSP;
1230 if (GetProcessSP (pid, procSP))
Greg Claytond8cf1a12013-06-12 00:46:38 +00001231 return procSP->CreateWatchpoint(addr, size, watch_flags, hardware) != NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001232 return false;
1233}
1234
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235nub_bool_t
Greg Claytond8cf1a12013-06-12 00:46:38 +00001236DNBWatchpointClear (nub_process_t pid, nub_addr_t addr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001237{
1238 MachProcessSP procSP;
1239 if (GetProcessSP (pid, procSP))
Greg Claytond8cf1a12013-06-12 00:46:38 +00001240 return procSP->DisableWatchpoint(addr, true);
1241 return false; // Failed
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001242}
1243
1244//----------------------------------------------------------------------
Johnny Chen64637202012-05-23 21:09:52 +00001245// Return the number of supported hardware watchpoints.
1246//----------------------------------------------------------------------
1247uint32_t
1248DNBWatchpointGetNumSupportedHWP (nub_process_t pid)
1249{
1250 MachProcessSP procSP;
1251 if (GetProcessSP (pid, procSP))
1252 return procSP->GetNumSupportedHardwareWatchpoints();
1253 return 0;
1254}
1255
1256//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001257// Read memory in the address space of process PID. This call will take
1258// care of setting and restoring permissions and breaking up the memory
1259// read into multiple chunks as required.
1260//
1261// RETURNS: number of bytes actually read
1262//----------------------------------------------------------------------
1263nub_size_t
1264DNBProcessMemoryRead (nub_process_t pid, nub_addr_t addr, nub_size_t size, void *buf)
1265{
1266 MachProcessSP procSP;
1267 if (GetProcessSP (pid, procSP))
1268 return procSP->ReadMemory(addr, size, buf);
1269 return 0;
1270}
1271
Greg Clayton0b90be12015-06-23 21:27:50 +00001272uint64_t
1273DNBProcessMemoryReadInteger (nub_process_t pid, nub_addr_t addr, nub_size_t integer_size, uint64_t fail_value)
1274{
1275 union Integers
1276 {
1277 uint8_t u8;
1278 uint16_t u16;
1279 uint32_t u32;
1280 uint64_t u64;
1281 };
1282
1283 if (integer_size <= sizeof(uint64_t))
1284 {
1285 Integers ints;
1286 if (DNBProcessMemoryRead(pid, addr, integer_size, &ints) == integer_size)
1287 {
1288 switch (integer_size)
1289 {
1290 case 1: return ints.u8;
1291 case 2: return ints.u16;
1292 case 3: return ints.u32 & 0xffffffu;
1293 case 4: return ints.u32;
1294 case 5: return ints.u32 & 0x000000ffffffffffull;
1295 case 6: return ints.u32 & 0x0000ffffffffffffull;
1296 case 7: return ints.u32 & 0x00ffffffffffffffull;
1297 case 8: return ints.u64;
1298 }
1299 }
1300 }
1301 return fail_value;
1302
1303}
1304
1305nub_addr_t
1306DNBProcessMemoryReadPointer (nub_process_t pid, nub_addr_t addr)
1307{
1308 cpu_type_t cputype = DNBProcessGetCPUType (pid);
1309 if (cputype)
1310 {
1311 const nub_size_t pointer_size = (cputype & CPU_ARCH_ABI64) ? 8 : 4;
1312 return DNBProcessMemoryReadInteger(pid, addr, pointer_size, 0);
1313 }
1314 return 0;
1315
1316}
1317
1318std::string
1319DNBProcessMemoryReadCString (nub_process_t pid, nub_addr_t addr)
1320{
1321 std::string cstr;
1322 char buffer[256];
1323 const nub_size_t max_buffer_cstr_length = sizeof(buffer)-1;
1324 buffer[max_buffer_cstr_length] = '\0';
1325 nub_size_t length = 0;
1326 nub_addr_t curr_addr = addr;
1327 do
1328 {
1329 nub_size_t bytes_read = DNBProcessMemoryRead(pid, curr_addr, max_buffer_cstr_length, buffer);
1330 if (bytes_read == 0)
1331 break;
1332 length = strlen(buffer);
1333 cstr.append(buffer, length);
1334 curr_addr += length;
1335 } while (length == max_buffer_cstr_length);
1336 return cstr;
1337}
1338
1339std::string
1340DNBProcessMemoryReadCStringFixed (nub_process_t pid, nub_addr_t addr, nub_size_t fixed_length)
1341{
1342 std::string cstr;
1343 char buffer[fixed_length+1];
1344 buffer[fixed_length] = '\0';
1345 nub_size_t bytes_read = DNBProcessMemoryRead(pid, addr, fixed_length, buffer);
1346 if (bytes_read > 0)
1347 cstr.assign(buffer);
1348 return cstr;
1349}
1350
1351
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001352//----------------------------------------------------------------------
1353// Write memory to the address space of process PID. This call will take
1354// care of setting and restoring permissions and breaking up the memory
1355// write into multiple chunks as required.
1356//
1357// RETURNS: number of bytes actually written
1358//----------------------------------------------------------------------
1359nub_size_t
1360DNBProcessMemoryWrite (nub_process_t pid, nub_addr_t addr, nub_size_t size, const void *buf)
1361{
1362 MachProcessSP procSP;
1363 if (GetProcessSP (pid, procSP))
1364 return procSP->WriteMemory(addr, size, buf);
1365 return 0;
1366}
1367
1368nub_addr_t
1369DNBProcessMemoryAllocate (nub_process_t pid, nub_size_t size, uint32_t permissions)
1370{
1371 MachProcessSP procSP;
1372 if (GetProcessSP (pid, procSP))
1373 return procSP->Task().AllocateMemory (size, permissions);
1374 return 0;
1375}
1376
1377nub_bool_t
1378DNBProcessMemoryDeallocate (nub_process_t pid, nub_addr_t addr)
1379{
1380 MachProcessSP procSP;
1381 if (GetProcessSP (pid, procSP))
1382 return procSP->Task().DeallocateMemory (addr);
1383 return 0;
1384}
1385
Jason Molenda1f3966b2011-11-08 04:28:12 +00001386//----------------------------------------------------------------------
Jason Molenda3dc85832011-11-09 08:03:56 +00001387// Find attributes of the memory region that contains ADDR for process PID,
1388// if possible, and return a string describing those attributes.
Jason Molenda1f3966b2011-11-08 04:28:12 +00001389//
Jason Molenda3dc85832011-11-09 08:03:56 +00001390// Returns 1 if we could find attributes for this region and OUTBUF can
1391// be sent to the remote debugger.
Jason Molenda1f3966b2011-11-08 04:28:12 +00001392//
Jason Molenda3dc85832011-11-09 08:03:56 +00001393// Returns 0 if we couldn't find the attributes for a region of memory at
1394// that address and OUTBUF should not be sent.
1395//
1396// Returns -1 if this platform cannot look up information about memory regions
1397// or if we do not yet have a valid launched process.
1398//
Jason Molenda1f3966b2011-11-08 04:28:12 +00001399//----------------------------------------------------------------------
1400int
Greg Claytonfc5dd292011-12-12 18:51:14 +00001401DNBProcessMemoryRegionInfo (nub_process_t pid, nub_addr_t addr, DNBRegionInfo *region_info)
Jason Molenda1f3966b2011-11-08 04:28:12 +00001402{
1403 MachProcessSP procSP;
1404 if (GetProcessSP (pid, procSP))
Greg Clayton46fb5582011-11-18 07:03:08 +00001405 return procSP->Task().GetMemoryRegionInfo (addr, region_info);
1406
Jason Molenda1f3966b2011-11-08 04:28:12 +00001407 return -1;
1408}
1409
Han Ming Ong929a94f2012-11-29 22:14:45 +00001410std::string
Han Ming Ong8764fe72013-03-04 21:25:51 +00001411DNBProcessGetProfileData (nub_process_t pid, DNBProfileDataScanType scanType)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001412{
1413 MachProcessSP procSP;
1414 if (GetProcessSP (pid, procSP))
Han Ming Ong8764fe72013-03-04 21:25:51 +00001415 return procSP->Task().GetProfileData(scanType);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001416
Han Ming Ong929a94f2012-11-29 22:14:45 +00001417 return std::string("");
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001418}
1419
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001420nub_bool_t
Han Ming Ong8764fe72013-03-04 21:25:51 +00001421DNBProcessSetEnableAsyncProfiling (nub_process_t pid, nub_bool_t enable, uint64_t interval_usec, DNBProfileDataScanType scan_type)
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001422{
1423 MachProcessSP procSP;
1424 if (GetProcessSP (pid, procSP))
1425 {
Han Ming Ong8764fe72013-03-04 21:25:51 +00001426 procSP->SetEnableAsyncProfiling(enable, interval_usec, scan_type);
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001427 return true;
1428 }
1429
1430 return false;
1431}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001432
1433//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001434// Get the number of threads for the specified process.
1435//----------------------------------------------------------------------
1436nub_size_t
1437DNBProcessGetNumThreads (nub_process_t pid)
1438{
1439 MachProcessSP procSP;
1440 if (GetProcessSP (pid, procSP))
1441 return procSP->GetNumThreads();
1442 return 0;
1443}
1444
1445//----------------------------------------------------------------------
1446// Get the thread ID of the current thread.
1447//----------------------------------------------------------------------
1448nub_thread_t
1449DNBProcessGetCurrentThread (nub_process_t pid)
1450{
1451 MachProcessSP procSP;
1452 if (GetProcessSP (pid, procSP))
1453 return procSP->GetCurrentThread();
1454 return 0;
1455}
1456
1457//----------------------------------------------------------------------
Jason Molendad5318c02013-04-03 04:18:47 +00001458// Get the mach port number of the current thread.
1459//----------------------------------------------------------------------
1460nub_thread_t
1461DNBProcessGetCurrentThreadMachPort (nub_process_t pid)
1462{
1463 MachProcessSP procSP;
1464 if (GetProcessSP (pid, procSP))
1465 return procSP->GetCurrentThreadMachPort();
1466 return 0;
1467}
1468
1469//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470// Change the current thread.
1471//----------------------------------------------------------------------
1472nub_thread_t
1473DNBProcessSetCurrentThread (nub_process_t pid, nub_thread_t tid)
1474{
1475 MachProcessSP procSP;
1476 if (GetProcessSP (pid, procSP))
1477 return procSP->SetCurrentThread (tid);
1478 return INVALID_NUB_THREAD;
1479}
1480
1481
1482//----------------------------------------------------------------------
1483// Dump a string describing a thread's stop reason to the specified file
1484// handle
1485//----------------------------------------------------------------------
1486nub_bool_t
1487DNBThreadGetStopReason (nub_process_t pid, nub_thread_t tid, struct DNBThreadStopInfo *stop_info)
1488{
1489 MachProcessSP procSP;
1490 if (GetProcessSP (pid, procSP))
1491 return procSP->GetThreadStoppedReason (tid, stop_info);
1492 return false;
1493}
1494
1495//----------------------------------------------------------------------
1496// Return string description for the specified thread.
1497//
1498// RETURNS: NULL if the thread isn't valid, else a NULL terminated C
1499// string from a static buffer that must be copied prior to subsequent
1500// calls.
1501//----------------------------------------------------------------------
1502const char *
1503DNBThreadGetInfo (nub_process_t pid, nub_thread_t tid)
1504{
1505 MachProcessSP procSP;
1506 if (GetProcessSP (pid, procSP))
1507 return procSP->GetThreadInfo (tid);
1508 return NULL;
1509}
1510
1511//----------------------------------------------------------------------
1512// Get the thread ID given a thread index.
1513//----------------------------------------------------------------------
1514nub_thread_t
1515DNBProcessGetThreadAtIndex (nub_process_t pid, size_t thread_idx)
1516{
1517 MachProcessSP procSP;
1518 if (GetProcessSP (pid, procSP))
1519 return procSP->GetThreadAtIndex (thread_idx);
1520 return INVALID_NUB_THREAD;
1521}
1522
Jim Ingham279ceec2012-07-25 21:12:43 +00001523//----------------------------------------------------------------------
1524// Do whatever is needed to sync the thread's register state with it's kernel values.
1525//----------------------------------------------------------------------
1526nub_bool_t
1527DNBProcessSyncThreadState (nub_process_t pid, nub_thread_t tid)
1528{
1529 MachProcessSP procSP;
1530 if (GetProcessSP (pid, procSP))
1531 return procSP->SyncThreadState (tid);
1532 return false;
1533
1534}
1535
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001536nub_addr_t
1537DNBProcessGetSharedLibraryInfoAddress (nub_process_t pid)
1538{
1539 MachProcessSP procSP;
1540 DNBError err;
1541 if (GetProcessSP (pid, procSP))
1542 return procSP->Task().GetDYLDAllImageInfosAddress (err);
1543 return INVALID_NUB_ADDRESS;
1544}
1545
1546
1547nub_bool_t
1548DNBProcessSharedLibrariesUpdated(nub_process_t pid)
1549{
1550 MachProcessSP procSP;
1551 if (GetProcessSP (pid, procSP))
1552 {
1553 procSP->SharedLibrariesUpdated ();
1554 return true;
1555 }
1556 return false;
1557}
1558
1559//----------------------------------------------------------------------
1560// Get the current shared library information for a process. Only return
1561// the shared libraries that have changed since the last shared library
1562// state changed event if only_changed is non-zero.
1563//----------------------------------------------------------------------
1564nub_size_t
1565DNBProcessGetSharedLibraryInfo (nub_process_t pid, nub_bool_t only_changed, struct DNBExecutableImageInfo **image_infos)
1566{
1567 MachProcessSP procSP;
1568 if (GetProcessSP (pid, procSP))
1569 return procSP->CopyImageInfos (image_infos, only_changed);
1570
1571 // If we have no process, then return NULL for the shared library info
1572 // and zero for shared library count
1573 *image_infos = NULL;
1574 return 0;
1575}
1576
Greg Claytond04f0ed2015-05-26 18:00:51 +00001577uint32_t
1578DNBGetRegisterCPUType()
1579{
1580 return DNBArchProtocol::GetRegisterCPUType ();
1581
1582}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001583//----------------------------------------------------------------------
1584// Get the register set information for a specific thread.
1585//----------------------------------------------------------------------
1586const DNBRegisterSetInfo *
1587DNBGetRegisterSetInfo (nub_size_t *num_reg_sets)
1588{
Greg Clayton3af9ea52010-11-18 05:57:03 +00001589 return DNBArchProtocol::GetRegisterSetInfo (num_reg_sets);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001590}
1591
1592
1593//----------------------------------------------------------------------
1594// Read a register value by register set and register index.
1595//----------------------------------------------------------------------
1596nub_bool_t
1597DNBThreadGetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value)
1598{
1599 MachProcessSP procSP;
1600 ::bzero (value, sizeof(DNBRegisterValue));
1601 if (GetProcessSP (pid, procSP))
1602 {
1603 if (tid != INVALID_NUB_THREAD)
1604 return procSP->GetRegisterValue (tid, set, reg, value);
1605 }
1606 return false;
1607}
1608
1609nub_bool_t
1610DNBThreadSetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value)
1611{
1612 if (tid != INVALID_NUB_THREAD)
1613 {
1614 MachProcessSP procSP;
1615 if (GetProcessSP (pid, procSP))
1616 return procSP->SetRegisterValue (tid, set, reg, value);
1617 }
1618 return false;
1619}
1620
1621nub_size_t
1622DNBThreadGetRegisterContext (nub_process_t pid, nub_thread_t tid, void *buf, size_t buf_len)
1623{
1624 MachProcessSP procSP;
1625 if (GetProcessSP (pid, procSP))
1626 {
1627 if (tid != INVALID_NUB_THREAD)
1628 return procSP->GetThreadList().GetRegisterContext (tid, buf, buf_len);
1629 }
1630 ::bzero (buf, buf_len);
1631 return 0;
1632
1633}
1634
1635nub_size_t
1636DNBThreadSetRegisterContext (nub_process_t pid, nub_thread_t tid, const void *buf, size_t buf_len)
1637{
1638 MachProcessSP procSP;
1639 if (GetProcessSP (pid, procSP))
1640 {
1641 if (tid != INVALID_NUB_THREAD)
1642 return procSP->GetThreadList().SetRegisterContext (tid, buf, buf_len);
1643 }
1644 return 0;
1645}
1646
Greg Claytonf74cf862013-11-13 23:28:31 +00001647uint32_t
1648DNBThreadSaveRegisterState (nub_process_t pid, nub_thread_t tid)
1649{
1650 if (tid != INVALID_NUB_THREAD)
1651 {
1652 MachProcessSP procSP;
1653 if (GetProcessSP (pid, procSP))
1654 return procSP->GetThreadList().SaveRegisterState (tid);
1655 }
1656 return 0;
1657}
1658nub_bool_t
1659DNBThreadRestoreRegisterState (nub_process_t pid, nub_thread_t tid, uint32_t save_id)
1660{
1661 if (tid != INVALID_NUB_THREAD)
1662 {
1663 MachProcessSP procSP;
1664 if (GetProcessSP (pid, procSP))
1665 return procSP->GetThreadList().RestoreRegisterState (tid, save_id);
1666 }
1667 return false;
1668}
1669
1670
1671
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001672//----------------------------------------------------------------------
1673// Read a register value by name.
1674//----------------------------------------------------------------------
1675nub_bool_t
1676DNBThreadGetRegisterValueByName (nub_process_t pid, nub_thread_t tid, uint32_t reg_set, const char *reg_name, DNBRegisterValue *value)
1677{
1678 MachProcessSP procSP;
1679 ::bzero (value, sizeof(DNBRegisterValue));
1680 if (GetProcessSP (pid, procSP))
1681 {
1682 const struct DNBRegisterSetInfo *set_info;
1683 nub_size_t num_reg_sets = 0;
1684 set_info = DNBGetRegisterSetInfo (&num_reg_sets);
1685 if (set_info)
1686 {
1687 uint32_t set = reg_set;
1688 uint32_t reg;
1689 if (set == REGISTER_SET_ALL)
1690 {
1691 for (set = 1; set < num_reg_sets; ++set)
1692 {
1693 for (reg = 0; reg < set_info[set].num_registers; ++reg)
1694 {
1695 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1696 return procSP->GetRegisterValue (tid, set, reg, value);
1697 }
1698 }
1699 }
1700 else
1701 {
1702 for (reg = 0; reg < set_info[set].num_registers; ++reg)
1703 {
1704 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1705 return procSP->GetRegisterValue (tid, set, reg, value);
1706 }
1707 }
1708 }
1709 }
1710 return false;
1711}
1712
1713
1714//----------------------------------------------------------------------
1715// Read a register set and register number from the register name.
1716//----------------------------------------------------------------------
1717nub_bool_t
1718DNBGetRegisterInfoByName (const char *reg_name, DNBRegisterInfo* info)
1719{
1720 const struct DNBRegisterSetInfo *set_info;
1721 nub_size_t num_reg_sets = 0;
1722 set_info = DNBGetRegisterSetInfo (&num_reg_sets);
1723 if (set_info)
1724 {
1725 uint32_t set, reg;
1726 for (set = 1; set < num_reg_sets; ++set)
1727 {
1728 for (reg = 0; reg < set_info[set].num_registers; ++reg)
1729 {
1730 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1731 {
1732 *info = set_info[set].registers[reg];
1733 return true;
1734 }
1735 }
1736 }
1737
1738 for (set = 1; set < num_reg_sets; ++set)
1739 {
1740 uint32_t reg;
1741 for (reg = 0; reg < set_info[set].num_registers; ++reg)
1742 {
1743 if (set_info[set].registers[reg].alt == NULL)
1744 continue;
1745
1746 if (strcasecmp(reg_name, set_info[set].registers[reg].alt) == 0)
1747 {
1748 *info = set_info[set].registers[reg];
1749 return true;
1750 }
1751 }
1752 }
1753 }
1754
1755 ::bzero (info, sizeof(DNBRegisterInfo));
1756 return false;
1757}
1758
1759
1760//----------------------------------------------------------------------
1761// Set the name to address callback function that this nub can use
1762// for any name to address lookups that are needed.
1763//----------------------------------------------------------------------
1764nub_bool_t
1765DNBProcessSetNameToAddressCallback (nub_process_t pid, DNBCallbackNameToAddress callback, void *baton)
1766{
1767 MachProcessSP procSP;
1768 if (GetProcessSP (pid, procSP))
1769 {
1770 procSP->SetNameToAddressCallback (callback, baton);
1771 return true;
1772 }
1773 return false;
1774}
1775
1776
1777//----------------------------------------------------------------------
1778// Set the name to address callback function that this nub can use
1779// for any name to address lookups that are needed.
1780//----------------------------------------------------------------------
1781nub_bool_t
1782DNBProcessSetSharedLibraryInfoCallback (nub_process_t pid, DNBCallbackCopyExecutableImageInfos callback, void *baton)
1783{
1784 MachProcessSP procSP;
1785 if (GetProcessSP (pid, procSP))
1786 {
1787 procSP->SetSharedLibraryInfoCallback (callback, baton);
1788 return true;
1789 }
1790 return false;
1791}
1792
1793nub_addr_t
1794DNBProcessLookupAddress (nub_process_t pid, const char *name, const char *shlib)
1795{
1796 MachProcessSP procSP;
1797 if (GetProcessSP (pid, procSP))
1798 {
1799 return procSP->LookupSymbol (name, shlib);
1800 }
1801 return INVALID_NUB_ADDRESS;
1802}
1803
1804
1805nub_size_t
1806DNBProcessGetAvailableSTDOUT (nub_process_t pid, char *buf, nub_size_t buf_size)
1807{
1808 MachProcessSP procSP;
1809 if (GetProcessSP (pid, procSP))
1810 return procSP->GetAvailableSTDOUT (buf, buf_size);
1811 return 0;
1812}
1813
1814nub_size_t
1815DNBProcessGetAvailableSTDERR (nub_process_t pid, char *buf, nub_size_t buf_size)
1816{
1817 MachProcessSP procSP;
1818 if (GetProcessSP (pid, procSP))
1819 return procSP->GetAvailableSTDERR (buf, buf_size);
1820 return 0;
1821}
1822
1823nub_size_t
Han Ming Ongab3b8b22012-11-17 00:21:04 +00001824DNBProcessGetAvailableProfileData (nub_process_t pid, char *buf, nub_size_t buf_size)
1825{
1826 MachProcessSP procSP;
1827 if (GetProcessSP (pid, procSP))
1828 return procSP->GetAsyncProfileData (buf, buf_size);
1829 return 0;
1830}
1831
1832nub_size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001833DNBProcessGetStopCount (nub_process_t pid)
1834{
1835 MachProcessSP procSP;
1836 if (GetProcessSP (pid, procSP))
1837 return procSP->StopCount();
1838 return 0;
1839}
1840
Greg Clayton71337622011-02-24 22:24:29 +00001841uint32_t
1842DNBProcessGetCPUType (nub_process_t pid)
1843{
1844 MachProcessSP procSP;
1845 if (GetProcessSP (pid, procSP))
1846 return procSP->GetCPUType ();
1847 return 0;
1848
1849}
1850
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001851nub_bool_t
1852DNBResolveExecutablePath (const char *path, char *resolved_path, size_t resolved_path_size)
1853{
1854 if (path == NULL || path[0] == '\0')
1855 return false;
1856
1857 char max_path[PATH_MAX];
1858 std::string result;
1859 CFString::GlobPath(path, result);
1860
1861 if (result.empty())
1862 result = path;
Greg Clayton48baf7a2012-10-31 21:44:39 +00001863
1864 struct stat path_stat;
1865 if (::stat(path, &path_stat) == 0)
1866 {
1867 if ((path_stat.st_mode & S_IFMT) == S_IFDIR)
1868 {
1869 CFBundle bundle (path);
1870 CFReleaser<CFURLRef> url(bundle.CopyExecutableURL ());
1871 if (url.get())
1872 {
1873 if (::CFURLGetFileSystemRepresentation (url.get(), true, (UInt8*)resolved_path, resolved_path_size))
1874 return true;
1875 }
1876 }
1877 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001878
1879 if (realpath(path, max_path))
1880 {
1881 // Found the path relatively...
1882 ::strncpy(resolved_path, max_path, resolved_path_size);
1883 return strlen(resolved_path) + 1 < resolved_path_size;
1884 }
1885 else
1886 {
1887 // Not a relative path, check the PATH environment variable if the
1888 const char *PATH = getenv("PATH");
1889 if (PATH)
1890 {
1891 const char *curr_path_start = PATH;
1892 const char *curr_path_end;
1893 while (curr_path_start && *curr_path_start)
1894 {
1895 curr_path_end = strchr(curr_path_start, ':');
1896 if (curr_path_end == NULL)
1897 {
1898 result.assign(curr_path_start);
1899 curr_path_start = NULL;
1900 }
1901 else if (curr_path_end > curr_path_start)
1902 {
1903 size_t len = curr_path_end - curr_path_start;
1904 result.assign(curr_path_start, len);
1905 curr_path_start += len + 1;
1906 }
1907 else
1908 break;
1909
1910 result += '/';
1911 result += path;
1912 struct stat s;
1913 if (stat(result.c_str(), &s) == 0)
1914 {
1915 ::strncpy(resolved_path, result.c_str(), resolved_path_size);
1916 return result.size() + 1 < resolved_path_size;
1917 }
1918 }
1919 }
1920 }
1921 return false;
1922}
1923
Greg Clayton3af9ea52010-11-18 05:57:03 +00001924
1925void
1926DNBInitialize()
1927{
1928 DNBLogThreadedIf (LOG_PROCESS, "DNBInitialize ()");
1929#if defined (__i386__) || defined (__x86_64__)
1930 DNBArchImplI386::Initialize();
1931 DNBArchImplX86_64::Initialize();
Todd Fiala013434e2014-07-09 01:29:05 +00001932#elif defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001933 DNBArchMachARM::Initialize();
Jason Molendaa3329782014-03-29 18:54:20 +00001934 DNBArchMachARM64::Initialize();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001935#endif
1936}
1937
1938void
1939DNBTerminate()
1940{
1941}
Greg Clayton3c144382010-12-01 22:45:40 +00001942
1943nub_bool_t
1944DNBSetArchitecture (const char *arch)
1945{
1946 if (arch && arch[0])
1947 {
1948 if (strcasecmp (arch, "i386") == 0)
1949 return DNBArchProtocol::SetArchitecture (CPU_TYPE_I386);
Greg Claytona86dc432014-01-22 23:42:03 +00001950 else if ((strcasecmp (arch, "x86_64") == 0) || (strcasecmp (arch, "x86_64h") == 0))
Greg Clayton3c144382010-12-01 22:45:40 +00001951 return DNBArchProtocol::SetArchitecture (CPU_TYPE_X86_64);
Todd Fiala013434e2014-07-09 01:29:05 +00001952 else if (strstr (arch, "arm64") == arch || strstr (arch, "armv8") == arch || strstr (arch, "aarch64") == arch)
Jason Molendaa3329782014-03-29 18:54:20 +00001953 return DNBArchProtocol::SetArchitecture (CPU_TYPE_ARM64);
Greg Clayton3c144382010-12-01 22:45:40 +00001954 else if (strstr (arch, "arm") == arch)
1955 return DNBArchProtocol::SetArchitecture (CPU_TYPE_ARM);
1956 }
1957 return false;
1958}