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