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