blob: 42469ce89e31fbd21f36ebcaebde2e0764102824 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- 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>
Greg Clayton8b82f082011-04-12 05:54:46 +000020#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>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026
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...
39nub_process_t g_pid = INVALID_NUB_PROCESS;
40
41//----------------------------------------------------------------------
42// Run loop modes which determine which run loop function will be called
43//----------------------------------------------------------------------
44typedef enum
45{
46 eRNBRunLoopModeInvalid = 0,
47 eRNBRunLoopModeGetStartModeFromRemoteProtocol,
48 eRNBRunLoopModeInferiorAttaching,
49 eRNBRunLoopModeInferiorLaunching,
50 eRNBRunLoopModeInferiorExecuting,
Greg Clayton7a5388b2011-03-20 04:57:14 +000051 eRNBRunLoopModePlatformMode,
Chris Lattner30fdc8d2010-06-08 16:52:24 +000052 eRNBRunLoopModeExit
53} RNBRunLoopMode;
54
55
56//----------------------------------------------------------------------
57// Global Variables
58//----------------------------------------------------------------------
59RNBRemoteSP g_remoteSP;
60static int g_lockdown_opt = 0;
61static int g_applist_opt = 0;
62static nub_launch_flavor_t g_launch_flavor = eLaunchFlavorDefault;
Greg Clayton6f35f5c2010-09-09 06:32:46 +000063int g_disable_aslr = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000064
65int 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//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071// 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//----------------------------------------------------------------------
76RNBRunLoopMode
Greg Clayton6779606a2011-01-22 23:43:18 +000077RNBRunLoopGetStartModeFromRemote (RNBRemote* remote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000078{
79 std::string packet;
80
Greg Clayton6779606a2011-01-22 23:43:18 +000081 if (remote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +000082 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +000083 RNBContext& ctx = remote->Context();
Greg Clayton71337622011-02-24 22:24:29 +000084 uint32_t event_mask = RNBContext::event_read_packet_available |
85 RNBContext::event_read_thread_exiting;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000086
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
Greg Clayton71337622011-02-24 22:24:29 +000094 if (set_events & RNBContext::event_read_thread_exiting)
95 {
Jim Inghame2ff0ba2013-02-25 19:31:37 +000096 RNBLogSTDERR ("error: packet read thread exited.\n");
Greg Clayton71337622011-02-24 22:24:29 +000097 return eRNBRunLoopModeExit;
98 }
99
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000100 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
Jim Inghamcd16df92012-07-20 21:37:13 +0000108 if (type == RNBRemote::vattach || type == RNBRemote::vattachwait || type == RNBRemote::vattachorwait)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000109 {
110 if (err == rnb_success)
Jim Inghame2ff0ba2013-02-25 19:31:37 +0000111 {
112 RNBLogSTDOUT ("Attach succeeded, ready to debug.\n");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000113 return eRNBRunLoopModeInferiorExecuting;
Jim Inghame2ff0ba2013-02-25 19:31:37 +0000114 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000115 else
116 {
Jim Inghame2ff0ba2013-02-25 19:31:37 +0000117 RNBLogSTDERR ("error: attach failed.\n");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000118 return eRNBRunLoopModeExit;
119 }
120 }
121
122 if (err == rnb_success)
123 {
124 // If we got our arguments we are ready to launch using the arguments
125 // and any environment variables we received.
126 if (type == RNBRemote::set_argv)
127 {
128 return eRNBRunLoopModeInferiorLaunching;
129 }
130 }
131 else if (err == rnb_not_connected)
132 {
Jim Inghame2ff0ba2013-02-25 19:31:37 +0000133 RNBLogSTDERR ("error: connection lost.\n");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000134 return eRNBRunLoopModeExit;
135 }
136 else
137 {
138 // a catch all for any other gdb remote packets that failed
139 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s Error getting packet.",__FUNCTION__);
140 continue;
141 }
142
143 DNBLogThreadedIf (LOG_RNB_MINIMAL, "#### %s", __FUNCTION__);
144 }
145 else
146 {
147 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s Connection closed before getting \"A\" packet.", __FUNCTION__);
148 return eRNBRunLoopModeExit;
149 }
150 }
151 }
152 return eRNBRunLoopModeExit;
153}
154
155
156//----------------------------------------------------------------------
157// This run loop mode will wait for the process to launch and hit its
158// entry point. It will currently ignore all events except for the
159// process state changed event, where it watches for the process stopped
160// or crash process state.
161//----------------------------------------------------------------------
162RNBRunLoopMode
Greg Clayton6779606a2011-01-22 23:43:18 +0000163RNBRunLoopLaunchInferior (RNBRemote *remote, const char *stdin_path, const char *stdout_path, const char *stderr_path, bool no_stdio)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000164{
165 RNBContext& ctx = remote->Context();
166
167 // The Process stuff takes a c array, the RNBContext has a vector...
168 // So make up a c array.
169
170 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s Launching '%s'...", __FUNCTION__, ctx.ArgumentAtIndex(0));
171
172 size_t inferior_argc = ctx.ArgumentCount();
173 // Initialize inferior_argv with inferior_argc + 1 NULLs
174 std::vector<const char *> inferior_argv(inferior_argc + 1, NULL);
175
176 size_t i;
177 for (i = 0; i < inferior_argc; i++)
178 inferior_argv[i] = ctx.ArgumentAtIndex(i);
179
180 // Pass the environment array the same way:
181
182 size_t inferior_envc = ctx.EnvironmentCount();
183 // Initialize inferior_argv with inferior_argc + 1 NULLs
184 std::vector<const char *> inferior_envp(inferior_envc + 1, NULL);
185
186 for (i = 0; i < inferior_envc; i++)
187 inferior_envp[i] = ctx.EnvironmentAtIndex(i);
188
189 // Our launch type hasn't been set to anything concrete, so we need to
190 // figure our how we are going to launch automatically.
191
192 nub_launch_flavor_t launch_flavor = g_launch_flavor;
193 if (launch_flavor == eLaunchFlavorDefault)
194 {
195 // Our default launch method is posix spawn
196 launch_flavor = eLaunchFlavorPosixSpawn;
197
Jason Molenda42999a42012-02-22 02:18:59 +0000198#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199 // Check if we have an app bundle, if so launch using SpringBoard.
200 if (strstr(inferior_argv[0], ".app"))
201 {
202 launch_flavor = eLaunchFlavorSpringBoard;
203 }
204#endif
205 }
206
207 ctx.SetLaunchFlavor(launch_flavor);
208 char resolved_path[PATH_MAX];
209
210 // If we fail to resolve the path to our executable, then just use what we
211 // were given and hope for the best
212 if ( !DNBResolveExecutablePath (inferior_argv[0], resolved_path, sizeof(resolved_path)) )
213 ::strncpy(resolved_path, inferior_argv[0], sizeof(resolved_path));
214
215 char launch_err_str[PATH_MAX];
216 launch_err_str[0] = '\0';
Johnny Chen725269a2011-02-26 01:36:13 +0000217 const char * cwd = (ctx.GetWorkingDirPath() != NULL ? ctx.GetWorkingDirPath()
218 : ctx.GetWorkingDirectory());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000219 nub_process_t pid = DNBProcessLaunch (resolved_path,
220 &inferior_argv[0],
221 &inferior_envp[0],
Johnny Chen725269a2011-02-26 01:36:13 +0000222 cwd,
Greg Clayton6779606a2011-01-22 23:43:18 +0000223 stdin_path,
224 stdout_path,
225 stderr_path,
Caroline Ticef8da8632010-12-03 18:46:09 +0000226 no_stdio,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000227 launch_flavor,
Greg Claytonf681b942010-08-31 18:35:14 +0000228 g_disable_aslr,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000229 launch_err_str,
230 sizeof(launch_err_str));
231
232 g_pid = pid;
233
Jason Molenda4e0c94b2011-07-08 00:00:32 +0000234 if (pid == INVALID_NUB_PROCESS && strlen (launch_err_str) > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000235 {
Greg Clayton3382c2c2010-07-30 23:14:42 +0000236 DNBLogThreaded ("%s DNBProcessLaunch() returned error: '%s'", __FUNCTION__, launch_err_str);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000237 ctx.LaunchStatus().SetError(-1, DNBError::Generic);
238 ctx.LaunchStatus().SetErrorString(launch_err_str);
239 }
Jason Molenda4e0c94b2011-07-08 00:00:32 +0000240 else if (pid == INVALID_NUB_PROCESS)
241 {
242 DNBLogThreaded ("%s DNBProcessLaunch() failed to launch process, unknown failure", __FUNCTION__);
243 ctx.LaunchStatus().SetError(-1, DNBError::Generic);
244 ctx.LaunchStatus().SetErrorString(launch_err_str);
245 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000246 else
Greg Clayton71337622011-02-24 22:24:29 +0000247 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000248 ctx.LaunchStatus().Clear();
Greg Clayton71337622011-02-24 22:24:29 +0000249 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000250
251 if (remote->Comm().IsConnected())
252 {
253 // It we are connected already, the next thing gdb will do is ask
254 // whether the launch succeeded, and if not, whether there is an
255 // error code. So we need to fetch one packet from gdb before we wait
256 // on the stop from the target.
257
258 uint32_t event_mask = RNBContext::event_read_packet_available;
259 nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
260
261 if (set_events & RNBContext::event_read_packet_available)
262 {
263 rnb_err_t err = rnb_err;
264 RNBRemote::PacketEnum type;
265
266 err = remote->HandleReceivedPacket (&type);
267
268 if (err != rnb_success)
269 {
270 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s Error getting packet.", __FUNCTION__);
271 return eRNBRunLoopModeExit;
272 }
273 if (type != RNBRemote::query_launch_success)
274 {
275 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s Didn't get the expected qLaunchSuccess packet.", __FUNCTION__);
276 }
277 }
278 }
279
280 while (pid != INVALID_NUB_PROCESS)
281 {
282 // Wait for process to start up and hit entry point
283 DNBLogThreadedIf (LOG_RNB_EVENTS, "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, true, INFINITE)...", __FUNCTION__, pid);
284 nub_event_t set_events = DNBProcessWaitForEvents (pid, eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, true, NULL);
285 DNBLogThreadedIf (LOG_RNB_EVENTS, "%s DNBProcessWaitForEvent (%4.4x, eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged, true, INFINITE) => 0x%8.8x", __FUNCTION__, pid, set_events);
286
287 if (set_events == 0)
288 {
289 pid = INVALID_NUB_PROCESS;
290 g_pid = pid;
291 }
292 else
293 {
294 if (set_events & (eEventProcessRunningStateChanged | eEventProcessStoppedStateChanged))
295 {
296 nub_state_t pid_state = DNBProcessGetState (pid);
297 DNBLogThreadedIf (LOG_RNB_EVENTS, "%s process %4.4x state changed (eEventProcessStateChanged): %s", __FUNCTION__, pid, DNBStateAsString(pid_state));
298
299 switch (pid_state)
300 {
301 default:
302 case eStateInvalid:
303 case eStateUnloaded:
304 case eStateAttaching:
305 case eStateLaunching:
306 case eStateSuspended:
307 break; // Ignore
308
309 case eStateRunning:
310 case eStateStepping:
311 // Still waiting to stop at entry point...
312 break;
313
314 case eStateStopped:
315 case eStateCrashed:
316 ctx.SetProcessID(pid);
317 return eRNBRunLoopModeInferiorExecuting;
318
319 case eStateDetached:
320 case eStateExited:
321 pid = INVALID_NUB_PROCESS;
322 g_pid = pid;
323 return eRNBRunLoopModeExit;
324 }
325 }
326
327 DNBProcessResetEvents(pid, set_events);
328 }
329 }
330
331 return eRNBRunLoopModeExit;
332}
333
334
335//----------------------------------------------------------------------
336// This run loop mode will wait for the process to launch and hit its
337// entry point. It will currently ignore all events except for the
338// process state changed event, where it watches for the process stopped
339// or crash process state.
340//----------------------------------------------------------------------
341RNBRunLoopMode
Greg Clayton6779606a2011-01-22 23:43:18 +0000342RNBRunLoopLaunchAttaching (RNBRemote *remote, nub_process_t attach_pid, nub_process_t& pid)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000343{
344 RNBContext& ctx = remote->Context();
345
346 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s Attaching to pid %i...", __FUNCTION__, attach_pid);
347 char err_str[1024];
348 pid = DNBProcessAttach (attach_pid, NULL, err_str, sizeof(err_str));
349 g_pid = pid;
350
351 if (pid == INVALID_NUB_PROCESS)
352 {
353 ctx.LaunchStatus().SetError(-1, DNBError::Generic);
354 if (err_str[0])
355 ctx.LaunchStatus().SetErrorString(err_str);
356 return eRNBRunLoopModeExit;
357 }
358 else
359 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000360 ctx.SetProcessID(pid);
361 return eRNBRunLoopModeInferiorExecuting;
362 }
363}
364
365//----------------------------------------------------------------------
366// Watch for signals:
367// SIGINT: so we can halt our inferior. (disabled for now)
368// SIGPIPE: in case our child process dies
369//----------------------------------------------------------------------
370int g_sigint_received = 0;
371int g_sigpipe_received = 0;
372void
373signal_handler(int signo)
374{
375 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s (%s)", __FUNCTION__, SysSignal::Name(signo));
376
377 switch (signo)
378 {
379 case SIGINT:
380 g_sigint_received++;
381 if (g_pid != INVALID_NUB_PROCESS)
382 {
383 // Only send a SIGINT once...
384 if (g_sigint_received == 1)
385 {
386 switch (DNBProcessGetState (g_pid))
387 {
388 case eStateRunning:
389 case eStateStepping:
390 DNBProcessSignal (g_pid, SIGSTOP);
391 return;
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000392 default:
393 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394 }
395 }
396 }
397 exit (SIGINT);
398 break;
399
400 case SIGPIPE:
401 g_sigpipe_received = 1;
402 break;
403 }
404}
405
406// Return the new run loop mode based off of the current process state
407RNBRunLoopMode
Greg Clayton6779606a2011-01-22 23:43:18 +0000408HandleProcessStateChange (RNBRemote *remote, bool initialize)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409{
410 RNBContext& ctx = remote->Context();
411 nub_process_t pid = ctx.ProcessID();
412
413 if (pid == INVALID_NUB_PROCESS)
414 {
415 DNBLogThreadedIf (LOG_RNB_MINIMAL, "#### %s error: pid invalid, exiting...", __FUNCTION__);
416 return eRNBRunLoopModeExit;
417 }
418 nub_state_t pid_state = DNBProcessGetState (pid);
419
420 DNBLogThreadedIf (LOG_RNB_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s", __FUNCTION__, (int)initialize, DNBStateAsString (pid_state));
421
422 switch (pid_state)
423 {
424 case eStateInvalid:
425 case eStateUnloaded:
426 // Something bad happened
427 return eRNBRunLoopModeExit;
428 break;
429
430 case eStateAttaching:
431 case eStateLaunching:
432 return eRNBRunLoopModeInferiorExecuting;
433
434 case eStateSuspended:
435 case eStateCrashed:
436 case eStateStopped:
437 // If we stop due to a signal, so clear the fact that we got a SIGINT
438 // so we can stop ourselves again (but only while our inferior
439 // process is running..)
440 g_sigint_received = 0;
441 if (initialize == false)
442 {
443 // Compare the last stop count to our current notion of a stop count
444 // to make sure we don't notify more than once for a given stop.
445 nub_size_t prev_pid_stop_count = ctx.GetProcessStopCount();
446 bool pid_stop_count_changed = ctx.SetProcessStopCount(DNBProcessGetStopCount(pid));
447 if (pid_stop_count_changed)
448 {
449 remote->FlushSTDIO();
450
451 if (ctx.GetProcessStopCount() == 1)
452 {
Greg Clayton43e0af02012-09-18 18:04:04 +0000453 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);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454 }
455 else
456 {
457
Greg Clayton43e0af02012-09-18 18:04:04 +0000458 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);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000459 remote->NotifyThatProcessStopped ();
460 }
461 }
462 else
463 {
Greg Clayton43e0af02012-09-18 18:04:04 +0000464 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);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000465 }
466 }
467 return eRNBRunLoopModeInferiorExecuting;
468
469 case eStateStepping:
470 case eStateRunning:
471 return eRNBRunLoopModeInferiorExecuting;
472
473 case eStateExited:
474 remote->HandlePacket_last_signal(NULL);
Greg Clayton95bf0fd2011-04-01 00:29:43 +0000475 case eStateDetached:
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000476 return eRNBRunLoopModeExit;
477
478 }
479
480 // Catch all...
481 return eRNBRunLoopModeExit;
482}
483// This function handles the case where our inferior program is stopped and
484// we are waiting for gdb remote protocol packets. When a packet occurs that
485// makes the inferior run, we need to leave this function with a new state
486// as the return code.
487RNBRunLoopMode
Greg Clayton6779606a2011-01-22 23:43:18 +0000488RNBRunLoopInferiorExecuting (RNBRemote *remote)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489{
490 DNBLogThreadedIf (LOG_RNB_MINIMAL, "#### %s", __FUNCTION__);
491 RNBContext& ctx = remote->Context();
492
493 // Init our mode and set 'is_running' based on the current process state
494 RNBRunLoopMode mode = HandleProcessStateChange (remote, true);
495
496 while (ctx.ProcessID() != INVALID_NUB_PROCESS)
497 {
498
499 std::string set_events_str;
500 uint32_t event_mask = ctx.NormalEventBits();
501
502 if (!ctx.ProcessStateRunning())
503 {
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000504 // Clear some bits if we are not running so we don't send any async packets
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000505 event_mask &= ~RNBContext::event_proc_stdio_available;
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000506 event_mask &= ~RNBContext::event_proc_profile_data;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000507 }
508
509 // We want to make sure we consume all process state changes and have
510 // whomever is notifying us to wait for us to reset the event bit before
511 // continuing.
512 //ctx.Events().SetResetAckMask (RNBContext::event_proc_state_changed);
513
514 DNBLogThreadedIf (LOG_RNB_EVENTS, "%s ctx.Events().WaitForSetEvents(0x%08x) ...",__FUNCTION__, event_mask);
515 nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
516 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));
517
518 if (set_events)
519 {
520 if ((set_events & RNBContext::event_proc_thread_exiting) ||
521 (set_events & RNBContext::event_proc_stdio_available))
522 {
523 remote->FlushSTDIO();
524 }
525
Han Ming Ongab3b8b22012-11-17 00:21:04 +0000526 if (set_events & RNBContext::event_proc_profile_data)
527 {
528 remote->SendAsyncProfileData();
529 }
530
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531 if (set_events & RNBContext::event_read_packet_available)
532 {
533 // handleReceivedPacket will take care of resetting the
534 // event_read_packet_available events when there are no more...
535 set_events ^= RNBContext::event_read_packet_available;
536
537 if (ctx.ProcessStateRunning())
538 {
539 if (remote->HandleAsyncPacket() == rnb_not_connected)
540 {
541 // TODO: connect again? Exit?
542 }
543 }
544 else
545 {
546 if (remote->HandleReceivedPacket() == rnb_not_connected)
547 {
548 // TODO: connect again? Exit?
549 }
550 }
551 }
552
553 if (set_events & RNBContext::event_proc_state_changed)
554 {
555 mode = HandleProcessStateChange (remote, false);
556 ctx.Events().ResetEvents(RNBContext::event_proc_state_changed);
557 set_events ^= RNBContext::event_proc_state_changed;
558 }
559
560 if (set_events & RNBContext::event_proc_thread_exiting)
561 {
562 mode = eRNBRunLoopModeExit;
563 }
564
565 if (set_events & RNBContext::event_read_thread_exiting)
566 {
567 // Out remote packet receiving thread exited, exit for now.
568 if (ctx.HasValidProcessID())
569 {
570 // TODO: We should add code that will leave the current process
571 // in its current state and listen for another connection...
572 if (ctx.ProcessStateRunning())
573 {
Jason Molenda6566d432013-03-23 05:35:57 +0000574 DNBLog ("debugserver's event read thread is exiting, killing the inferior process.");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000575 DNBProcessKill (ctx.ProcessID());
576 }
577 }
578 mode = eRNBRunLoopModeExit;
579 }
580 }
581
582 // Reset all event bits that weren't reset for now...
583 if (set_events != 0)
584 ctx.Events().ResetEvents(set_events);
585
586 if (mode != eRNBRunLoopModeInferiorExecuting)
587 break;
588 }
589
590 return mode;
591}
592
593
Greg Clayton7a5388b2011-03-20 04:57:14 +0000594RNBRunLoopMode
595RNBRunLoopPlatform (RNBRemote *remote)
596{
597 RNBRunLoopMode mode = eRNBRunLoopModePlatformMode;
598 RNBContext& ctx = remote->Context();
599
600 while (mode == eRNBRunLoopModePlatformMode)
601 {
602 std::string set_events_str;
603 const uint32_t event_mask = RNBContext::event_read_packet_available |
604 RNBContext::event_read_thread_exiting;
605
606 DNBLogThreadedIf (LOG_RNB_EVENTS, "%s ctx.Events().WaitForSetEvents(0x%08x) ...",__FUNCTION__, event_mask);
607 nub_event_t set_events = ctx.Events().WaitForSetEvents(event_mask);
608 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));
609
610 if (set_events)
611 {
612 if (set_events & RNBContext::event_read_packet_available)
613 {
614 if (remote->HandleReceivedPacket() == rnb_not_connected)
615 mode = eRNBRunLoopModeExit;
616 }
617
618 if (set_events & RNBContext::event_read_thread_exiting)
619 {
620 mode = eRNBRunLoopModeExit;
621 }
622 ctx.Events().ResetEvents(set_events);
623 }
624 }
625 return eRNBRunLoopModeExit;
626}
627
Greg Clayton8b82f082011-04-12 05:54:46 +0000628static void
Greg Clayton91a9b2472013-12-04 19:19:12 +0000629PortWasBoundCallbackNamedPipe (const void *baton, in_port_t port)
Greg Clayton8b82f082011-04-12 05:54:46 +0000630{
Greg Clayton91a9b2472013-12-04 19:19:12 +0000631 const char *named_pipe = (const char *)baton;
632 if (named_pipe && named_pipe[0])
Greg Clayton8b82f082011-04-12 05:54:46 +0000633 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000634 int fd = ::open(named_pipe, O_WRONLY);
635 if (fd > -1)
Greg Clayton8b82f082011-04-12 05:54:46 +0000636 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000637 char port_str[64];
638 const ssize_t port_str_len = ::snprintf (port_str, sizeof(port_str), "%u", port);
639 // Write the port number as a C string with the NULL terminator
640 ::write (fd, port_str, port_str_len + 1);
641 close (fd);
Greg Clayton8b82f082011-04-12 05:54:46 +0000642 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000643 }
644}
645
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646static int
Greg Clayton00fe87b2013-12-05 22:58:22 +0000647ConnectRemote (RNBRemote *remote, const char *host, int port, bool reverse_connect, const char *named_pipe_path)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000648{
Greg Clayton6779606a2011-01-22 23:43:18 +0000649 if (!remote->Comm().IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000650 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000651 if (reverse_connect)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000652 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000653 if (port == 0)
654 {
655 DNBLogThreaded("error: invalid port supplied for reverse connection: %i.\n", port);
656 return 0;
657 }
658 if (remote->Comm().Connect(host, port) != rnb_success)
659 {
660 DNBLogThreaded("Failed to reverse connect to %s:%i.\n", host, port);
661 return 0;
662 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000663 }
664 else
665 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000666 if (port != 0)
667 RNBLogSTDOUT ("Listening to port %i for a connection from %s...\n", port, host ? host : "localhost");
668 if (remote->Comm().Listen(host, port, PortWasBoundCallbackNamedPipe, named_pipe_path) != rnb_success)
669 {
670 RNBLogSTDERR ("Failed to get connection from a remote gdb process.\n");
671 return 0;
672 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000673 }
Greg Clayton00fe87b2013-12-05 22:58:22 +0000674 remote->StartReadRemoteDataThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675 }
676 return 1;
677}
678
679//----------------------------------------------------------------------
680// ASL Logging callback that can be registered with DNBLogSetLogCallback
681//----------------------------------------------------------------------
682void
683ASLLogCallback(void *baton, uint32_t flags, const char *format, va_list args)
684{
685 if (format == NULL)
686 return;
687 static aslmsg g_aslmsg = NULL;
688 if (g_aslmsg == NULL)
689 {
690 g_aslmsg = ::asl_new (ASL_TYPE_MSG);
691 char asl_key_sender[PATH_MAX];
692 snprintf(asl_key_sender, sizeof(asl_key_sender), "com.apple.%s-%g", DEBUGSERVER_PROGRAM_NAME, DEBUGSERVER_VERSION_NUM);
693 ::asl_set (g_aslmsg, ASL_KEY_SENDER, asl_key_sender);
694 }
695
696 int asl_level;
697 if (flags & DNBLOG_FLAG_FATAL) asl_level = ASL_LEVEL_CRIT;
698 else if (flags & DNBLOG_FLAG_ERROR) asl_level = ASL_LEVEL_ERR;
699 else if (flags & DNBLOG_FLAG_WARNING) asl_level = ASL_LEVEL_WARNING;
700 else if (flags & DNBLOG_FLAG_VERBOSE) asl_level = ASL_LEVEL_WARNING; //ASL_LEVEL_INFO;
701 else asl_level = ASL_LEVEL_WARNING; //ASL_LEVEL_DEBUG;
702
703 ::asl_vlog (NULL, g_aslmsg, asl_level, format, args);
704}
705
706//----------------------------------------------------------------------
707// FILE based Logging callback that can be registered with
708// DNBLogSetLogCallback
709//----------------------------------------------------------------------
710void
711FileLogCallback(void *baton, uint32_t flags, const char *format, va_list args)
712{
713 if (baton == NULL || format == NULL)
714 return;
715
716 ::vfprintf ((FILE *)baton, format, args);
717 ::fprintf ((FILE *)baton, "\n");
718}
719
720
721void
722show_usage_and_exit (int exit_code)
723{
724 RNBLogSTDERR ("Usage:\n %s host:port [program-name program-arg1 program-arg2 ...]\n", DEBUGSERVER_PROGRAM_NAME);
725 RNBLogSTDERR (" %s /path/file [program-name program-arg1 program-arg2 ...]\n", DEBUGSERVER_PROGRAM_NAME);
726 RNBLogSTDERR (" %s host:port --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME);
727 RNBLogSTDERR (" %s /path/file --attach=<pid>\n", DEBUGSERVER_PROGRAM_NAME);
728 RNBLogSTDERR (" %s host:port --attach=<process_name>\n", DEBUGSERVER_PROGRAM_NAME);
729 RNBLogSTDERR (" %s /path/file --attach=<process_name>\n", DEBUGSERVER_PROGRAM_NAME);
730 exit (exit_code);
731}
732
733
734//----------------------------------------------------------------------
Greg Claytonb7ad58a2013-04-04 20:35:24 +0000735// option descriptors for getopt_long_only()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736//----------------------------------------------------------------------
737static struct option g_long_options[] =
738{
739 { "attach", required_argument, NULL, 'a' },
Greg Clayton3af9ea52010-11-18 05:57:03 +0000740 { "arch", required_argument, NULL, 'A' },
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741 { "debug", no_argument, NULL, 'g' },
742 { "verbose", no_argument, NULL, 'v' },
743 { "lockdown", no_argument, &g_lockdown_opt, 1 }, // short option "-k"
744 { "applist", no_argument, &g_applist_opt, 1 }, // short option "-t"
745 { "log-file", required_argument, NULL, 'l' },
746 { "log-flags", required_argument, NULL, 'f' },
747 { "launch", required_argument, NULL, 'x' }, // Valid values are "auto", "posix-spawn", "fork-exec", "springboard" (arm only)
748 { "waitfor", required_argument, NULL, 'w' }, // Wait for a process whose name starts with ARG
749 { "waitfor-interval", required_argument, NULL, 'i' }, // Time in usecs to wait between sampling the pid list when waiting for a process by name
750 { "waitfor-duration", required_argument, NULL, 'd' }, // The time in seconds to wait for a process to show up by name
751 { "native-regs", no_argument, NULL, 'r' }, // Specify to use the native registers instead of the gdb defaults for the architecture.
Greg Claytonbd82a5d2011-01-23 05:56:20 +0000752 { "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)
753 { "stdin-path", required_argument, NULL, 'I' }, // Set the STDIN path to be used when launching applications (only if debugserver launches the process)
Johnny Chena3435452011-01-25 16:56:01 +0000754 { "stdout-path", required_argument, NULL, 'O' }, // Set the STDOUT path to be used when launching applications (only if debugserver launches the process)
755 { "stderr-path", required_argument, NULL, 'E' }, // Set the STDERR path to be used when launching applications (only if debugserver launches the process)
Greg Claytonbd82a5d2011-01-23 05:56:20 +0000756 { "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)
757 { "setsid", no_argument, NULL, 'S' }, // call setsid() to make debugserver run in its own session
Greg Claytonf681b942010-08-31 18:35:14 +0000758 { "disable-aslr", no_argument, NULL, 'D' }, // Use _POSIX_SPAWN_DISABLE_ASLR to avoid shared library randomization
Greg Claytonbd82a5d2011-01-23 05:56:20 +0000759 { "working-dir", required_argument, NULL, 'W' }, // The working directory that the inferior process should have (only if debugserver launches the process)
Greg Clayton7a5388b2011-03-20 04:57:14 +0000760 { "platform", required_argument, NULL, 'p' }, // Put this executable into a remote platform mode
Greg Clayton91a9b2472013-12-04 19:19:12 +0000761 { "named-pipe", required_argument, NULL, 'P' },
Greg Clayton00fe87b2013-12-05 22:58:22 +0000762 { "reverse-connect", no_argument, NULL, 'R' },
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000763 { NULL, 0, NULL, 0 }
764};
765
766
767//----------------------------------------------------------------------
768// main
769//----------------------------------------------------------------------
770int
771main (int argc, char *argv[])
772{
Jason Molenda0b2dbe02012-11-01 02:02:59 +0000773 const char *argv_sub_zero = argv[0]; // save a copy of argv[0] for error reporting post-launch
774
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000775 g_isatty = ::isatty (STDIN_FILENO);
776
777 // ::printf ("uid=%u euid=%u gid=%u egid=%u\n",
778 // getuid(),
779 // geteuid(),
780 // getgid(),
781 // getegid());
782
783
784 // signal (SIGINT, signal_handler);
785 signal (SIGPIPE, signal_handler);
Greg Clayton3382c2c2010-07-30 23:14:42 +0000786 signal (SIGHUP, signal_handler);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787
Greg Clayton71337622011-02-24 22:24:29 +0000788 g_remoteSP.reset (new RNBRemote ());
789
790
791 RNBRemote *remote = g_remoteSP.get();
792 if (remote == NULL)
793 {
794 RNBLogSTDERR ("error: failed to create a remote connection class\n");
795 return -1;
796 }
797
798 RNBContext& ctx = remote->Context();
799
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800 int i;
801 int attach_pid = INVALID_NUB_PROCESS;
802
803 FILE* log_file = NULL;
804 uint32_t log_flags = 0;
805 // Parse our options
806 int ch;
807 int long_option_index = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808 int debug = 0;
809 std::string compile_options;
810 std::string waitfor_pid_name; // Wait for a process that starts with this name
811 std::string attach_pid_name;
Greg Clayton3af9ea52010-11-18 05:57:03 +0000812 std::string arch_name;
Greg Clayton8b82f082011-04-12 05:54:46 +0000813 std::string working_dir; // The new working directory to use for the inferior
Greg Clayton91a9b2472013-12-04 19:19:12 +0000814 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
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000815 useconds_t waitfor_interval = 1000; // Time in usecs between process lists polls when waiting for a process by name, default 1 msec.
816 useconds_t waitfor_duration = 0; // Time in seconds to wait for a process by name, 0 means wait forever.
Caroline Ticef8da8632010-12-03 18:46:09 +0000817 bool no_stdio = false;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000818 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
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819
820#if !defined (DNBLOG_ENABLED)
821 compile_options += "(no-logging) ";
822#endif
823
824 RNBRunLoopMode start_mode = eRNBRunLoopModeExit;
825
Greg Clayton8d400e172011-05-23 18:04:09 +0000826 char short_options[512];
827 uint32_t short_options_idx = 0;
828
829 // Handle the two case that don't have short options in g_long_options
830 short_options[short_options_idx++] = 'k';
831 short_options[short_options_idx++] = 't';
832
833 for (i=0; g_long_options[i].name != NULL; ++i)
834 {
835 if (isalpha(g_long_options[i].val))
836 {
837 short_options[short_options_idx++] = g_long_options[i].val;
838 switch (g_long_options[i].has_arg)
839 {
840 default:
841 case no_argument:
842 break;
843
844 case optional_argument:
845 short_options[short_options_idx++] = ':';
846 // Fall through to required_argument case below...
847 case required_argument:
848 short_options[short_options_idx++] = ':';
849 break;
850 }
851 }
852 }
853 // NULL terminate the short option string.
854 short_options[short_options_idx++] = '\0';
Greg Claytond4724cf2013-11-22 18:55:04 +0000855
856#if __GLIBC__
857 optind = 0;
858#else
859 optreset = 1;
860 optind = 1;
861#endif
862
Greg Claytonb7ad58a2013-04-04 20:35:24 +0000863 while ((ch = getopt_long_only(argc, argv, short_options, g_long_options, &long_option_index)) != -1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864 {
865 DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n",
866 ch, (uint8_t)ch,
867 g_long_options[long_option_index].name,
868 g_long_options[long_option_index].has_arg ? '=' : ' ',
869 optarg ? optarg : "");
870 switch (ch)
871 {
872 case 0: // Any optional that auto set themselves will return 0
873 break;
874
Greg Clayton3af9ea52010-11-18 05:57:03 +0000875 case 'A':
876 if (optarg && optarg[0])
877 arch_name.assign(optarg);
878 break;
879
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880 case 'a':
881 if (optarg && optarg[0])
882 {
883 if (isdigit(optarg[0]))
884 {
885 char *end = NULL;
886 attach_pid = strtoul(optarg, &end, 0);
887 if (end == NULL || *end != '\0')
888 {
889 RNBLogSTDERR ("error: invalid pid option '%s'\n", optarg);
890 exit (4);
891 }
892 }
893 else
894 {
895 attach_pid_name = optarg;
896 }
897 start_mode = eRNBRunLoopModeInferiorAttaching;
898 }
899 break;
900
901 // --waitfor=NAME
902 case 'w':
903 if (optarg && optarg[0])
904 {
905 waitfor_pid_name = optarg;
906 start_mode = eRNBRunLoopModeInferiorAttaching;
907 }
908 break;
909
910 // --waitfor-interval=USEC
911 case 'i':
912 if (optarg && optarg[0])
913 {
914 char *end = NULL;
915 waitfor_interval = strtoul(optarg, &end, 0);
916 if (end == NULL || *end != '\0')
917 {
918 RNBLogSTDERR ("error: invalid waitfor-interval option value '%s'.\n", optarg);
919 exit (6);
920 }
921 }
922 break;
923
924 // --waitfor-duration=SEC
925 case 'd':
926 if (optarg && optarg[0])
927 {
928 char *end = NULL;
929 waitfor_duration = strtoul(optarg, &end, 0);
930 if (end == NULL || *end != '\0')
931 {
932 RNBLogSTDERR ("error: invalid waitfor-duration option value '%s'.\n", optarg);
933 exit (7);
934 }
935 }
936 break;
937
Greg Claytonbd82a5d2011-01-23 05:56:20 +0000938 case 'W':
Greg Clayton6779606a2011-01-22 23:43:18 +0000939 if (optarg && optarg[0])
Greg Claytonbd82a5d2011-01-23 05:56:20 +0000940 working_dir.assign(optarg);
Greg Clayton6779606a2011-01-22 23:43:18 +0000941 break;
942
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000943 case 'x':
944 if (optarg && optarg[0])
945 {
946 if (strcasecmp(optarg, "auto") == 0)
947 g_launch_flavor = eLaunchFlavorDefault;
948 else if (strcasestr(optarg, "posix") == optarg)
949 g_launch_flavor = eLaunchFlavorPosixSpawn;
950 else if (strcasestr(optarg, "fork") == optarg)
951 g_launch_flavor = eLaunchFlavorForkExec;
Jason Molenda42999a42012-02-22 02:18:59 +0000952#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000953 else if (strcasestr(optarg, "spring") == optarg)
954 g_launch_flavor = eLaunchFlavorSpringBoard;
955#endif
956 else
957 {
958 RNBLogSTDERR ("error: invalid TYPE for the --launch=TYPE (-x TYPE) option: '%s'\n", optarg);
959 RNBLogSTDERR ("Valid values TYPE are:\n");
960 RNBLogSTDERR (" auto Auto-detect the best launch method to use.\n");
961 RNBLogSTDERR (" posix Launch the executable using posix_spawn.\n");
962 RNBLogSTDERR (" fork Launch the executable using fork and exec.\n");
Jason Molenda42999a42012-02-22 02:18:59 +0000963#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000964 RNBLogSTDERR (" spring Launch the executable through Springboard.\n");
965#endif
966 exit (5);
967 }
968 }
969 break;
970
971 case 'l': // Set Log File
972 if (optarg && optarg[0])
973 {
974 if (strcasecmp(optarg, "stdout") == 0)
975 log_file = stdout;
976 else if (strcasecmp(optarg, "stderr") == 0)
977 log_file = stderr;
978 else
Jim Inghamc530be62011-01-24 03:46:59 +0000979 {
Greg Claytonbd82a5d2011-01-23 05:56:20 +0000980 log_file = fopen(optarg, "w");
Jim Inghamc530be62011-01-24 03:46:59 +0000981 if (log_file != NULL)
982 setlinebuf(log_file);
983 }
984
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985 if (log_file == NULL)
986 {
987 const char *errno_str = strerror(errno);
988 RNBLogSTDERR ("Failed to open log file '%s' for writing: errno = %i (%s)", optarg, errno, errno_str ? errno_str : "unknown error");
989 }
990 }
991 break;
992
993 case 'f': // Log Flags
994 if (optarg && optarg[0])
995 log_flags = strtoul(optarg, NULL, 0);
996 break;
997
998 case 'g':
999 debug = 1;
Johnny Chen2fe7dd42011-08-10 23:01:39 +00001000 DNBLogSetDebug(debug);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001001 break;
1002
1003 case 't':
1004 g_applist_opt = 1;
1005 break;
1006
1007 case 'k':
1008 g_lockdown_opt = 1;
1009 break;
1010
1011 case 'r':
Greg Clayton85480022013-11-09 00:33:46 +00001012 // Do nothing, native regs is the default these days
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001013 break;
1014
Greg Clayton00fe87b2013-12-05 22:58:22 +00001015 case 'R':
1016 reverse_connect = true;
1017 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001018 case 'v':
1019 DNBLogSetVerbose(1);
1020 break;
1021
1022 case 's':
Greg Clayton71337622011-02-24 22:24:29 +00001023 ctx.GetSTDIN().assign(optarg);
1024 ctx.GetSTDOUT().assign(optarg);
1025 ctx.GetSTDERR().assign(optarg);
Greg Clayton6779606a2011-01-22 23:43:18 +00001026 break;
1027
1028 case 'I':
Greg Clayton71337622011-02-24 22:24:29 +00001029 ctx.GetSTDIN().assign(optarg);
Greg Clayton6779606a2011-01-22 23:43:18 +00001030 break;
1031
1032 case 'O':
Greg Clayton71337622011-02-24 22:24:29 +00001033 ctx.GetSTDOUT().assign(optarg);
Greg Clayton6779606a2011-01-22 23:43:18 +00001034 break;
1035
1036 case 'E':
Greg Clayton71337622011-02-24 22:24:29 +00001037 ctx.GetSTDERR().assign(optarg);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001038 break;
1039
Caroline Ticef8da8632010-12-03 18:46:09 +00001040 case 'n':
1041 no_stdio = true;
1042 break;
1043
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001044 case 'S':
1045 // Put debugserver into a new session. Terminals group processes
1046 // into sessions and when a special terminal key sequences
1047 // (like control+c) are typed they can cause signals to go out to
1048 // all processes in a session. Using this --setsid (-S) option
1049 // will cause debugserver to run in its own sessions and be free
1050 // from such issues.
1051 //
1052 // This is useful when debugserver is spawned from a command
1053 // line application that uses debugserver to do the debugging,
1054 // yet that application doesn't want debugserver receiving the
1055 // signals sent to the session (i.e. dying when anyone hits ^C).
1056 setsid();
1057 break;
Greg Claytonf681b942010-08-31 18:35:14 +00001058 case 'D':
1059 g_disable_aslr = 1;
1060 break;
Greg Clayton7a5388b2011-03-20 04:57:14 +00001061
1062 case 'p':
1063 start_mode = eRNBRunLoopModePlatformMode;
1064 break;
Greg Clayton8b82f082011-04-12 05:54:46 +00001065
Greg Clayton91a9b2472013-12-04 19:19:12 +00001066 case 'P':
1067 named_pipe_path.assign (optarg);
Greg Clayton8b82f082011-04-12 05:54:46 +00001068 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069 }
1070 }
Greg Clayton3af9ea52010-11-18 05:57:03 +00001071
1072 if (arch_name.empty())
1073 {
Greg Clayton71337622011-02-24 22:24:29 +00001074#if defined (__arm__)
Greg Clayton3af9ea52010-11-18 05:57:03 +00001075 arch_name.assign ("arm");
1076#endif
1077 }
Greg Clayton3c144382010-12-01 22:45:40 +00001078 else
1079 {
1080 DNBSetArchitecture (arch_name.c_str());
1081 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001082
Greg Clayton71337622011-02-24 22:24:29 +00001083// if (arch_name.empty())
1084// {
1085// fprintf(stderr, "error: no architecture was specified\n");
1086// exit (8);
1087// }
Greg Claytonb7ad58a2013-04-04 20:35:24 +00001088 // Skip any options we consumed with getopt_long_only
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001089 argc -= optind;
1090 argv += optind;
1091
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001093 if (!working_dir.empty())
Greg Clayton6779606a2011-01-22 23:43:18 +00001094 {
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001095 if (remote->Context().SetWorkingDirectory (working_dir.c_str()) == false)
Greg Clayton6779606a2011-01-22 23:43:18 +00001096 {
Greg Claytonbd82a5d2011-01-23 05:56:20 +00001097 RNBLogSTDERR ("error: working directory doesn't exist '%s'.\n", working_dir.c_str());
Greg Clayton6779606a2011-01-22 23:43:18 +00001098 exit (8);
1099 }
1100 }
1101
1102 remote->Initialize();
Greg Clayton3af9ea52010-11-18 05:57:03 +00001103
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 // It is ok for us to set NULL as the logfile (this will disable any logging)
1105
1106 if (log_file != NULL)
1107 {
1108 DNBLogSetLogCallback(FileLogCallback, log_file);
1109 // If our log file was set, yet we have no log flags, log everything!
1110 if (log_flags == 0)
1111 log_flags = LOG_ALL | LOG_RNB_ALL;
1112
1113 DNBLogSetLogMask (log_flags);
1114 }
1115 else
1116 {
1117 // Enable DNB logging
1118 DNBLogSetLogCallback(ASLLogCallback, NULL);
1119 DNBLogSetLogMask (log_flags);
1120
1121 }
1122
1123 if (DNBLogEnabled())
1124 {
1125 for (i=0; i<argc; i++)
1126 DNBLogDebug("argv[%i] = %s", i, argv[i]);
1127 }
1128
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001129 // as long as we're dropping remotenub in as a replacement for gdbserver,
1130 // explicitly note that this is not gdbserver.
1131
1132 RNBLogSTDOUT ("%s-%g %sfor %s.\n",
1133 DEBUGSERVER_PROGRAM_NAME,
1134 DEBUGSERVER_VERSION_NUM,
1135 compile_options.c_str(),
1136 RNB_ARCH);
1137
Greg Clayton00fe87b2013-12-05 22:58:22 +00001138 std::string host;
1139 int port = INT32_MAX;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140 char str[PATH_MAX];
Greg Clayton23f59502012-07-17 03:23:13 +00001141 str[0] = '\0';
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001142
1143 if (g_lockdown_opt == 0 && g_applist_opt == 0)
1144 {
1145 // Make sure we at least have port
1146 if (argc < 1)
1147 {
1148 show_usage_and_exit (1);
1149 }
1150 // accept 'localhost:' prefix on port number
1151
Greg Clayton00fe87b2013-12-05 22:58:22 +00001152 int items_scanned = ::sscanf (argv[0], "%[^:]:%i", str, &port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001153 if (items_scanned == 2)
1154 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001155 host = str;
1156 DNBLogDebug("host = '%s' port = %i", host.c_str(), port);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 }
1158 else
1159 {
Greg Claytonfd238892013-06-06 22:44:19 +00001160 // No hostname means "localhost"
Greg Clayton00fe87b2013-12-05 22:58:22 +00001161 int items_scanned = ::sscanf (argv[0], "%i", &port);
Greg Claytonfd238892013-06-06 22:44:19 +00001162 if (items_scanned == 1)
1163 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001164 host = "localhost";
1165 DNBLogDebug("host = '%s' port = %i", host.c_str(), port);
Greg Claytonfd238892013-06-06 22:44:19 +00001166 }
1167 else if (argv[0][0] == '/')
1168 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001169 port = INT32_MAX;
Greg Claytonfd238892013-06-06 22:44:19 +00001170 strncpy(str, argv[0], sizeof(str));
1171 }
1172 else
1173 {
1174 show_usage_and_exit (2);
1175 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176 }
1177
1178 // We just used the 'host:port' or the '/path/file' arg...
1179 argc--;
1180 argv++;
1181
1182 }
1183
1184 // If we know we're waiting to attach, we don't need any of this other info.
Greg Clayton7a5388b2011-03-20 04:57:14 +00001185 if (start_mode != eRNBRunLoopModeInferiorAttaching &&
1186 start_mode != eRNBRunLoopModePlatformMode)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001187 {
1188 if (argc == 0 || g_lockdown_opt)
1189 {
1190 if (g_lockdown_opt != 0)
1191 {
1192 // Work around for SIGPIPE crashes due to posix_spawn issue.
1193 // We have to close STDOUT and STDERR, else the first time we
1194 // try and do any, we get SIGPIPE and die as posix_spawn is
1195 // doing bad things with our file descriptors at the moment.
1196 int null = open("/dev/null", O_RDWR);
1197 dup2(null, STDOUT_FILENO);
1198 dup2(null, STDERR_FILENO);
1199 }
1200 else if (g_applist_opt != 0)
1201 {
1202 // List all applications we are able to see
1203 std::string applist_plist;
1204 int err = ListApplications(applist_plist, false, false);
1205 if (err == 0)
1206 {
1207 fputs (applist_plist.c_str(), stdout);
1208 }
1209 else
1210 {
1211 RNBLogSTDERR ("error: ListApplications returned error %i\n", err);
1212 }
1213 // Exit with appropriate error if we were asked to list the applications
1214 // with no other args were given (and we weren't trying to do this over
1215 // lockdown)
1216 return err;
1217 }
1218
1219 DNBLogDebug("Get args from remote protocol...");
1220 start_mode = eRNBRunLoopModeGetStartModeFromRemoteProtocol;
1221 }
1222 else
1223 {
1224 start_mode = eRNBRunLoopModeInferiorLaunching;
1225 // Fill in the argv array in the context from the rest of our args.
1226 // Skip the name of this executable and the port number
1227 for (int i = 0; i < argc; i++)
1228 {
1229 DNBLogDebug("inferior_argv[%i] = '%s'", i, argv[i]);
1230 ctx.PushArgument (argv[i]);
1231 }
1232 }
1233 }
1234
1235 if (start_mode == eRNBRunLoopModeExit)
1236 return -1;
1237
1238 RNBRunLoopMode mode = start_mode;
1239 char err_str[1024] = {'\0'};
1240
1241 while (mode != eRNBRunLoopModeExit)
1242 {
1243 switch (mode)
1244 {
1245 case eRNBRunLoopModeGetStartModeFromRemoteProtocol:
Jason Molenda42999a42012-02-22 02:18:59 +00001246#ifdef WITH_LOCKDOWN
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001247 if (g_lockdown_opt)
1248 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001249 if (!remote->Comm().IsConnected())
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001250 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001251 if (remote->Comm().ConnectToService () != rnb_success)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001252 {
1253 RNBLogSTDERR ("Failed to get connection from a remote gdb process.\n");
1254 mode = eRNBRunLoopModeExit;
1255 }
1256 else if (g_applist_opt != 0)
1257 {
1258 // List all applications we are able to see
1259 std::string applist_plist;
1260 if (ListApplications(applist_plist, false, false) == 0)
1261 {
1262 DNBLogDebug("Task list: %s", applist_plist.c_str());
1263
Greg Clayton6779606a2011-01-22 23:43:18 +00001264 remote->Comm().Write(applist_plist.c_str(), applist_plist.size());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001265 // Issue a read that will never yield any data until the other side
1266 // closes the socket so this process doesn't just exit and cause the
1267 // socket to close prematurely on the other end and cause data loss.
1268 std::string buf;
Greg Clayton6779606a2011-01-22 23:43:18 +00001269 remote->Comm().Read(buf);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001270 }
Greg Clayton6779606a2011-01-22 23:43:18 +00001271 remote->Comm().Disconnect(false);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001272 mode = eRNBRunLoopModeExit;
1273 break;
1274 }
1275 else
1276 {
1277 // Start watching for remote packets
Greg Clayton6779606a2011-01-22 23:43:18 +00001278 remote->StartReadRemoteDataThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279 }
1280 }
1281 }
1282 else
1283#endif
Greg Clayton00fe87b2013-12-05 22:58:22 +00001284 if (port != INT32_MAX)
Greg Clayton7a5388b2011-03-20 04:57:14 +00001285 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001286 if (!ConnectRemote (remote, host.c_str(), port, reverse_connect, named_pipe_path.c_str()))
Greg Clayton7a5388b2011-03-20 04:57:14 +00001287 mode = eRNBRunLoopModeExit;
1288 }
1289 else if (str[0] == '/')
1290 {
1291 if (remote->Comm().OpenFile (str))
1292 mode = eRNBRunLoopModeExit;
1293 }
1294
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001295 if (mode != eRNBRunLoopModeExit)
1296 {
1297 RNBLogSTDOUT ("Got a connection, waiting for process information for launching or attaching.\n");
1298
Greg Clayton6779606a2011-01-22 23:43:18 +00001299 mode = RNBRunLoopGetStartModeFromRemote (remote);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001300 }
1301 break;
1302
1303 case eRNBRunLoopModeInferiorAttaching:
1304 if (!waitfor_pid_name.empty())
1305 {
1306 // Set our end wait time if we are using a waitfor-duration
1307 // option that may have been specified
1308 struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1309 if (waitfor_duration != 0)
1310 {
1311 DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration, 0);
1312 timeout_ptr = &attach_timeout_abstime;
1313 }
1314 nub_launch_flavor_t launch_flavor = g_launch_flavor;
1315 if (launch_flavor == eLaunchFlavorDefault)
1316 {
1317 // Our default launch method is posix spawn
1318 launch_flavor = eLaunchFlavorPosixSpawn;
1319
Jason Molenda42999a42012-02-22 02:18:59 +00001320#ifdef WITH_SPRINGBOARD
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001321 // Check if we have an app bundle, if so launch using SpringBoard.
1322 if (waitfor_pid_name.find (".app") != std::string::npos)
1323 {
1324 launch_flavor = eLaunchFlavorSpringBoard;
1325 }
1326#endif
1327 }
1328
1329 ctx.SetLaunchFlavor(launch_flavor);
Jim Inghamcd16df92012-07-20 21:37:13 +00001330 bool ignore_existing = false;
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001331 RNBLogSTDOUT ("Waiting to attach to process %s...\n", waitfor_pid_name.c_str());
Jim Inghamcd16df92012-07-20 21:37:13 +00001332 nub_process_t pid = DNBProcessAttachWait (waitfor_pid_name.c_str(), launch_flavor, ignore_existing, timeout_ptr, waitfor_interval, err_str, sizeof(err_str));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333 g_pid = pid;
1334
1335 if (pid == INVALID_NUB_PROCESS)
1336 {
1337 ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1338 if (err_str[0])
1339 ctx.LaunchStatus().SetErrorString(err_str);
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001340 RNBLogSTDERR ("error: failed to attach to process named: \"%s\" %s\n", waitfor_pid_name.c_str(), err_str);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001341 mode = eRNBRunLoopModeExit;
1342 }
1343 else
1344 {
1345 ctx.SetProcessID(pid);
1346 mode = eRNBRunLoopModeInferiorExecuting;
1347 }
1348 }
1349 else if (attach_pid != INVALID_NUB_PROCESS)
1350 {
1351
1352 RNBLogSTDOUT ("Attaching to process %i...\n", attach_pid);
1353 nub_process_t attached_pid;
Greg Clayton6779606a2011-01-22 23:43:18 +00001354 mode = RNBRunLoopLaunchAttaching (remote, attach_pid, attached_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001355 if (mode != eRNBRunLoopModeInferiorExecuting)
1356 {
1357 const char *error_str = remote->Context().LaunchStatus().AsString();
1358 RNBLogSTDERR ("error: failed to attach process %i: %s\n", attach_pid, error_str ? error_str : "unknown error.");
1359 mode = eRNBRunLoopModeExit;
1360 }
1361 }
1362 else if (!attach_pid_name.empty ())
1363 {
1364 struct timespec attach_timeout_abstime, *timeout_ptr = NULL;
1365 if (waitfor_duration != 0)
1366 {
1367 DNBTimer::OffsetTimeOfDay(&attach_timeout_abstime, waitfor_duration, 0);
1368 timeout_ptr = &attach_timeout_abstime;
1369 }
1370
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001371 RNBLogSTDOUT ("Attaching to process %s...\n", attach_pid_name.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001372 nub_process_t pid = DNBProcessAttachByName (attach_pid_name.c_str(), timeout_ptr, err_str, sizeof(err_str));
1373 g_pid = pid;
1374 if (pid == INVALID_NUB_PROCESS)
1375 {
1376 ctx.LaunchStatus().SetError(-1, DNBError::Generic);
1377 if (err_str[0])
1378 ctx.LaunchStatus().SetErrorString(err_str);
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001379 RNBLogSTDERR ("error: failed to attach to process named: \"%s\" %s\n", waitfor_pid_name.c_str(), err_str);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001380 mode = eRNBRunLoopModeExit;
1381 }
1382 else
1383 {
1384 ctx.SetProcessID(pid);
1385 mode = eRNBRunLoopModeInferiorExecuting;
1386 }
1387
1388 }
1389 else
1390 {
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001391 RNBLogSTDERR ("error: asked to attach with empty name and invalid PID.\n");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001392 mode = eRNBRunLoopModeExit;
1393 }
1394
1395 if (mode != eRNBRunLoopModeExit)
1396 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001397 if (port != INT32_MAX)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001398 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001399 if (!ConnectRemote (remote, host.c_str(), port, reverse_connect, named_pipe_path.c_str()))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001400 mode = eRNBRunLoopModeExit;
1401 }
1402 else if (str[0] == '/')
1403 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001404 if (remote->Comm().OpenFile (str))
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405 mode = eRNBRunLoopModeExit;
1406 }
1407 if (mode != eRNBRunLoopModeExit)
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001408 RNBLogSTDOUT ("Waiting for debugger instructions for process %d.\n", attach_pid);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001409 }
1410 break;
1411
1412 case eRNBRunLoopModeInferiorLaunching:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001413 {
Greg Clayton6779606a2011-01-22 23:43:18 +00001414 mode = RNBRunLoopLaunchInferior (remote,
Greg Clayton71337622011-02-24 22:24:29 +00001415 ctx.GetSTDINPath(),
1416 ctx.GetSTDOUTPath(),
1417 ctx.GetSTDERRPath(),
Greg Clayton6779606a2011-01-22 23:43:18 +00001418 no_stdio);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001419
Greg Clayton6779606a2011-01-22 23:43:18 +00001420 if (mode == eRNBRunLoopModeInferiorExecuting)
1421 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001422 if (port != INT32_MAX)
Greg Clayton6779606a2011-01-22 23:43:18 +00001423 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001424 if (!ConnectRemote (remote, host.c_str(), port, reverse_connect, named_pipe_path.c_str()))
Greg Clayton6779606a2011-01-22 23:43:18 +00001425 mode = eRNBRunLoopModeExit;
1426 }
1427 else if (str[0] == '/')
1428 {
1429 if (remote->Comm().OpenFile (str))
1430 mode = eRNBRunLoopModeExit;
1431 }
1432
1433 if (mode != eRNBRunLoopModeExit)
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001434 RNBLogSTDOUT ("Got a connection, launched process %s.\n", argv_sub_zero);
Greg Clayton6779606a2011-01-22 23:43:18 +00001435 }
1436 else
1437 {
1438 const char *error_str = remote->Context().LaunchStatus().AsString();
Jason Molenda0b2dbe02012-11-01 02:02:59 +00001439 RNBLogSTDERR ("error: failed to launch process %s: %s\n", argv_sub_zero, error_str ? error_str : "unknown error.");
Greg Clayton6779606a2011-01-22 23:43:18 +00001440 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001441 }
1442 break;
1443
1444 case eRNBRunLoopModeInferiorExecuting:
Greg Clayton6779606a2011-01-22 23:43:18 +00001445 mode = RNBRunLoopInferiorExecuting(remote);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001446 break;
1447
Greg Clayton7a5388b2011-03-20 04:57:14 +00001448 case eRNBRunLoopModePlatformMode:
Greg Clayton00fe87b2013-12-05 22:58:22 +00001449 if (port != INT32_MAX)
Greg Clayton7a5388b2011-03-20 04:57:14 +00001450 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001451 if (!ConnectRemote (remote, host.c_str(), port, reverse_connect, named_pipe_path.c_str()))
Greg Clayton7a5388b2011-03-20 04:57:14 +00001452 mode = eRNBRunLoopModeExit;
1453 }
1454 else if (str[0] == '/')
1455 {
1456 if (remote->Comm().OpenFile (str))
1457 mode = eRNBRunLoopModeExit;
1458 }
1459
1460 if (mode != eRNBRunLoopModeExit)
1461 mode = RNBRunLoopPlatform (remote);
1462 break;
1463
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001464 default:
1465 mode = eRNBRunLoopModeExit;
1466 case eRNBRunLoopModeExit:
1467 break;
1468 }
1469 }
1470
Greg Clayton6779606a2011-01-22 23:43:18 +00001471 remote->StopReadRemoteDataThread ();
1472 remote->Context().SetProcessID(INVALID_NUB_PROCESS);
Jim Inghame2ff0ba2013-02-25 19:31:37 +00001473 RNBLogSTDOUT ("Exiting.\n");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001474
1475 return 0;
1476}