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