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