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