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     return eRNBRunLoopModeExit;
496   case eStateDetached:
497     return eRNBRunLoopModeExit;
498   }
499 
500   // Catch all...
501   return eRNBRunLoopModeExit;
502 }
503 // This function handles the case where our inferior program is stopped and
504 // we are waiting for gdb remote protocol packets. When a packet occurs that
505 // makes the inferior run, we need to leave this function with a new state
506 // as the return code.
507 RNBRunLoopMode RNBRunLoopInferiorExecuting(RNBRemote *remote) {
508   DNBLogThreadedIf(LOG_RNB_MINIMAL, "#### %s", __FUNCTION__);
509   RNBContext &ctx = remote->Context();
510 
511   // Init our mode and set 'is_running' based on the current process state
512   RNBRunLoopMode mode = HandleProcessStateChange(remote, true);
513 
514   while (ctx.ProcessID() != INVALID_NUB_PROCESS) {
515 
516     std::string set_events_str;
517     uint32_t event_mask = ctx.NormalEventBits();
518 
519     if (!ctx.ProcessStateRunning()) {
520       // Clear some bits if we are not running so we don't send any async
521       // packets
522       event_mask &= ~RNBContext::event_proc_stdio_available;
523       event_mask &= ~RNBContext::event_proc_profile_data;
524       // When we enable async structured data packets over another logical
525       // channel,
526       // this can be relaxed.
527       event_mask &= ~RNBContext::event_darwin_log_data_available;
528     }
529 
530     // We want to make sure we consume all process state changes and have
531     // whomever is notifying us to wait for us to reset the event bit before
532     // continuing.
533     // ctx.Events().SetResetAckMask (RNBContext::event_proc_state_changed);
534 
535     DNBLogThreadedIf(LOG_RNB_EVENTS,
536                      "%s ctx.Events().WaitForSetEvents(0x%08x) ...",
537                      __FUNCTION__, event_mask);
538     nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
539     DNBLogThreadedIf(LOG_RNB_EVENTS,
540                      "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)",
541                      __FUNCTION__, event_mask, set_events,
542                      ctx.EventsAsString(set_events, set_events_str));
543 
544     if (set_events) {
545       if ((set_events & RNBContext::event_proc_thread_exiting) ||
546           (set_events & RNBContext::event_proc_stdio_available)) {
547         remote->FlushSTDIO();
548       }
549 
550       if (set_events & RNBContext::event_proc_profile_data) {
551         remote->SendAsyncProfileData();
552       }
553 
554       if (set_events & RNBContext::event_darwin_log_data_available) {
555         remote->SendAsyncDarwinLogData();
556       }
557 
558       if (set_events & RNBContext::event_read_packet_available) {
559         // handleReceivedPacket will take care of resetting the
560         // event_read_packet_available events when there are no more...
561         set_events ^= RNBContext::event_read_packet_available;
562 
563         if (ctx.ProcessStateRunning()) {
564           if (remote->HandleAsyncPacket() == rnb_not_connected) {
565             // TODO: connect again? Exit?
566           }
567         } else {
568           if (remote->HandleReceivedPacket() == rnb_not_connected) {
569             // TODO: connect again? Exit?
570           }
571         }
572       }
573 
574       if (set_events & RNBContext::event_proc_state_changed) {
575         mode = HandleProcessStateChange(remote, false);
576         ctx.Events().ResetEvents(RNBContext::event_proc_state_changed);
577         set_events ^= RNBContext::event_proc_state_changed;
578       }
579 
580       if (set_events & RNBContext::event_proc_thread_exiting) {
581         mode = eRNBRunLoopModeExit;
582       }
583 
584       if (set_events & RNBContext::event_read_thread_exiting) {
585         // Out remote packet receiving thread exited, exit for now.
586         if (ctx.HasValidProcessID()) {
587           // TODO: We should add code that will leave the current process
588           // in its current state and listen for another connection...
589           if (ctx.ProcessStateRunning()) {
590             if (ctx.GetDetachOnError()) {
591               DNBLog("debugserver's event read thread is exiting, detaching "
592                      "from the inferior process.");
593               DNBProcessDetach(ctx.ProcessID());
594             } else {
595               DNBLog("debugserver's event read thread is exiting, killing the "
596                      "inferior process.");
597               DNBProcessKill(ctx.ProcessID());
598             }
599           } else {
600             if (ctx.GetDetachOnError()) {
601               DNBLog("debugserver's event read thread is exiting, detaching "
602                      "from the inferior process.");
603               DNBProcessDetach(ctx.ProcessID());
604             }
605           }
606         }
607         mode = eRNBRunLoopModeExit;
608       }
609     }
610 
611     // Reset all event bits that weren't reset for now...
612     if (set_events != 0)
613       ctx.Events().ResetEvents(set_events);
614 
615     if (mode != eRNBRunLoopModeInferiorExecuting)
616       break;
617   }
618 
619   return mode;
620 }
621 
622 RNBRunLoopMode RNBRunLoopPlatform(RNBRemote *remote) {
623   RNBRunLoopMode mode = eRNBRunLoopModePlatformMode;
624   RNBContext &ctx = remote->Context();
625 
626   while (mode == eRNBRunLoopModePlatformMode) {
627     std::string set_events_str;
628     const uint32_t event_mask = RNBContext::event_read_packet_available |
629                                 RNBContext::event_read_thread_exiting;
630 
631     DNBLogThreadedIf(LOG_RNB_EVENTS,
632                      "%s ctx.Events().WaitForSetEvents(0x%08x) ...",
633                      __FUNCTION__, event_mask);
634     nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
635     DNBLogThreadedIf(LOG_RNB_EVENTS,
636                      "%s ctx.Events().WaitForSetEvents(0x%08x) => 0x%08x (%s)",
637                      __FUNCTION__, event_mask, set_events,
638                      ctx.EventsAsString(set_events, set_events_str));
639 
640     if (set_events) {
641       if (set_events & RNBContext::event_read_packet_available) {
642         if (remote->HandleReceivedPacket() == rnb_not_connected)
643           mode = eRNBRunLoopModeExit;
644       }
645 
646       if (set_events & RNBContext::event_read_thread_exiting) {
647         mode = eRNBRunLoopModeExit;
648       }
649       ctx.Events().ResetEvents(set_events);
650     }
651   }
652   return eRNBRunLoopModeExit;
653 }
654 
655 //----------------------------------------------------------------------
656 // Convenience function to set up the remote listening port
657 // Returns 1 for success 0 for failure.
658 //----------------------------------------------------------------------
659 
660 static void PortWasBoundCallbackUnixSocket(const void *baton, in_port_t port) {
661   //::printf ("PortWasBoundCallbackUnixSocket (baton = %p, port = %u)\n", baton,
662   //port);
663 
664   const char *unix_socket_name = (const char *)baton;
665 
666   if (unix_socket_name && unix_socket_name[0]) {
667     // We were given a unix socket name to use to communicate the port
668     // that we ended up binding to back to our parent process
669     struct sockaddr_un saddr_un;
670     int s = ::socket(AF_UNIX, SOCK_STREAM, 0);
671     if (s < 0) {
672       perror("error: socket (AF_UNIX, SOCK_STREAM, 0)");
673       exit(1);
674     }
675 
676     saddr_un.sun_family = AF_UNIX;
677     ::strlcpy(saddr_un.sun_path, unix_socket_name,
678               sizeof(saddr_un.sun_path) - 1);
679     saddr_un.sun_path[sizeof(saddr_un.sun_path) - 1] = '\0';
680     saddr_un.sun_len = SUN_LEN(&saddr_un);
681 
682     if (::connect(s, (struct sockaddr *)&saddr_un,
683                   static_cast<socklen_t>(SUN_LEN(&saddr_un))) < 0) {
684       perror("error: connect (socket, &saddr_un, saddr_un_len)");
685       exit(1);
686     }
687 
688     //::printf ("connect () sucess!!\n");
689 
690     // We were able to connect to the socket, now write our PID so whomever
691     // launched us will know this process's ID
692     RNBLogSTDOUT("Listening to port %i...\n", port);
693 
694     char pid_str[64];
695     const int pid_str_len = ::snprintf(pid_str, sizeof(pid_str), "%u", port);
696     const ssize_t bytes_sent = ::send(s, pid_str, pid_str_len, 0);
697 
698     if (pid_str_len != bytes_sent) {
699       perror("error: send (s, pid_str, pid_str_len, 0)");
700       exit(1);
701     }
702 
703     //::printf ("send () sucess!!\n");
704 
705     // We are done with the socket
706     close(s);
707   }
708 }
709 
710 static void PortWasBoundCallbackNamedPipe(const void *baton, uint16_t port) {
711   const char *named_pipe = (const char *)baton;
712   if (named_pipe && named_pipe[0]) {
713     int fd = ::open(named_pipe, O_WRONLY);
714     if (fd > -1) {
715       char port_str[64];
716       const ssize_t port_str_len =
717           ::snprintf(port_str, sizeof(port_str), "%u", port);
718       // Write the port number as a C string with the NULL terminator
719       ::write(fd, port_str, port_str_len + 1);
720       close(fd);
721     }
722   }
723 }
724 
725 static int ConnectRemote(RNBRemote *remote, const char *host, int port,
726                          bool reverse_connect, const char *named_pipe_path,
727                          const char *unix_socket_name) {
728   if (!remote->Comm().IsConnected()) {
729     if (reverse_connect) {
730       if (port == 0) {
731         DNBLogThreaded(
732             "error: invalid port supplied for reverse connection: %i.\n", port);
733         return 0;
734       }
735       if (remote->Comm().Connect(host, port) != rnb_success) {
736         DNBLogThreaded("Failed to reverse connect to %s:%i.\n", host, port);
737         return 0;
738       }
739     } else {
740       if (port != 0)
741         RNBLogSTDOUT("Listening to port %i for a connection from %s...\n", port,
742                      host ? host : "127.0.0.1");
743       if (unix_socket_name && unix_socket_name[0]) {
744         if (remote->Comm().Listen(host, port, PortWasBoundCallbackUnixSocket,
745                                   unix_socket_name) != rnb_success) {
746           RNBLogSTDERR("Failed to get connection from a remote gdb process.\n");
747           return 0;
748         }
749       } else {
750         if (remote->Comm().Listen(host, port, PortWasBoundCallbackNamedPipe,
751                                   named_pipe_path) != rnb_success) {
752           RNBLogSTDERR("Failed to get connection from a remote gdb process.\n");
753           return 0;
754         }
755       }
756     }
757     remote->StartReadRemoteDataThread();
758   }
759   return 1;
760 }
761 
762 //----------------------------------------------------------------------
763 // ASL Logging callback that can be registered with DNBLogSetLogCallback
764 //----------------------------------------------------------------------
765 void ASLLogCallback(void *baton, uint32_t flags, const char *format,
766                     va_list args) {
767   if (format == NULL)
768     return;
769   static aslmsg g_aslmsg = NULL;
770   if (g_aslmsg == NULL) {
771     g_aslmsg = ::asl_new(ASL_TYPE_MSG);
772     char asl_key_sender[PATH_MAX];
773     snprintf(asl_key_sender, sizeof(asl_key_sender), "com.apple.%s-%s",
774              DEBUGSERVER_PROGRAM_NAME, DEBUGSERVER_VERSION_STR);
775     ::asl_set(g_aslmsg, ASL_KEY_SENDER, asl_key_sender);
776   }
777 
778   int asl_level;
779   if (flags & DNBLOG_FLAG_FATAL)
780     asl_level = ASL_LEVEL_CRIT;
781   else if (flags & DNBLOG_FLAG_ERROR)
782     asl_level = ASL_LEVEL_ERR;
783   else if (flags & DNBLOG_FLAG_WARNING)
784     asl_level = ASL_LEVEL_WARNING;
785   else if (flags & DNBLOG_FLAG_VERBOSE)
786     asl_level = ASL_LEVEL_WARNING; // ASL_LEVEL_INFO;
787   else
788     asl_level = ASL_LEVEL_WARNING; // ASL_LEVEL_DEBUG;
789 
790   ::asl_vlog(NULL, g_aslmsg, asl_level, format, args);
791 }
792 
793 //----------------------------------------------------------------------
794 // FILE based Logging callback that can be registered with
795 // DNBLogSetLogCallback
796 //----------------------------------------------------------------------
797 void FileLogCallback(void *baton, uint32_t flags, const char *format,
798                      va_list args) {
799   if (baton == NULL || format == NULL)
800     return;
801 
802   ::vfprintf((FILE *)baton, format, args);
803   ::fprintf((FILE *)baton, "\n");
804   ::fflush((FILE *)baton);
805 }
806 
807 void show_usage_and_exit(int exit_code) {
808   RNBLogSTDERR(
809       "Usage:\n  %s host:port [program-name program-arg1 program-arg2 ...]\n",
810       DEBUGSERVER_PROGRAM_NAME);
811   RNBLogSTDERR("  %s /path/file [program-name program-arg1 program-arg2 ...]\n",
812                DEBUGSERVER_PROGRAM_NAME);
813   RNBLogSTDERR("  %s host:port --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME);
814   RNBLogSTDERR("  %s /path/file --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME);
815   RNBLogSTDERR("  %s host:port --attach=<process_name>\n",
816                DEBUGSERVER_PROGRAM_NAME);
817   RNBLogSTDERR("  %s /path/file --attach=<process_name>\n",
818                DEBUGSERVER_PROGRAM_NAME);
819   exit(exit_code);
820 }
821 
822 //----------------------------------------------------------------------
823 // option descriptors for getopt_long_only()
824 //----------------------------------------------------------------------
825 static struct option g_long_options[] = {
826     {"attach", required_argument, NULL, 'a'},
827     {"arch", required_argument, NULL, 'A'},
828     {"debug", no_argument, NULL, 'g'},
829     {"kill-on-error", no_argument, NULL, 'K'},
830     {"verbose", no_argument, NULL, 'v'},
831     {"lockdown", no_argument, &g_lockdown_opt, 1}, // short option "-k"
832     {"applist", no_argument, &g_applist_opt, 1},   // short option "-t"
833     {"log-file", required_argument, NULL, 'l'},
834     {"log-flags", required_argument, NULL, 'f'},
835     {"launch", required_argument, NULL, 'x'}, // Valid values are "auto",
836                                               // "posix-spawn", "fork-exec",
837                                               // "springboard" (arm only)
838     {"waitfor", required_argument, NULL,
839      'w'}, // Wait for a process whose name starts with ARG
840     {"waitfor-interval", required_argument, NULL,
841      'i'}, // Time in usecs to wait between sampling the pid list when waiting
842            // for a process by name
843     {"waitfor-duration", required_argument, NULL,
844      'd'}, // The time in seconds to wait for a process to show up by name
845     {"native-regs", no_argument, NULL, 'r'}, // Specify to use the native
846                                              // registers instead of the gdb
847                                              // defaults for the architecture.
848     {"stdio-path", required_argument, NULL,
849      's'}, // Set the STDIO path to be used when launching applications (STDIN,
850            // STDOUT and STDERR) (only if debugserver launches the process)
851     {"stdin-path", required_argument, NULL,
852      'I'}, // Set the STDIN path to be used when launching applications (only if
853            // debugserver launches the process)
854     {"stdout-path", required_argument, NULL,
855      'O'}, // Set the STDOUT path to be used when launching applications (only
856            // if debugserver launches the process)
857     {"stderr-path", required_argument, NULL,
858      'E'}, // Set the STDERR path to be used when launching applications (only
859            // if debugserver launches the process)
860     {"no-stdio", no_argument, NULL,
861      'n'}, // Do not set up any stdio (perhaps the program is a GUI program)
862            // (only if debugserver launches the process)
863     {"setsid", no_argument, NULL,
864      'S'}, // call setsid() to make debugserver run in its own session
865     {"disable-aslr", no_argument, NULL, 'D'}, // Use _POSIX_SPAWN_DISABLE_ASLR
866                                               // to avoid shared library
867                                               // randomization
868     {"working-dir", required_argument, NULL,
869      'W'}, // The working directory that the inferior process should have (only
870            // if debugserver launches the process)
871     {"platform", required_argument, NULL,
872      'p'}, // Put this executable into a remote platform mode
873     {"unix-socket", required_argument, NULL,
874      'u'}, // If we need to handshake with our parent process, an option will be
875            // passed down that specifies a unix socket name to use
876     {"fd", required_argument, NULL,
877      '2'}, // A file descriptor was passed to this process when spawned that
878            // is already open and ready for communication
879     {"named-pipe", required_argument, NULL, 'P'},
880     {"reverse-connect", no_argument, NULL, 'R'},
881     {"env", required_argument, NULL,
882      'e'}, // When debugserver launches the process, set a single environment
883            // entry as specified by the option value ("./debugserver -e FOO=1 -e
884            // BAR=2 localhost:1234 -- /bin/ls")
885     {"forward-env", no_argument, NULL,
886      'F'}, // When debugserver launches the process, forward debugserver's
887            // current environment variables to the child process ("./debugserver
888            // -F localhost:1234 -- /bin/ls"
889     {NULL, 0, NULL, 0}};
890 
891 //----------------------------------------------------------------------
892 // main
893 //----------------------------------------------------------------------
894 int main(int argc, char *argv[]) {
895   // If debugserver is launched with DYLD_INSERT_LIBRARIES, unset it so we
896   // don't spawn child processes with this enabled.
897   unsetenv("DYLD_INSERT_LIBRARIES");
898 
899   const char *argv_sub_zero =
900       argv[0]; // save a copy of argv[0] for error reporting post-launch
901 
902 #if defined(__APPLE__)
903   pthread_setname_np("main thread");
904 #if defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
905   struct sched_param thread_param;
906   int thread_sched_policy;
907   if (pthread_getschedparam(pthread_self(), &thread_sched_policy,
908                             &thread_param) == 0) {
909     thread_param.sched_priority = 47;
910     pthread_setschedparam(pthread_self(), thread_sched_policy, &thread_param);
911   }
912 
913   ::proc_set_wakemon_params(
914       getpid(), 500,
915       0); // Allow up to 500 wakeups/sec to avoid EXC_RESOURCE for normal use.
916 #endif
917 #endif
918 
919   g_isatty = ::isatty(STDIN_FILENO);
920 
921   //  ::printf ("uid=%u euid=%u gid=%u egid=%u\n",
922   //            getuid(),
923   //            geteuid(),
924   //            getgid(),
925   //            getegid());
926 
927   //    signal (SIGINT, signal_handler);
928   signal(SIGPIPE, signal_handler);
929   signal(SIGHUP, signal_handler);
930 
931   // We're always sitting in waitpid or kevent waiting on our target process'
932   // death,
933   // we don't need no stinking SIGCHLD's...
934 
935   sigset_t sigset;
936   sigemptyset(&sigset);
937   sigaddset(&sigset, SIGCHLD);
938   sigprocmask(SIG_BLOCK, &sigset, NULL);
939 
940   g_remoteSP.reset(new RNBRemote());
941 
942   RNBRemote *remote = g_remoteSP.get();
943   if (remote == NULL) {
944     RNBLogSTDERR("error: failed to create a remote connection class\n");
945     return -1;
946   }
947 
948   RNBContext &ctx = remote->Context();
949 
950   int i;
951   int attach_pid = INVALID_NUB_PROCESS;
952 
953   FILE *log_file = NULL;
954   uint32_t log_flags = 0;
955   // Parse our options
956   int ch;
957   int long_option_index = 0;
958   int debug = 0;
959   int communication_fd = -1;
960   std::string compile_options;
961   std::string waitfor_pid_name; // Wait for a process that starts with this name
962   std::string attach_pid_name;
963   std::string arch_name;
964   std::string working_dir; // The new working directory to use for the inferior
965   std::string unix_socket_name; // If we need to handshake with our parent
966                                 // process, an option will be passed down that
967                                 // specifies a unix socket name to use
968   std::string named_pipe_path;  // If we need to handshake with our parent
969                                 // process, an option will be passed down that
970                                 // specifies a named pipe to use
971   useconds_t waitfor_interval = 1000; // Time in usecs between process lists
972                                       // polls when waiting for a process by
973                                       // name, default 1 msec.
974   useconds_t waitfor_duration =
975       0; // Time in seconds to wait for a process by name, 0 means wait forever.
976   bool no_stdio = false;
977   bool reverse_connect = false; // Set to true by an option to indicate we
978                                 // should reverse connect to the host:port
979                                 // supplied as the first debugserver argument
980 
981 #if !defined(DNBLOG_ENABLED)
982   compile_options += "(no-logging) ";
983 #endif
984 
985   RNBRunLoopMode start_mode = eRNBRunLoopModeExit;
986 
987   char short_options[512];
988   uint32_t short_options_idx = 0;
989 
990   // Handle the two case that don't have short options in g_long_options
991   short_options[short_options_idx++] = 'k';
992   short_options[short_options_idx++] = 't';
993 
994   for (i = 0; g_long_options[i].name != NULL; ++i) {
995     if (isalpha(g_long_options[i].val)) {
996       short_options[short_options_idx++] = g_long_options[i].val;
997       switch (g_long_options[i].has_arg) {
998       default:
999       case no_argument:
1000         break;
1001 
1002       case optional_argument:
1003         short_options[short_options_idx++] = ':';
1004         short_options[short_options_idx++] = ':';
1005         break;
1006       case required_argument:
1007         short_options[short_options_idx++] = ':';
1008         break;
1009       }
1010     }
1011   }
1012   // NULL terminate the short option string.
1013   short_options[short_options_idx++] = '\0';
1014 
1015 #if __GLIBC__
1016   optind = 0;
1017 #else
1018   optreset = 1;
1019   optind = 1;
1020 #endif
1021 
1022   bool forward_env = false;
1023   while ((ch = getopt_long_only(argc, argv, short_options, g_long_options,
1024                                 &long_option_index)) != -1) {
1025     DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n", ch, (uint8_t)ch,
1026                 g_long_options[long_option_index].name,
1027                 g_long_options[long_option_index].has_arg ? '=' : ' ',
1028                 optarg ? optarg : "");
1029     switch (ch) {
1030     case 0: // Any optional that auto set themselves will return 0
1031       break;
1032 
1033     case 'A':
1034       if (optarg && optarg[0])
1035         arch_name.assign(optarg);
1036       break;
1037 
1038     case 'a':
1039       if (optarg && optarg[0]) {
1040         if (isdigit(optarg[0])) {
1041           char *end = NULL;
1042           attach_pid = static_cast<int>(strtoul(optarg, &end, 0));
1043           if (end == NULL || *end != '\0') {
1044             RNBLogSTDERR("error: invalid pid option '%s'\n", optarg);
1045             exit(4);
1046           }
1047         } else {
1048           attach_pid_name = optarg;
1049         }
1050         start_mode = eRNBRunLoopModeInferiorAttaching;
1051       }
1052       break;
1053 
1054     // --waitfor=NAME
1055     case 'w':
1056       if (optarg && optarg[0]) {
1057         waitfor_pid_name = optarg;
1058         start_mode = eRNBRunLoopModeInferiorAttaching;
1059       }
1060       break;
1061 
1062     // --waitfor-interval=USEC
1063     case 'i':
1064       if (optarg && optarg[0]) {
1065         char *end = NULL;
1066         waitfor_interval = static_cast<useconds_t>(strtoul(optarg, &end, 0));
1067         if (end == NULL || *end != '\0') {
1068           RNBLogSTDERR("error: invalid waitfor-interval option value '%s'.\n",
1069                        optarg);
1070           exit(6);
1071         }
1072       }
1073       break;
1074 
1075     // --waitfor-duration=SEC
1076     case 'd':
1077       if (optarg && optarg[0]) {
1078         char *end = NULL;
1079         waitfor_duration = static_cast<useconds_t>(strtoul(optarg, &end, 0));
1080         if (end == NULL || *end != '\0') {
1081           RNBLogSTDERR("error: invalid waitfor-duration option value '%s'.\n",
1082                        optarg);
1083           exit(7);
1084         }
1085       }
1086       break;
1087 
1088     case 'K':
1089       g_detach_on_error = false;
1090       break;
1091     case 'W':
1092       if (optarg && optarg[0])
1093         working_dir.assign(optarg);
1094       break;
1095 
1096     case 'x':
1097       if (optarg && optarg[0]) {
1098         if (strcasecmp(optarg, "auto") == 0)
1099           g_launch_flavor = eLaunchFlavorDefault;
1100         else if (strcasestr(optarg, "posix") == optarg)
1101           g_launch_flavor = eLaunchFlavorPosixSpawn;
1102         else if (strcasestr(optarg, "fork") == optarg)
1103           g_launch_flavor = eLaunchFlavorForkExec;
1104 #ifdef WITH_SPRINGBOARD
1105         else if (strcasestr(optarg, "spring") == optarg)
1106           g_launch_flavor = eLaunchFlavorSpringBoard;
1107 #endif
1108 #ifdef WITH_BKS
1109         else if (strcasestr(optarg, "backboard") == optarg)
1110           g_launch_flavor = eLaunchFlavorBKS;
1111 #endif
1112 #ifdef WITH_FBS
1113         else if (strcasestr(optarg, "frontboard") == optarg)
1114           g_launch_flavor = eLaunchFlavorFBS;
1115 #endif
1116 
1117         else {
1118           RNBLogSTDERR("error: invalid TYPE for the --launch=TYPE (-x TYPE) "
1119                        "option: '%s'\n",
1120                        optarg);
1121           RNBLogSTDERR("Valid values TYPE are:\n");
1122           RNBLogSTDERR(
1123               "  auto       Auto-detect the best launch method to use.\n");
1124           RNBLogSTDERR(
1125               "  posix      Launch the executable using posix_spawn.\n");
1126           RNBLogSTDERR(
1127               "  fork       Launch the executable using fork and exec.\n");
1128 #ifdef WITH_SPRINGBOARD
1129           RNBLogSTDERR(
1130               "  spring     Launch the executable through Springboard.\n");
1131 #endif
1132 #ifdef WITH_BKS
1133           RNBLogSTDERR("  backboard  Launch the executable through BackBoard "
1134                        "Services.\n");
1135 #endif
1136 #ifdef WITH_FBS
1137           RNBLogSTDERR("  frontboard  Launch the executable through FrontBoard "
1138                        "Services.\n");
1139 #endif
1140           exit(5);
1141         }
1142       }
1143       break;
1144 
1145     case 'l': // Set Log File
1146       if (optarg && optarg[0]) {
1147         if (strcasecmp(optarg, "stdout") == 0)
1148           log_file = stdout;
1149         else if (strcasecmp(optarg, "stderr") == 0)
1150           log_file = stderr;
1151         else {
1152           log_file = fopen(optarg, "w");
1153           if (log_file != NULL)
1154             setlinebuf(log_file);
1155         }
1156 
1157         if (log_file == NULL) {
1158           const char *errno_str = strerror(errno);
1159           RNBLogSTDERR(
1160               "Failed to open log file '%s' for writing: errno = %i (%s)",
1161               optarg, errno, errno_str ? errno_str : "unknown error");
1162         }
1163       }
1164       break;
1165 
1166     case 'f': // Log Flags
1167       if (optarg && optarg[0])
1168         log_flags = static_cast<uint32_t>(strtoul(optarg, NULL, 0));
1169       break;
1170 
1171     case 'g':
1172       debug = 1;
1173       DNBLogSetDebug(debug);
1174       break;
1175 
1176     case 't':
1177       g_applist_opt = 1;
1178       break;
1179 
1180     case 'k':
1181       g_lockdown_opt = 1;
1182       break;
1183 
1184     case 'r':
1185       // Do nothing, native regs is the default these days
1186       break;
1187 
1188     case 'R':
1189       reverse_connect = true;
1190       break;
1191     case 'v':
1192       DNBLogSetVerbose(1);
1193       break;
1194 
1195     case 's':
1196       ctx.GetSTDIN().assign(optarg);
1197       ctx.GetSTDOUT().assign(optarg);
1198       ctx.GetSTDERR().assign(optarg);
1199       break;
1200 
1201     case 'I':
1202       ctx.GetSTDIN().assign(optarg);
1203       break;
1204 
1205     case 'O':
1206       ctx.GetSTDOUT().assign(optarg);
1207       break;
1208 
1209     case 'E':
1210       ctx.GetSTDERR().assign(optarg);
1211       break;
1212 
1213     case 'n':
1214       no_stdio = true;
1215       break;
1216 
1217     case 'S':
1218       // Put debugserver into a new session. Terminals group processes
1219       // into sessions and when a special terminal key sequences
1220       // (like control+c) are typed they can cause signals to go out to
1221       // all processes in a session. Using this --setsid (-S) option
1222       // will cause debugserver to run in its own sessions and be free
1223       // from such issues.
1224       //
1225       // This is useful when debugserver is spawned from a command
1226       // line application that uses debugserver to do the debugging,
1227       // yet that application doesn't want debugserver receiving the
1228       // signals sent to the session (i.e. dying when anyone hits ^C).
1229       setsid();
1230       break;
1231     case 'D':
1232       g_disable_aslr = 1;
1233       break;
1234 
1235     case 'p':
1236       start_mode = eRNBRunLoopModePlatformMode;
1237       break;
1238 
1239     case 'u':
1240       unix_socket_name.assign(optarg);
1241       break;
1242 
1243     case 'P':
1244       named_pipe_path.assign(optarg);
1245       break;
1246 
1247     case 'e':
1248       // Pass a single specified environment variable down to the process that
1249       // gets launched
1250       remote->Context().PushEnvironment(optarg);
1251       break;
1252 
1253     case 'F':
1254       forward_env = true;
1255       break;
1256 
1257     case '2':
1258       // File descriptor passed to this process during fork/exec and is already
1259       // open and ready for communication.
1260       communication_fd = atoi(optarg);
1261       break;
1262     }
1263   }
1264 
1265   if (arch_name.empty()) {
1266 #if defined(__arm__)
1267     arch_name.assign("arm");
1268 #endif
1269   } else {
1270     DNBSetArchitecture(arch_name.c_str());
1271   }
1272 
1273   //    if (arch_name.empty())
1274   //    {
1275   //        fprintf(stderr, "error: no architecture was specified\n");
1276   //        exit (8);
1277   //    }
1278   // Skip any options we consumed with getopt_long_only
1279   argc -= optind;
1280   argv += optind;
1281 
1282   if (!working_dir.empty()) {
1283     if (remote->Context().SetWorkingDirectory(working_dir.c_str()) == false) {
1284       RNBLogSTDERR("error: working directory doesn't exist '%s'.\n",
1285                    working_dir.c_str());
1286       exit(8);
1287     }
1288   }
1289 
1290   remote->Context().SetDetachOnError(g_detach_on_error);
1291 
1292   remote->Initialize();
1293 
1294   // It is ok for us to set NULL as the logfile (this will disable any logging)
1295 
1296   if (log_file != NULL) {
1297     DNBLogSetLogCallback(FileLogCallback, log_file);
1298     // If our log file was set, yet we have no log flags, log everything!
1299     if (log_flags == 0)
1300       log_flags = LOG_ALL | LOG_RNB_ALL;
1301 
1302     DNBLogSetLogMask(log_flags);
1303   } else {
1304     // Enable DNB logging
1305 
1306     // if os_log() support is available, log through that.
1307     auto log_callback = OsLogger::GetLogFunction();
1308     if (log_callback) {
1309       DNBLogSetLogCallback(log_callback, nullptr);
1310       DNBLog("debugserver will use os_log for internal logging.");
1311     } else {
1312       // Fall back to ASL support.
1313       DNBLogSetLogCallback(ASLLogCallback, NULL);
1314       DNBLog("debugserver will use ASL for internal logging.");
1315     }
1316     DNBLogSetLogMask(log_flags);
1317   }
1318 
1319   if (DNBLogEnabled()) {
1320     for (i = 0; i < argc; i++)
1321       DNBLogDebug("argv[%i] = %s", i, argv[i]);
1322   }
1323 
1324   // as long as we're dropping remotenub in as a replacement for gdbserver,
1325   // explicitly note that this is not gdbserver.
1326 
1327   RNBLogSTDOUT("%s-%s %sfor %s.\n", DEBUGSERVER_PROGRAM_NAME,
1328                DEBUGSERVER_VERSION_STR, compile_options.c_str(), RNB_ARCH);
1329 
1330   std::string host;
1331   int port = INT32_MAX;
1332   char str[PATH_MAX];
1333   str[0] = '\0';
1334 
1335   if (g_lockdown_opt == 0 && g_applist_opt == 0 && communication_fd == -1) {
1336     // Make sure we at least have port
1337     if (argc < 1) {
1338       show_usage_and_exit(1);
1339     }
1340     // accept 'localhost:' prefix on port number
1341     std::string host_specifier = argv[0];
1342     auto colon_location = host_specifier.rfind(':');
1343     if (colon_location != std::string::npos) {
1344       host = host_specifier.substr(0, colon_location);
1345       std::string port_str =
1346           host_specifier.substr(colon_location + 1, std::string::npos);
1347       char *end_ptr;
1348       port = strtoul(port_str.c_str(), &end_ptr, 0);
1349       if (end_ptr < port_str.c_str() + port_str.size())
1350         show_usage_and_exit(2);
1351       if (host.front() == '[' && host.back() == ']')
1352         host = host.substr(1, host.size() - 2);
1353       DNBLogDebug("host = '%s'  port = %i", host.c_str(), port);
1354     } else {
1355       // No hostname means "localhost"
1356       int items_scanned = ::sscanf(argv[0], "%i", &port);
1357       if (items_scanned == 1) {
1358         host = "127.0.0.1";
1359         DNBLogDebug("host = '%s'  port = %i", host.c_str(), port);
1360       } else if (argv[0][0] == '/') {
1361         port = INT32_MAX;
1362         strlcpy(str, argv[0], sizeof(str));
1363       } else {
1364         show_usage_and_exit(2);
1365       }
1366     }
1367 
1368     // We just used the 'host:port' or the '/path/file' arg...
1369     argc--;
1370     argv++;
1371   }
1372 
1373   //  If we know we're waiting to attach, we don't need any of this other info.
1374   if (start_mode != eRNBRunLoopModeInferiorAttaching &&
1375       start_mode != eRNBRunLoopModePlatformMode) {
1376     if (argc == 0 || g_lockdown_opt) {
1377       if (g_lockdown_opt != 0) {
1378         // Work around for SIGPIPE crashes due to posix_spawn issue.
1379         // We have to close STDOUT and STDERR, else the first time we
1380         // try and do any, we get SIGPIPE and die as posix_spawn is
1381         // doing bad things with our file descriptors at the moment.
1382         int null = open("/dev/null", O_RDWR);
1383         dup2(null, STDOUT_FILENO);
1384         dup2(null, STDERR_FILENO);
1385       } else if (g_applist_opt != 0) {
1386         // List all applications we are able to see
1387         std::string applist_plist;
1388         int err = ListApplications(applist_plist, false, false);
1389         if (err == 0) {
1390           fputs(applist_plist.c_str(), stdout);
1391         } else {
1392           RNBLogSTDERR("error: ListApplications returned error %i\n", err);
1393         }
1394         // Exit with appropriate error if we were asked to list the applications
1395         // with no other args were given (and we weren't trying to do this over
1396         // lockdown)
1397         return err;
1398       }
1399 
1400       DNBLogDebug("Get args from remote protocol...");
1401       start_mode = eRNBRunLoopModeGetStartModeFromRemoteProtocol;
1402     } else {
1403       start_mode = eRNBRunLoopModeInferiorLaunching;
1404       // Fill in the argv array in the context from the rest of our args.
1405       // Skip the name of this executable and the port number
1406       for (int i = 0; i < argc; i++) {
1407         DNBLogDebug("inferior_argv[%i] = '%s'", i, argv[i]);
1408         ctx.PushArgument(argv[i]);
1409       }
1410     }
1411   }
1412 
1413   if (start_mode == eRNBRunLoopModeExit)
1414     return -1;
1415 
1416   if (forward_env || start_mode == eRNBRunLoopModeInferiorLaunching) {
1417     // Pass the current environment down to the process that gets launched
1418     // This happens automatically in the "launching" mode. For the rest, we
1419     // only do that if the user explicitly requested this via --forward-env
1420     // argument.
1421     char **host_env = *_NSGetEnviron();
1422     char *env_entry;
1423     size_t i;
1424     for (i = 0; (env_entry = host_env[i]) != NULL; ++i)
1425       remote->Context().PushEnvironmentIfNeeded(env_entry);
1426   }
1427 
1428   RNBRunLoopMode mode = start_mode;
1429   char err_str[1024] = {'\0'};
1430 
1431   while (mode != eRNBRunLoopModeExit) {
1432     switch (mode) {
1433     case eRNBRunLoopModeGetStartModeFromRemoteProtocol:
1434 #ifdef WITH_LOCKDOWN
1435       if (g_lockdown_opt) {
1436         if (!remote->Comm().IsConnected()) {
1437           if (remote->Comm().ConnectToService() != rnb_success) {
1438             RNBLogSTDERR(
1439                 "Failed to get connection from a remote gdb process.\n");
1440             mode = eRNBRunLoopModeExit;
1441           } else if (g_applist_opt != 0) {
1442             // List all applications we are able to see
1443             std::string applist_plist;
1444             if (ListApplications(applist_plist, false, false) == 0) {
1445               DNBLogDebug("Task list: %s", applist_plist.c_str());
1446 
1447               remote->Comm().Write(applist_plist.c_str(), applist_plist.size());
1448               // Issue a read that will never yield any data until the other
1449               // side
1450               // closes the socket so this process doesn't just exit and cause
1451               // the
1452               // socket to close prematurely on the other end and cause data
1453               // loss.
1454               std::string buf;
1455               remote->Comm().Read(buf);
1456             }
1457             remote->Comm().Disconnect(false);
1458             mode = eRNBRunLoopModeExit;
1459             break;
1460           } else {
1461             // Start watching for remote packets
1462             remote->StartReadRemoteDataThread();
1463           }
1464         }
1465       } else
1466 #endif
1467           if (port != INT32_MAX) {
1468         if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1469                            named_pipe_path.c_str(), unix_socket_name.c_str()))
1470           mode = eRNBRunLoopModeExit;
1471       } else if (str[0] == '/') {
1472         if (remote->Comm().OpenFile(str))
1473           mode = eRNBRunLoopModeExit;
1474       } else if (communication_fd >= 0) {
1475         // We were passed a file descriptor to use during fork/exec that is
1476         // already open
1477         // in our process, so lets just use it!
1478         if (remote->Comm().useFD(communication_fd))
1479           mode = eRNBRunLoopModeExit;
1480         else
1481           remote->StartReadRemoteDataThread();
1482       }
1483 
1484       if (mode != eRNBRunLoopModeExit) {
1485         RNBLogSTDOUT("Got a connection, waiting for process information for "
1486                      "launching or attaching.\n");
1487 
1488         mode = RNBRunLoopGetStartModeFromRemote(remote);
1489       }
1490       break;
1491 
1492     case eRNBRunLoopModeInferiorAttaching:
1493       if (!waitfor_pid_name.empty()) {
1494         // Set our end wait time if we are using a waitfor-duration
1495         // option that may have been specified
1496         struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1497         if (waitfor_duration != 0) {
1498           DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration,
1499                                     0);
1500           timeout_ptr = &attach_timeout_abstime;
1501         }
1502         nub_launch_flavor_t launch_flavor = g_launch_flavor;
1503         if (launch_flavor == eLaunchFlavorDefault) {
1504           // Our default launch method is posix spawn
1505           launch_flavor = eLaunchFlavorPosixSpawn;
1506 
1507 #if defined WITH_FBS
1508           // Check if we have an app bundle, if so launch using SpringBoard.
1509           if (waitfor_pid_name.find(".app") != std::string::npos) {
1510             launch_flavor = eLaunchFlavorFBS;
1511           }
1512 #elif defined WITH_BKS
1513           // Check if we have an app bundle, if so launch using SpringBoard.
1514           if (waitfor_pid_name.find(".app") != std::string::npos) {
1515             launch_flavor = eLaunchFlavorBKS;
1516           }
1517 #elif defined WITH_SPRINGBOARD
1518           // Check if we have an app bundle, if so launch using SpringBoard.
1519           if (waitfor_pid_name.find(".app") != std::string::npos) {
1520             launch_flavor = eLaunchFlavorSpringBoard;
1521           }
1522 #endif
1523         }
1524 
1525         ctx.SetLaunchFlavor(launch_flavor);
1526         bool ignore_existing = false;
1527         RNBLogSTDOUT("Waiting to attach to process %s...\n",
1528                      waitfor_pid_name.c_str());
1529         nub_process_t pid = DNBProcessAttachWait(
1530             waitfor_pid_name.c_str(), launch_flavor, ignore_existing,
1531             timeout_ptr, waitfor_interval, err_str, sizeof(err_str));
1532         g_pid = pid;
1533 
1534         if (pid == INVALID_NUB_PROCESS) {
1535           ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1536           if (err_str[0])
1537             ctx.LaunchStatus().SetErrorString(err_str);
1538           RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n",
1539                        waitfor_pid_name.c_str(), err_str);
1540           mode = eRNBRunLoopModeExit;
1541         } else {
1542           ctx.SetProcessID(pid);
1543           mode = eRNBRunLoopModeInferiorExecuting;
1544         }
1545       } else if (attach_pid != INVALID_NUB_PROCESS) {
1546 
1547         RNBLogSTDOUT("Attaching to process %i...\n", attach_pid);
1548         nub_process_t attached_pid;
1549         mode = RNBRunLoopLaunchAttaching(remote, attach_pid, attached_pid);
1550         if (mode != eRNBRunLoopModeInferiorExecuting) {
1551           const char *error_str = remote->Context().LaunchStatus().AsString();
1552           RNBLogSTDERR("error: failed to attach process %i: %s\n", attach_pid,
1553                        error_str ? error_str : "unknown error.");
1554           mode = eRNBRunLoopModeExit;
1555         }
1556       } else if (!attach_pid_name.empty()) {
1557         struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1558         if (waitfor_duration != 0) {
1559           DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration,
1560                                     0);
1561           timeout_ptr = &attach_timeout_abstime;
1562         }
1563 
1564         RNBLogSTDOUT("Attaching to process %s...\n", attach_pid_name.c_str());
1565         nub_process_t pid = DNBProcessAttachByName(
1566             attach_pid_name.c_str(), timeout_ptr, err_str, sizeof(err_str));
1567         g_pid = pid;
1568         if (pid == INVALID_NUB_PROCESS) {
1569           ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1570           if (err_str[0])
1571             ctx.LaunchStatus().SetErrorString(err_str);
1572           RNBLogSTDERR("error: failed to attach to process named: \"%s\" %s\n",
1573                        waitfor_pid_name.c_str(), err_str);
1574           mode = eRNBRunLoopModeExit;
1575         } else {
1576           ctx.SetProcessID(pid);
1577           mode = eRNBRunLoopModeInferiorExecuting;
1578         }
1579 
1580       } else {
1581         RNBLogSTDERR(
1582             "error: asked to attach with empty name and invalid PID.\n");
1583         mode = eRNBRunLoopModeExit;
1584       }
1585 
1586       if (mode != eRNBRunLoopModeExit) {
1587         if (port != INT32_MAX) {
1588           if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1589                              named_pipe_path.c_str(), unix_socket_name.c_str()))
1590             mode = eRNBRunLoopModeExit;
1591         } else if (str[0] == '/') {
1592           if (remote->Comm().OpenFile(str))
1593             mode = eRNBRunLoopModeExit;
1594         } else if (communication_fd >= 0) {
1595           // We were passed a file descriptor to use during fork/exec that is
1596           // already open
1597           // in our process, so lets just use it!
1598           if (remote->Comm().useFD(communication_fd))
1599             mode = eRNBRunLoopModeExit;
1600           else
1601             remote->StartReadRemoteDataThread();
1602         }
1603 
1604         if (mode != eRNBRunLoopModeExit)
1605           RNBLogSTDOUT("Waiting for debugger instructions for process %d.\n",
1606                        attach_pid);
1607       }
1608       break;
1609 
1610     case eRNBRunLoopModeInferiorLaunching: {
1611       mode = RNBRunLoopLaunchInferior(remote, ctx.GetSTDINPath(),
1612                                       ctx.GetSTDOUTPath(), ctx.GetSTDERRPath(),
1613                                       no_stdio);
1614 
1615       if (mode == eRNBRunLoopModeInferiorExecuting) {
1616         if (port != INT32_MAX) {
1617           if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1618                              named_pipe_path.c_str(), unix_socket_name.c_str()))
1619             mode = eRNBRunLoopModeExit;
1620         } else if (str[0] == '/') {
1621           if (remote->Comm().OpenFile(str))
1622             mode = eRNBRunLoopModeExit;
1623         } else if (communication_fd >= 0) {
1624           // We were passed a file descriptor to use during fork/exec that is
1625           // already open
1626           // in our process, so lets just use it!
1627           if (remote->Comm().useFD(communication_fd))
1628             mode = eRNBRunLoopModeExit;
1629           else
1630             remote->StartReadRemoteDataThread();
1631         }
1632 
1633         if (mode != eRNBRunLoopModeExit) {
1634           const char *proc_name = "<unknown>";
1635           if (ctx.ArgumentCount() > 0)
1636             proc_name = ctx.ArgumentAtIndex(0);
1637           RNBLogSTDOUT("Got a connection, launched process %s (pid = %d).\n",
1638                        proc_name, ctx.ProcessID());
1639         }
1640       } else {
1641         const char *error_str = remote->Context().LaunchStatus().AsString();
1642         RNBLogSTDERR("error: failed to launch process %s: %s\n", argv_sub_zero,
1643                      error_str ? error_str : "unknown error.");
1644       }
1645     } break;
1646 
1647     case eRNBRunLoopModeInferiorExecuting:
1648       mode = RNBRunLoopInferiorExecuting(remote);
1649       break;
1650 
1651     case eRNBRunLoopModePlatformMode:
1652       if (port != INT32_MAX) {
1653         if (!ConnectRemote(remote, host.c_str(), port, reverse_connect,
1654                            named_pipe_path.c_str(), unix_socket_name.c_str()))
1655           mode = eRNBRunLoopModeExit;
1656       } else if (str[0] == '/') {
1657         if (remote->Comm().OpenFile(str))
1658           mode = eRNBRunLoopModeExit;
1659       } else if (communication_fd >= 0) {
1660         // We were passed a file descriptor to use during fork/exec that is
1661         // already open
1662         // in our process, so lets just use it!
1663         if (remote->Comm().useFD(communication_fd))
1664           mode = eRNBRunLoopModeExit;
1665         else
1666           remote->StartReadRemoteDataThread();
1667       }
1668 
1669       if (mode != eRNBRunLoopModeExit)
1670         mode = RNBRunLoopPlatform(remote);
1671       break;
1672 
1673     default:
1674       mode = eRNBRunLoopModeExit;
1675       break;
1676     case eRNBRunLoopModeExit:
1677       break;
1678     }
1679   }
1680 
1681   remote->StopReadRemoteDataThread();
1682   remote->Context().SetProcessID(INVALID_NUB_PROCESS);
1683   RNBLogSTDOUT("Exiting.\n");
1684 
1685   return 0;
1686 }
1687