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