blob: a88ec7b09d4c695b8f27c8eb06bb6860e438007d [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- GDBServer.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
21#include "GDBServerLog.h"
22#include "GDBRemoteSession.h"
23
24using namespace lldb;
25
26//----------------------------------------------------------------------
27// Run loop modes which determine which run loop function will be called
28//----------------------------------------------------------------------
29typedef enum
30{
31 eDCGSRunLoopModeInvalid = 0,
32 eDCGSRunLoopModeGetStartModeFromRemoteProtocol,
33 eDCGSRunLoopModeInferiorAttaching,
34 eDCGSRunLoopModeInferiorLaunching,
35 eDCGSRunLoopModeInferiorExecuting,
36 eDCGSRunLoopModeInferiorKillOrDetach,
37 eDCGSRunLoopModeExit
38} GSRunLoopMode;
39
40typedef enum
41{
42 eLaunchFlavorDefault = 0,
43 eLaunchFlavorPosixSpawn,
44#if defined (__arm__)
45 eLaunchFlavorSpringBoard,
46#endif
47 eLaunchFlavorForkExec,
48} GSLaunchFlavor;
49
50typedef lldb::shared_ptr<GDBRemoteSession> GDBRemoteSP;
51
52typedef struct HandleBroadcastEventInfo
53{
54 TargetSP target_sp;
55 GDBRemoteSP remote_sp;
56 GSRunLoopMode mode;
57
58 Target *
59 GetTarget ()
60 {
61 return target_sp.get();
62 }
63
64 Process *
65 GetProcess()
66 {
67 if (target_sp.get())
68 return target_sp->GetProcess().get();
69 return NULL;
70 }
71
72 GDBRemoteSession *
73 GetRemote ()
74 {
75 return remote_sp.get();
76 }
77
78};
79
80
81//----------------------------------------------------------------------
82// Global Variables
83//----------------------------------------------------------------------
84static int g_lockdown_opt = 0;
85static int g_applist_opt = 0;
86static GSLaunchFlavor g_launch_flavor = eLaunchFlavorDefault;
87int g_isatty = 0;
88
89//----------------------------------------------------------------------
90// Run Loop function prototypes
91//----------------------------------------------------------------------
92void GSRunLoopGetStartModeFromRemote (HandleBroadcastEventInfo *info);
93void GSRunLoopInferiorExecuting (HandleBroadcastEventInfo *info);
94
95
96//----------------------------------------------------------------------
97// Get our program path and arguments from the remote connection.
98// We will need to start up the remote connection without a PID, get the
99// arguments, wait for the new process to finish launching and hit its
100// entry point, and then return the run loop mode that should come next.
101//----------------------------------------------------------------------
102void
103GSRunLoopGetStartModeFromRemote (HandleBroadcastEventInfo *info)
104{
105 std::string packet;
106
107 Target *target = info->GetTarget();
108 GDBRemoteSession *remote = info->GetRemote();
109 if (target != NULL && remote != NULL)
110 {
111 // Spin waiting to get the A packet.
112 while (1)
113 {
114 gdb_err_t err = gdb_err;
115 GDBRemoteSession::PacketEnum type;
116
117 err = remote->HandleReceivedPacket (&type);
118
119 // check if we tried to attach to a process
120 if (type == GDBRemoteSession::vattach || type == GDBRemoteSession::vattachwait)
121 {
122 if (err == gdb_success)
123 {
124 info->mode = eDCGSRunLoopModeInferiorExecuting;
125 return;
126 }
127 else
128 {
129 Log::STDERR ("error: attach failed.");
130 info->mode = eDCGSRunLoopModeExit;
131 return;
132 }
133 }
134
135 if (err == gdb_success)
136 {
137 // If we got our arguments we are ready to launch using the arguments
138 // and any environment variables we received.
139 if (type == GDBRemoteSession::set_argv)
140 {
141 info->mode = eDCGSRunLoopModeInferiorLaunching;
142 return;
143 }
144 }
145 else if (err == gdb_not_connected)
146 {
147 Log::STDERR ("error: connection lost.");
148 info->mode = eDCGSRunLoopModeExit;
149 return;
150 }
151 else
152 {
153 // a catch all for any other gdb remote packets that failed
154 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Error getting packet.",__FUNCTION__);
155 continue;
156 }
157
158 GDBServerLog::LogIf (GS_LOG_MINIMAL, "#### %s", __FUNCTION__);
159 }
160 }
161 info->mode = eDCGSRunLoopModeExit;
162}
163
164
165//----------------------------------------------------------------------
166// This run loop mode will wait for the process to launch and hit its
167// entry point. It will currently ignore all events except for the
168// process state changed event, where it watches for the process stopped
169// or crash process state.
170//----------------------------------------------------------------------
171GSRunLoopMode
172GSRunLoopLaunchInferior (HandleBroadcastEventInfo *info)
173{
174 // The Process stuff takes a c array, the GSContext has a vector...
175 // So make up a c array.
176 Target *target = info->GetTarget();
177 GDBRemoteSession *remote = info->GetRemote();
178 Process* process = info->GetProcess();
179
180 if (process == NULL)
181 return eDCGSRunLoopModeExit;
182
183 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Launching '%s'...", __FUNCTION__, target->GetExecutableModule()->GetFileSpec().GetFilename().AsCString());
184
185 // Our launch type hasn't been set to anything concrete, so we need to
186 // figure our how we are going to launch automatically.
187
188 GSLaunchFlavor launch_flavor = g_launch_flavor;
189 if (launch_flavor == eLaunchFlavorDefault)
190 {
191 // Our default launch method is posix spawn
192 launch_flavor = eLaunchFlavorPosixSpawn;
193
194#if defined (__arm__)
195 // Check if we have an app bundle, if so launch using SpringBoard.
196 if (strstr(inferior_argv[0], ".app"))
197 {
198 launch_flavor = eLaunchFlavorSpringBoard;
199 }
200#endif
201 }
202
203 //ctx.SetLaunchFlavor(launch_flavor);
204
205 const char *stdio_file = NULL;
206 lldb::pid_t pid = process->Launch (remote->GetARGV(), remote->GetENVP(), stdio_file, stdio_file, stdio_file);
207
208 if (pid == LLDB_INVALID_PROCESS_ID)
209 {
210 Log::STDERR ("error: process launch failed: %s", process->GetError().AsCString());
211 }
212 else
213 {
214 if (remote->IsConnected())
215 {
216 // It we are connected already, the next thing gdb will do is ask
217 // whether the launch succeeded, and if not, whether there is an
218 // error code. So we need to fetch one packet from gdb before we wait
219 // on the stop from the target.
220 gdb_err_t err = gdb_err;
221 GDBRemoteSession::PacketEnum type;
222
223 err = remote->HandleReceivedPacket (&type);
224
225 if (err != gdb_success)
226 {
227 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Error getting packet.", __FUNCTION__);
228 return eDCGSRunLoopModeExit;
229 }
230 if (type != GDBRemoteSession::query_launch_success)
231 {
232 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Didn't get the expected qLaunchSuccess packet.", __FUNCTION__);
233 }
234 }
235 }
236
237 Listener listener("GSRunLoopLaunchInferior");
238 listener.StartListeningForEvents (process, Process::eBroadcastBitStateChanged);
239 while (process->GetID() != LLDB_INVALID_PROCESS_ID)
240 {
241 uint32_t event_mask = 0;
242 while (listener.WaitForEvent(NULL, &event_mask))
243 {
244 if (event_mask & Process::eBroadcastBitStateChanged)
245 {
246 Event event;
247 StateType event_state;
248 while ((event_state = process->GetNextEvent (&event)))
249 if (StateIsStoppedState(event_state))
250 {
251 GDBServerLog::LogIf (GS_LOG_EVENTS, "%s process %4.4x stopped with state %s", __FUNCTION__, pid, StateAsCString(event_state));
252
253 switch (event_state)
254 {
255 default:
256 case eStateInvalid:
257 case eStateUnloaded:
258 case eStateAttaching:
259 case eStateLaunching:
260 case eStateSuspended:
261 break; // Ignore
262
263 case eStateRunning:
264 case eStateStepping:
265 // Still waiting to stop at entry point...
266 break;
267
268 case eStateStopped:
269 case eStateCrashed:
270 return eDCGSRunLoopModeInferiorExecuting;
271
272 case eStateDetached:
273 case eStateExited:
274 pid = LLDB_INVALID_PROCESS_ID;
275 return eDCGSRunLoopModeExit;
276 }
277 }
278
279 if (event_state = eStateInvalid)
280 break;
281 }
282 }
283 }
284
285 return eDCGSRunLoopModeExit;
286}
287
288
289//----------------------------------------------------------------------
290// This run loop mode will wait for the process to launch and hit its
291// entry point. It will currently ignore all events except for the
292// process state changed event, where it watches for the process stopped
293// or crash process state.
294//----------------------------------------------------------------------
295GSRunLoopMode
296GSRunLoopLaunchAttaching (HandleBroadcastEventInfo *info, lldb::pid_t& pid)
297{
298 Process* process = info->GetProcess();
299
300 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s Attaching to pid %i...", __FUNCTION__, pid);
301 pid = process->Attach(pid);
302
303 if (pid == LLDB_INVALID_PROCESS_ID)
304 return eDCGSRunLoopModeExit;
305 return eDCGSRunLoopModeInferiorExecuting;
306}
307
308//----------------------------------------------------------------------
309// Watch for signals:
310// SIGINT: so we can halt our inferior. (disabled for now)
311// SIGPIPE: in case our child process dies
312//----------------------------------------------------------------------
313lldb::pid_t g_pid;
314int g_sigpipe_received = 0;
315void
316signal_handler(int signo)
317{
318 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (%s)", __FUNCTION__, Host::GetSignalAsCString(signo));
319
320 switch (signo)
321 {
322// case SIGINT:
323// DNBProcessKill (g_pid, signo);
324// break;
325
326 case SIGPIPE:
327 g_sigpipe_received = 1;
328 break;
329 }
330}
331
332// Return the new run loop mode based off of the current process state
333void
334HandleProcessStateChange (HandleBroadcastEventInfo *info, bool initialize)
335{
336 Process *process = info->GetProcess();
337 if (process == NULL)
338 {
339 info->mode = eDCGSRunLoopModeExit;
340 return;
341 }
342
343 if (process->GetID() == LLDB_INVALID_PROCESS_ID)
344 {
345 GDBServerLog::LogIf (GS_LOG_MINIMAL, "#### %s error: pid invalid, exiting...", __FUNCTION__);
346 info->mode = eDCGSRunLoopModeExit;
347 return;
348 }
349 StateType pid_state = process->GetState ();
350
351 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (info, initialize=%i) pid_state = %s", __FUNCTION__, (int)initialize, StateAsCString(pid_state));
352
353 switch (pid_state)
354 {
355 case eStateInvalid:
356 case eStateUnloaded:
357 // Something bad happened
358 info->mode = eDCGSRunLoopModeExit;
359 return;
360
361 case eStateAttaching:
362 case eStateLaunching:
363 info->mode = eDCGSRunLoopModeInferiorExecuting;
364 return;
365
366 case eStateSuspended:
367 case eStateCrashed:
368 case eStateStopped:
369 if (initialize == false)
370 {
371 // Compare the last stop count to our current notion of a stop count
372 // to make sure we don't notify more than once for a given stop.
373 static uint32_t g_prev_stop_id = 0;
374 uint32_t stop_id = process->GetStopID();
375 bool pid_stop_count_changed = g_prev_stop_id != stop_id;
376 if (pid_stop_count_changed)
377 {
378 info->GetRemote()->FlushSTDIO();
379
380 if (stop_id == 1)
381 {
382 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s pid_stop_count %u (old %u)) Notify??? no, first stop...", __FUNCTION__, (int)initialize, StateAsCString (pid_state), stop_id, g_prev_stop_id);
383 }
384 else
385 {
386
387 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s pid_stop_count %u (old %u)) Notify??? YES!!!", __FUNCTION__, (int)initialize, StateAsCString (pid_state), stop_id, g_prev_stop_id);
388 info->GetRemote()->NotifyThatProcessStopped ();
389 }
390 }
391 else
392 {
393 GDBServerLog::LogIf (GS_LOG_MINIMAL, "%s (&remote, initialize=%i) pid_state = %s pid_stop_count %u (old %u)) Notify??? skipping...", __FUNCTION__, (int)initialize, StateAsCString (pid_state), stop_id, g_prev_stop_id);
394 }
395 }
396 info->mode = eDCGSRunLoopModeInferiorExecuting;
397 return;
398
399 case eStateStepping:
400 case eStateRunning:
401 info->mode = eDCGSRunLoopModeInferiorExecuting;
402 return;
403
404 case eStateExited:
405 info->GetRemote()->HandlePacket_last_signal (NULL);
406 info->mode = eDCGSRunLoopModeExit;
407 return;
408
409 }
410
411 // Catch all...
412 info->mode = eDCGSRunLoopModeExit;
413}
414
415bool
416CommunicationHandleBroadcastEvent (Broadcaster *broadcaster, uint32_t event_mask, void *baton)
417{
418 HandleBroadcastEventInfo *info = (HandleBroadcastEventInfo *)baton;
419 Process *process = info->GetProcess();
420
421 if (process == NULL)
422 {
423 info->mode = eDCGSRunLoopModeExit;
424 return true;
425 }
426
427 if (event_mask & Communication::eBroadcastBitPacketAvailable)
428 {
429 if (process->IsRunning())
430 {
431 if (info->GetRemote()->HandleAsyncPacket() == gdb_not_connected)
432 info->mode = eDCGSRunLoopModeExit;
433 }
434 else
435 {
436 if (info->GetRemote()->HandleReceivedPacket() == gdb_not_connected)
437 info->mode = eDCGSRunLoopModeExit;
438 }
439 }
440 if (event_mask & Communication::eBroadcastBitReadThreadDidExit)
441 {
442 info->mode = eDCGSRunLoopModeExit;
443 }
444 if (event_mask & Communication::eBroadcastBitDisconnected)
445 {
446 info->mode = eDCGSRunLoopModeExit;
447 }
448
449 return true;
450
451}
452
453bool
454ProcessHandleBroadcastEvent (Broadcaster *broadcaster, uint32_t event_mask, void *baton)
455{
456 HandleBroadcastEventInfo *info = (HandleBroadcastEventInfo *)baton;
457 Process *process = info->GetProcess();
458 if (process == NULL)
459 {
460 info->mode = eDCGSRunLoopModeExit;
461 return true;
462 }
463
464 if (event_mask & Process::eBroadcastBitStateChanged)
465 {
466 // Consume all available process events with no timeout
467 Event event;
468 StateType process_state;
469 while ((process_state = process->GetNextEvent (&event)) != eStateInvalid)
470 {
471 if (StateIsStoppedState(process_state))
472 info->GetRemote()->FlushSTDIO();
473 HandleProcessStateChange (info, false);
474
475 if (info->mode != eDCGSRunLoopModeInferiorExecuting)
476 break;
477 }
478 }
479 else
480 if (event_mask & (Process::eBroadcastBitSTDOUT | Process::eBroadcastBitSTDERR))
481 {
482 info->GetRemote()->FlushSTDIO();
483 }
484 return true;
485}
486
487// This function handles the case where our inferior program is stopped and
488// we are waiting for gdb remote protocol packets. When a packet occurs that
489// makes the inferior run, we need to leave this function with a new state
490// as the return code.
491void
492GSRunLoopInferiorExecuting (HandleBroadcastEventInfo *info)
493{
494 GDBServerLog::LogIf (GS_LOG_MINIMAL, "#### %s", __FUNCTION__);
495
496 // Init our mode and set 'is_running' based on the current process state
497 HandleProcessStateChange (info, true);
498
499 uint32_t desired_mask, acquired_mask;
500 Listener listener("GSRunLoopInferiorExecuting");
501
502 desired_mask = Communication::eBroadcastBitPacketAvailable |
503 Communication::eBroadcastBitReadThreadDidExit |
504 Communication::eBroadcastBitDisconnected;
505
506 acquired_mask = listener.StartListeningForEvents (&(info->GetRemote()->GetPacketComm()),
507 desired_mask,
508 CommunicationHandleBroadcastEvent,
509 info);
510
511 assert (acquired_mask == desired_mask);
512 desired_mask = GDBRemotePacket::eBroadcastBitPacketAvailable;
513
514 acquired_mask = listener.StartListeningForEvents (&(info->GetRemote()->GetPacketComm()),
515 desired_mask,
516 CommunicationHandleBroadcastEvent,
517 info);
518
519 assert (acquired_mask == desired_mask);
520
521 desired_mask = Process::eBroadcastBitStateChanged |
522 Process::eBroadcastBitSTDOUT |
523 Process::eBroadcastBitSTDERR ;
524 acquired_mask = listener.StartListeningForEvents (info->GetProcess (),
525 desired_mask,
526 ProcessHandleBroadcastEvent,
527 info);
528
529 assert (acquired_mask == desired_mask);
530
531 Process *process = info->GetProcess();
532
533 while (process->IsAlive())
534 {
535 if (!info->GetRemote()->IsConnected())
536 {
537 info->mode = eDCGSRunLoopModeInferiorKillOrDetach;
538 break;
539 }
540
541 // We want to make sure we consume all process state changes and have
542 // whomever is notifying us to wait for us to reset the event bit before
543 // continuing.
544 //ctx.Events().SetResetAckMask (GSContext::event_proc_state_changed);
545 uint32_t event_mask = 0;
546 Broadcaster *broadcaster = listener.WaitForEvent(NULL, &event_mask);
547 if (broadcaster)
548 {
549 listener.HandleBroadcastEvent(broadcaster, event_mask);
550 }
551 }
552}
553
554
555//----------------------------------------------------------------------
556// Convenience function to set up the remote listening port
557// Returns 1 for success 0 for failure.
558//----------------------------------------------------------------------
559
560static bool
561StartListening (HandleBroadcastEventInfo *info, int listen_port)
562{
563 if (!info->GetRemote()->IsConnected())
564 {
565 Log::STDOUT ("Listening to port %i...\n", listen_port);
566 char connect_url[256];
567 snprintf(connect_url, sizeof(connect_url), "listen://%i", listen_port);
568
569 Communication &comm = info->remote_sp->GetPacketComm();
570 comm.SetConnection (new ConnectionFileDescriptor);
571
572 if (comm.Connect (connect_url))
573 {
574 if (comm.StartReadThread())
575 return true;
576
577 Log::STDERR ("Failed to start the communication read thread.\n", connect_url);
578 comm.Disconnect();
579 }
580 else
581 {
582 Log::STDERR ("Failed to connection to %s.\n", connect_url);
583 }
584 return false;
585 }
586 return true;
587}
588
589//----------------------------------------------------------------------
590// ASL Logging callback that can be registered with DNBLogSetLogDCScriptInterpreter::Type
591//----------------------------------------------------------------------
592//void
593//ASLLogDCScriptInterpreter::Type(void *baton, uint32_t flags, const char *format, va_list args)
594//{
595// if (format == NULL)
596// return;
597// static aslmsg g_aslmsg = NULL;
598// if (g_aslmsg == NULL)
599// {
600// g_aslmsg = ::asl_new (ASL_TYPE_MSG);
601// char asl_key_sender[PATH_MAX];
602// snprintf(asl_key_sender, sizeof(asl_key_sender), "com.apple.dc-gdbserver-%g", dc_gdbserverVersionNumber);
603// ::asl_set (g_aslmsg, ASL_KEY_SENDER, asl_key_sender);
604// }
605//
606// int asl_level;
607// if (flags & DNBLOG_FLAG_FATAL) asl_level = ASL_LEVEL_CRIT;
608// else if (flags & DNBLOG_FLAG_ERROR) asl_level = ASL_LEVEL_ERR;
609// else if (flags & DNBLOG_FLAG_WARNING) asl_level = ASL_LEVEL_WARNING;
610// else if (flags & DNBLOG_FLAG_VERBOSE) asl_level = ASL_LEVEL_WARNING; //ASL_LEVEL_INFO;
611// else asl_level = ASL_LEVEL_WARNING; //ASL_LEVEL_DEBUG;
612//
613// ::asl_vlog (NULL, g_aslmsg, asl_level, format, args);
614//}
615
616//----------------------------------------------------------------------
617// FILE based Logging callback that can be registered with
618// DNBLogSetLogDCScriptInterpreter::Type
619//----------------------------------------------------------------------
620void
621FileLogDCScriptInterpreter::Type(void *baton, uint32_t flags, const char *format, va_list args)
622{
623 if (baton == NULL || format == NULL)
624 return;
625
626 ::vfprintf ((FILE *)baton, format, args);
627 ::fprintf ((FILE *)baton, "\n");
628}
629
630//----------------------------------------------------------------------
631// option descriptors for getopt_long()
632//----------------------------------------------------------------------
633static struct option g_long_options[] =
634{
635 { "arch", required_argument, NULL, 'c' },
636 { "attach", required_argument, NULL, 'a' },
637 { "debug", no_argument, NULL, 'g' },
638 { "verbose", no_argument, NULL, 'v' },
639 { "lockdown", no_argument, &g_lockdown_opt, 1 }, // short option "-k"
640 { "applist", no_argument, &g_applist_opt, 1 }, // short option "-t"
641 { "log-file", required_argument, NULL, 'l' },
642 { "log-flags", required_argument, NULL, 'f' },
643 { "launch", required_argument, NULL, 'x' }, // Valid values are "auto", "posix-spawn", "fork-exec", "springboard" (arm only)
644 { "waitfor", required_argument, NULL, 'w' }, // Wait for a process whose namet starts with ARG
645 { "waitfor-interval", required_argument, NULL, 'i' }, // Time in usecs to wait between sampling the pid list when waiting for a process by name
646 { "waitfor-duration", required_argument, NULL, 'd' }, // The time in seconds to wait for a process to show up by name
647 { NULL, 0, NULL, 0 }
648};
649
650extern const double dc_gdbserverVersionNumber;
651int
652main (int argc, char *argv[])
653{
654 Initialize();
655 Host::ThreadCreated ("[main]");
656
657 g_isatty = ::isatty (STDIN_FILENO);
658
659// signal (SIGINT, signal_handler);
660 signal (SIGPIPE, signal_handler);
661
662 Log *log = GDBServerLog::GetLogIfAllCategoriesSet(GS_LOG_ALL);
663 const char *this_exe_name = argv[0];
664 int i;
665 int attach_pid = LLDB_INVALID_PROCESS_ID;
666 for (i=0; i<argc; i++)
667 GDBServerLog::LogIf(GS_LOG_DEBUG, "argv[%i] = %s", i, argv[i]);
668
669 FILE* log_file = NULL;
670 uint32_t log_flags = 0;
671 // Parse our options
672 int ch;
673 int long_option_index = 0;
674 int debug = 0;
675 std::string waitfor_pid_name; // Wait for a process that starts with this name
676 std::string attach_pid_name;
677 useconds_t waitfor_interval = 1000; // Time in usecs between process lists polls when waiting for a process by name, default 1 msec.
678 useconds_t waitfor_duration = 0; // Time in seconds to wait for a process by name, 0 means wait forever.
679 ArchSpec arch;
680 GSRunLoopMode start_mode = eDCGSRunLoopModeExit;
681
682 while ((ch = getopt_long(argc, argv, "a:c:d:gi:vktl:f:w:x:", g_long_options, &long_option_index)) != -1)
683 {
684// DNBLogDebug("option: ch == %c (0x%2.2x) --%s%c%s\n",
685// ch, (uint8_t)ch,
686// g_long_options[long_option_index].name,
687// g_long_options[long_option_index].has_arg ? '=' : ' ',
688// optarg ? optarg : "");
689 switch (ch)
690 {
691 case 0: // Any optional that auto set themselves will return 0
692 break;
693
694 case 'c':
695 arch.SetArch(optarg);
696 if (!arch.IsValid())
697 {
698 Log::STDERR ("error: invalid arch string '%s'\n", optarg);
699 exit (8);
700 }
701 break;
702
703 case 'a':
704 if (optarg && optarg[0])
705 {
706 if (isdigit(optarg[0]))
707 {
708 char *end = NULL;
709 attach_pid = strtoul(optarg, &end, 0);
710 if (end == NULL || *end != '\0')
711 {
712 Log::STDERR ("error: invalid pid option '%s'\n", optarg);
713 exit (4);
714 }
715 }
716 else
717 {
718 attach_pid_name = optarg;
719 }
720 start_mode = eDCGSRunLoopModeInferiorAttaching;
721 }
722 break;
723
724 // --waitfor=NAME
725 case 'w':
726 if (optarg && optarg[0])
727 {
728 waitfor_pid_name = optarg;
729 start_mode = eDCGSRunLoopModeInferiorAttaching;
730 }
731 break;
732
733 // --waitfor-interval=USEC
734 case 'i':
735 if (optarg && optarg[0])
736 {
737 char *end = NULL;
738 waitfor_interval = strtoul(optarg, &end, 0);
739 if (end == NULL || *end != '\0')
740 {
741 Log::STDERR ("error: invalid waitfor-interval option value '%s'.\n", optarg);
742 exit (6);
743 }
744 }
745 break;
746
747 // --waitfor-duration=SEC
748 case 'd':
749 if (optarg && optarg[0])
750 {
751 char *end = NULL;
752 waitfor_duration = strtoul(optarg, &end, 0);
753 if (end == NULL || *end != '\0')
754 {
755 Log::STDERR ("error: invalid waitfor-duration option value '%s'.\n", optarg);
756 exit (7);
757 }
758 }
759 break;
760
761 case 'x':
762 if (optarg && optarg[0])
763 {
764 if (strcasecmp(optarg, "auto") == 0)
765 g_launch_flavor = eLaunchFlavorDefault;
766 else if (strcasestr(optarg, "posix") == optarg)
767 g_launch_flavor = eLaunchFlavorPosixSpawn;
768 else if (strcasestr(optarg, "fork") == optarg)
769 g_launch_flavor = eLaunchFlavorForkExec;
770#if defined (__arm__)
771 else if (strcasestr(optarg, "spring") == optarg)
772 g_launch_flavor = eLaunchFlavorSpringBoard;
773#endif
774 else
775 {
776 Log::STDERR ("error: invalid TYPE for the --launch=TYPE (-x TYPE) option: '%s'\n", optarg);
777 Log::STDERR ("Valid values TYPE are:\n");
778 Log::STDERR (" auto Auto-detect the best launch method to use.\n");
779 Log::STDERR (" posix Launch the executable using posix_spawn.\n");
780 Log::STDERR (" fork Launch the executable using fork and exec.\n");
781#if defined (__arm__)
782 Log::STDERR (" spring Launch the executable through Springboard.\n");
783#endif
784 exit (5);
785 }
786 }
787 break;
788
789 case 'l': // Set Log File
790 if (optarg && optarg[0])
791 {
792 if (strcasecmp(optarg, "stdout") == 0)
793 log_file = stdout;
794 else if (strcasecmp(optarg, "stderr") == 0)
795 log_file = stderr;
796 else
797 log_file = fopen(optarg, "w+");
798
799 if (log_file == NULL)
800 {
801 const char *errno_str = strerror(errno);
802 Log::STDERR ("Failed to open log file '%s' for writing: errno = %i (%s)", optarg, errno, errno_str ? errno_str : "unknown error");
803 }
804 }
805 break;
806
807 case 'f': // Log Flags
808 if (optarg && optarg[0])
809 log_flags = strtoul(optarg, NULL, 0);
810 break;
811
812 case 'g':
813 debug = 1;
814 //DNBLogSetDebug(1);
815 break;
816
817 case 't':
818 g_applist_opt = 1;
819 break;
820
821 case 'k':
822 g_lockdown_opt = 1;
823 break;
824
825 case 'v':
826 //DNBLogSetVerbose(1);
827 break;
828 }
829 }
830
831 // Skip any options we consumed with getopt_long
832 argc -= optind;
833 argv += optind;
834
835 // It is ok for us to set NULL as the logfile (this will disable any logging)
836
837// if (log_file != NULL)
838// {
839// DNBLogSetLogDCScriptInterpreter::Type(FileLogDCScriptInterpreter::Type, log_file);
840// // If our log file was set, yet we have no log flags, log everything!
841// if (log_flags == 0)
842// log_flags = LOG_ALL | LOG_DCGS_ALL;
843//
844// DNBLogSetLogMask (log_flags);
845// }
846// else
847// {
848// // Enable DNB logging
849// DNBLogSetLogDCScriptInterpreter::Type(ASLLogDCScriptInterpreter::Type, NULL);
850// DNBLogSetLogMask (log_flags);
851//
852// }
853
854 // as long as we're dropping remotenub in as a replacement for gdbserver,
855 // explicitly note that this is not gdbserver.
856
857 Log::STDOUT ("debugserver-%g \n", dc_gdbserverVersionNumber);
858 int listen_port = -1;
859 if (g_lockdown_opt == 0 && g_applist_opt == 0)
860 {
861 // Make sure we at least have port
862 if (argc < 1)
863 {
864 Log::STDERR ("Usage: %s host:port [program-name program-arg1 program-arg2 ...]\n", this_exe_name);
865 exit (1);
866 }
867 // accept 'localhost:' prefix on port number
868
869 std::string host_str;
870 std::string port_str(argv[0]);
871
872 // We just used the host:port arg...
873 argc--;
874 argv++;
875
876 size_t port_idx = port_str.find(':');
877 if (port_idx != std::string::npos)
878 {
879 host_str.assign(port_str, 0, port_idx);
880 port_str.erase(0, port_idx + 1);
881 }
882
883 if (port_str.empty())
884 {
885 Log::STDERR ("error: no port specified\nUsage: %s host:port [program-name program-arg1 program-arg2 ...]\n", this_exe_name);
886 exit (2);
887 }
888 else if (port_str.find_first_not_of("0123456789") != std::string::npos)
889 {
890 Log::STDERR ("error: port must be an integer: %s\nUsage: %s host:port [program-name program-arg1 program-arg2 ...]\n", port_str.c_str(), this_exe_name);
891 exit (3);
892 }
893 //DNBLogDebug("host_str = '%s' port_str = '%s'", host_str.c_str(), port_str.c_str());
894 listen_port = atoi (port_str.c_str());
895 }
896
897
898 // We must set up some communications now.
899
900 FileSpec exe_spec;
901 if (argv[0])
902 exe_spec.SetFile (argv[0]);
903
904 HandleBroadcastEventInfo info;
905 info.target_sp = TargetList::SharedList().CreateTarget(&exe_spec, &arch);
906 ProcessSP process_sp (info.target_sp->CreateProcess ());
907 info.remote_sp.reset (new GDBRemoteSession (process_sp));
908
909 info.remote_sp->SetLog (log);
910 StreamString sstr;
911 sstr.Printf("ConnectionFileDescriptor(%s)", argv[0]);
912
913 if (info.remote_sp.get() == NULL)
914 {
915 Log::STDERR ("error: failed to create a GDBRemoteSession class\n");
916 return -1;
917 }
918
919
920
921 // If we know we're waiting to attach, we don't need any of this other info.
922 if (start_mode != eDCGSRunLoopModeInferiorAttaching)
923 {
924 if (argc == 0 || g_lockdown_opt)
925 {
926 if (g_lockdown_opt != 0)
927 {
928 // Work around for SIGPIPE crashes due to posix_spawn issue. We have to close
929 // STDOUT and STDERR, else the first time we try and do any, we get SIGPIPE and
930 // die as posix_spawn is doing bad things with our file descriptors at the moment.
931 int null = open("/dev/null", O_RDWR);
932 dup2(null, STDOUT_FILENO);
933 dup2(null, STDERR_FILENO);
934 }
935 else if (g_applist_opt != 0)
936 {
937// // List all applications we are able to see
938// std::string applist_plist;
939// int err = ListApplications(applist_plist, false, false);
940// if (err == 0)
941// {
942// fputs (applist_plist.c_str(), stdout);
943// }
944// else
945// {
946// Log::STDERR ("error: ListApplications returned error %i\n", err);
947// }
948// // Exit with appropriate error if we were asked to list the applications
949// // with no other args were given (and we weren't trying to do this over
950// // lockdown)
951// return err;
952 return 0;
953 }
954
955 //DNBLogDebug("Get args from remote protocol...");
956 start_mode = eDCGSRunLoopModeGetStartModeFromRemoteProtocol;
957 }
958 else
959 {
960 start_mode = eDCGSRunLoopModeInferiorLaunching;
961 // Fill in the argv array in the context from the rest of our args.
962 // Skip the name of this executable and the port number
963 info.remote_sp->SetArguments (argc, argv);
964 }
965 }
966
967 if (start_mode == eDCGSRunLoopModeExit)
968 return -1;
969
970 info.mode = start_mode;
971
972 while (info.mode != eDCGSRunLoopModeExit)
973 {
974 switch (info.mode)
975 {
976 case eDCGSRunLoopModeGetStartModeFromRemoteProtocol:
977 #if defined (__arm__)
978 if (g_lockdown_opt)
979 {
980 if (!info.remote_sp->GetCommunication()->IsConnected())
981 {
982 if (info.remote_sp->GetCommunication()->ConnectToService () != gdb_success)
983 {
984 Log::STDERR ("Failed to get connection from a remote gdb process.\n");
985 info.mode = eDCGSRunLoopModeExit;
986 }
987 else if (g_applist_opt != 0)
988 {
989 // List all applications we are able to see
990 std::string applist_plist;
991 if (ListApplications(applist_plist, false, false) == 0)
992 {
993 //DNBLogDebug("Task list: %s", applist_plist.c_str());
994
995 info.remote_sp->GetCommunication()->Write(applist_plist.c_str(), applist_plist.size());
996 // Issue a read that will never yield any data until the other side
997 // closes the socket so this process doesn't just exit and cause the
998 // socket to close prematurely on the other end and cause data loss.
999 std::string buf;
1000 info.remote_sp->GetCommunication()->Read(buf);
1001 }
1002 info.remote_sp->GetCommunication()->Disconnect(false);
1003 info.mode = eDCGSRunLoopModeExit;
1004 break;
1005 }
1006 else
1007 {
1008 // Start watching for remote packets
1009 info.remote_sp->StartReadRemoteDataThread();
1010 }
1011 }
1012 }
1013 else
1014#endif
1015 {
1016 if (StartListening (&info, listen_port))
1017 Log::STDOUT ("Got a connection, waiting for process information for launching or attaching.\n");
1018 else
1019 info.mode = eDCGSRunLoopModeExit;
1020 }
1021
1022 if (info.mode != eDCGSRunLoopModeExit)
1023 GSRunLoopGetStartModeFromRemote (&info);
1024 break;
1025
1026 case eDCGSRunLoopModeInferiorAttaching:
1027 if (!waitfor_pid_name.empty())
1028 {
1029 // Set our end wait time if we are using a waitfor-duration
1030 // option that may have been specified
1031
1032 TimeValue attach_timeout_abstime;
1033 if (waitfor_duration != 0)
1034 {
1035 attach_timeout_abstime = TimeValue::Now();
1036 attach_timeout_abstime.OffsetWithSeconds (waitfor_duration);
1037 }
1038 GSLaunchFlavor launch_flavor = g_launch_flavor;
1039 if (launch_flavor == eLaunchFlavorDefault)
1040 {
1041 // Our default launch method is posix spawn
1042 launch_flavor = eLaunchFlavorPosixSpawn;
1043
1044#if defined (__arm__)
1045 // Check if we have an app bundle, if so launch using SpringBoard.
1046 if (waitfor_pid_name.find (".app") != std::string::npos)
1047 {
1048 launch_flavor = eLaunchFlavorSpringBoard;
1049 }
1050#endif
1051 }
1052
1053 //ctx.SetLaunchFlavor(launch_flavor);
1054
1055
1056 lldb::pid_t pid = info.GetProcess()->Attach (waitfor_pid_name.c_str());
1057 if (pid == LLDB_INVALID_PROCESS_ID)
1058 {
1059 info.GetRemote()->GetLaunchError() = info.GetProcess()->GetError();
1060 Log::STDERR ("error: failed to attach to process named: \"%s\" %s", waitfor_pid_name.c_str(), info.GetRemote()->GetLaunchError().AsCString());
1061 info.mode = eDCGSRunLoopModeExit;
1062 }
1063 else
1064 {
1065 info.mode = eDCGSRunLoopModeInferiorExecuting;
1066 }
1067 }
1068 else if (attach_pid != LLDB_INVALID_PROCESS_ID)
1069 {
1070 Log::STDOUT ("Attaching to process %i...\n", attach_pid);
1071 info.mode = GSRunLoopLaunchAttaching (&info, attach_pid);
1072 if (info.mode != eDCGSRunLoopModeInferiorExecuting)
1073 {
1074 const char *error_str = info.GetRemote()->GetLaunchError().AsCString();
1075 Log::STDERR ("error: failed to attach process %i: %s\n", attach_pid, error_str ? error_str : "unknown error.");
1076 info.mode = eDCGSRunLoopModeExit;
1077 }
1078 }
1079 else if (!attach_pid_name.empty ())
1080 {
1081 lldb::pid_t pid = info.GetProcess()->Attach (waitfor_pid_name.c_str());
1082 if (pid == LLDB_INVALID_PROCESS_ID)
1083 {
1084 info.GetRemote()->GetLaunchError() = info.GetProcess()->GetError();
1085 Log::STDERR ("error: failed to attach to process named: \"%s\" %s", waitfor_pid_name.c_str(), info.GetRemote()->GetLaunchError().AsCString());
1086 info.mode = eDCGSRunLoopModeExit;
1087 }
1088 else
1089 {
1090 info.mode = eDCGSRunLoopModeInferiorExecuting;
1091 }
1092 }
1093 else
1094 {
1095 Log::STDERR ("error: asked to attach with empty name and invalid PID.");
1096 info.mode = eDCGSRunLoopModeExit;
1097 }
1098
1099 if (info.mode != eDCGSRunLoopModeExit)
1100 {
1101 if (StartListening (&info, listen_port))
1102 Log::STDOUT ("Got a connection, waiting for debugger instructions for process %d.\n", attach_pid);
1103 else
1104 info.mode = eDCGSRunLoopModeExit;
1105 }
1106 break;
1107
1108 case eDCGSRunLoopModeInferiorLaunching:
1109 info.mode = GSRunLoopLaunchInferior (&info);
1110
1111 if (info.mode == eDCGSRunLoopModeInferiorExecuting)
1112 {
1113 if (StartListening (&info, listen_port))
1114 Log::STDOUT ("Got a connection, waiting for debugger instructions for task \"%s\".\n", argv[0]);
1115 else
1116 info.mode = eDCGSRunLoopModeExit;
1117 }
1118 else
1119 {
1120 Log::STDERR ("error: failed to launch process %s: %s\n", argv[0], info.GetRemote()->GetLaunchError().AsCString());
1121 }
1122 break;
1123
1124 case eDCGSRunLoopModeInferiorExecuting:
1125 GSRunLoopInferiorExecuting (&info);
1126 break;
1127
1128 case eDCGSRunLoopModeInferiorKillOrDetach:
1129 {
1130 Process *process = info.GetProcess();
1131 if (process && process->IsAlive())
1132 {
1133 process->Kill(SIGCONT);
1134 process->Kill(SIGKILL);
1135 }
1136 }
1137 info.mode = eDCGSRunLoopModeExit;
1138 break;
1139
1140 default:
1141 info.mode = eDCGSRunLoopModeExit;
1142 case eDCGSRunLoopModeExit:
1143 break;
1144 }
1145 }
1146
1147 return 0;
1148}