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 // Read memory in the address space of process PID. This call will take
1085 // care of setting and restoring permissions and breaking up the memory
1086 // read into multiple chunks as required.
1087 //
1088 // RETURNS: number of bytes actually read
1089 //----------------------------------------------------------------------
1090 nub_size_t
1091 DNBProcessMemoryRead (nub_process_t pid, nub_addr_t addr, nub_size_t size, void *buf)
1092 {
1093     MachProcessSP procSP;
1094     if (GetProcessSP (pid, procSP))
1095         return procSP->ReadMemory(addr, size, buf);
1096     return 0;
1097 }
1098 
1099 //----------------------------------------------------------------------
1100 // Write memory to the address space of process PID. This call will take
1101 // care of setting and restoring permissions and breaking up the memory
1102 // write into multiple chunks as required.
1103 //
1104 // RETURNS: number of bytes actually written
1105 //----------------------------------------------------------------------
1106 nub_size_t
1107 DNBProcessMemoryWrite (nub_process_t pid, nub_addr_t addr, nub_size_t size, const void *buf)
1108 {
1109     MachProcessSP procSP;
1110     if (GetProcessSP (pid, procSP))
1111         return procSP->WriteMemory(addr, size, buf);
1112     return 0;
1113 }
1114 
1115 nub_addr_t
1116 DNBProcessMemoryAllocate (nub_process_t pid, nub_size_t size, uint32_t permissions)
1117 {
1118     MachProcessSP procSP;
1119     if (GetProcessSP (pid, procSP))
1120         return procSP->Task().AllocateMemory (size, permissions);
1121     return 0;
1122 }
1123 
1124 nub_bool_t
1125 DNBProcessMemoryDeallocate (nub_process_t pid, nub_addr_t addr)
1126 {
1127     MachProcessSP procSP;
1128     if (GetProcessSP (pid, procSP))
1129         return procSP->Task().DeallocateMemory (addr);
1130     return 0;
1131 }
1132 
1133 //----------------------------------------------------------------------
1134 // Find attributes of the memory region that contains ADDR for process PID,
1135 // if possible, and return a string describing those attributes.
1136 //
1137 // Returns 1 if we could find attributes for this region and OUTBUF can
1138 // be sent to the remote debugger.
1139 //
1140 // Returns 0 if we couldn't find the attributes for a region of memory at
1141 // that address and OUTBUF should not be sent.
1142 //
1143 // Returns -1 if this platform cannot look up information about memory regions
1144 // or if we do not yet have a valid launched process.
1145 //
1146 //----------------------------------------------------------------------
1147 int
1148 DNBProcessMemoryRegionInfo (nub_process_t pid, nub_addr_t addr, DNBRegionInfo *region_info)
1149 {
1150     MachProcessSP procSP;
1151     if (GetProcessSP (pid, procSP))
1152         return procSP->Task().GetMemoryRegionInfo (addr, region_info);
1153 
1154     return -1;
1155 }
1156 
1157 
1158 //----------------------------------------------------------------------
1159 // Formatted output that uses memory and registers from process and
1160 // thread in place of arguments.
1161 //----------------------------------------------------------------------
1162 nub_size_t
1163 DNBPrintf (nub_process_t pid, nub_thread_t tid, nub_addr_t base_addr, FILE *file, const char *format)
1164 {
1165     if (file == NULL)
1166         return 0;
1167     enum printf_flags
1168     {
1169         alternate_form          = (1 << 0),
1170         zero_padding            = (1 << 1),
1171         negative_field_width    = (1 << 2),
1172         blank_space             = (1 << 3),
1173         show_sign               = (1 << 4),
1174         show_thousands_separator= (1 << 5),
1175     };
1176 
1177     enum printf_length_modifiers
1178     {
1179         length_mod_h            = (1 << 0),
1180         length_mod_hh           = (1 << 1),
1181         length_mod_l            = (1 << 2),
1182         length_mod_ll           = (1 << 3),
1183         length_mod_L            = (1 << 4),
1184         length_mod_j            = (1 << 5),
1185         length_mod_t            = (1 << 6),
1186         length_mod_z            = (1 << 7),
1187         length_mod_q            = (1 << 8),
1188     };
1189 
1190     nub_addr_t addr = base_addr;
1191     char *end_format = (char*)format + strlen(format);
1192     char *end = NULL;    // For strtoXXXX calls;
1193     std::basic_string<uint8_t> buf;
1194     nub_size_t total_bytes_read = 0;
1195     DNBDataRef data;
1196     const char *f;
1197     for (f = format; *f != '\0' && f < end_format; f++)
1198     {
1199         char ch = *f;
1200         switch (ch)
1201         {
1202         case '%':
1203             {
1204                 f++;    // Skip the '%' character
1205                 int min_field_width = 0;
1206                 int precision = 0;
1207                 uint32_t flags = 0;
1208                 uint32_t length_modifiers = 0;
1209                 uint32_t byte_size = 0;
1210                 uint32_t actual_byte_size = 0;
1211                 bool is_string = false;
1212                 bool is_register = false;
1213                 DNBRegisterValue register_value;
1214                 int64_t    register_offset = 0;
1215                 nub_addr_t register_addr = INVALID_NUB_ADDRESS;
1216 
1217                 // Create the format string to use for this conversion specification
1218                 // so we can remove and mprintf specific flags and formatters.
1219                 std::string fprintf_format("%");
1220 
1221                 // Decode any flags
1222                 switch (*f)
1223                 {
1224                 case '#': fprintf_format += *f++; flags |= alternate_form;            break;
1225                 case '0': fprintf_format += *f++; flags |= zero_padding;            break;
1226                 case '-': fprintf_format += *f++; flags |= negative_field_width;    break;
1227                 case ' ': fprintf_format += *f++; flags |= blank_space;                break;
1228                 case '+': fprintf_format += *f++; flags |= show_sign;                break;
1229                 case ',': fprintf_format += *f++; flags |= show_thousands_separator;break;
1230                 case '{':
1231                 case '[':
1232                     {
1233                         // We have a register name specification that can take two forms:
1234                         // ${regname} or ${regname+offset}
1235                         //        The action is to read the register value and add the signed offset
1236                         //        (if any) and use that as the value to format.
1237                         // $[regname] or $[regname+offset]
1238                         //        The action is to read the register value and add the signed offset
1239                         //        (if any) and use the result as an address to dereference. The size
1240                         //        of what is dereferenced is specified by the actual byte size that
1241                         //        follows the minimum field width and precision (see comments below).
1242                         switch (*f)
1243                         {
1244                         case '{':
1245                         case '[':
1246                             {
1247                                 char open_scope_ch = *f;
1248                                 f++;
1249                                 const char *reg_name = f;
1250                                 size_t reg_name_length = strcspn(f, "+-}]");
1251                                 if (reg_name_length > 0)
1252                                 {
1253                                     std::string register_name(reg_name, reg_name_length);
1254                                     f += reg_name_length;
1255                                     register_offset = strtoll(f, &end, 0);
1256                                     if (f < end)
1257                                         f = end;
1258                                     if ((open_scope_ch == '{' && *f != '}') || (open_scope_ch == '[' && *f != ']'))
1259                                     {
1260                                         fprintf(file, "error: Invalid register format string. Valid formats are %%{regname} or %%{regname+offset}, %%[regname] or %%[regname+offset]\n");
1261                                         return total_bytes_read;
1262                                     }
1263                                     else
1264                                     {
1265                                         f++;
1266                                         if (DNBThreadGetRegisterValueByName(pid, tid, REGISTER_SET_ALL, register_name.c_str(), &register_value))
1267                                         {
1268                                             // Set the address to dereference using the register value plus the offset
1269                                             switch (register_value.info.size)
1270                                             {
1271                                             default:
1272                                             case 0:
1273                                                 fprintf (file, "error: unsupported register size of %u.\n", register_value.info.size);
1274                                                 return total_bytes_read;
1275 
1276                                             case 1:        register_addr = register_value.value.uint8  + register_offset; break;
1277                                             case 2:        register_addr = register_value.value.uint16 + register_offset; break;
1278                                             case 4:        register_addr = register_value.value.uint32 + register_offset; break;
1279                                             case 8:        register_addr = register_value.value.uint64 + register_offset; break;
1280                                             case 16:
1281                                                 if (open_scope_ch == '[')
1282                                                 {
1283                                                     fprintf (file, "error: register size (%u) too large for address.\n", register_value.info.size);
1284                                                     return total_bytes_read;
1285                                                 }
1286                                                 break;
1287                                             }
1288 
1289                                             if (open_scope_ch == '{')
1290                                             {
1291                                                 byte_size = register_value.info.size;
1292                                                 is_register = true;    // value is in a register
1293 
1294                                             }
1295                                             else
1296                                             {
1297                                                 addr = register_addr;    // Use register value and offset as the address
1298                                             }
1299                                         }
1300                                         else
1301                                         {
1302                                             fprintf(file, "error: unable to read register '%s' for process %#.4x and thread %#.4x\n", register_name.c_str(), pid, tid);
1303                                             return total_bytes_read;
1304                                         }
1305                                     }
1306                                 }
1307                             }
1308                             break;
1309 
1310                         default:
1311                             fprintf(file, "error: %%$ must be followed by (regname + n) or [regname + n]\n");
1312                             return total_bytes_read;
1313                         }
1314                     }
1315                     break;
1316                 }
1317 
1318                 // Check for a minimum field width
1319                 if (isdigit(*f))
1320                 {
1321                     min_field_width = strtoul(f, &end, 10);
1322                     if (end > f)
1323                     {
1324                         fprintf_format.append(f, end - f);
1325                         f = end;
1326                     }
1327                 }
1328 
1329 
1330                 // Check for a precision
1331                 if (*f == '.')
1332                 {
1333                     f++;
1334                     if (isdigit(*f))
1335                     {
1336                         fprintf_format += '.';
1337                         precision = strtoul(f, &end, 10);
1338                         if (end > f)
1339                         {
1340                             fprintf_format.append(f, end - f);
1341                             f = end;
1342                         }
1343                     }
1344                 }
1345 
1346 
1347                 // mprintf specific: read the optional actual byte size (abs)
1348                 // after the standard minimum field width (mfw) and precision (prec).
1349                 // Standard printf calls you can have "mfw.prec" or ".prec", but
1350                 // mprintf can have "mfw.prec.abs", ".prec.abs" or "..abs". This is nice
1351                 // for strings that may be in a fixed size buffer, but may not use all bytes
1352                 // in that buffer for printable characters.
1353                 if (*f == '.')
1354                 {
1355                     f++;
1356                     actual_byte_size = strtoul(f, &end, 10);
1357                     if (end > f)
1358                     {
1359                         byte_size = actual_byte_size;
1360                         f = end;
1361                     }
1362                 }
1363 
1364                 // Decode the length modifiers
1365                 switch (*f)
1366                 {
1367                 case 'h':    // h and hh length modifiers
1368                     fprintf_format += *f++;
1369                     length_modifiers |= length_mod_h;
1370                     if (*f == 'h')
1371                     {
1372                         fprintf_format += *f++;
1373                         length_modifiers |= length_mod_hh;
1374                     }
1375                     break;
1376 
1377                 case 'l': // l and ll length modifiers
1378                     fprintf_format += *f++;
1379                     length_modifiers |= length_mod_l;
1380                     if (*f == 'h')
1381                     {
1382                         fprintf_format += *f++;
1383                         length_modifiers |= length_mod_ll;
1384                     }
1385                     break;
1386 
1387                 case 'L':    fprintf_format += *f++;    length_modifiers |= length_mod_L;    break;
1388                 case 'j':    fprintf_format += *f++;    length_modifiers |= length_mod_j;    break;
1389                 case 't':    fprintf_format += *f++;    length_modifiers |= length_mod_t;    break;
1390                 case 'z':    fprintf_format += *f++;    length_modifiers |= length_mod_z;    break;
1391                 case 'q':    fprintf_format += *f++;    length_modifiers |= length_mod_q;    break;
1392                 }
1393 
1394                 // Decode the conversion specifier
1395                 switch (*f)
1396                 {
1397                 case '_':
1398                     // mprintf specific format items
1399                     {
1400                         ++f;    // Skip the '_' character
1401                         switch (*f)
1402                         {
1403                         case 'a':    // Print the current address
1404                             ++f;
1405                             fprintf_format += "ll";
1406                             fprintf_format += *f;    // actual format to show address with folows the 'a' ("%_ax")
1407                             fprintf (file, fprintf_format.c_str(), addr);
1408                             break;
1409                         case 'o':    // offset from base address
1410                             ++f;
1411                             fprintf_format += "ll";
1412                             fprintf_format += *f;    // actual format to show address with folows the 'a' ("%_ox")
1413                             fprintf(file, fprintf_format.c_str(), addr - base_addr);
1414                             break;
1415                         default:
1416                             fprintf (file, "error: unsupported mprintf specific format character '%c'.\n", *f);
1417                             break;
1418                         }
1419                         continue;
1420                     }
1421                     break;
1422 
1423                 case 'D':
1424                 case 'O':
1425                 case 'U':
1426                     fprintf_format += *f;
1427                     if (byte_size == 0)
1428                         byte_size = sizeof(long int);
1429                     break;
1430 
1431                 case 'd':
1432                 case 'i':
1433                 case 'o':
1434                 case 'u':
1435                 case 'x':
1436                 case 'X':
1437                     fprintf_format += *f;
1438                     if (byte_size == 0)
1439                     {
1440                         if (length_modifiers & length_mod_hh)
1441                             byte_size = sizeof(char);
1442                         else if (length_modifiers & length_mod_h)
1443                             byte_size = sizeof(short);
1444                         if (length_modifiers & length_mod_ll)
1445                             byte_size = sizeof(long long);
1446                         else if (length_modifiers & length_mod_l)
1447                             byte_size = sizeof(long);
1448                         else
1449                             byte_size = sizeof(int);
1450                     }
1451                     break;
1452 
1453                 case 'a':
1454                 case 'A':
1455                 case 'f':
1456                 case 'F':
1457                 case 'e':
1458                 case 'E':
1459                 case 'g':
1460                 case 'G':
1461                     fprintf_format += *f;
1462                     if (byte_size == 0)
1463                     {
1464                         if (length_modifiers & length_mod_L)
1465                             byte_size = sizeof(long double);
1466                         else
1467                             byte_size = sizeof(double);
1468                     }
1469                     break;
1470 
1471                 case 'c':
1472                     if ((length_modifiers & length_mod_l) == 0)
1473                     {
1474                         fprintf_format += *f;
1475                         if (byte_size == 0)
1476                             byte_size = sizeof(char);
1477                         break;
1478                     }
1479                     // Fall through to 'C' modifier below...
1480 
1481                 case 'C':
1482                     fprintf_format += *f;
1483                     if (byte_size == 0)
1484                         byte_size = sizeof(wchar_t);
1485                     break;
1486 
1487                 case 's':
1488                     fprintf_format += *f;
1489                     if (is_register || byte_size == 0)
1490                         is_string = 1;
1491                     break;
1492 
1493                 case 'p':
1494                     fprintf_format += *f;
1495                     if (byte_size == 0)
1496                         byte_size = sizeof(void*);
1497                     break;
1498                 }
1499 
1500                 if (is_string)
1501                 {
1502                     std::string mem_string;
1503                     const size_t string_buf_len = 4;
1504                     char string_buf[string_buf_len+1];
1505                     char *string_buf_end = string_buf + string_buf_len;
1506                     string_buf[string_buf_len] = '\0';
1507                     nub_size_t bytes_read;
1508                     nub_addr_t str_addr = is_register ? register_addr : addr;
1509                     while ((bytes_read = DNBProcessMemoryRead(pid, str_addr, string_buf_len, &string_buf[0])) > 0)
1510                     {
1511                         // Did we get a NULL termination character yet?
1512                         if (strchr(string_buf, '\0') == string_buf_end)
1513                         {
1514                             // no NULL terminator yet, append as a std::string
1515                             mem_string.append(string_buf, string_buf_len);
1516                             str_addr += string_buf_len;
1517                         }
1518                         else
1519                         {
1520                             // yep
1521                             break;
1522                         }
1523                     }
1524                     // Append as a C-string so we don't get the extra NULL
1525                     // characters in the temp buffer (since it was resized)
1526                     mem_string += string_buf;
1527                     size_t mem_string_len = mem_string.size() + 1;
1528                     fprintf(file, fprintf_format.c_str(), mem_string.c_str());
1529                     if (mem_string_len > 0)
1530                     {
1531                         if (!is_register)
1532                         {
1533                             addr += mem_string_len;
1534                             total_bytes_read += mem_string_len;
1535                         }
1536                     }
1537                     else
1538                         return total_bytes_read;
1539                 }
1540                 else
1541                 if (byte_size > 0)
1542                 {
1543                     buf.resize(byte_size);
1544                     nub_size_t bytes_read = 0;
1545                     if (is_register)
1546                         bytes_read = register_value.info.size;
1547                     else
1548                         bytes_read = DNBProcessMemoryRead(pid, addr, buf.size(), &buf[0]);
1549                     if (bytes_read > 0)
1550                     {
1551                         if (!is_register)
1552                             total_bytes_read += bytes_read;
1553 
1554                         if (bytes_read == byte_size)
1555                         {
1556                             switch (*f)
1557                             {
1558                             case 'd':
1559                             case 'i':
1560                             case 'o':
1561                             case 'u':
1562                             case 'X':
1563                             case 'x':
1564                             case 'a':
1565                             case 'A':
1566                             case 'f':
1567                             case 'F':
1568                             case 'e':
1569                             case 'E':
1570                             case 'g':
1571                             case 'G':
1572                             case 'p':
1573                             case 'c':
1574                             case 'C':
1575                                 {
1576                                     if (is_register)
1577                                         data.SetData(&register_value.value.v_uint8[0], register_value.info.size);
1578                                     else
1579                                         data.SetData(&buf[0], bytes_read);
1580                                     DNBDataRef::offset_t data_offset = 0;
1581                                     if (byte_size <= 4)
1582                                     {
1583                                         uint32_t u32 = data.GetMax32(&data_offset, byte_size);
1584                                         // Show the actual byte width when displaying hex
1585                                         fprintf(file, fprintf_format.c_str(), u32);
1586                                     }
1587                                     else if (byte_size <= 8)
1588                                     {
1589                                         uint64_t u64 = data.GetMax64(&data_offset, byte_size);
1590                                         // Show the actual byte width when displaying hex
1591                                         fprintf(file, fprintf_format.c_str(), u64);
1592                                     }
1593                                     else
1594                                     {
1595                                         fprintf(file, "error: integer size not supported, must be 8 bytes or less (%u bytes).\n", byte_size);
1596                                     }
1597                                     if (!is_register)
1598                                         addr += byte_size;
1599                                 }
1600                                 break;
1601 
1602                             case 's':
1603                                 fprintf(file, fprintf_format.c_str(), buf.c_str());
1604                                 addr += byte_size;
1605                                 break;
1606 
1607                             default:
1608                                 fprintf(file, "error: unsupported conversion specifier '%c'.\n", *f);
1609                                 break;
1610                             }
1611                         }
1612                     }
1613                 }
1614                 else
1615                     return total_bytes_read;
1616             }
1617             break;
1618 
1619         case '\\':
1620             {
1621                 f++;
1622                 switch (*f)
1623                 {
1624                 case 'e': ch = '\e'; break;
1625                 case 'a': ch = '\a'; break;
1626                 case 'b': ch = '\b'; break;
1627                 case 'f': ch = '\f'; break;
1628                 case 'n': ch = '\n'; break;
1629                 case 'r': ch = '\r'; break;
1630                 case 't': ch = '\t'; break;
1631                 case 'v': ch = '\v'; break;
1632                 case '\'': ch = '\''; break;
1633                 case '\\': ch = '\\'; break;
1634                 case '0':
1635                 case '1':
1636                 case '2':
1637                 case '3':
1638                 case '4':
1639                 case '5':
1640                 case '6':
1641                 case '7':
1642                     ch = strtoul(f, &end, 8);
1643                     f = end;
1644                     break;
1645                 default:
1646                     ch = *f;
1647                     break;
1648                 }
1649                 fputc(ch, file);
1650             }
1651             break;
1652 
1653         default:
1654             fputc(ch, file);
1655             break;
1656         }
1657     }
1658     return total_bytes_read;
1659 }
1660 
1661 
1662 //----------------------------------------------------------------------
1663 // Get the number of threads for the specified process.
1664 //----------------------------------------------------------------------
1665 nub_size_t
1666 DNBProcessGetNumThreads (nub_process_t pid)
1667 {
1668     MachProcessSP procSP;
1669     if (GetProcessSP (pid, procSP))
1670         return procSP->GetNumThreads();
1671     return 0;
1672 }
1673 
1674 //----------------------------------------------------------------------
1675 // Get the thread ID of the current thread.
1676 //----------------------------------------------------------------------
1677 nub_thread_t
1678 DNBProcessGetCurrentThread (nub_process_t pid)
1679 {
1680     MachProcessSP procSP;
1681     if (GetProcessSP (pid, procSP))
1682         return procSP->GetCurrentThread();
1683     return 0;
1684 }
1685 
1686 //----------------------------------------------------------------------
1687 // Change the current thread.
1688 //----------------------------------------------------------------------
1689 nub_thread_t
1690 DNBProcessSetCurrentThread (nub_process_t pid, nub_thread_t tid)
1691 {
1692     MachProcessSP procSP;
1693     if (GetProcessSP (pid, procSP))
1694         return procSP->SetCurrentThread (tid);
1695     return INVALID_NUB_THREAD;
1696 }
1697 
1698 
1699 //----------------------------------------------------------------------
1700 // Dump a string describing a thread's stop reason to the specified file
1701 // handle
1702 //----------------------------------------------------------------------
1703 nub_bool_t
1704 DNBThreadGetStopReason (nub_process_t pid, nub_thread_t tid, struct DNBThreadStopInfo *stop_info)
1705 {
1706     MachProcessSP procSP;
1707     if (GetProcessSP (pid, procSP))
1708         return procSP->GetThreadStoppedReason (tid, stop_info);
1709     return false;
1710 }
1711 
1712 //----------------------------------------------------------------------
1713 // Return string description for the specified thread.
1714 //
1715 // RETURNS: NULL if the thread isn't valid, else a NULL terminated C
1716 // string from a static buffer that must be copied prior to subsequent
1717 // calls.
1718 //----------------------------------------------------------------------
1719 const char *
1720 DNBThreadGetInfo (nub_process_t pid, nub_thread_t tid)
1721 {
1722     MachProcessSP procSP;
1723     if (GetProcessSP (pid, procSP))
1724         return procSP->GetThreadInfo (tid);
1725     return NULL;
1726 }
1727 
1728 //----------------------------------------------------------------------
1729 // Get the thread ID given a thread index.
1730 //----------------------------------------------------------------------
1731 nub_thread_t
1732 DNBProcessGetThreadAtIndex (nub_process_t pid, size_t thread_idx)
1733 {
1734     MachProcessSP procSP;
1735     if (GetProcessSP (pid, procSP))
1736         return procSP->GetThreadAtIndex (thread_idx);
1737     return INVALID_NUB_THREAD;
1738 }
1739 
1740 nub_addr_t
1741 DNBProcessGetSharedLibraryInfoAddress (nub_process_t pid)
1742 {
1743     MachProcessSP procSP;
1744     DNBError err;
1745     if (GetProcessSP (pid, procSP))
1746         return procSP->Task().GetDYLDAllImageInfosAddress (err);
1747     return INVALID_NUB_ADDRESS;
1748 }
1749 
1750 
1751 nub_bool_t
1752 DNBProcessSharedLibrariesUpdated(nub_process_t pid)
1753 {
1754     MachProcessSP procSP;
1755     if (GetProcessSP (pid, procSP))
1756     {
1757         procSP->SharedLibrariesUpdated ();
1758         return true;
1759     }
1760     return false;
1761 }
1762 
1763 //----------------------------------------------------------------------
1764 // Get the current shared library information for a process. Only return
1765 // the shared libraries that have changed since the last shared library
1766 // state changed event if only_changed is non-zero.
1767 //----------------------------------------------------------------------
1768 nub_size_t
1769 DNBProcessGetSharedLibraryInfo (nub_process_t pid, nub_bool_t only_changed, struct DNBExecutableImageInfo **image_infos)
1770 {
1771     MachProcessSP procSP;
1772     if (GetProcessSP (pid, procSP))
1773         return procSP->CopyImageInfos (image_infos, only_changed);
1774 
1775     // If we have no process, then return NULL for the shared library info
1776     // and zero for shared library count
1777     *image_infos = NULL;
1778     return 0;
1779 }
1780 
1781 //----------------------------------------------------------------------
1782 // Get the register set information for a specific thread.
1783 //----------------------------------------------------------------------
1784 const DNBRegisterSetInfo *
1785 DNBGetRegisterSetInfo (nub_size_t *num_reg_sets)
1786 {
1787     return DNBArchProtocol::GetRegisterSetInfo (num_reg_sets);
1788 }
1789 
1790 
1791 //----------------------------------------------------------------------
1792 // Read a register value by register set and register index.
1793 //----------------------------------------------------------------------
1794 nub_bool_t
1795 DNBThreadGetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value)
1796 {
1797     MachProcessSP procSP;
1798     ::bzero (value, sizeof(DNBRegisterValue));
1799     if (GetProcessSP (pid, procSP))
1800     {
1801         if (tid != INVALID_NUB_THREAD)
1802             return procSP->GetRegisterValue (tid, set, reg, value);
1803     }
1804     return false;
1805 }
1806 
1807 nub_bool_t
1808 DNBThreadSetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value)
1809 {
1810     if (tid != INVALID_NUB_THREAD)
1811     {
1812         MachProcessSP procSP;
1813         if (GetProcessSP (pid, procSP))
1814             return procSP->SetRegisterValue (tid, set, reg, value);
1815     }
1816     return false;
1817 }
1818 
1819 nub_size_t
1820 DNBThreadGetRegisterContext (nub_process_t pid, nub_thread_t tid, void *buf, size_t buf_len)
1821 {
1822     MachProcessSP procSP;
1823     if (GetProcessSP (pid, procSP))
1824     {
1825         if (tid != INVALID_NUB_THREAD)
1826             return procSP->GetThreadList().GetRegisterContext (tid, buf, buf_len);
1827     }
1828     ::bzero (buf, buf_len);
1829     return 0;
1830 
1831 }
1832 
1833 nub_size_t
1834 DNBThreadSetRegisterContext (nub_process_t pid, nub_thread_t tid, const 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().SetRegisterContext (tid, buf, buf_len);
1841     }
1842     return 0;
1843 }
1844 
1845 //----------------------------------------------------------------------
1846 // Read a register value by name.
1847 //----------------------------------------------------------------------
1848 nub_bool_t
1849 DNBThreadGetRegisterValueByName (nub_process_t pid, nub_thread_t tid, uint32_t reg_set, const char *reg_name, DNBRegisterValue *value)
1850 {
1851     MachProcessSP procSP;
1852     ::bzero (value, sizeof(DNBRegisterValue));
1853     if (GetProcessSP (pid, procSP))
1854     {
1855         const struct DNBRegisterSetInfo *set_info;
1856         nub_size_t num_reg_sets = 0;
1857         set_info = DNBGetRegisterSetInfo (&num_reg_sets);
1858         if (set_info)
1859         {
1860             uint32_t set = reg_set;
1861             uint32_t reg;
1862             if (set == REGISTER_SET_ALL)
1863             {
1864                 for (set = 1; set < num_reg_sets; ++set)
1865                 {
1866                     for (reg = 0; reg < set_info[set].num_registers; ++reg)
1867                     {
1868                         if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1869                             return procSP->GetRegisterValue (tid, set, reg, value);
1870                     }
1871                 }
1872             }
1873             else
1874             {
1875                 for (reg = 0; reg < set_info[set].num_registers; ++reg)
1876                 {
1877                     if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1878                         return procSP->GetRegisterValue (tid, set, reg, value);
1879                 }
1880             }
1881         }
1882     }
1883     return false;
1884 }
1885 
1886 
1887 //----------------------------------------------------------------------
1888 // Read a register set and register number from the register name.
1889 //----------------------------------------------------------------------
1890 nub_bool_t
1891 DNBGetRegisterInfoByName (const char *reg_name, DNBRegisterInfo* info)
1892 {
1893     const struct DNBRegisterSetInfo *set_info;
1894     nub_size_t num_reg_sets = 0;
1895     set_info = DNBGetRegisterSetInfo (&num_reg_sets);
1896     if (set_info)
1897     {
1898         uint32_t set, reg;
1899         for (set = 1; set < num_reg_sets; ++set)
1900         {
1901             for (reg = 0; reg < set_info[set].num_registers; ++reg)
1902             {
1903                 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1904                 {
1905                     *info = set_info[set].registers[reg];
1906                     return true;
1907                 }
1908             }
1909         }
1910 
1911         for (set = 1; set < num_reg_sets; ++set)
1912         {
1913             uint32_t reg;
1914             for (reg = 0; reg < set_info[set].num_registers; ++reg)
1915             {
1916                 if (set_info[set].registers[reg].alt == NULL)
1917                     continue;
1918 
1919                 if (strcasecmp(reg_name, set_info[set].registers[reg].alt) == 0)
1920                 {
1921                     *info = set_info[set].registers[reg];
1922                     return true;
1923                 }
1924             }
1925         }
1926     }
1927 
1928     ::bzero (info, sizeof(DNBRegisterInfo));
1929     return false;
1930 }
1931 
1932 
1933 //----------------------------------------------------------------------
1934 // Set the name to address callback function that this nub can use
1935 // for any name to address lookups that are needed.
1936 //----------------------------------------------------------------------
1937 nub_bool_t
1938 DNBProcessSetNameToAddressCallback (nub_process_t pid, DNBCallbackNameToAddress callback, void *baton)
1939 {
1940     MachProcessSP procSP;
1941     if (GetProcessSP (pid, procSP))
1942     {
1943         procSP->SetNameToAddressCallback (callback, baton);
1944         return true;
1945     }
1946     return false;
1947 }
1948 
1949 
1950 //----------------------------------------------------------------------
1951 // Set the name to address callback function that this nub can use
1952 // for any name to address lookups that are needed.
1953 //----------------------------------------------------------------------
1954 nub_bool_t
1955 DNBProcessSetSharedLibraryInfoCallback (nub_process_t pid, DNBCallbackCopyExecutableImageInfos callback, void  *baton)
1956 {
1957     MachProcessSP procSP;
1958     if (GetProcessSP (pid, procSP))
1959     {
1960         procSP->SetSharedLibraryInfoCallback (callback, baton);
1961         return true;
1962     }
1963     return false;
1964 }
1965 
1966 nub_addr_t
1967 DNBProcessLookupAddress (nub_process_t pid, const char *name, const char *shlib)
1968 {
1969     MachProcessSP procSP;
1970     if (GetProcessSP (pid, procSP))
1971     {
1972         return procSP->LookupSymbol (name, shlib);
1973     }
1974     return INVALID_NUB_ADDRESS;
1975 }
1976 
1977 
1978 nub_size_t
1979 DNBProcessGetAvailableSTDOUT (nub_process_t pid, char *buf, nub_size_t buf_size)
1980 {
1981     MachProcessSP procSP;
1982     if (GetProcessSP (pid, procSP))
1983         return procSP->GetAvailableSTDOUT (buf, buf_size);
1984     return 0;
1985 }
1986 
1987 nub_size_t
1988 DNBProcessGetAvailableSTDERR (nub_process_t pid, char *buf, nub_size_t buf_size)
1989 {
1990     MachProcessSP procSP;
1991     if (GetProcessSP (pid, procSP))
1992         return procSP->GetAvailableSTDERR (buf, buf_size);
1993     return 0;
1994 }
1995 
1996 nub_size_t
1997 DNBProcessGetStopCount (nub_process_t pid)
1998 {
1999     MachProcessSP procSP;
2000     if (GetProcessSP (pid, procSP))
2001         return procSP->StopCount();
2002     return 0;
2003 }
2004 
2005 uint32_t
2006 DNBProcessGetCPUType (nub_process_t pid)
2007 {
2008     MachProcessSP procSP;
2009     if (GetProcessSP (pid, procSP))
2010         return procSP->GetCPUType ();
2011     return 0;
2012 
2013 }
2014 
2015 nub_bool_t
2016 DNBResolveExecutablePath (const char *path, char *resolved_path, size_t resolved_path_size)
2017 {
2018     if (path == NULL || path[0] == '\0')
2019         return false;
2020 
2021     char max_path[PATH_MAX];
2022     std::string result;
2023     CFString::GlobPath(path, result);
2024 
2025     if (result.empty())
2026         result = path;
2027 
2028     if (realpath(path, max_path))
2029     {
2030         // Found the path relatively...
2031         ::strncpy(resolved_path, max_path, resolved_path_size);
2032         return strlen(resolved_path) + 1 < resolved_path_size;
2033     }
2034     else
2035     {
2036         // Not a relative path, check the PATH environment variable if the
2037         const char *PATH = getenv("PATH");
2038         if (PATH)
2039         {
2040             const char *curr_path_start = PATH;
2041             const char *curr_path_end;
2042             while (curr_path_start && *curr_path_start)
2043             {
2044                 curr_path_end = strchr(curr_path_start, ':');
2045                 if (curr_path_end == NULL)
2046                 {
2047                     result.assign(curr_path_start);
2048                     curr_path_start = NULL;
2049                 }
2050                 else if (curr_path_end > curr_path_start)
2051                 {
2052                     size_t len = curr_path_end - curr_path_start;
2053                     result.assign(curr_path_start, len);
2054                     curr_path_start += len + 1;
2055                 }
2056                 else
2057                     break;
2058 
2059                 result += '/';
2060                 result += path;
2061                 struct stat s;
2062                 if (stat(result.c_str(), &s) == 0)
2063                 {
2064                     ::strncpy(resolved_path, result.c_str(), resolved_path_size);
2065                     return result.size() + 1 < resolved_path_size;
2066                 }
2067             }
2068         }
2069     }
2070     return false;
2071 }
2072 
2073 
2074 void
2075 DNBInitialize()
2076 {
2077     DNBLogThreadedIf (LOG_PROCESS, "DNBInitialize ()");
2078 #if defined (__i386__) || defined (__x86_64__)
2079     DNBArchImplI386::Initialize();
2080     DNBArchImplX86_64::Initialize();
2081 #elif defined (__arm__)
2082     DNBArchMachARM::Initialize();
2083 #endif
2084 }
2085 
2086 void
2087 DNBTerminate()
2088 {
2089 }
2090 
2091 nub_bool_t
2092 DNBSetArchitecture (const char *arch)
2093 {
2094     if (arch && arch[0])
2095     {
2096         if (strcasecmp (arch, "i386") == 0)
2097             return DNBArchProtocol::SetArchitecture (CPU_TYPE_I386);
2098         else if (strcasecmp (arch, "x86_64") == 0)
2099             return DNBArchProtocol::SetArchitecture (CPU_TYPE_X86_64);
2100         else if (strstr (arch, "arm") == arch)
2101             return DNBArchProtocol::SetArchitecture (CPU_TYPE_ARM);
2102     }
2103     return false;
2104 }
2105