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