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 || type == RNBRemote::vattachorwait)
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 %llu (old %llu)) Notify??? no, first stop...", __FUNCTION__, (int)initialize, DNBStateAsString (pid_state), (uint64_t)ctx.GetProcessStopCount(), (uint64_t)prev_pid_stop_count);
451                     }
452                     else
453                     {
454 
455                         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);
456                         remote->NotifyThatProcessStopped ();
457                     }
458                 }
459                 else
460                 {
461                     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);
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     const char *argv_sub_zero = argv[0]; // save a copy of argv[0] for error reporting post-launch
791 
792     g_isatty = ::isatty (STDIN_FILENO);
793 
794     //  ::printf ("uid=%u euid=%u gid=%u egid=%u\n",
795     //            getuid(),
796     //            geteuid(),
797     //            getgid(),
798     //            getegid());
799 
800 
801     //    signal (SIGINT, signal_handler);
802     signal (SIGPIPE, signal_handler);
803     signal (SIGHUP, signal_handler);
804 
805     g_remoteSP.reset (new RNBRemote ());
806 
807 
808     RNBRemote *remote = g_remoteSP.get();
809     if (remote == NULL)
810     {
811         RNBLogSTDERR ("error: failed to create a remote connection class\n");
812         return -1;
813     }
814 
815     RNBContext& ctx = remote->Context();
816 
817     int i;
818     int attach_pid = INVALID_NUB_PROCESS;
819 
820     FILE* log_file = NULL;
821     uint32_t log_flags = 0;
822     // Parse our options
823     int ch;
824     int long_option_index = 0;
825     int debug = 0;
826     std::string compile_options;
827     std::string waitfor_pid_name;           // Wait for a process that starts with this name
828     std::string attach_pid_name;
829     std::string arch_name;
830     std::string working_dir;                // The new working directory to use for the inferior
831     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
832     useconds_t waitfor_interval = 1000;     // Time in usecs between process lists polls when waiting for a process by name, default 1 msec.
833     useconds_t waitfor_duration = 0;        // Time in seconds to wait for a process by name, 0 means wait forever.
834     bool no_stdio = false;
835 
836 #if !defined (DNBLOG_ENABLED)
837     compile_options += "(no-logging) ";
838 #endif
839 
840     RNBRunLoopMode start_mode = eRNBRunLoopModeExit;
841 
842     char short_options[512];
843     uint32_t short_options_idx = 0;
844 
845      // Handle the two case that don't have short options in g_long_options
846     short_options[short_options_idx++] = 'k';
847     short_options[short_options_idx++] = 't';
848 
849     for (i=0; g_long_options[i].name != NULL; ++i)
850     {
851         if (isalpha(g_long_options[i].val))
852         {
853             short_options[short_options_idx++] = g_long_options[i].val;
854             switch (g_long_options[i].has_arg)
855             {
856                 default:
857                 case no_argument:
858                     break;
859 
860                 case optional_argument:
861                     short_options[short_options_idx++] = ':';
862                     // Fall through to required_argument case below...
863                 case required_argument:
864                     short_options[short_options_idx++] = ':';
865                     break;
866             }
867         }
868     }
869     // NULL terminate the short option string.
870     short_options[short_options_idx++] = '\0';
871     while ((ch = getopt_long(argc, argv, short_options, g_long_options, &long_option_index)) != -1)
872     {
873         DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n",
874                     ch, (uint8_t)ch,
875                     g_long_options[long_option_index].name,
876                     g_long_options[long_option_index].has_arg ? '=' : ' ',
877                     optarg ? optarg : "");
878         switch (ch)
879         {
880             case 0:   // Any optional that auto set themselves will return 0
881                 break;
882 
883             case 'A':
884                 if (optarg && optarg[0])
885                     arch_name.assign(optarg);
886                 break;
887 
888             case 'a':
889                 if (optarg && optarg[0])
890                 {
891                     if (isdigit(optarg[0]))
892                     {
893                         char *end = NULL;
894                         attach_pid = strtoul(optarg, &end, 0);
895                         if (end == NULL || *end != '\0')
896                         {
897                             RNBLogSTDERR ("error: invalid pid option '%s'\n", optarg);
898                             exit (4);
899                         }
900                     }
901                     else
902                     {
903                         attach_pid_name = optarg;
904                     }
905                     start_mode = eRNBRunLoopModeInferiorAttaching;
906                 }
907                 break;
908 
909                 // --waitfor=NAME
910             case 'w':
911                 if (optarg && optarg[0])
912                 {
913                     waitfor_pid_name = optarg;
914                     start_mode = eRNBRunLoopModeInferiorAttaching;
915                 }
916                 break;
917 
918                 // --waitfor-interval=USEC
919             case 'i':
920                 if (optarg && optarg[0])
921                 {
922                     char *end = NULL;
923                     waitfor_interval = strtoul(optarg, &end, 0);
924                     if (end == NULL || *end != '\0')
925                     {
926                         RNBLogSTDERR ("error: invalid waitfor-interval option value '%s'.\n", optarg);
927                         exit (6);
928                     }
929                 }
930                 break;
931 
932                 // --waitfor-duration=SEC
933             case 'd':
934                 if (optarg && optarg[0])
935                 {
936                     char *end = NULL;
937                     waitfor_duration = strtoul(optarg, &end, 0);
938                     if (end == NULL || *end != '\0')
939                     {
940                         RNBLogSTDERR ("error: invalid waitfor-duration option value '%s'.\n", optarg);
941                         exit (7);
942                     }
943                 }
944                 break;
945 
946             case 'W':
947                 if (optarg && optarg[0])
948                     working_dir.assign(optarg);
949                 break;
950 
951             case 'x':
952                 if (optarg && optarg[0])
953                 {
954                     if (strcasecmp(optarg, "auto") == 0)
955                         g_launch_flavor = eLaunchFlavorDefault;
956                     else if (strcasestr(optarg, "posix") == optarg)
957                         g_launch_flavor = eLaunchFlavorPosixSpawn;
958                     else if (strcasestr(optarg, "fork") == optarg)
959                         g_launch_flavor = eLaunchFlavorForkExec;
960 #ifdef WITH_SPRINGBOARD
961                     else if (strcasestr(optarg, "spring") == optarg)
962                         g_launch_flavor = eLaunchFlavorSpringBoard;
963 #endif
964                     else
965                     {
966                         RNBLogSTDERR ("error: invalid TYPE for the --launch=TYPE (-x TYPE) option: '%s'\n", optarg);
967                         RNBLogSTDERR ("Valid values TYPE are:\n");
968                         RNBLogSTDERR ("  auto    Auto-detect the best launch method to use.\n");
969                         RNBLogSTDERR ("  posix   Launch the executable using posix_spawn.\n");
970                         RNBLogSTDERR ("  fork    Launch the executable using fork and exec.\n");
971 #ifdef WITH_SPRINGBOARD
972                         RNBLogSTDERR ("  spring  Launch the executable through Springboard.\n");
973 #endif
974                         exit (5);
975                     }
976                 }
977                 break;
978 
979             case 'l': // Set Log File
980                 if (optarg && optarg[0])
981                 {
982                     if (strcasecmp(optarg, "stdout") == 0)
983                         log_file = stdout;
984                     else if (strcasecmp(optarg, "stderr") == 0)
985                         log_file = stderr;
986                     else
987                     {
988                         log_file = fopen(optarg, "w");
989                         if (log_file != NULL)
990                             setlinebuf(log_file);
991                     }
992 
993                     if (log_file == NULL)
994                     {
995                         const char *errno_str = strerror(errno);
996                         RNBLogSTDERR ("Failed to open log file '%s' for writing: errno = %i (%s)", optarg, errno, errno_str ? errno_str : "unknown error");
997                     }
998                 }
999                 break;
1000 
1001             case 'f': // Log Flags
1002                 if (optarg && optarg[0])
1003                     log_flags = strtoul(optarg, NULL, 0);
1004                 break;
1005 
1006             case 'g':
1007                 debug = 1;
1008                 DNBLogSetDebug(debug);
1009                 break;
1010 
1011             case 't':
1012                 g_applist_opt = 1;
1013                 break;
1014 
1015             case 'k':
1016                 g_lockdown_opt = 1;
1017                 break;
1018 
1019             case 'r':
1020                 remote->SetUseNativeRegisters (true);
1021                 break;
1022 
1023             case 'v':
1024                 DNBLogSetVerbose(1);
1025                 break;
1026 
1027             case 's':
1028                 ctx.GetSTDIN().assign(optarg);
1029                 ctx.GetSTDOUT().assign(optarg);
1030                 ctx.GetSTDERR().assign(optarg);
1031                 break;
1032 
1033             case 'I':
1034                 ctx.GetSTDIN().assign(optarg);
1035                 break;
1036 
1037             case 'O':
1038                 ctx.GetSTDOUT().assign(optarg);
1039                 break;
1040 
1041             case 'E':
1042                 ctx.GetSTDERR().assign(optarg);
1043                 break;
1044 
1045             case 'n':
1046                 no_stdio = true;
1047                 break;
1048 
1049             case 'S':
1050                 // Put debugserver into a new session. Terminals group processes
1051                 // into sessions and when a special terminal key sequences
1052                 // (like control+c) are typed they can cause signals to go out to
1053                 // all processes in a session. Using this --setsid (-S) option
1054                 // will cause debugserver to run in its own sessions and be free
1055                 // from such issues.
1056                 //
1057                 // This is useful when debugserver is spawned from a command
1058                 // line application that uses debugserver to do the debugging,
1059                 // yet that application doesn't want debugserver receiving the
1060                 // signals sent to the session (i.e. dying when anyone hits ^C).
1061                 setsid();
1062                 break;
1063             case 'D':
1064                 g_disable_aslr = 1;
1065                 break;
1066 
1067             case 'p':
1068                 start_mode = eRNBRunLoopModePlatformMode;
1069                 break;
1070 
1071             case 'u':
1072                 unix_socket_name.assign (optarg);
1073                 break;
1074 
1075         }
1076     }
1077 
1078     if (arch_name.empty())
1079     {
1080 #if defined (__arm__)
1081         arch_name.assign ("arm");
1082 #endif
1083     }
1084     else
1085     {
1086         DNBSetArchitecture (arch_name.c_str());
1087     }
1088 
1089 //    if (arch_name.empty())
1090 //    {
1091 //        fprintf(stderr, "error: no architecture was specified\n");
1092 //        exit (8);
1093 //    }
1094     // Skip any options we consumed with getopt_long
1095     argc -= optind;
1096     argv += optind;
1097 
1098 
1099     if (!working_dir.empty())
1100     {
1101         if (remote->Context().SetWorkingDirectory (working_dir.c_str()) == false)
1102         {
1103             RNBLogSTDERR ("error: working directory doesn't exist '%s'.\n", working_dir.c_str());
1104             exit (8);
1105         }
1106     }
1107 
1108     remote->Initialize();
1109 
1110     // It is ok for us to set NULL as the logfile (this will disable any logging)
1111 
1112     if (log_file != NULL)
1113     {
1114         DNBLogSetLogCallback(FileLogCallback, log_file);
1115         // If our log file was set, yet we have no log flags, log everything!
1116         if (log_flags == 0)
1117             log_flags = LOG_ALL | LOG_RNB_ALL;
1118 
1119         DNBLogSetLogMask (log_flags);
1120     }
1121     else
1122     {
1123         // Enable DNB logging
1124         DNBLogSetLogCallback(ASLLogCallback, NULL);
1125         DNBLogSetLogMask (log_flags);
1126 
1127     }
1128 
1129     if (DNBLogEnabled())
1130     {
1131         for (i=0; i<argc; i++)
1132             DNBLogDebug("argv[%i] = %s", i, argv[i]);
1133     }
1134 
1135     // as long as we're dropping remotenub in as a replacement for gdbserver,
1136     // explicitly note that this is not gdbserver.
1137 
1138     RNBLogSTDOUT ("%s-%g %sfor %s.\n",
1139                   DEBUGSERVER_PROGRAM_NAME,
1140                   DEBUGSERVER_VERSION_NUM,
1141                   compile_options.c_str(),
1142                   RNB_ARCH);
1143 
1144     int listen_port = INT32_MAX;
1145     char str[PATH_MAX];
1146     str[0] = '\0';
1147 
1148     if (g_lockdown_opt == 0 && g_applist_opt == 0)
1149     {
1150         // Make sure we at least have port
1151         if (argc < 1)
1152         {
1153             show_usage_and_exit (1);
1154         }
1155         // accept 'localhost:' prefix on port number
1156 
1157         int items_scanned = ::sscanf (argv[0], "%[^:]:%i", str, &listen_port);
1158         if (items_scanned == 2)
1159         {
1160             DNBLogDebug("host = '%s'  port = %i", str, listen_port);
1161         }
1162         else if (argv[0][0] == '/')
1163         {
1164             listen_port = INT32_MAX;
1165             strncpy(str, argv[0], sizeof(str));
1166         }
1167         else
1168         {
1169             show_usage_and_exit (2);
1170         }
1171 
1172         // We just used the 'host:port' or the '/path/file' arg...
1173         argc--;
1174         argv++;
1175 
1176     }
1177 
1178     //  If we know we're waiting to attach, we don't need any of this other info.
1179     if (start_mode != eRNBRunLoopModeInferiorAttaching &&
1180         start_mode != eRNBRunLoopModePlatformMode)
1181     {
1182         if (argc == 0 || g_lockdown_opt)
1183         {
1184             if (g_lockdown_opt != 0)
1185             {
1186                 // Work around for SIGPIPE crashes due to posix_spawn issue.
1187                 // We have to close STDOUT and STDERR, else the first time we
1188                 // try and do any, we get SIGPIPE and die as posix_spawn is
1189                 // doing bad things with our file descriptors at the moment.
1190                 int null = open("/dev/null", O_RDWR);
1191                 dup2(null, STDOUT_FILENO);
1192                 dup2(null, STDERR_FILENO);
1193             }
1194             else if (g_applist_opt != 0)
1195             {
1196                 // List all applications we are able to see
1197                 std::string applist_plist;
1198                 int err = ListApplications(applist_plist, false, false);
1199                 if (err == 0)
1200                 {
1201                     fputs (applist_plist.c_str(), stdout);
1202                 }
1203                 else
1204                 {
1205                     RNBLogSTDERR ("error: ListApplications returned error %i\n", err);
1206                 }
1207                 // Exit with appropriate error if we were asked to list the applications
1208                 // with no other args were given (and we weren't trying to do this over
1209                 // lockdown)
1210                 return err;
1211             }
1212 
1213             DNBLogDebug("Get args from remote protocol...");
1214             start_mode = eRNBRunLoopModeGetStartModeFromRemoteProtocol;
1215         }
1216         else
1217         {
1218             start_mode = eRNBRunLoopModeInferiorLaunching;
1219             // Fill in the argv array in the context from the rest of our args.
1220             // Skip the name of this executable and the port number
1221             for (int i = 0; i < argc; i++)
1222             {
1223                 DNBLogDebug("inferior_argv[%i] = '%s'", i, argv[i]);
1224                 ctx.PushArgument (argv[i]);
1225             }
1226         }
1227     }
1228 
1229     if (start_mode == eRNBRunLoopModeExit)
1230         return -1;
1231 
1232     RNBRunLoopMode mode = start_mode;
1233     char err_str[1024] = {'\0'};
1234 
1235     while (mode != eRNBRunLoopModeExit)
1236     {
1237         switch (mode)
1238         {
1239             case eRNBRunLoopModeGetStartModeFromRemoteProtocol:
1240 #ifdef WITH_LOCKDOWN
1241                 if (g_lockdown_opt)
1242                 {
1243                     if (!remote->Comm().IsConnected())
1244                     {
1245                         if (remote->Comm().ConnectToService () != rnb_success)
1246                         {
1247                             RNBLogSTDERR ("Failed to get connection from a remote gdb process.\n");
1248                             mode = eRNBRunLoopModeExit;
1249                         }
1250                         else if (g_applist_opt != 0)
1251                         {
1252                             // List all applications we are able to see
1253                             std::string applist_plist;
1254                             if (ListApplications(applist_plist, false, false) == 0)
1255                             {
1256                                 DNBLogDebug("Task list: %s", applist_plist.c_str());
1257 
1258                                 remote->Comm().Write(applist_plist.c_str(), applist_plist.size());
1259                                 // Issue a read that will never yield any data until the other side
1260                                 // closes the socket so this process doesn't just exit and cause the
1261                                 // socket to close prematurely on the other end and cause data loss.
1262                                 std::string buf;
1263                                 remote->Comm().Read(buf);
1264                             }
1265                             remote->Comm().Disconnect(false);
1266                             mode = eRNBRunLoopModeExit;
1267                             break;
1268                         }
1269                         else
1270                         {
1271                             // Start watching for remote packets
1272                             remote->StartReadRemoteDataThread();
1273                         }
1274                     }
1275                 }
1276                 else
1277 #endif
1278                 if (listen_port != INT32_MAX)
1279                 {
1280                     if (!StartListening (remote, listen_port, unix_socket_name.c_str()))
1281                         mode = eRNBRunLoopModeExit;
1282                 }
1283                 else if (str[0] == '/')
1284                 {
1285                     if (remote->Comm().OpenFile (str))
1286                         mode = eRNBRunLoopModeExit;
1287                 }
1288 
1289                 if (mode != eRNBRunLoopModeExit)
1290                 {
1291                     RNBLogSTDOUT ("Got a connection, waiting for process information for launching or attaching.\n");
1292 
1293                     mode = RNBRunLoopGetStartModeFromRemote (remote);
1294                 }
1295                 break;
1296 
1297             case eRNBRunLoopModeInferiorAttaching:
1298                 if (!waitfor_pid_name.empty())
1299                 {
1300                     // Set our end wait time if we are using a waitfor-duration
1301                     // option that may have been specified
1302                     struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1303                     if (waitfor_duration != 0)
1304                     {
1305                         DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration, 0);
1306                         timeout_ptr = &attach_timeout_abstime;
1307                     }
1308                     nub_launch_flavor_t launch_flavor = g_launch_flavor;
1309                     if (launch_flavor == eLaunchFlavorDefault)
1310                     {
1311                         // Our default launch method is posix spawn
1312                         launch_flavor = eLaunchFlavorPosixSpawn;
1313 
1314 #ifdef WITH_SPRINGBOARD
1315                         // Check if we have an app bundle, if so launch using SpringBoard.
1316                         if (waitfor_pid_name.find (".app") != std::string::npos)
1317                         {
1318                             launch_flavor = eLaunchFlavorSpringBoard;
1319                         }
1320 #endif
1321                     }
1322 
1323                     ctx.SetLaunchFlavor(launch_flavor);
1324                     bool ignore_existing = false;
1325                     nub_process_t pid = DNBProcessAttachWait (waitfor_pid_name.c_str(), launch_flavor, ignore_existing, timeout_ptr, waitfor_interval, err_str, sizeof(err_str));
1326                     g_pid = pid;
1327 
1328                     if (pid == INVALID_NUB_PROCESS)
1329                     {
1330                         ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1331                         if (err_str[0])
1332                             ctx.LaunchStatus().SetErrorString(err_str);
1333                         RNBLogSTDERR ("error: failed to attach to process named: \"%s\" %s", waitfor_pid_name.c_str(), err_str);
1334                         mode = eRNBRunLoopModeExit;
1335                     }
1336                     else
1337                     {
1338                         ctx.SetProcessID(pid);
1339                         mode = eRNBRunLoopModeInferiorExecuting;
1340                     }
1341                 }
1342                 else if (attach_pid != INVALID_NUB_PROCESS)
1343                 {
1344 
1345                     RNBLogSTDOUT ("Attaching to process %i...\n", attach_pid);
1346                     nub_process_t attached_pid;
1347                     mode = RNBRunLoopLaunchAttaching (remote, attach_pid, attached_pid);
1348                     if (mode != eRNBRunLoopModeInferiorExecuting)
1349                     {
1350                         const char *error_str = remote->Context().LaunchStatus().AsString();
1351                         RNBLogSTDERR ("error: failed to attach process %i: %s\n", attach_pid, error_str ? error_str : "unknown error.");
1352                         mode = eRNBRunLoopModeExit;
1353                     }
1354                 }
1355                 else if (!attach_pid_name.empty ())
1356                 {
1357                     struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1358                     if (waitfor_duration != 0)
1359                     {
1360                         DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration, 0);
1361                         timeout_ptr = &attach_timeout_abstime;
1362                     }
1363 
1364                     nub_process_t pid = DNBProcessAttachByName (attach_pid_name.c_str(), timeout_ptr, err_str, sizeof(err_str));
1365                     g_pid = pid;
1366                     if (pid == INVALID_NUB_PROCESS)
1367                     {
1368                         ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1369                         if (err_str[0])
1370                             ctx.LaunchStatus().SetErrorString(err_str);
1371                         RNBLogSTDERR ("error: failed to attach to process named: \"%s\" %s", waitfor_pid_name.c_str(), err_str);
1372                         mode = eRNBRunLoopModeExit;
1373                     }
1374                     else
1375                     {
1376                         ctx.SetProcessID(pid);
1377                         mode = eRNBRunLoopModeInferiorExecuting;
1378                     }
1379 
1380                 }
1381                 else
1382                 {
1383                     RNBLogSTDERR ("error: asked to attach with empty name and invalid PID.");
1384                     mode = eRNBRunLoopModeExit;
1385                 }
1386 
1387                 if (mode != eRNBRunLoopModeExit)
1388                 {
1389                     if (listen_port != INT32_MAX)
1390                     {
1391                         if (!StartListening (remote, listen_port, unix_socket_name.c_str()))
1392                             mode = eRNBRunLoopModeExit;
1393                     }
1394                     else if (str[0] == '/')
1395                     {
1396                         if (remote->Comm().OpenFile (str))
1397                             mode = eRNBRunLoopModeExit;
1398                     }
1399                     if (mode != eRNBRunLoopModeExit)
1400                         RNBLogSTDOUT ("Got a connection, waiting for debugger instructions for process %d.\n", attach_pid);
1401                 }
1402                 break;
1403 
1404             case eRNBRunLoopModeInferiorLaunching:
1405                 {
1406                     mode = RNBRunLoopLaunchInferior (remote,
1407                                                      ctx.GetSTDINPath(),
1408                                                      ctx.GetSTDOUTPath(),
1409                                                      ctx.GetSTDERRPath(),
1410                                                      no_stdio);
1411 
1412                     if (mode == eRNBRunLoopModeInferiorExecuting)
1413                     {
1414                         if (listen_port != INT32_MAX)
1415                         {
1416                             if (!StartListening (remote, listen_port, unix_socket_name.c_str()))
1417                                 mode = eRNBRunLoopModeExit;
1418                         }
1419                         else if (str[0] == '/')
1420                         {
1421                             if (remote->Comm().OpenFile (str))
1422                                 mode = eRNBRunLoopModeExit;
1423                         }
1424 
1425                         if (mode != eRNBRunLoopModeExit)
1426                             RNBLogSTDOUT ("Got a connection, waiting for debugger instructions.\n");
1427                     }
1428                     else
1429                     {
1430                         const char *error_str = remote->Context().LaunchStatus().AsString();
1431                         RNBLogSTDERR ("error: failed to launch process %s: %s\n", argv_sub_zero, error_str ? error_str : "unknown error.");
1432                     }
1433                 }
1434                 break;
1435 
1436             case eRNBRunLoopModeInferiorExecuting:
1437                 mode = RNBRunLoopInferiorExecuting(remote);
1438                 break;
1439 
1440             case eRNBRunLoopModePlatformMode:
1441                 if (listen_port != INT32_MAX)
1442                 {
1443                     if (!StartListening (remote, listen_port, unix_socket_name.c_str()))
1444                         mode = eRNBRunLoopModeExit;
1445                 }
1446                 else if (str[0] == '/')
1447                 {
1448                     if (remote->Comm().OpenFile (str))
1449                         mode = eRNBRunLoopModeExit;
1450                 }
1451 
1452                 if (mode != eRNBRunLoopModeExit)
1453                     mode = RNBRunLoopPlatform (remote);
1454                 break;
1455 
1456             default:
1457                 mode = eRNBRunLoopModeExit;
1458             case eRNBRunLoopModeExit:
1459                 break;
1460         }
1461     }
1462 
1463     remote->StopReadRemoteDataThread ();
1464     remote->Context().SetProcessID(INVALID_NUB_PROCESS);
1465 
1466     return 0;
1467 }
1468