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