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