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