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