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