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