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