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