1 //===-- debugserver.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 #include <arpa/inet.h>
11 #include <asl.h>
12 #include <crt_externs.h>
13 #include <errno.h>
14 #include <getopt.h>
15 #include <netdb.h>
16 #include <netinet/in.h>
17 #include <netinet/tcp.h>
18 #include <string>
19 #include <sys/select.h>
20 #include <sys/socket.h>
21 #include <sys/sysctl.h>
22 #include <sys/types.h>
23 #include <sys/un.h>
24 #include <vector>
25 
26 #if defined(__APPLE__)
27 #include <sched.h>
28 extern "C" int proc_set_wakemon_params(pid_t, int,
29                                        int); // <libproc_internal.h> SPI
30 #endif
31 
32 #include "CFString.h"
33 #include "DNB.h"
34 #include "DNBLog.h"
35 #include "DNBTimer.h"
36 #include "OsLogger.h"
37 #include "PseudoTerminal.h"
38 #include "RNBContext.h"
39 #include "RNBRemote.h"
40 #include "RNBServices.h"
41 #include "RNBSocket.h"
42 #include "SysSignal.h"
43 
44 // Global PID in case we get a signal and need to stop the process...
45 nub_process_t g_pid = INVALID_NUB_PROCESS;
46 
47 //----------------------------------------------------------------------
48 // Run loop modes which determine which run loop function will be called
49 //----------------------------------------------------------------------
50 typedef enum {
51   eRNBRunLoopModeInvalid = 0,
52   eRNBRunLoopModeGetStartModeFromRemoteProtocol,
53   eRNBRunLoopModeInferiorAttaching,
54   eRNBRunLoopModeInferiorLaunching,
55   eRNBRunLoopModeInferiorExecuting,
56   eRNBRunLoopModePlatformMode,
57   eRNBRunLoopModeExit
58 } RNBRunLoopMode;
59 
60 //----------------------------------------------------------------------
61 // Global Variables
62 //----------------------------------------------------------------------
63 RNBRemoteSP g_remoteSP;
64 static int g_lockdown_opt = 0;
65 static int g_applist_opt = 0;
66 static nub_launch_flavor_t g_launch_flavor = eLaunchFlavorDefault;
67 int g_disable_aslr = 0;
68 
69 int g_isatty = 0;
70 bool g_detach_on_error = true;
71 
72 #define RNBLogSTDOUT(fmt, ...)                                                 \
73   do {                                                                         \
74     if (g_isatty) {                                                            \
75       fprintf(stdout, fmt, ##__VA_ARGS__);                                     \
76     } else {                                                                   \
77       _DNBLog(0, fmt, ##__VA_ARGS__);                                          \
78     }                                                                          \
79   } while (0)
80 #define RNBLogSTDERR(fmt, ...)                                                 \
81   do {                                                                         \
82     if (g_isatty) {                                                            \
83       fprintf(stderr, fmt, ##__VA_ARGS__);                                     \
84     } else {                                                                   \
85       _DNBLog(0, fmt, ##__VA_ARGS__);                                          \
86     }                                                                          \
87   } while (0)
88 
89 //----------------------------------------------------------------------
90 // Get our program path and arguments from the remote connection.
91 // We will need to start up the remote connection without a PID, get the
92 // arguments, wait for the new process to finish launching and hit its
93 // entry point,  and then return the run loop mode that should come next.
94 //----------------------------------------------------------------------
95 RNBRunLoopMode RNBRunLoopGetStartModeFromRemote(RNBRemote *remote) {
96   std::string packet;
97 
98   if (remote) {
99     RNBContext &ctx = remote->Context();
100     uint32_t event_mask = RNBContext::event_read_packet_available |
101                           RNBContext::event_read_thread_exiting;
102 
103     // Spin waiting to get the A packet.
104     while (1) {
105       DNBLogThreadedIf(LOG_RNB_MAX,
106                        "%s ctx.Events().WaitForSetEvents( 0x%08x ) ...",
107                        __FUNCTION__, event_mask);
108       nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
109       DNBLogThreadedIf(LOG_RNB_MAX,
110                        "%s ctx.Events().WaitForSetEvents( 0x%08x ) => 0x%08x",
111                        __FUNCTION__, event_mask, set_events);
112 
113       if (set_events & RNBContext::event_read_thread_exiting) {
114         RNBLogSTDERR("error: packet read thread exited.\n");
115         return eRNBRunLoopModeExit;
116       }
117 
118       if (set_events & RNBContext::event_read_packet_available) {
119         rnb_err_t err = rnb_err;
120         RNBRemote::PacketEnum type;
121 
122         err = remote->HandleReceivedPacket(&type);
123 
124         // check if we tried to attach to a process
125         if (type == RNBRemote::vattach || type == RNBRemote::vattachwait ||
126             type == RNBRemote::vattachorwait) {
127           if (err == rnb_success) {
128             RNBLogSTDOUT("Attach succeeded, ready to debug.\n");
129             return eRNBRunLoopModeInferiorExecuting;
130           } else {
131             RNBLogSTDERR("error: attach failed.\n");
132             return eRNBRunLoopModeExit;
133           }
134         }
135 
136         if (err == rnb_success) {
137           // If we got our arguments we are ready to launch using the arguments
138           // and any environment variables we received.
139           if (type == RNBRemote::set_argv) {
140             return eRNBRunLoopModeInferiorLaunching;
141           }
142         } else if (err == rnb_not_connected) {
143           RNBLogSTDERR("error: connection lost.\n");
144           return eRNBRunLoopModeExit;
145         } else {
146           // a catch all for any other gdb remote packets that failed
147           DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Error getting packet.",
148                            __FUNCTION__);
149           continue;
150         }
151 
152         DNBLogThreadedIf(LOG_RNB_MINIMAL, "#### %s", __FUNCTION__);
153       } else {
154         DNBLogThreadedIf(LOG_RNB_MINIMAL,
155                          "%s Connection closed before getting \"A\" packet.",
156                          __FUNCTION__);
157         return eRNBRunLoopModeExit;
158       }
159     }
160   }
161   return eRNBRunLoopModeExit;
162 }
163 
164 //----------------------------------------------------------------------
165 // This run loop mode will wait for the process to launch and hit its
166 // entry point. It will currently ignore all events except for the
167 // process state changed event, where it watches for the process stopped
168 // or crash process state.
169 //----------------------------------------------------------------------
170 RNBRunLoopMode RNBRunLoopLaunchInferior(RNBRemote *remote,
171                                         const char *stdin_path,
172                                         const char *stdout_path,
173                                         const char *stderr_path,
174                                         bool no_stdio) {
175   RNBContext &ctx = remote->Context();
176 
177   // The Process stuff takes a c array, the RNBContext has a vector...
178   // So make up a c array.
179 
180   DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Launching '%s'...", __FUNCTION__,
181                    ctx.ArgumentAtIndex(0));
182 
183   size_t inferior_argc = ctx.ArgumentCount();
184   // Initialize inferior_argv with inferior_argc + 1 NULLs
185   std::vector<const char *> inferior_argv(inferior_argc + 1, NULL);
186 
187   size_t i;
188   for (i = 0; i < inferior_argc; i++)
189     inferior_argv[i] = ctx.ArgumentAtIndex(i);
190 
191   // Pass the environment array the same way:
192 
193   size_t inferior_envc = ctx.EnvironmentCount();
194   // Initialize inferior_argv with inferior_argc + 1 NULLs
195   std::vector<const char *> inferior_envp(inferior_envc + 1, NULL);
196 
197   for (i = 0; i < inferior_envc; i++)
198     inferior_envp[i] = ctx.EnvironmentAtIndex(i);
199 
200   // Our launch type hasn't been set to anything concrete, so we need to
201   // figure our how we are going to launch automatically.
202 
203   nub_launch_flavor_t launch_flavor = g_launch_flavor;
204   if (launch_flavor == eLaunchFlavorDefault) {
205     // Our default launch method is posix spawn
206     launch_flavor = eLaunchFlavorPosixSpawn;
207 
208 #if defined WITH_FBS
209     // Check if we have an app bundle, if so launch using BackBoard Services.
210     if (strstr(inferior_argv[0], ".app")) {
211       launch_flavor = eLaunchFlavorFBS;
212     }
213 #elif defined WITH_BKS
214     // Check if we have an app bundle, if so launch using BackBoard Services.
215     if (strstr(inferior_argv[0], ".app")) {
216       launch_flavor = eLaunchFlavorBKS;
217     }
218 #elif defined WITH_SPRINGBOARD
219     // Check if we have an app bundle, if so launch using SpringBoard.
220     if (strstr(inferior_argv[0], ".app")) {
221       launch_flavor = eLaunchFlavorSpringBoard;
222     }
223 #endif
224   }
225 
226   ctx.SetLaunchFlavor(launch_flavor);
227   char resolved_path[PATH_MAX];
228 
229   // If we fail to resolve the path to our executable, then just use what we
230   // were given and hope for the best
231   if (!DNBResolveExecutablePath(inferior_argv[0], resolved_path,
232                                 sizeof(resolved_path)))
233     ::strlcpy(resolved_path, inferior_argv[0], sizeof(resolved_path));
234 
235   char launch_err_str[PATH_MAX];
236   launch_err_str[0] = '\0';
237   const char *cwd =
238       (ctx.GetWorkingDirPath() != NULL ? ctx.GetWorkingDirPath()
239                                        : ctx.GetWorkingDirectory());
240   const char *process_event = ctx.GetProcessEvent();
241   nub_process_t pid = DNBProcessLaunch(
242       resolved_path, &inferior_argv[0], &inferior_envp[0], cwd, stdin_path,
243       stdout_path, stderr_path, no_stdio, launch_flavor, g_disable_aslr,
244       process_event, launch_err_str, sizeof(launch_err_str));
245 
246   g_pid = pid;
247 
248   if (pid == INVALID_NUB_PROCESS && strlen(launch_err_str) > 0) {
249     DNBLogThreaded("%s DNBProcessLaunch() returned error: '%s'", __FUNCTION__,
250                    launch_err_str);
251     ctx.LaunchStatus().SetError(-1, DNBError::Generic);
252     ctx.LaunchStatus().SetErrorString(launch_err_str);
253   } else if (pid == INVALID_NUB_PROCESS) {
254     DNBLogThreaded(
255         "%s DNBProcessLaunch() failed to launch process, unknown failure",
256         __FUNCTION__);
257     ctx.LaunchStatus().SetError(-1, DNBError::Generic);
258     ctx.LaunchStatus().SetErrorString("<unknown failure>");
259   } else {
260     ctx.LaunchStatus().Clear();
261   }
262 
263   if (remote->Comm().IsConnected()) {
264     // It we are connected already, the next thing gdb will do is ask
265     // whether the launch succeeded, and if not, whether there is an
266     // error code.  So we need to fetch one packet from gdb before we wait
267     // on the stop from the target.
268 
269     uint32_t event_mask = RNBContext::event_read_packet_available;
270     nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
271 
272     if (set_events & RNBContext::event_read_packet_available) {
273       rnb_err_t err = rnb_err;
274       RNBRemote::PacketEnum type;
275 
276       err = remote->HandleReceivedPacket(&type);
277 
278       if (err != rnb_success) {
279         DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Error getting packet.",
280                          __FUNCTION__);
281         return eRNBRunLoopModeExit;
282       }
283       if (type != RNBRemote::query_launch_success) {
284         DNBLogThreadedIf(LOG_RNB_MINIMAL,
285                          "%s Didn't get the expected qLaunchSuccess packet.",
286                          __FUNCTION__);
287       }
288     }
289   }
290 
291   while (pid != INVALID_NUB_PROCESS) {
292     // Wait for process to start up and hit entry point
293     DNBLogThreadedIf(LOG_RNB_EVENTS, "%s DNBProcessWaitForEvent (%4.4x, "
294                                      "eEventProcessRunningStateChanged | "
295                                      "eEventProcessStoppedStateChanged, true, "
296                                      "INFINITE)...",
297                      __FUNCTION__, pid);
298     nub_event_t set_events =
299         DNBProcessWaitForEvents(pid, eEventProcessRunningStateChanged |
300                                          eEventProcessStoppedStateChanged,
301                                 true, NULL);
302     DNBLogThreadedIf(LOG_RNB_EVENTS, "%s DNBProcessWaitForEvent (%4.4x, "
303                                      "eEventProcessRunningStateChanged | "
304                                      "eEventProcessStoppedStateChanged, true, "
305                                      "INFINITE) => 0x%8.8x",
306                      __FUNCTION__, pid, set_events);
307 
308     if (set_events == 0) {
309       pid = INVALID_NUB_PROCESS;
310       g_pid = pid;
311     } else {
312       if (set_events & (eEventProcessRunningStateChanged |
313                         eEventProcessStoppedStateChanged)) {
314         nub_state_t pid_state = DNBProcessGetState(pid);
315         DNBLogThreadedIf(
316             LOG_RNB_EVENTS,
317             "%s process %4.4x state changed (eEventProcessStateChanged): %s",
318             __FUNCTION__, pid, DNBStateAsString(pid_state));
319 
320         switch (pid_state) {
321         case eStateInvalid:
322         case eStateUnloaded:
323         case eStateAttaching:
324         case eStateLaunching:
325         case eStateSuspended:
326           break; // Ignore
327 
328         case eStateRunning:
329         case eStateStepping:
330           // Still waiting to stop at entry point...
331           break;
332 
333         case eStateStopped:
334         case eStateCrashed:
335           ctx.SetProcessID(pid);
336           return eRNBRunLoopModeInferiorExecuting;
337 
338         case eStateDetached:
339         case eStateExited:
340           pid = INVALID_NUB_PROCESS;
341           g_pid = pid;
342           return eRNBRunLoopModeExit;
343         }
344       }
345 
346       DNBProcessResetEvents(pid, set_events);
347     }
348   }
349 
350   return eRNBRunLoopModeExit;
351 }
352 
353 //----------------------------------------------------------------------
354 // This run loop mode will wait for the process to launch and hit its
355 // entry point. It will currently ignore all events except for the
356 // process state changed event, where it watches for the process stopped
357 // or crash process state.
358 //----------------------------------------------------------------------
359 RNBRunLoopMode RNBRunLoopLaunchAttaching(RNBRemote *remote,
360                                          nub_process_t attach_pid,
361                                          nub_process_t &pid) {
362   RNBContext &ctx = remote->Context();
363 
364   DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s Attaching to pid %i...", __FUNCTION__,
365                    attach_pid);
366   char err_str[1024];
367   pid = DNBProcessAttach(attach_pid, NULL, err_str, sizeof(err_str));
368   g_pid = pid;
369 
370   if (pid == INVALID_NUB_PROCESS) {
371     ctx.LaunchStatus().SetError(-1, DNBError::Generic);
372     if (err_str[0])
373       ctx.LaunchStatus().SetErrorString(err_str);
374     return eRNBRunLoopModeExit;
375   } else {
376     ctx.SetProcessID(pid);
377     return eRNBRunLoopModeInferiorExecuting;
378   }
379 }
380 
381 //----------------------------------------------------------------------
382 // Watch for signals:
383 // SIGINT: so we can halt our inferior. (disabled for now)
384 // SIGPIPE: in case our child process dies
385 //----------------------------------------------------------------------
386 int g_sigint_received = 0;
387 int g_sigpipe_received = 0;
388 void signal_handler(int signo) {
389   DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s (%s)", __FUNCTION__,
390                    SysSignal::Name(signo));
391 
392   switch (signo) {
393   case SIGINT:
394     g_sigint_received++;
395     if (g_pid != INVALID_NUB_PROCESS) {
396       // Only send a SIGINT once...
397       if (g_sigint_received == 1) {
398         switch (DNBProcessGetState(g_pid)) {
399         case eStateRunning:
400         case eStateStepping:
401           DNBProcessSignal(g_pid, SIGSTOP);
402           return;
403         default:
404           break;
405         }
406       }
407     }
408     exit(SIGINT);
409     break;
410 
411   case SIGPIPE:
412     g_sigpipe_received = 1;
413     break;
414   }
415 }
416 
417 // Return the new run loop mode based off of the current process state
418 RNBRunLoopMode HandleProcessStateChange(RNBRemote *remote, bool initialize) {
419   RNBContext &ctx = remote->Context();
420   nub_process_t pid = ctx.ProcessID();
421 
422   if (pid == INVALID_NUB_PROCESS) {
423     DNBLogThreadedIf(LOG_RNB_MINIMAL, "#### %s error: pid invalid, exiting...",
424                      __FUNCTION__);
425     return eRNBRunLoopModeExit;
426   }
427   nub_state_t pid_state = DNBProcessGetState(pid);
428 
429   DNBLogThreadedIf(LOG_RNB_MINIMAL,
430                    "%s (&remote, initialize=%i)  pid_state = %s", __FUNCTION__,
431                    (int)initialize, DNBStateAsString(pid_state));
432 
433   switch (pid_state) {
434   case eStateInvalid:
435   case eStateUnloaded:
436     // Something bad happened
437     return eRNBRunLoopModeExit;
438     break;
439 
440   case eStateAttaching:
441   case eStateLaunching:
442     return eRNBRunLoopModeInferiorExecuting;
443 
444   case eStateSuspended:
445   case eStateCrashed:
446   case eStateStopped:
447     // If we stop due to a signal, so clear the fact that we got a SIGINT
448     // so we can stop ourselves again (but only while our inferior
449     // process is running..)
450     g_sigint_received = 0;
451     if (initialize == false) {
452       // Compare the last stop count to our current notion of a stop count
453       // to make sure we don't notify more than once for a given stop.
454       nub_size_t prev_pid_stop_count = ctx.GetProcessStopCount();
455       bool pid_stop_count_changed =
456           ctx.SetProcessStopCount(DNBProcessGetStopCount(pid));
457       if (pid_stop_count_changed) {
458         remote->FlushSTDIO();
459 
460         if (ctx.GetProcessStopCount() == 1) {
461           DNBLogThreadedIf(
462               LOG_RNB_MINIMAL, "%s (&remote, initialize=%i)  pid_state = %s "
463                                "pid_stop_count %llu (old %llu)) Notify??? no, "
464                                "first stop...",
465               __FUNCTION__, (int)initialize, DNBStateAsString(pid_state),
466               (uint64_t)ctx.GetProcessStopCount(),
467               (uint64_t)prev_pid_stop_count);
468         } else {
469 
470           DNBLogThreadedIf(LOG_RNB_MINIMAL, "%s (&remote, initialize=%i)  "
471                                             "pid_state = %s pid_stop_count "
472                                             "%llu (old %llu)) Notify??? YES!!!",
473                            __FUNCTION__, (int)initialize,
474                            DNBStateAsString(pid_state),
475                            (uint64_t)ctx.GetProcessStopCount(),
476                            (uint64_t)prev_pid_stop_count);
477           remote->NotifyThatProcessStopped();
478         }
479       } else {
480         DNBLogThreadedIf(
481             LOG_RNB_MINIMAL, "%s (&remote, initialize=%i)  pid_state = %s "
482                              "pid_stop_count %llu (old %llu)) Notify??? "
483                              "skipping...",
484             __FUNCTION__, (int)initialize, DNBStateAsString(pid_state),
485             (uint64_t)ctx.GetProcessStopCount(), (uint64_t)prev_pid_stop_count);
486       }
487     }
488     return eRNBRunLoopModeInferiorExecuting;
489 
490   case eStateStepping:
491   case eStateRunning:
492     return eRNBRunLoopModeInferiorExecuting;
493 
494   case eStateExited:
495     remote->HandlePacket_last_signal(NULL);
496   case eStateDetached:
497     return eRNBRunLoopModeExit;
498   }
499 
500   // Catch all...
501   return eRNBRunLoopModeExit;
502 }
503 // This function handles the case where our inferior program is stopped and
504 // we are waiting for gdb remote protocol packets. When a packet occurs that
505 // makes the inferior run, we need to leave this function with a new state
506 // as the return code.
507 RNBRunLoopMode RNBRunLoopInferiorExecuting(RNBRemote *remote) {
508   DNBLogThreadedIf(LOG_RNB_MINIMAL, "#### %s", __FUNCTION__);
509   RNBContext &ctx = remote->Context();
510 
511   // Init our mode and set 'is_running' based on the current process state
512   RNBRunLoopMode mode = HandleProcessStateChange(remote, true);
513 
514   while (ctx.ProcessID() != INVALID_NUB_PROCESS) {
515 
516     std::string set_events_str;
517     uint32_t event_mask = ctx.NormalEventBits();
518 
519     if (!ctx.ProcessStateRunning()) {
520       // Clear some bits if we are not running so we don't send any async
521       // packets
522       event_mask &= ~RNBContext::event_proc_stdio_available;
523       event_mask &= ~RNBContext::event_proc_profile_data;
524       // When we enable async structured data packets over another logical
525       // channel,
526       // this can be relaxed.
527       event_mask &= ~RNBContext::event_darwin_log_data_available;
528     }
529 
530     // We want to make sure we consume all process state changes and have
531     // whomever is notifying us to wait for us to reset the event bit before
532     // continuing.
533     // ctx.Events().SetResetAckMask (RNBContext::event_proc_state_changed);
534 
535     DNBLogThreadedIf(LOG_RNB_EVENTS,
536                      "%s ctx.Events().WaitForSetEvents(0x%08x) ...",
537                      __FUNCTION__, event_mask);
538     nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
539     DNBLogThreadedIf(LOG_RNB_EVENTS,
540                      "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)",
541                      __FUNCTION__, event_mask, set_events,
542                      ctx.EventsAsString(set_events, set_events_str));
543 
544     if (set_events) {
545       if ((set_events & RNBContext::event_proc_thread_exiting) ||
546           (set_events & RNBContext::event_proc_stdio_available)) {
547         remote->FlushSTDIO();
548       }
549 
550       if (set_events & RNBContext::event_proc_profile_data) {
551         remote->SendAsyncProfileData();
552       }
553 
554       if (set_events & RNBContext::event_darwin_log_data_available) {
555         remote->SendAsyncDarwinLogData();
556       }
557 
558       if (set_events & RNBContext::event_read_packet_available) {
559         // handleReceivedPacket will take care of resetting the
560         // event_read_packet_available events when there are no more...
561         set_events ^= RNBContext::event_read_packet_available;
562 
563         if (ctx.ProcessStateRunning()) {
564           if (remote->HandleAsyncPacket() == rnb_not_connected) {
565             // TODO: connect again? Exit?
566           }
567         } else {
568           if (remote->HandleReceivedPacket() == rnb_not_connected) {
569             // TODO: connect again? Exit?
570           }
571         }
572       }
573 
574       if (set_events & RNBContext::event_proc_state_changed) {
575         mode = HandleProcessStateChange(remote, false);
576         ctx.Events().ResetEvents(RNBContext::event_proc_state_changed);
577         set_events ^= RNBContext::event_proc_state_changed;
578       }
579 
580       if (set_events & RNBContext::event_proc_thread_exiting) {
581         mode = eRNBRunLoopModeExit;
582       }
583 
584       if (set_events & RNBContext::event_read_thread_exiting) {
585         // Out remote packet receiving thread exited, exit for now.
586         if (ctx.HasValidProcessID()) {
587           // TODO: We should add code that will leave the current process
588           // in its current state and listen for another connection...
589           if (ctx.ProcessStateRunning()) {
590             if (ctx.GetDetachOnError()) {
591               DNBLog("debugserver's event read thread is exiting, detaching "
592                      "from the inferior process.");
593               DNBProcessDetach(ctx.ProcessID());
594             } else {
595               DNBLog("debugserver's event read thread is exiting, killing the "
596                      "inferior process.");
597               DNBProcessKill(ctx.ProcessID());
598             }
599           } else {
600             if (ctx.GetDetachOnError()) {
601               DNBLog("debugserver's event read thread is exiting, detaching "
602                      "from the inferior process.");
603               DNBProcessDetach(ctx.ProcessID());
604             }
605           }
606         }
607         mode = eRNBRunLoopModeExit;
608       }
609     }
610 
611     // Reset all event bits that weren't reset for now...
612     if (set_events != 0)
613       ctx.Events().ResetEvents(set_events);
614 
615     if (mode != eRNBRunLoopModeInferiorExecuting)
616       break;
617   }
618 
619   return mode;
620 }
621 
622 RNBRunLoopMode RNBRunLoopPlatform(RNBRemote *remote) {
623   RNBRunLoopMode mode = eRNBRunLoopModePlatformMode;
624   RNBContext &ctx = remote->Context();
625 
626   while (mode == eRNBRunLoopModePlatformMode) {
627     std::string set_events_str;
628     const uint32_t event_mask = RNBContext::event_read_packet_available |
629                                 RNBContext::event_read_thread_exiting;
630 
631     DNBLogThreadedIf(LOG_RNB_EVENTS,
632                      "%s ctx.Events().WaitForSetEvents(0x%08x) ...",
633                      __FUNCTION__, event_mask);
634     nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
635     DNBLogThreadedIf(LOG_RNB_EVENTS,
636                      "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)",
637                      __FUNCTION__, event_mask, set_events,
638                      ctx.EventsAsString(set_events, set_events_str));
639 
640     if (set_events) {
641       if (set_events & RNBContext::event_read_packet_available) {
642         if (remote->HandleReceivedPacket() == rnb_not_connected)
643           mode = eRNBRunLoopModeExit;
644       }
645 
646       if (set_events & RNBContext::event_read_thread_exiting) {
647         mode = eRNBRunLoopModeExit;
648       }
649       ctx.Events().ResetEvents(set_events);
650     }
651   }
652   return eRNBRunLoopModeExit;
653 }
654 
655 //----------------------------------------------------------------------
656 // Convenience function to set up the remote listening port
657 // Returns 1 for success 0 for failure.
658 //----------------------------------------------------------------------
659 
660 static void PortWasBoundCallbackUnixSocket(const void *baton, in_port_t port) {
661   //::printf ("PortWasBoundCallbackUnixSocket (baton = %p, port = %u)\n", baton,
662   //port);
663 
664   const char *unix_socket_name = (const char *)baton;
665 
666   if (unix_socket_name && unix_socket_name[0]) {
667     // We were given a unix socket name to use to communicate the port
668     // that we ended up binding to back to our parent process
669     struct sockaddr_un saddr_un;
670     int s = ::socket(AF_UNIX, SOCK_STREAM, 0);
671     if (s < 0) {
672       perror("error: socket (AF_UNIX, SOCK_STREAM, 0)");
673       exit(1);
674     }
675 
676     saddr_un.sun_family = AF_UNIX;
677     ::strlcpy(saddr_un.sun_path, unix_socket_name,
678               sizeof(saddr_un.sun_path) - 1);
679     saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
680     saddr_un.sun_len = SUN_LEN(&saddr_un);
681 
682     if (::connect(s, (struct sockaddr *)&saddr_un,
683                   static_cast<socklen_t>(SUN_LEN(&saddr_un))) < 0) {
684       perror("error: connect (socket, &saddr_un, saddr_un_len)");
685       exit(1);
686     }
687 
688     //::printf ("connect () sucess!!\n");
689 
690     // We were able to connect to the socket, now write our PID so whomever
691     // launched us will know this process's ID
692     RNBLogSTDOUT("Listening to port %i...\n", port);
693 
694     char pid_str[64];
695     const int pid_str_len = ::snprintf(pid_str, sizeof(pid_str), "%u", port);
696     const ssize_t bytes_sent = ::send(s, pid_str, pid_str_len, 0);
697 
698     if (pid_str_len != bytes_sent) {
699       perror("error: send (s, pid_str, pid_str_len, 0)");
700       exit(1);
701     }
702 
703     //::printf ("send () sucess!!\n");
704 
705     // We are done with the socket
706     close(s);
707   }
708 }
709 
710 static void PortWasBoundCallbackNamedPipe(const void *baton, uint16_t port) {
711   const char *named_pipe = (const char *)baton;
712   if (named_pipe && named_pipe[0]) {
713     int fd = ::open(named_pipe, O_WRONLY);
714     if (fd > -1) {
715       char port_str[64];
716       const ssize_t port_str_len =
717           ::snprintf(port_str, sizeof(port_str), "%u", port);
718       // Write the port number as a C string with the NULL terminator
719       ::write(fd, port_str, port_str_len + 1);
720       close(fd);
721     }
722   }
723 }
724 
725 static int ConnectRemote(RNBRemote *remote, const char *host, int port,
726                          bool reverse_connect, const char *named_pipe_path,
727                          const char *unix_socket_name) {
728   if (!remote->Comm().IsConnected()) {
729     if (reverse_connect) {
730       if (port == 0) {
731         DNBLogThreaded(
732             "error: invalid port supplied for reverse connection: %i.\n", port);
733         return 0;
734       }
735       if (remote->Comm().Connect(host, port) != rnb_success) {
736         DNBLogThreaded("Failed to reverse connect to %s:%i.\n", host, port);
737         return 0;
738       }
739     } else {
740       if (port != 0)
741         RNBLogSTDOUT("Listening to port %i for a connection from %s...\n", port,
742                      host ? host : "127.0.0.1");
743       if (unix_socket_name && unix_socket_name[0]) {
744         if (remote->Comm().Listen(host, port, PortWasBoundCallbackUnixSocket,
745                                   unix_socket_name) != rnb_success) {
746           RNBLogSTDERR("Failed to get connection from a remote gdb process.\n");
747           return 0;
748         }
749       } else {
750         if (remote->Comm().Listen(host, port, PortWasBoundCallbackNamedPipe,
751                                   named_pipe_path) != rnb_success) {
752           RNBLogSTDERR("Failed to get connection from a remote gdb process.\n");
753           return 0;
754         }
755       }
756     }
757     remote->StartReadRemoteDataThread();
758   }
759   return 1;
760 }
761 
762 //----------------------------------------------------------------------
763 // ASL Logging callback that can be registered with DNBLogSetLogCallback
764 //----------------------------------------------------------------------
765 void ASLLogCallback(void *baton, uint32_t flags, const char *format,
766                     va_list args) {
767   if (format == NULL)
768     return;
769   static aslmsg g_aslmsg = NULL;
770   if (g_aslmsg == NULL) {
771     g_aslmsg = ::asl_new(ASL_TYPE_MSG);
772     char asl_key_sender[PATH_MAX];
773     snprintf(asl_key_sender, sizeof(asl_key_sender), "com.apple.%s-%s",
774              DEBUGSERVER_PROGRAM_NAME, DEBUGSERVER_VERSION_STR);
775     ::asl_set(g_aslmsg, ASL_KEY_SENDER, asl_key_sender);
776   }
777 
778   int asl_level;
779   if (flags & DNBLOG_FLAG_FATAL)
780     asl_level = ASL_LEVEL_CRIT;
781   else if (flags & DNBLOG_FLAG_ERROR)
782     asl_level = ASL_LEVEL_ERR;
783   else if (flags & DNBLOG_FLAG_WARNING)
784     asl_level = ASL_LEVEL_WARNING;
785   else if (flags & DNBLOG_FLAG_VERBOSE)
786     asl_level = ASL_LEVEL_WARNING; // ASL_LEVEL_INFO;
787   else
788     asl_level = ASL_LEVEL_WARNING; // ASL_LEVEL_DEBUG;
789 
790   ::asl_vlog(NULL, g_aslmsg, asl_level, format, args);
791 }
792 
793 //----------------------------------------------------------------------
794 // FILE based Logging callback that can be registered with
795 // DNBLogSetLogCallback
796 //----------------------------------------------------------------------
797 void FileLogCallback(void *baton, uint32_t flags, const char *format,
798                      va_list args) {
799   if (baton == NULL || format == NULL)
800     return;
801 
802   ::vfprintf((FILE *)baton, format, args);
803   ::fprintf((FILE *)baton, "\n");
804   ::fflush((FILE *)baton);
805 }
806 
807 void show_usage_and_exit(int exit_code) {
808   RNBLogSTDERR(
809       "Usage:\n  %s host:port [program-name program-arg1 program-arg2 ...]\n",
810       DEBUGSERVER_PROGRAM_NAME);
811   RNBLogSTDERR("  %s /path/file [program-name program-arg1 program-arg2 ...]\n",
812                DEBUGSERVER_PROGRAM_NAME);
813   RNBLogSTDERR("  %s host:port --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME);
814   RNBLogSTDERR("  %s /path/file --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME);
815   RNBLogSTDERR("  %s host:port --attach=<process_name>\n",
816                DEBUGSERVER_PROGRAM_NAME);
817   RNBLogSTDERR("  %s /path/file --attach=<process_name>\n",
818                DEBUGSERVER_PROGRAM_NAME);
819   exit(exit_code);
820 }
821 
822 //----------------------------------------------------------------------
823 // option descriptors for getopt_long_only()
824 //----------------------------------------------------------------------
825 static struct option g_long_options[] = {
826     {"attach", required_argument, NULL, 'a'},
827     {"arch", required_argument, NULL, 'A'},
828     {"debug", no_argument, NULL, 'g'},
829     {"kill-on-error", no_argument, NULL, 'K'},
830     {"verbose", no_argument, NULL, 'v'},
831     {"lockdown", no_argument, &g_lockdown_opt, 1}, // short option "-k"
832     {"applist", no_argument, &g_applist_opt, 1},   // short option "-t"
833     {"log-file", required_argument, NULL, 'l'},
834     {"log-flags", required_argument, NULL, 'f'},
835     {"launch", required_argument, NULL, 'x'}, // Valid values are "auto",
836                                               // "posix-spawn", "fork-exec",
837                                               // "springboard" (arm only)
838     {"waitfor", required_argument, NULL,
839      'w'}, // Wait for a process whose name starts with ARG
840     {"waitfor-interval", required_argument, NULL,
841      'i'}, // Time in usecs to wait between sampling the pid list when waiting
842            // for a process by name
843     {"waitfor-duration", required_argument, NULL,
844      'd'}, // The time in seconds to wait for a process to show up by name
845     {"native-regs", no_argument, NULL, 'r'}, // Specify to use the native
846                                              // registers instead of the gdb
847                                              // defaults for the architecture.
848     {"stdio-path", required_argument, NULL,
849      's'}, // Set the STDIO path to be used when launching applications (STDIN,
850            // STDOUT and STDERR) (only if debugserver launches the process)
851     {"stdin-path", required_argument, NULL,
852      'I'}, // Set the STDIN path to be used when launching applications (only if
853            // debugserver launches the process)
854     {"stdout-path", required_argument, NULL,
855      'O'}, // Set the STDOUT path to be used when launching applications (only
856            // if debugserver launches the process)
857     {"stderr-path", required_argument, NULL,
858      'E'}, // Set the STDERR path to be used when launching applications (only
859            // if debugserver launches the process)
860     {"no-stdio", no_argument, NULL,
861      'n'}, // Do not set up any stdio (perhaps the program is a GUI program)
862            // (only if debugserver launches the process)
863     {"setsid", no_argument, NULL,
864      'S'}, // call setsid() to make debugserver run in its own session
865     {"disable-aslr", no_argument, NULL, 'D'}, // Use _POSIX_SPAWN_DISABLE_ASLR
866                                               // to avoid shared library
867                                               // randomization
868     {"working-dir", required_argument, NULL,
869      'W'}, // The working directory that the inferior process should have (only
870            // if debugserver launches the process)
871     {"platform", required_argument, NULL,
872      'p'}, // Put this executable into a remote platform mode
873     {"unix-socket", required_argument, NULL,
874      'u'}, // If we need to handshake with our parent process, an option will be
875            // passed down that specifies a unix socket name to use
876     {"fd", required_argument, NULL,
877      '2'}, // A file descriptor was passed to this process when spawned that
878            // is already open and ready for communication
879     {"named-pipe", required_argument, NULL, 'P'},
880     {"reverse-connect", no_argument, NULL, 'R'},
881     {"env", required_argument, NULL,
882      'e'}, // When debugserver launches the process, set a single environment
883            // entry as specified by the option value ("./debugserver -e FOO=1 -e
884            // BAR=2 localhost:1234 -- /bin/ls")
885     {"forward-env", no_argument, NULL,
886      'F'}, // When debugserver launches the process, forward debugserver's
887            // current environment variables to the child process ("./debugserver
888            // -F localhost:1234 -- /bin/ls"
889     {NULL, 0, NULL, 0}};
890 
891 //----------------------------------------------------------------------
892 // main
893 //----------------------------------------------------------------------
894 int main(int argc, char *argv[]) {
895   // If debugserver is launched with DYLD_INSERT_LIBRARIES, unset it so we
896   // don't spawn child processes with this enabled.
897   unsetenv("DYLD_INSERT_LIBRARIES");
898 
899   const char *argv_sub_zero =
900       argv[0]; // save a copy of argv[0] for error reporting post-launch
901 
902 #if defined(__APPLE__)
903   pthread_setname_np("main thread");
904 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
905   struct sched_param thread_param;
906   int thread_sched_policy;
907   if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
908                             &thread_param) == 0) {
909     thread_param.sched_priority = 47;
910     pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
911   }
912 
913   ::proc_set_wakemon_params(
914       getpid(), 500,
915       0); // Allow up to 500 wakeups/sec to avoid EXC_RESOURCE for normal use.
916 #endif
917 #endif
918 
919   g_isatty = ::isatty(STDIN_FILENO);
920 
921   //  ::printf ("uid=%u euid=%u gid=%u egid=%u\n",
922   //            getuid(),
923   //            geteuid(),
924   //            getgid(),
925   //            getegid());
926 
927   //    signal (SIGINT, signal_handler);
928   signal(SIGPIPE, signal_handler);
929   signal(SIGHUP, signal_handler);
930 
931   // We're always sitting in waitpid or kevent waiting on our target process'
932   // death,
933   // we don't need no stinking SIGCHLD's...
934 
935   sigset_t sigset;
936   sigemptyset(&sigset);
937   sigaddset(&sigset, SIGCHLD);
938   sigprocmask(SIG_BLOCK, &sigset, NULL);
939 
940   g_remoteSP.reset(new RNBRemote());
941 
942   RNBRemote *remote = g_remoteSP.get();
943   if (remote == NULL) {
944     RNBLogSTDERR("error: failed to create a remote connection class\n");
945     return -1;
946   }
947 
948   RNBContext &ctx = remote->Context();
949 
950   int i;
951   int attach_pid = INVALID_NUB_PROCESS;
952 
953   FILE *log_file = NULL;
954   uint32_t log_flags = 0;
955   // Parse our options
956   int ch;
957   int long_option_index = 0;
958   int debug = 0;
959   int communication_fd = -1;
960   std::string compile_options;
961   std::string waitfor_pid_name; // Wait for a process that starts with this name
962   std::string attach_pid_name;
963   std::string arch_name;
964   std::string working_dir; // The new working directory to use for the inferior
965   std::string unix_socket_name; // If we need to handshake with our parent
966                                 // process, an option will be passed down that
967                                 // specifies a unix socket name to use
968   std::string named_pipe_path;  // If we need to handshake with our parent
969                                 // process, an option will be passed down that
970                                 // specifies a named pipe to use
971   useconds_t waitfor_interval = 1000; // Time in usecs between process lists
972                                       // polls when waiting for a process by
973                                       // name, default 1 msec.
974   useconds_t waitfor_duration =
975       0; // Time in seconds to wait for a process by name, 0 means wait forever.
976   bool no_stdio = false;
977   bool reverse_connect = false; // Set to true by an option to indicate we
978                                 // should reverse connect to the host:port
979                                 // supplied as the first debugserver argument
980 
981 #if !defined(DNBLOG_ENABLED)
982   compile_options += "(no-logging) ";
983 #endif
984 
985   RNBRunLoopMode start_mode = eRNBRunLoopModeExit;
986 
987   char short_options[512];
988   uint32_t short_options_idx = 0;
989 
990   // Handle the two case that don't have short options in g_long_options
991   short_options[short_options_idx++] = 'k';
992   short_options[short_options_idx++] = 't';
993 
994   for (i = 0; g_long_options[i].name != NULL; ++i) {
995     if (isalpha(g_long_options[i].val)) {
996       short_options[short_options_idx++] = g_long_options[i].val;
997       switch (g_long_options[i].has_arg) {
998       default:
999       case no_argument:
1000         break;
1001 
1002       case optional_argument:
1003         short_options[short_options_idx++] = ':';
1004       // Fall through to required_argument case below...
1005       case required_argument:
1006         short_options[short_options_idx++] = ':';
1007         break;
1008       }
1009     }
1010   }
1011   // NULL terminate the short option string.
1012   short_options[short_options_idx++] = '\0';
1013 
1014 #if __GLIBC__
1015   optind = 0;
1016 #else
1017   optreset = 1;
1018   optind = 1;
1019 #endif
1020 
1021   bool forward_env = false;
1022   while ((ch = getopt_long_only(argc, argv, short_options, g_long_options,
1023                                 &long_option_index)) != -1) {
1024     DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n", ch, (uint8_t)ch,
1025                 g_long_options[long_option_index].name,
1026                 g_long_options[long_option_index].has_arg ? '=' : ' ',
1027                 optarg ? optarg : "");
1028     switch (ch) {
1029     case 0: // Any optional that auto set themselves will return 0
1030       break;
1031 
1032     case 'A':
1033       if (optarg && optarg[0])
1034         arch_name.assign(optarg);
1035       break;
1036 
1037     case 'a':
1038       if (optarg && optarg[0]) {
1039         if (isdigit(optarg[0])) {
1040           char *end = NULL;
1041           attach_pid = static_cast<int>(strtoul(optarg, &end, 0));
1042           if (end == NULL || *end != '\0') {
1043             RNBLogSTDERR("error: invalid pid option '%s'\n", optarg);
1044             exit(4);
1045           }
1046         } else {
1047           attach_pid_name = optarg;
1048         }
1049         start_mode = eRNBRunLoopModeInferiorAttaching;
1050       }
1051       break;
1052 
1053     // --waitfor=NAME
1054     case 'w':
1055       if (optarg && optarg[0]) {
1056         waitfor_pid_name = optarg;
1057         start_mode = eRNBRunLoopModeInferiorAttaching;
1058       }
1059       break;
1060 
1061     // --waitfor-interval=USEC
1062     case 'i':
1063       if (optarg && optarg[0]) {
1064         char *end = NULL;
1065         waitfor_interval = static_cast<useconds_t>(strtoul(optarg, &end, 0));
1066         if (end == NULL || *end != '\0') {
1067           RNBLogSTDERR("error: invalid waitfor-interval option value '%s'.\n",
1068                        optarg);
1069           exit(6);
1070         }
1071       }
1072       break;
1073 
1074     // --waitfor-duration=SEC
1075     case 'd':
1076       if (optarg && optarg[0]) {
1077         char *end = NULL;
1078         waitfor_duration = static_cast<useconds_t>(strtoul(optarg, &end, 0));
1079         if (end == NULL || *end != '\0') {
1080           RNBLogSTDERR("error: invalid waitfor-duration option value '%s'.\n",
1081                        optarg);
1082           exit(7);
1083         }
1084       }
1085       break;
1086 
1087     case 'K':
1088       g_detach_on_error = false;
1089       break;
1090     case 'W':
1091       if (optarg && optarg[0])
1092         working_dir.assign(optarg);
1093       break;
1094 
1095     case 'x':
1096       if (optarg && optarg[0]) {
1097         if (strcasecmp(optarg, "auto") == 0)
1098           g_launch_flavor = eLaunchFlavorDefault;
1099         else if (strcasestr(optarg, "posix") == optarg)
1100           g_launch_flavor = eLaunchFlavorPosixSpawn;
1101         else if (strcasestr(optarg, "fork") == optarg)
1102           g_launch_flavor = eLaunchFlavorForkExec;
1103 #ifdef WITH_SPRINGBOARD
1104         else if (strcasestr(optarg, "spring") == optarg)
1105           g_launch_flavor = eLaunchFlavorSpringBoard;
1106 #endif
1107 #ifdef WITH_BKS
1108         else if (strcasestr(optarg, "backboard") == optarg)
1109           g_launch_flavor = eLaunchFlavorBKS;
1110 #endif
1111 #ifdef WITH_FBS
1112         else if (strcasestr(optarg, "frontboard") == optarg)
1113           g_launch_flavor = eLaunchFlavorFBS;
1114 #endif
1115 
1116         else {
1117           RNBLogSTDERR("error: invalid TYPE for the --launch=TYPE (-x TYPE) "
1118                        "option: '%s'\n",
1119                        optarg);
1120           RNBLogSTDERR("Valid values TYPE are:\n");
1121           RNBLogSTDERR(
1122               "  auto       Auto-detect the best launch method to use.\n");
1123           RNBLogSTDERR(
1124               "  posix      Launch the executable using posix_spawn.\n");
1125           RNBLogSTDERR(
1126               "  fork       Launch the executable using fork and exec.\n");
1127 #ifdef WITH_SPRINGBOARD
1128           RNBLogSTDERR(
1129               "  spring     Launch the executable through Springboard.\n");
1130 #endif
1131 #ifdef WITH_BKS
1132           RNBLogSTDERR("  backboard  Launch the executable through BackBoard "
1133                        "Services.\n");
1134 #endif
1135 #ifdef WITH_FBS
1136           RNBLogSTDERR("  frontboard  Launch the executable through FrontBoard "
1137                        "Services.\n");
1138 #endif
1139           exit(5);
1140         }
1141       }
1142       break;
1143 
1144     case 'l': // Set Log File
1145       if (optarg && optarg[0]) {
1146         if (strcasecmp(optarg, "stdout") == 0)
1147           log_file = stdout;
1148         else if (strcasecmp(optarg, "stderr") == 0)
1149           log_file = stderr;
1150         else {
1151           log_file = fopen(optarg, "w");
1152           if (log_file != NULL)
1153             setlinebuf(log_file);
1154         }
1155 
1156         if (log_file == NULL) {
1157           const char *errno_str = strerror(errno);
1158           RNBLogSTDERR(
1159               "Failed to open log file '%s' for writing: errno = %i (%s)",
1160               optarg, errno, errno_str ? errno_str : "unknown error");
1161         }
1162       }
1163       break;
1164 
1165     case 'f': // Log Flags
1166       if (optarg && optarg[0])
1167         log_flags = static_cast<uint32_t>(strtoul(optarg, NULL, 0));
1168       break;
1169 
1170     case 'g':
1171       debug = 1;
1172       DNBLogSetDebug(debug);
1173       break;
1174 
1175     case 't':
1176       g_applist_opt = 1;
1177       break;
1178 
1179     case 'k':
1180       g_lockdown_opt = 1;
1181       break;
1182 
1183     case 'r':
1184       // Do nothing, native regs is the default these days
1185       break;
1186 
1187     case 'R':
1188       reverse_connect = true;
1189       break;
1190     case 'v':
1191       DNBLogSetVerbose(1);
1192       break;
1193 
1194     case 's':
1195       ctx.GetSTDIN().assign(optarg);
1196       ctx.GetSTDOUT().assign(optarg);
1197       ctx.GetSTDERR().assign(optarg);
1198       break;
1199 
1200     case 'I':
1201       ctx.GetSTDIN().assign(optarg);
1202       break;
1203 
1204     case 'O':
1205       ctx.GetSTDOUT().assign(optarg);
1206       break;
1207 
1208     case 'E':
1209       ctx.GetSTDERR().assign(optarg);
1210       break;
1211 
1212     case 'n':
1213       no_stdio = true;
1214       break;
1215 
1216     case 'S':
1217       // Put debugserver into a new session. Terminals group processes
1218       // into sessions and when a special terminal key sequences
1219       // (like control+c) are typed they can cause signals to go out to
1220       // all processes in a session. Using this --setsid (-S) option
1221       // will cause debugserver to run in its own sessions and be free
1222       // from such issues.
1223       //
1224       // This is useful when debugserver is spawned from a command
1225       // line application that uses debugserver to do the debugging,
1226       // yet that application doesn't want debugserver receiving the
1227       // signals sent to the session (i.e. dying when anyone hits ^C).
1228       setsid();
1229       break;
1230     case 'D':
1231       g_disable_aslr = 1;
1232       break;
1233 
1234     case 'p':
1235       start_mode = eRNBRunLoopModePlatformMode;
1236       break;
1237 
1238     case 'u':
1239       unix_socket_name.assign(optarg);
1240       break;
1241 
1242     case 'P':
1243       named_pipe_path.assign(optarg);
1244       break;
1245 
1246     case 'e':
1247       // Pass a single specified environment variable down to the process that
1248       // gets launched
1249       remote->Context().PushEnvironment(optarg);
1250       break;
1251 
1252     case 'F':
1253       forward_env = true;
1254       break;
1255 
1256     case '2':
1257       // File descriptor passed to this process during fork/exec and is already
1258       // open and ready for communication.
1259       communication_fd = atoi(optarg);
1260       break;
1261     }
1262   }
1263 
1264   if (arch_name.empty()) {
1265 #if defined(__arm__)
1266     arch_name.assign("arm");
1267 #endif
1268   } else {
1269     DNBSetArchitecture(arch_name.c_str());
1270   }
1271 
1272   //    if (arch_name.empty())
1273   //    {
1274   //        fprintf(stderr, "error: no architecture was specified\n");
1275   //        exit (8);
1276   //    }
1277   // Skip any options we consumed with getopt_long_only
1278   argc -= optind;
1279   argv += optind;
1280 
1281   if (!working_dir.empty()) {
1282     if (remote->Context().SetWorkingDirectory(working_dir.c_str()) == false) {
1283       RNBLogSTDERR("error: working directory doesn't exist '%s'.\n",
1284                    working_dir.c_str());
1285       exit(8);
1286     }
1287   }
1288 
1289   remote->Context().SetDetachOnError(g_detach_on_error);
1290 
1291   remote->Initialize();
1292 
1293   // It is ok for us to set NULL as the logfile (this will disable any logging)
1294 
1295   if (log_file != NULL) {
1296     DNBLogSetLogCallback(FileLogCallback, log_file);
1297     // If our log file was set, yet we have no log flags, log everything!
1298     if (log_flags == 0)
1299       log_flags = LOG_ALL | LOG_RNB_ALL;
1300 
1301     DNBLogSetLogMask(log_flags);
1302   } else {
1303     // Enable DNB logging
1304 
1305     // if os_log() support is available, log through that.
1306     auto log_callback = OsLogger::GetLogFunction();
1307     if (log_callback) {
1308       DNBLogSetLogCallback(log_callback, nullptr);
1309       DNBLog("debugserver will use os_log for internal logging.");
1310     } else {
1311       // Fall back to ASL support.
1312       DNBLogSetLogCallback(ASLLogCallback, NULL);
1313       DNBLog("debugserver will use ASL for internal logging.");
1314     }
1315     DNBLogSetLogMask(log_flags);
1316   }
1317 
1318   if (DNBLogEnabled()) {
1319     for (i = 0; i < argc; i++)
1320       DNBLogDebug("argv[%i] = %s", i, argv[i]);
1321   }
1322 
1323   // as long as we're dropping remotenub in as a replacement for gdbserver,
1324   // explicitly note that this is not gdbserver.
1325 
1326   RNBLogSTDOUT("%s-%s %sfor %s.\n", DEBUGSERVER_PROGRAM_NAME,
1327                DEBUGSERVER_VERSION_STR, compile_options.c_str(), RNB_ARCH);
1328 
1329   std::string host;
1330   int port = INT32_MAX;
1331   char str[PATH_MAX];
1332   str[0] = '\0';
1333 
1334   if (g_lockdown_opt == 0 && g_applist_opt == 0 && communication_fd == -1) {
1335     // Make sure we at least have port
1336     if (argc < 1) {
1337       show_usage_and_exit(1);
1338     }
1339     // accept 'localhost:' prefix on port number
1340     std::string host_specifier = argv[0];
1341     auto colon_location = host_specifier.rfind(':');
1342     if (colon_location != std::string::npos) {
1343       host = host_specifier.substr(0, colon_location);
1344       std::string port_str =
1345           host_specifier.substr(colon_location + 1, std::string::npos);
1346       char *end_ptr;
1347       port = strtoul(port_str.c_str(), &end_ptr, 0);
1348       if (end_ptr < port_str.c_str() + port_str.size())
1349         show_usage_and_exit(2);
1350       if (host.front() == '[' && host.back() == ']')
1351         host = host.substr(1, host.size() - 2);
1352       DNBLogDebug("host = '%s'  port = %i", host.c_str(), port);
1353     } else {
1354       // No hostname means "localhost"
1355       int items_scanned = ::sscanf(argv[0], "%i", &port);
1356       if (items_scanned == 1) {
1357         host = "127.0.0.1";
1358         DNBLogDebug("host = '%s'  port = %i", host.c_str(), port);
1359       } else if (argv[0][0] == '/') {
1360         port = INT32_MAX;
1361         strlcpy(str, argv[0], sizeof(str));
1362       } else {
1363         show_usage_and_exit(2);
1364       }
1365     }
1366 
1367     // We just used the 'host:port' or the '/path/file' arg...
1368     argc--;
1369     argv++;
1370   }
1371 
1372   //  If we know we're waiting to attach, we don't need any of this other info.
1373   if (start_mode != eRNBRunLoopModeInferiorAttaching &&
1374       start_mode != eRNBRunLoopModePlatformMode) {
1375     if (argc == 0 || g_lockdown_opt) {
1376       if (g_lockdown_opt != 0) {
1377         // Work around for SIGPIPE crashes due to posix_spawn issue.
1378         // We have to close STDOUT and STDERR, else the first time we
1379         // try and do any, we get SIGPIPE and die as posix_spawn is
1380         // doing bad things with our file descriptors at the moment.
1381         int null = open("/dev/null", O_RDWR);
1382         dup2(null, STDOUT_FILENO);
1383         dup2(null, STDERR_FILENO);
1384       } else if (g_applist_opt != 0) {
1385         // List all applications we are able to see
1386         std::string applist_plist;
1387         int err = ListApplications(applist_plist, false, false);
1388         if (err == 0) {
1389           fputs(applist_plist.c_str(), stdout);
1390         } else {
1391           RNBLogSTDERR("error: ListApplications returned error %i\n", err);
1392         }
1393         // Exit with appropriate error if we were asked to list the applications
1394         // with no other args were given (and we weren't trying to do this over
1395         // lockdown)
1396         return err;
1397       }
1398 
1399       DNBLogDebug("Get args from remote protocol...");
1400       start_mode = eRNBRunLoopModeGetStartModeFromRemoteProtocol;
1401     } else {
1402       start_mode = eRNBRunLoopModeInferiorLaunching;
1403       // Fill in the argv array in the context from the rest of our args.
1404       // Skip the name of this executable and the port number
1405       for (int i = 0; i < argc; i++) {
1406         DNBLogDebug("inferior_argv[%i] = '%s'", i, argv[i]);
1407         ctx.PushArgument(argv[i]);
1408       }
1409     }
1410   }
1411 
1412   if (start_mode == eRNBRunLoopModeExit)
1413     return -1;
1414 
1415   if (forward_env || start_mode == eRNBRunLoopModeInferiorLaunching) {
1416     // Pass the current environment down to the process that gets launched
1417     // This happens automatically in the "launching" mode. For the rest, we
1418     // only do that if the user explicitly requested this via --forward-env
1419     // argument.
1420     char **host_env = *_NSGetEnviron();
1421     char *env_entry;
1422     size_t i;
1423     for (i = 0; (env_entry = host_env[i]) != NULL; ++i)
1424       remote->Context().PushEnvironmentIfNeeded(env_entry);
1425   }
1426 
1427   RNBRunLoopMode mode = start_mode;
1428   char err_str[1024] = {'\0'};
1429 
1430   while (mode != eRNBRunLoopModeExit) {
1431     switch (mode) {
1432     case eRNBRunLoopModeGetStartModeFromRemoteProtocol:
1433 #ifdef WITH_LOCKDOWN
1434       if (g_lockdown_opt) {
1435         if (!remote->Comm().IsConnected()) {
1436           if (remote->Comm().ConnectToService() != rnb_success) {
1437             RNBLogSTDERR(
1438                 "Failed to get connection from a remote gdb process.\n");
1439             mode = eRNBRunLoopModeExit;
1440           } else if (g_applist_opt != 0) {
1441             // List all applications we are able to see
1442             std::string applist_plist;
1443             if (ListApplications(applist_plist, false, false) == 0) {
1444               DNBLogDebug("Task list: %s", applist_plist.c_str());
1445 
1446               remote->Comm().Write(applist_plist.c_str(), applist_plist.size());
1447               // Issue a read that will never yield any data until the other
1448               // side
1449               // closes the socket so this process doesn't just exit and cause
1450               // the
1451               // socket to close prematurely on the other end and cause data
1452               // loss.
1453               std::string buf;
1454               remote->Comm().Read(buf);
1455             }
1456             remote->Comm().Disconnect(false);
1457             mode = eRNBRunLoopModeExit;
1458             break;
1459           } else {
1460             // Start watching for remote packets
1461             remote->StartReadRemoteDataThread();
1462           }
1463         }
1464       } else
1465 #endif
1466           if (port != INT32_MAX) {
1467         if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1468                            named_pipe_path.c_str(), unix_socket_name.c_str()))
1469           mode = eRNBRunLoopModeExit;
1470       } else if (str[0] == '/') {
1471         if (remote->Comm().OpenFile(str))
1472           mode = eRNBRunLoopModeExit;
1473       } else if (communication_fd >= 0) {
1474         // We were passed a file descriptor to use during fork/exec that is
1475         // already open
1476         // in our process, so lets just use it!
1477         if (remote->Comm().useFD(communication_fd))
1478           mode = eRNBRunLoopModeExit;
1479         else
1480           remote->StartReadRemoteDataThread();
1481       }
1482 
1483       if (mode != eRNBRunLoopModeExit) {
1484         RNBLogSTDOUT("Got a connection, waiting for process information for "
1485                      "launching or attaching.\n");
1486 
1487         mode = RNBRunLoopGetStartModeFromRemote(remote);
1488       }
1489       break;
1490 
1491     case eRNBRunLoopModeInferiorAttaching:
1492       if (!waitfor_pid_name.empty()) {
1493         // Set our end wait time if we are using a waitfor-duration
1494         // option that may have been specified
1495         struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1496         if (waitfor_duration != 0) {
1497           DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration,
1498                                     0);
1499           timeout_ptr = &attach_timeout_abstime;
1500         }
1501         nub_launch_flavor_t launch_flavor = g_launch_flavor;
1502         if (launch_flavor == eLaunchFlavorDefault) {
1503           // Our default launch method is posix spawn
1504           launch_flavor = eLaunchFlavorPosixSpawn;
1505 
1506 #if defined WITH_FBS
1507           // Check if we have an app bundle, if so launch using SpringBoard.
1508           if (waitfor_pid_name.find(".app") != std::string::npos) {
1509             launch_flavor = eLaunchFlavorFBS;
1510           }
1511 #elif defined WITH_BKS
1512           // Check if we have an app bundle, if so launch using SpringBoard.
1513           if (waitfor_pid_name.find(".app") != std::string::npos) {
1514             launch_flavor = eLaunchFlavorBKS;
1515           }
1516 #elif defined WITH_SPRINGBOARD
1517           // Check if we have an app bundle, if so launch using SpringBoard.
1518           if (waitfor_pid_name.find(".app") != std::string::npos) {
1519             launch_flavor = eLaunchFlavorSpringBoard;
1520           }
1521 #endif
1522         }
1523 
1524         ctx.SetLaunchFlavor(launch_flavor);
1525         bool ignore_existing = false;
1526         RNBLogSTDOUT("Waiting to attach to process %s...\n",
1527                      waitfor_pid_name.c_str());
1528         nub_process_t pid = DNBProcessAttachWait(
1529             waitfor_pid_name.c_str(), launch_flavor, ignore_existing,
1530             timeout_ptr, waitfor_interval, err_str, sizeof(err_str));
1531         g_pid = pid;
1532 
1533         if (pid == INVALID_NUB_PROCESS) {
1534           ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1535           if (err_str[0])
1536             ctx.LaunchStatus().SetErrorString(err_str);
1537           RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n",
1538                        waitfor_pid_name.c_str(), err_str);
1539           mode = eRNBRunLoopModeExit;
1540         } else {
1541           ctx.SetProcessID(pid);
1542           mode = eRNBRunLoopModeInferiorExecuting;
1543         }
1544       } else if (attach_pid != INVALID_NUB_PROCESS) {
1545 
1546         RNBLogSTDOUT("Attaching to process %i...\n", attach_pid);
1547         nub_process_t attached_pid;
1548         mode = RNBRunLoopLaunchAttaching(remote, attach_pid, attached_pid);
1549         if (mode != eRNBRunLoopModeInferiorExecuting) {
1550           const char *error_str = remote->Context().LaunchStatus().AsString();
1551           RNBLogSTDERR("error: failed to attach process %i: %s\n", attach_pid,
1552                        error_str ? error_str : "unknown error.");
1553           mode = eRNBRunLoopModeExit;
1554         }
1555       } else if (!attach_pid_name.empty()) {
1556         struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1557         if (waitfor_duration != 0) {
1558           DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration,
1559                                     0);
1560           timeout_ptr = &attach_timeout_abstime;
1561         }
1562 
1563         RNBLogSTDOUT("Attaching to process %s...\n", attach_pid_name.c_str());
1564         nub_process_t pid = DNBProcessAttachByName(
1565             attach_pid_name.c_str(), timeout_ptr, err_str, sizeof(err_str));
1566         g_pid = pid;
1567         if (pid == INVALID_NUB_PROCESS) {
1568           ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1569           if (err_str[0])
1570             ctx.LaunchStatus().SetErrorString(err_str);
1571           RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n",
1572                        waitfor_pid_name.c_str(), err_str);
1573           mode = eRNBRunLoopModeExit;
1574         } else {
1575           ctx.SetProcessID(pid);
1576           mode = eRNBRunLoopModeInferiorExecuting;
1577         }
1578 
1579       } else {
1580         RNBLogSTDERR(
1581             "error: asked to attach with empty name and invalid PID.\n");
1582         mode = eRNBRunLoopModeExit;
1583       }
1584 
1585       if (mode != eRNBRunLoopModeExit) {
1586         if (port != INT32_MAX) {
1587           if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1588                              named_pipe_path.c_str(), unix_socket_name.c_str()))
1589             mode = eRNBRunLoopModeExit;
1590         } else if (str[0] == '/') {
1591           if (remote->Comm().OpenFile(str))
1592             mode = eRNBRunLoopModeExit;
1593         } else if (communication_fd >= 0) {
1594           // We were passed a file descriptor to use during fork/exec that is
1595           // already open
1596           // in our process, so lets just use it!
1597           if (remote->Comm().useFD(communication_fd))
1598             mode = eRNBRunLoopModeExit;
1599           else
1600             remote->StartReadRemoteDataThread();
1601         }
1602 
1603         if (mode != eRNBRunLoopModeExit)
1604           RNBLogSTDOUT("Waiting for debugger instructions for process %d.\n",
1605                        attach_pid);
1606       }
1607       break;
1608 
1609     case eRNBRunLoopModeInferiorLaunching: {
1610       mode = RNBRunLoopLaunchInferior(remote, ctx.GetSTDINPath(),
1611                                       ctx.GetSTDOUTPath(), ctx.GetSTDERRPath(),
1612                                       no_stdio);
1613 
1614       if (mode == eRNBRunLoopModeInferiorExecuting) {
1615         if (port != INT32_MAX) {
1616           if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1617                              named_pipe_path.c_str(), unix_socket_name.c_str()))
1618             mode = eRNBRunLoopModeExit;
1619         } else if (str[0] == '/') {
1620           if (remote->Comm().OpenFile(str))
1621             mode = eRNBRunLoopModeExit;
1622         } else if (communication_fd >= 0) {
1623           // We were passed a file descriptor to use during fork/exec that is
1624           // already open
1625           // in our process, so lets just use it!
1626           if (remote->Comm().useFD(communication_fd))
1627             mode = eRNBRunLoopModeExit;
1628           else
1629             remote->StartReadRemoteDataThread();
1630         }
1631 
1632         if (mode != eRNBRunLoopModeExit) {
1633           const char *proc_name = "<unknown>";
1634           if (ctx.ArgumentCount() > 0)
1635             proc_name = ctx.ArgumentAtIndex(0);
1636           RNBLogSTDOUT("Got a connection, launched process %s (pid = %d).\n",
1637                        proc_name, ctx.ProcessID());
1638         }
1639       } else {
1640         const char *error_str = remote->Context().LaunchStatus().AsString();
1641         RNBLogSTDERR("error: failed to launch process %s: %s\n", argv_sub_zero,
1642                      error_str ? error_str : "unknown error.");
1643       }
1644     } break;
1645 
1646     case eRNBRunLoopModeInferiorExecuting:
1647       mode = RNBRunLoopInferiorExecuting(remote);
1648       break;
1649 
1650     case eRNBRunLoopModePlatformMode:
1651       if (port != INT32_MAX) {
1652         if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1653                            named_pipe_path.c_str(), unix_socket_name.c_str()))
1654           mode = eRNBRunLoopModeExit;
1655       } else if (str[0] == '/') {
1656         if (remote->Comm().OpenFile(str))
1657           mode = eRNBRunLoopModeExit;
1658       } else if (communication_fd >= 0) {
1659         // We were passed a file descriptor to use during fork/exec that is
1660         // already open
1661         // in our process, so lets just use it!
1662         if (remote->Comm().useFD(communication_fd))
1663           mode = eRNBRunLoopModeExit;
1664         else
1665           remote->StartReadRemoteDataThread();
1666       }
1667 
1668       if (mode != eRNBRunLoopModeExit)
1669         mode = RNBRunLoopPlatform(remote);
1670       break;
1671 
1672     default:
1673       mode = eRNBRunLoopModeExit;
1674     case eRNBRunLoopModeExit:
1675       break;
1676     }
1677   }
1678 
1679   remote->StopReadRemoteDataThread();
1680   remote->Context().SetProcessID(INVALID_NUB_PROCESS);
1681   RNBLogSTDOUT("Exiting.\n");
1682 
1683   return 0;
1684 }
1685