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