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