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++; flags |= alternate_form;            break;
1237                 case '0': fprintf_format += *f++; flags |= zero_padding;            break;
1238                 case '-': fprintf_format += *f++; flags |= negative_field_width;    break;
1239                 case ' ': fprintf_format += *f++; flags |= blank_space;                break;
1240                 case '+': fprintf_format += *f++; flags |= show_sign;                break;
1241                 case ',': fprintf_format += *f++; 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                     if (end > f)
1335                     {
1336                         fprintf_format.append(f, end - f);
1337                         f = end;
1338                     }
1339                 }
1340 
1341 
1342                 // Check for a precision
1343                 if (*f == '.')
1344                 {
1345                     f++;
1346                     if (isdigit(*f))
1347                     {
1348                         fprintf_format += '.';
1349                         precision = strtoul(f, &end, 10);
1350                         if (end > f)
1351                         {
1352                             fprintf_format.append(f, end - f);
1353                             f = end;
1354                         }
1355                     }
1356                 }
1357 
1358 
1359                 // mprintf specific: read the optional actual byte size (abs)
1360                 // after the standard minimum field width (mfw) and precision (prec).
1361                 // Standard printf calls you can have "mfw.prec" or ".prec", but
1362                 // mprintf can have "mfw.prec.abs", ".prec.abs" or "..abs". This is nice
1363                 // for strings that may be in a fixed size buffer, but may not use all bytes
1364                 // in that buffer for printable characters.
1365                 if (*f == '.')
1366                 {
1367                     f++;
1368                     actual_byte_size = strtoul(f, &end, 10);
1369                     if (end > f)
1370                     {
1371                         byte_size = actual_byte_size;
1372                         f = end;
1373                     }
1374                 }
1375 
1376                 // Decode the length modifiers
1377                 switch (*f)
1378                 {
1379                 case 'h':    // h and hh length modifiers
1380                     fprintf_format += *f++;
1381                     length_modifiers |= length_mod_h;
1382                     if (*f == 'h')
1383                     {
1384                         fprintf_format += *f++;
1385                         length_modifiers |= length_mod_hh;
1386                     }
1387                     break;
1388 
1389                 case 'l': // l and ll length modifiers
1390                     fprintf_format += *f++;
1391                     length_modifiers |= length_mod_l;
1392                     if (*f == 'h')
1393                     {
1394                         fprintf_format += *f++;
1395                         length_modifiers |= length_mod_ll;
1396                     }
1397                     break;
1398 
1399                 case 'L':    fprintf_format += *f++;    length_modifiers |= length_mod_L;    break;
1400                 case 'j':    fprintf_format += *f++;    length_modifiers |= length_mod_j;    break;
1401                 case 't':    fprintf_format += *f++;    length_modifiers |= length_mod_t;    break;
1402                 case 'z':    fprintf_format += *f++;    length_modifiers |= length_mod_z;    break;
1403                 case 'q':    fprintf_format += *f++;    length_modifiers |= length_mod_q;    break;
1404                 }
1405 
1406                 // Decode the conversion specifier
1407                 switch (*f)
1408                 {
1409                 case '_':
1410                     // mprintf specific format items
1411                     {
1412                         ++f;    // Skip the '_' character
1413                         switch (*f)
1414                         {
1415                         case 'a':    // Print the current address
1416                             ++f;
1417                             fprintf_format += "ll";
1418                             fprintf_format += *f;    // actual format to show address with folows the 'a' ("%_ax")
1419                             fprintf (file, fprintf_format.c_str(), addr);
1420                             break;
1421                         case 'o':    // offset from base address
1422                             ++f;
1423                             fprintf_format += "ll";
1424                             fprintf_format += *f;    // actual format to show address with folows the 'a' ("%_ox")
1425                             fprintf(file, fprintf_format.c_str(), addr - base_addr);
1426                             break;
1427                         default:
1428                             fprintf (file, "error: unsupported mprintf specific format character '%c'.\n", *f);
1429                             break;
1430                         }
1431                         continue;
1432                     }
1433                     break;
1434 
1435                 case 'D':
1436                 case 'O':
1437                 case 'U':
1438                     fprintf_format += *f;
1439                     if (byte_size == 0)
1440                         byte_size = sizeof(long int);
1441                     break;
1442 
1443                 case 'd':
1444                 case 'i':
1445                 case 'o':
1446                 case 'u':
1447                 case 'x':
1448                 case 'X':
1449                     fprintf_format += *f;
1450                     if (byte_size == 0)
1451                     {
1452                         if (length_modifiers & length_mod_hh)
1453                             byte_size = sizeof(char);
1454                         else if (length_modifiers & length_mod_h)
1455                             byte_size = sizeof(short);
1456                         if (length_modifiers & length_mod_ll)
1457                             byte_size = sizeof(long long);
1458                         else if (length_modifiers & length_mod_l)
1459                             byte_size = sizeof(long);
1460                         else
1461                             byte_size = sizeof(int);
1462                     }
1463                     break;
1464 
1465                 case 'a':
1466                 case 'A':
1467                 case 'f':
1468                 case 'F':
1469                 case 'e':
1470                 case 'E':
1471                 case 'g':
1472                 case 'G':
1473                     fprintf_format += *f;
1474                     if (byte_size == 0)
1475                     {
1476                         if (length_modifiers & length_mod_L)
1477                             byte_size = sizeof(long double);
1478                         else
1479                             byte_size = sizeof(double);
1480                     }
1481                     break;
1482 
1483                 case 'c':
1484                     if ((length_modifiers & length_mod_l) == 0)
1485                     {
1486                         fprintf_format += *f;
1487                         if (byte_size == 0)
1488                             byte_size = sizeof(char);
1489                         break;
1490                     }
1491                     // Fall through to 'C' modifier below...
1492 
1493                 case 'C':
1494                     fprintf_format += *f;
1495                     if (byte_size == 0)
1496                         byte_size = sizeof(wchar_t);
1497                     break;
1498 
1499                 case 's':
1500                     fprintf_format += *f;
1501                     if (is_register || byte_size == 0)
1502                         is_string = 1;
1503                     break;
1504 
1505                 case 'p':
1506                     fprintf_format += *f;
1507                     if (byte_size == 0)
1508                         byte_size = sizeof(void*);
1509                     break;
1510                 }
1511 
1512                 if (is_string)
1513                 {
1514                     std::string mem_string;
1515                     const size_t string_buf_len = 4;
1516                     char string_buf[string_buf_len+1];
1517                     char *string_buf_end = string_buf + string_buf_len;
1518                     string_buf[string_buf_len] = '\0';
1519                     nub_size_t bytes_read;
1520                     nub_addr_t str_addr = is_register ? register_addr : addr;
1521                     while ((bytes_read = DNBProcessMemoryRead(pid, str_addr, string_buf_len, &string_buf[0])) > 0)
1522                     {
1523                         // Did we get a NULL termination character yet?
1524                         if (strchr(string_buf, '\0') == string_buf_end)
1525                         {
1526                             // no NULL terminator yet, append as a std::string
1527                             mem_string.append(string_buf, string_buf_len);
1528                             str_addr += string_buf_len;
1529                         }
1530                         else
1531                         {
1532                             // yep
1533                             break;
1534                         }
1535                     }
1536                     // Append as a C-string so we don't get the extra NULL
1537                     // characters in the temp buffer (since it was resized)
1538                     mem_string += string_buf;
1539                     size_t mem_string_len = mem_string.size() + 1;
1540                     fprintf(file, fprintf_format.c_str(), mem_string.c_str());
1541                     if (mem_string_len > 0)
1542                     {
1543                         if (!is_register)
1544                         {
1545                             addr += mem_string_len;
1546                             total_bytes_read += mem_string_len;
1547                         }
1548                     }
1549                     else
1550                         return total_bytes_read;
1551                 }
1552                 else
1553                 if (byte_size > 0)
1554                 {
1555                     buf.resize(byte_size);
1556                     nub_size_t bytes_read = 0;
1557                     if (is_register)
1558                         bytes_read = register_value.info.size;
1559                     else
1560                         bytes_read = DNBProcessMemoryRead(pid, addr, buf.size(), &buf[0]);
1561                     if (bytes_read > 0)
1562                     {
1563                         if (!is_register)
1564                             total_bytes_read += bytes_read;
1565 
1566                         if (bytes_read == byte_size)
1567                         {
1568                             switch (*f)
1569                             {
1570                             case 'd':
1571                             case 'i':
1572                             case 'o':
1573                             case 'u':
1574                             case 'X':
1575                             case 'x':
1576                             case 'a':
1577                             case 'A':
1578                             case 'f':
1579                             case 'F':
1580                             case 'e':
1581                             case 'E':
1582                             case 'g':
1583                             case 'G':
1584                             case 'p':
1585                             case 'c':
1586                             case 'C':
1587                                 {
1588                                     if (is_register)
1589                                         data.SetData(&register_value.value.v_uint8[0], register_value.info.size);
1590                                     else
1591                                         data.SetData(&buf[0], bytes_read);
1592                                     DNBDataRef::offset_t data_offset = 0;
1593                                     if (byte_size <= 4)
1594                                     {
1595                                         uint32_t u32 = data.GetMax32(&data_offset, byte_size);
1596                                         // Show the actual byte width when displaying hex
1597                                         fprintf(file, fprintf_format.c_str(), u32);
1598                                     }
1599                                     else if (byte_size <= 8)
1600                                     {
1601                                         uint64_t u64 = data.GetMax64(&data_offset, byte_size);
1602                                         // Show the actual byte width when displaying hex
1603                                         fprintf(file, fprintf_format.c_str(), u64);
1604                                     }
1605                                     else
1606                                     {
1607                                         fprintf(file, "error: integer size not supported, must be 8 bytes or less (%u bytes).\n", byte_size);
1608                                     }
1609                                     if (!is_register)
1610                                         addr += byte_size;
1611                                 }
1612                                 break;
1613 
1614                             case 's':
1615                                 fprintf(file, fprintf_format.c_str(), buf.c_str());
1616                                 addr += byte_size;
1617                                 break;
1618 
1619                             default:
1620                                 fprintf(file, "error: unsupported conversion specifier '%c'.\n", *f);
1621                                 break;
1622                             }
1623                         }
1624                     }
1625                 }
1626                 else
1627                     return total_bytes_read;
1628             }
1629             break;
1630 
1631         case '\\':
1632             {
1633                 f++;
1634                 switch (*f)
1635                 {
1636                 case 'e': ch = '\e'; break;
1637                 case 'a': ch = '\a'; break;
1638                 case 'b': ch = '\b'; break;
1639                 case 'f': ch = '\f'; break;
1640                 case 'n': ch = '\n'; break;
1641                 case 'r': ch = '\r'; break;
1642                 case 't': ch = '\t'; break;
1643                 case 'v': ch = '\v'; break;
1644                 case '\'': ch = '\''; break;
1645                 case '\\': ch = '\\'; break;
1646                 case '0':
1647                 case '1':
1648                 case '2':
1649                 case '3':
1650                 case '4':
1651                 case '5':
1652                 case '6':
1653                 case '7':
1654                     ch = strtoul(f, &end, 8);
1655                     f = end;
1656                     break;
1657                 default:
1658                     ch = *f;
1659                     break;
1660                 }
1661                 fputc(ch, file);
1662             }
1663             break;
1664 
1665         default:
1666             fputc(ch, file);
1667             break;
1668         }
1669     }
1670     return total_bytes_read;
1671 }
1672 
1673 
1674 //----------------------------------------------------------------------
1675 // Get the number of threads for the specified process.
1676 //----------------------------------------------------------------------
1677 nub_size_t
1678 DNBProcessGetNumThreads (nub_process_t pid)
1679 {
1680     MachProcessSP procSP;
1681     if (GetProcessSP (pid, procSP))
1682         return procSP->GetNumThreads();
1683     return 0;
1684 }
1685 
1686 //----------------------------------------------------------------------
1687 // Get the thread ID of the current thread.
1688 //----------------------------------------------------------------------
1689 nub_thread_t
1690 DNBProcessGetCurrentThread (nub_process_t pid)
1691 {
1692     MachProcessSP procSP;
1693     if (GetProcessSP (pid, procSP))
1694         return procSP->GetCurrentThread();
1695     return 0;
1696 }
1697 
1698 //----------------------------------------------------------------------
1699 // Change the current thread.
1700 //----------------------------------------------------------------------
1701 nub_thread_t
1702 DNBProcessSetCurrentThread (nub_process_t pid, nub_thread_t tid)
1703 {
1704     MachProcessSP procSP;
1705     if (GetProcessSP (pid, procSP))
1706         return procSP->SetCurrentThread (tid);
1707     return INVALID_NUB_THREAD;
1708 }
1709 
1710 
1711 //----------------------------------------------------------------------
1712 // Dump a string describing a thread's stop reason to the specified file
1713 // handle
1714 //----------------------------------------------------------------------
1715 nub_bool_t
1716 DNBThreadGetStopReason (nub_process_t pid, nub_thread_t tid, struct DNBThreadStopInfo *stop_info)
1717 {
1718     MachProcessSP procSP;
1719     if (GetProcessSP (pid, procSP))
1720         return procSP->GetThreadStoppedReason (tid, stop_info);
1721     return false;
1722 }
1723 
1724 //----------------------------------------------------------------------
1725 // Return string description for the specified thread.
1726 //
1727 // RETURNS: NULL if the thread isn't valid, else a NULL terminated C
1728 // string from a static buffer that must be copied prior to subsequent
1729 // calls.
1730 //----------------------------------------------------------------------
1731 const char *
1732 DNBThreadGetInfo (nub_process_t pid, nub_thread_t tid)
1733 {
1734     MachProcessSP procSP;
1735     if (GetProcessSP (pid, procSP))
1736         return procSP->GetThreadInfo (tid);
1737     return NULL;
1738 }
1739 
1740 //----------------------------------------------------------------------
1741 // Get the thread ID given a thread index.
1742 //----------------------------------------------------------------------
1743 nub_thread_t
1744 DNBProcessGetThreadAtIndex (nub_process_t pid, size_t thread_idx)
1745 {
1746     MachProcessSP procSP;
1747     if (GetProcessSP (pid, procSP))
1748         return procSP->GetThreadAtIndex (thread_idx);
1749     return INVALID_NUB_THREAD;
1750 }
1751 
1752 nub_addr_t
1753 DNBProcessGetSharedLibraryInfoAddress (nub_process_t pid)
1754 {
1755     MachProcessSP procSP;
1756     DNBError err;
1757     if (GetProcessSP (pid, procSP))
1758         return procSP->Task().GetDYLDAllImageInfosAddress (err);
1759     return INVALID_NUB_ADDRESS;
1760 }
1761 
1762 
1763 nub_bool_t
1764 DNBProcessSharedLibrariesUpdated(nub_process_t pid)
1765 {
1766     MachProcessSP procSP;
1767     if (GetProcessSP (pid, procSP))
1768     {
1769         procSP->SharedLibrariesUpdated ();
1770         return true;
1771     }
1772     return false;
1773 }
1774 
1775 //----------------------------------------------------------------------
1776 // Get the current shared library information for a process. Only return
1777 // the shared libraries that have changed since the last shared library
1778 // state changed event if only_changed is non-zero.
1779 //----------------------------------------------------------------------
1780 nub_size_t
1781 DNBProcessGetSharedLibraryInfo (nub_process_t pid, nub_bool_t only_changed, struct DNBExecutableImageInfo **image_infos)
1782 {
1783     MachProcessSP procSP;
1784     if (GetProcessSP (pid, procSP))
1785         return procSP->CopyImageInfos (image_infos, only_changed);
1786 
1787     // If we have no process, then return NULL for the shared library info
1788     // and zero for shared library count
1789     *image_infos = NULL;
1790     return 0;
1791 }
1792 
1793 //----------------------------------------------------------------------
1794 // Get the register set information for a specific thread.
1795 //----------------------------------------------------------------------
1796 const DNBRegisterSetInfo *
1797 DNBGetRegisterSetInfo (nub_size_t *num_reg_sets)
1798 {
1799     return DNBArchProtocol::GetRegisterSetInfo (num_reg_sets);
1800 }
1801 
1802 
1803 //----------------------------------------------------------------------
1804 // Read a register value by register set and register index.
1805 //----------------------------------------------------------------------
1806 nub_bool_t
1807 DNBThreadGetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, DNBRegisterValue *value)
1808 {
1809     MachProcessSP procSP;
1810     ::bzero (value, sizeof(DNBRegisterValue));
1811     if (GetProcessSP (pid, procSP))
1812     {
1813         if (tid != INVALID_NUB_THREAD)
1814             return procSP->GetRegisterValue (tid, set, reg, value);
1815     }
1816     return false;
1817 }
1818 
1819 nub_bool_t
1820 DNBThreadSetRegisterValueByID (nub_process_t pid, nub_thread_t tid, uint32_t set, uint32_t reg, const DNBRegisterValue *value)
1821 {
1822     if (tid != INVALID_NUB_THREAD)
1823     {
1824         MachProcessSP procSP;
1825         if (GetProcessSP (pid, procSP))
1826             return procSP->SetRegisterValue (tid, set, reg, value);
1827     }
1828     return false;
1829 }
1830 
1831 nub_size_t
1832 DNBThreadGetRegisterContext (nub_process_t pid, nub_thread_t tid, void *buf, size_t buf_len)
1833 {
1834     MachProcessSP procSP;
1835     if (GetProcessSP (pid, procSP))
1836     {
1837         if (tid != INVALID_NUB_THREAD)
1838             return procSP->GetThreadList().GetRegisterContext (tid, buf, buf_len);
1839     }
1840     ::bzero (buf, buf_len);
1841     return 0;
1842 
1843 }
1844 
1845 nub_size_t
1846 DNBThreadSetRegisterContext (nub_process_t pid, nub_thread_t tid, const void *buf, size_t buf_len)
1847 {
1848     MachProcessSP procSP;
1849     if (GetProcessSP (pid, procSP))
1850     {
1851         if (tid != INVALID_NUB_THREAD)
1852             return procSP->GetThreadList().SetRegisterContext (tid, buf, buf_len);
1853     }
1854     return 0;
1855 }
1856 
1857 //----------------------------------------------------------------------
1858 // Read a register value by name.
1859 //----------------------------------------------------------------------
1860 nub_bool_t
1861 DNBThreadGetRegisterValueByName (nub_process_t pid, nub_thread_t tid, uint32_t reg_set, const char *reg_name, DNBRegisterValue *value)
1862 {
1863     MachProcessSP procSP;
1864     ::bzero (value, sizeof(DNBRegisterValue));
1865     if (GetProcessSP (pid, procSP))
1866     {
1867         const struct DNBRegisterSetInfo *set_info;
1868         nub_size_t num_reg_sets = 0;
1869         set_info = DNBGetRegisterSetInfo (&num_reg_sets);
1870         if (set_info)
1871         {
1872             uint32_t set = reg_set;
1873             uint32_t reg;
1874             if (set == REGISTER_SET_ALL)
1875             {
1876                 for (set = 1; set < num_reg_sets; ++set)
1877                 {
1878                     for (reg = 0; reg < set_info[set].num_registers; ++reg)
1879                     {
1880                         if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1881                             return procSP->GetRegisterValue (tid, set, reg, value);
1882                     }
1883                 }
1884             }
1885             else
1886             {
1887                 for (reg = 0; reg < set_info[set].num_registers; ++reg)
1888                 {
1889                     if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1890                         return procSP->GetRegisterValue (tid, set, reg, value);
1891                 }
1892             }
1893         }
1894     }
1895     return false;
1896 }
1897 
1898 
1899 //----------------------------------------------------------------------
1900 // Read a register set and register number from the register name.
1901 //----------------------------------------------------------------------
1902 nub_bool_t
1903 DNBGetRegisterInfoByName (const char *reg_name, DNBRegisterInfo* info)
1904 {
1905     const struct DNBRegisterSetInfo *set_info;
1906     nub_size_t num_reg_sets = 0;
1907     set_info = DNBGetRegisterSetInfo (&num_reg_sets);
1908     if (set_info)
1909     {
1910         uint32_t set, reg;
1911         for (set = 1; set < num_reg_sets; ++set)
1912         {
1913             for (reg = 0; reg < set_info[set].num_registers; ++reg)
1914             {
1915                 if (strcasecmp(reg_name, set_info[set].registers[reg].name) == 0)
1916                 {
1917                     *info = set_info[set].registers[reg];
1918                     return true;
1919                 }
1920             }
1921         }
1922 
1923         for (set = 1; set < num_reg_sets; ++set)
1924         {
1925             uint32_t reg;
1926             for (reg = 0; reg < set_info[set].num_registers; ++reg)
1927             {
1928                 if (set_info[set].registers[reg].alt == NULL)
1929                     continue;
1930 
1931                 if (strcasecmp(reg_name, set_info[set].registers[reg].alt) == 0)
1932                 {
1933                     *info = set_info[set].registers[reg];
1934                     return true;
1935                 }
1936             }
1937         }
1938     }
1939 
1940     ::bzero (info, sizeof(DNBRegisterInfo));
1941     return false;
1942 }
1943 
1944 
1945 //----------------------------------------------------------------------
1946 // Set the name to address callback function that this nub can use
1947 // for any name to address lookups that are needed.
1948 //----------------------------------------------------------------------
1949 nub_bool_t
1950 DNBProcessSetNameToAddressCallback (nub_process_t pid, DNBCallbackNameToAddress callback, void *baton)
1951 {
1952     MachProcessSP procSP;
1953     if (GetProcessSP (pid, procSP))
1954     {
1955         procSP->SetNameToAddressCallback (callback, baton);
1956         return true;
1957     }
1958     return false;
1959 }
1960 
1961 
1962 //----------------------------------------------------------------------
1963 // Set the name to address callback function that this nub can use
1964 // for any name to address lookups that are needed.
1965 //----------------------------------------------------------------------
1966 nub_bool_t
1967 DNBProcessSetSharedLibraryInfoCallback (nub_process_t pid, DNBCallbackCopyExecutableImageInfos callback, void  *baton)
1968 {
1969     MachProcessSP procSP;
1970     if (GetProcessSP (pid, procSP))
1971     {
1972         procSP->SetSharedLibraryInfoCallback (callback, baton);
1973         return true;
1974     }
1975     return false;
1976 }
1977 
1978 nub_addr_t
1979 DNBProcessLookupAddress (nub_process_t pid, const char *name, const char *shlib)
1980 {
1981     MachProcessSP procSP;
1982     if (GetProcessSP (pid, procSP))
1983     {
1984         return procSP->LookupSymbol (name, shlib);
1985     }
1986     return INVALID_NUB_ADDRESS;
1987 }
1988 
1989 
1990 nub_size_t
1991 DNBProcessGetAvailableSTDOUT (nub_process_t pid, char *buf, nub_size_t buf_size)
1992 {
1993     MachProcessSP procSP;
1994     if (GetProcessSP (pid, procSP))
1995         return procSP->GetAvailableSTDOUT (buf, buf_size);
1996     return 0;
1997 }
1998 
1999 nub_size_t
2000 DNBProcessGetAvailableSTDERR (nub_process_t pid, char *buf, nub_size_t buf_size)
2001 {
2002     MachProcessSP procSP;
2003     if (GetProcessSP (pid, procSP))
2004         return procSP->GetAvailableSTDERR (buf, buf_size);
2005     return 0;
2006 }
2007 
2008 nub_size_t
2009 DNBProcessGetStopCount (nub_process_t pid)
2010 {
2011     MachProcessSP procSP;
2012     if (GetProcessSP (pid, procSP))
2013         return procSP->StopCount();
2014     return 0;
2015 }
2016 
2017 uint32_t
2018 DNBProcessGetCPUType (nub_process_t pid)
2019 {
2020     MachProcessSP procSP;
2021     if (GetProcessSP (pid, procSP))
2022         return procSP->GetCPUType ();
2023     return 0;
2024 
2025 }
2026 
2027 nub_bool_t
2028 DNBResolveExecutablePath (const char *path, char *resolved_path, size_t resolved_path_size)
2029 {
2030     if (path == NULL || path[0] == '\0')
2031         return false;
2032 
2033     char max_path[PATH_MAX];
2034     std::string result;
2035     CFString::GlobPath(path, result);
2036 
2037     if (result.empty())
2038         result = path;
2039 
2040     if (realpath(path, max_path))
2041     {
2042         // Found the path relatively...
2043         ::strncpy(resolved_path, max_path, resolved_path_size);
2044         return strlen(resolved_path) + 1 < resolved_path_size;
2045     }
2046     else
2047     {
2048         // Not a relative path, check the PATH environment variable if the
2049         const char *PATH = getenv("PATH");
2050         if (PATH)
2051         {
2052             const char *curr_path_start = PATH;
2053             const char *curr_path_end;
2054             while (curr_path_start && *curr_path_start)
2055             {
2056                 curr_path_end = strchr(curr_path_start, ':');
2057                 if (curr_path_end == NULL)
2058                 {
2059                     result.assign(curr_path_start);
2060                     curr_path_start = NULL;
2061                 }
2062                 else if (curr_path_end > curr_path_start)
2063                 {
2064                     size_t len = curr_path_end - curr_path_start;
2065                     result.assign(curr_path_start, len);
2066                     curr_path_start += len + 1;
2067                 }
2068                 else
2069                     break;
2070 
2071                 result += '/';
2072                 result += path;
2073                 struct stat s;
2074                 if (stat(result.c_str(), &s) == 0)
2075                 {
2076                     ::strncpy(resolved_path, result.c_str(), resolved_path_size);
2077                     return result.size() + 1 < resolved_path_size;
2078                 }
2079             }
2080         }
2081     }
2082     return false;
2083 }
2084 
2085 
2086 void
2087 DNBInitialize()
2088 {
2089     DNBLogThreadedIf (LOG_PROCESS, "DNBInitialize ()");
2090 #if defined (__i386__) || defined (__x86_64__)
2091     DNBArchImplI386::Initialize();
2092     DNBArchImplX86_64::Initialize();
2093 #elif defined (__arm__)
2094     DNBArchMachARM::Initialize();
2095 #endif
2096 }
2097 
2098 void
2099 DNBTerminate()
2100 {
2101 }
2102 
2103 nub_bool_t
2104 DNBSetArchitecture (const char *arch)
2105 {
2106     if (arch && arch[0])
2107     {
2108         if (strcasecmp (arch, "i386") == 0)
2109             return DNBArchProtocol::SetArchitecture (CPU_TYPE_I386);
2110         else if (strcasecmp (arch, "x86_64") == 0)
2111             return DNBArchProtocol::SetArchitecture (CPU_TYPE_X86_64);
2112         else if (strstr (arch, "arm") == arch)
2113             return DNBArchProtocol::SetArchitecture (CPU_TYPE_ARM);
2114     }
2115     return false;
2116 }
2117