1 //===-- lldb-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 // C Includes
11 #include <errno.h>
12 #include <getopt.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 
18 #ifndef _WIN32
19 #include <signal.h>
20 #include <unistd.h>
21 #endif
22 
23 // C++ Includes
24 
25 // Other libraries and framework includes
26 #include "lldb/Core/Error.h"
27 #include "lldb/Core/ConnectionMachPort.h"
28 #include "lldb/Core/Debugger.h"
29 #include "lldb/Core/PluginManager.h"
30 #include "lldb/Core/StreamFile.h"
31 #include "lldb/Host/ConnectionFileDescriptor.h"
32 #include "lldb/Host/HostThread.h"
33 #include "lldb/Host/Pipe.h"
34 #include "lldb/Host/OptionParser.h"
35 #include "lldb/Host/Socket.h"
36 #include "lldb/Host/StringConvert.h"
37 #include "lldb/Host/ThreadLauncher.h"
38 #include "lldb/Interpreter/CommandInterpreter.h"
39 #include "lldb/Interpreter/CommandReturnObject.h"
40 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
41 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
42 
43 #ifndef LLGS_PROGRAM_NAME
44 #define LLGS_PROGRAM_NAME "lldb-server"
45 #endif
46 
47 #ifndef LLGS_VERSION_STR
48 #define LLGS_VERSION_STR "local_build"
49 #endif
50 
51 using namespace lldb;
52 using namespace lldb_private;
53 using namespace lldb_private::process_gdb_remote;
54 
55 // lldb-gdbserver state
56 
57 namespace
58 {
59 HostThread s_listen_thread;
60     std::unique_ptr<ConnectionFileDescriptor> s_listen_connection_up;
61     std::string s_listen_url;
62 }
63 
64 //----------------------------------------------------------------------
65 // option descriptors for getopt_long_only()
66 //----------------------------------------------------------------------
67 
68 static int g_debug = 0;
69 static int g_verbose = 0;
70 
71 static struct option g_long_options[] =
72 {
73     { "debug",              no_argument,        &g_debug,           1   },
74     { "platform",           required_argument,  NULL,               'p' },
75     { "verbose",            no_argument,        &g_verbose,         1   },
76     { "lldb-command",       required_argument,  NULL,               'c' },
77     { "log-file",           required_argument,  NULL,               'l' },
78     { "log-flags",          required_argument,  NULL,               'f' },
79     { "attach",             required_argument,  NULL,               'a' },
80     { "named-pipe",         required_argument,  NULL,               'N' },
81     { "pipe",               required_argument,  NULL,               'U' },
82     { "native-regs",        no_argument,        NULL,               'r' },  // Specify to use the native registers instead of the gdb defaults for the architecture.  NOTE: this is a do-nothing arg as it's behavior is default now.  FIXME remove call from lldb-platform.
83     { "reverse-connect",    no_argument,        NULL,               'R' },  // Specifies that llgs attaches to the client address:port rather than llgs listening for a connection from address on port.
84     { "setsid",             no_argument,        NULL,               'S' },  // Call setsid() to make llgs run in its own session.
85     { NULL,                 0,                  NULL,               0   }
86 };
87 
88 
89 //----------------------------------------------------------------------
90 // Watch for signals
91 //----------------------------------------------------------------------
92 static int g_sigpipe_received = 0;
93 static int g_sighup_received_count = 0;
94 
95 #ifndef _WIN32
96 
97 static void
98 signal_handler(int signo)
99 {
100     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
101 
102     fprintf (stderr, "lldb-server:%s received signal %d\n", __FUNCTION__, signo);
103     if (log)
104         log->Printf ("lldb-server:%s received signal %d", __FUNCTION__, signo);
105 
106     switch (signo)
107     {
108     case SIGPIPE:
109         g_sigpipe_received = 1;
110         break;
111     case SIGHUP:
112         ++g_sighup_received_count;
113 
114         // For now, swallow SIGHUP.
115         if (log)
116             log->Printf ("lldb-server:%s swallowing SIGHUP (receive count=%d)", __FUNCTION__, g_sighup_received_count);
117         signal (SIGHUP, signal_handler);
118         break;
119     }
120 }
121 #endif // #ifndef _WIN32
122 
123 static void
124 display_usage (const char *progname, const char* subcommand)
125 {
126     fprintf(stderr, "Usage:\n  %s %s "
127             "[--log-file log-file-path] "
128             "[--log-flags flags] "
129             "[--lldb-command command]* "
130             "[--platform platform_name] "
131             "[--setsid] "
132             "[--named-pipe named-pipe-path] "
133             "[--native-regs] "
134             "[--attach pid] "
135             "[[HOST]:PORT] "
136             "[-- PROGRAM ARG1 ARG2 ...]\n", progname, subcommand);
137     exit(0);
138 }
139 
140 static void
141 dump_available_platforms (FILE *output_file)
142 {
143     fprintf (output_file, "Available platform plugins:\n");
144     for (int i = 0; ; ++i)
145     {
146         const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex (i);
147         const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex (i);
148 
149         if (!plugin_name || !plugin_desc)
150             break;
151 
152         fprintf (output_file, "%s\t%s\n", plugin_name, plugin_desc);
153     }
154 
155     if ( Platform::GetHostPlatform () )
156     {
157         // add this since the default platform doesn't necessarily get registered by
158         // the plugin name (e.g. 'host' doesn't show up as a
159         // registered platform plugin even though it's the default).
160         fprintf (output_file, "%s\tDefault platform for this host.\n", Platform::GetHostPlatform ()->GetPluginName ().AsCString ());
161     }
162 }
163 
164 static void
165 run_lldb_commands (const lldb::DebuggerSP &debugger_sp, const std::vector<std::string> &lldb_commands)
166 {
167     for (const auto &lldb_command : lldb_commands)
168     {
169         printf("(lldb) %s\n", lldb_command.c_str ());
170 
171         lldb_private::CommandReturnObject result;
172         debugger_sp->GetCommandInterpreter ().HandleCommand (lldb_command.c_str (), eLazyBoolNo, result);
173         const char *output = result.GetOutputData ();
174         if (output && output[0])
175             puts (output);
176     }
177 }
178 
179 static lldb::PlatformSP
180 setup_platform (const std::string &platform_name)
181 {
182     lldb::PlatformSP platform_sp;
183 
184     if (platform_name.empty())
185     {
186         printf ("using the default platform: ");
187         platform_sp = Platform::GetHostPlatform ();
188         printf ("%s\n", platform_sp->GetPluginName ().AsCString ());
189         return platform_sp;
190     }
191 
192     Error error;
193     platform_sp = Platform::Create (lldb_private::ConstString(platform_name), error);
194     if (error.Fail ())
195     {
196         // the host platform isn't registered with that name (at
197         // least, not always.  Check if the given name matches
198         // the default platform name.  If so, use it.
199         if ( Platform::GetHostPlatform () && ( Platform::GetHostPlatform ()->GetPluginName () == ConstString (platform_name.c_str()) ) )
200         {
201             platform_sp = Platform::GetHostPlatform ();
202         }
203         else
204         {
205             fprintf (stderr, "error: failed to create platform with name '%s'\n", platform_name.c_str());
206             dump_available_platforms (stderr);
207             exit (1);
208         }
209     }
210     printf ("using platform: %s\n", platform_name.c_str ());
211 
212     return platform_sp;
213 }
214 
215 void
216 handle_attach_to_pid (GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid)
217 {
218     Error error = gdb_server.AttachToProcess (pid);
219     if (error.Fail ())
220     {
221         fprintf (stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString());
222         exit(1);
223     }
224 }
225 
226 void
227 handle_attach_to_process_name (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &process_name)
228 {
229     // FIXME implement.
230 }
231 
232 void
233 handle_attach (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &attach_target)
234 {
235     assert (!attach_target.empty () && "attach_target cannot be empty");
236 
237     // First check if the attach_target is convertable to a long. If so, we'll use it as a pid.
238     char *end_p = nullptr;
239     const long int pid = strtol (attach_target.c_str (), &end_p, 10);
240 
241     // We'll call it a match if the entire argument is consumed.
242     if (end_p && static_cast<size_t> (end_p - attach_target.c_str ()) == attach_target.size ())
243         handle_attach_to_pid (gdb_server, static_cast<lldb::pid_t> (pid));
244     else
245         handle_attach_to_process_name (gdb_server, attach_target);
246 }
247 
248 void
249 handle_launch (GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[])
250 {
251     Error error;
252     error = gdb_server.SetLaunchArguments (argv, argc);
253     if (error.Fail ())
254     {
255         fprintf (stderr, "error: failed to set launch args for '%s': %s\n", argv[0], error.AsCString());
256         exit(1);
257     }
258 
259     unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
260 
261     error = gdb_server.SetLaunchFlags (launch_flags);
262     if (error.Fail ())
263     {
264         fprintf (stderr, "error: failed to set launch flags for '%s': %s\n", argv[0], error.AsCString());
265         exit(1);
266     }
267 
268     error = gdb_server.LaunchProcess ();
269     if (error.Fail ())
270     {
271         fprintf (stderr, "error: failed to launch '%s': %s\n", argv[0], error.AsCString());
272         exit(1);
273     }
274 }
275 
276 static lldb::thread_result_t
277 ListenThread (lldb::thread_arg_t /* arg */)
278 {
279     Error error;
280 
281     if (s_listen_connection_up)
282     {
283         // Do the listen on another thread so we can continue on...
284         if (s_listen_connection_up->Connect(s_listen_url.c_str(), &error) != eConnectionStatusSuccess)
285             s_listen_connection_up.reset();
286     }
287     return nullptr;
288 }
289 
290 static Error
291 StartListenThread (const char *hostname, uint16_t port)
292 {
293     Error error;
294     if (s_listen_thread.IsJoinable())
295     {
296         error.SetErrorString("listen thread already running");
297     }
298     else
299     {
300         char listen_url[512];
301         if (hostname && hostname[0])
302             snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
303         else
304             snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
305 
306         s_listen_url = listen_url;
307         s_listen_connection_up.reset (new ConnectionFileDescriptor ());
308         s_listen_thread = ThreadLauncher::LaunchThread(listen_url, ListenThread, nullptr, &error);
309     }
310     return error;
311 }
312 
313 static bool
314 JoinListenThread ()
315 {
316     if (s_listen_thread.IsJoinable())
317         s_listen_thread.Join(nullptr);
318     return true;
319 }
320 
321 Error
322 WritePortToPipe(Pipe &port_pipe, const uint16_t port)
323 {
324     char port_str[64];
325     const auto port_str_len = ::snprintf(port_str, sizeof(port_str), "%u", port);
326 
327     size_t bytes_written = 0;
328     // Write the port number as a C string with the NULL terminator.
329     return port_pipe.Write(port_str, port_str_len + 1, bytes_written);
330 }
331 
332 Error
333 writePortToPipe(const char *const named_pipe_path, const uint16_t port)
334 {
335     Pipe port_name_pipe;
336     // Wait for 10 seconds for pipe to be opened.
337     auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
338             std::chrono::seconds{10});
339     if (error.Fail())
340         return error;
341     return WritePortToPipe(port_name_pipe, port);
342 }
343 
344 Error
345 writePortToPipe(int unnamed_pipe_fd, const uint16_t port)
346 {
347 #if defined(_WIN32)
348     return Error("Unnamed pipes are not supported on Windows.");
349 #else
350     Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
351     return WritePortToPipe(port_pipe, port);
352 #endif
353 }
354 
355 void
356 ConnectToRemote(GDBRemoteCommunicationServerLLGS &gdb_server,
357         bool reverse_connect, const char *const host_and_port,
358         const char *const progname, const char *const subcommand,
359         const char *const named_pipe_path, int unnamed_pipe_fd)
360 {
361     Error error;
362 
363     if (host_and_port && host_and_port[0])
364     {
365         // Parse out host and port.
366         std::string final_host_and_port;
367         std::string connection_host;
368         std::string connection_port;
369         uint32_t connection_portno = 0;
370 
371         // If host_and_port starts with ':', default the host to be "localhost" and expect the remainder to be the port.
372         if (host_and_port[0] == ':')
373             final_host_and_port.append ("localhost");
374         final_host_and_port.append (host_and_port);
375 
376         const std::string::size_type colon_pos = final_host_and_port.find (':');
377         if (colon_pos != std::string::npos)
378         {
379             connection_host = final_host_and_port.substr (0, colon_pos);
380             connection_port = final_host_and_port.substr (colon_pos + 1);
381             connection_portno = StringConvert::ToUInt32 (connection_port.c_str (), 0);
382         }
383         else
384         {
385             fprintf (stderr, "failed to parse host and port from connection string '%s'\n", final_host_and_port.c_str ());
386             display_usage (progname, subcommand);
387             exit (1);
388         }
389 
390         if (reverse_connect)
391         {
392             // llgs will connect to the gdb-remote client.
393 
394             // Ensure we have a port number for the connection.
395             if (connection_portno == 0)
396             {
397                 fprintf (stderr, "error: port number must be specified on when using reverse connect");
398                 exit (1);
399             }
400 
401             // Build the connection string.
402             char connection_url[512];
403             snprintf(connection_url, sizeof(connection_url), "connect://%s", final_host_and_port.c_str ());
404 
405             // Create the connection.
406             std::unique_ptr<ConnectionFileDescriptor> connection_up (new ConnectionFileDescriptor ());
407             connection_up.reset (new ConnectionFileDescriptor ());
408             auto connection_result = connection_up->Connect (connection_url, &error);
409             if (connection_result != eConnectionStatusSuccess)
410             {
411                 fprintf (stderr, "error: failed to connect to client at '%s' (connection status: %d)", connection_url, static_cast<int> (connection_result));
412                 exit (-1);
413             }
414             if (error.Fail ())
415             {
416                 fprintf (stderr, "error: failed to connect to client at '%s': %s", connection_url, error.AsCString ());
417                 exit (-1);
418             }
419 
420             // We're connected.
421             printf ("Connection established.\n");
422             gdb_server.SetConnection (connection_up.release());
423         }
424         else
425         {
426             // llgs will listen for connections on the given port from the given address.
427             // Start the listener on a new thread.  We need to do this so we can resolve the
428             // bound listener port.
429             StartListenThread(connection_host.c_str (), static_cast<uint16_t> (connection_portno));
430             printf ("Listening to port %s for a connection from %s...\n", connection_port.c_str (), connection_host.c_str ());
431 
432             // If we have a named pipe to write the port number back to, do that now.
433             if (named_pipe_path && named_pipe_path[0] && connection_portno == 0)
434             {
435                 const uint16_t bound_port = s_listen_connection_up->GetListeningPort (10);
436                 if (bound_port > 0)
437                 {
438                     error = writePortToPipe (named_pipe_path, bound_port);
439                     if (error.Fail ())
440                     {
441                         fprintf (stderr, "failed to write to the named pipe \'%s\': %s", named_pipe_path, error.AsCString());
442                     }
443                 }
444                 else
445                 {
446                     fprintf (stderr, "unable to get the bound port for the listening connection\n");
447                 }
448             }
449 
450             // If we have an unnamed pipe to write the port number back to, do that now.
451             if (unnamed_pipe_fd >= 0 && connection_portno == 0)
452             {
453                 const uint16_t bound_port = s_listen_connection_up->GetListeningPort(10);
454                 if (bound_port > 0)
455                 {
456                     error = writePortToPipe(unnamed_pipe_fd, bound_port);
457                     if (error.Fail())
458                     {
459                         fprintf(stderr, "failed to write to the unnamed pipe: %s",
460                                 error.AsCString());
461                     }
462                 }
463                 else
464                 {
465                     fprintf(stderr, "unable to get the bound port for the listening connection\n");
466                 }
467             }
468 
469             // Join the listener thread.
470             if (!JoinListenThread ())
471             {
472                 fprintf (stderr, "failed to join the listener thread\n");
473                 display_usage (progname, subcommand);
474                 exit (1);
475             }
476 
477             // Ensure we connected.
478             if (s_listen_connection_up)
479             {
480                 printf ("Connection established '%s'\n", s_listen_connection_up->GetURI().c_str());
481                 gdb_server.SetConnection (s_listen_connection_up.release());
482             }
483             else
484             {
485                 fprintf (stderr, "failed to connect to '%s': %s\n", final_host_and_port.c_str (), error.AsCString ());
486                 display_usage (progname, subcommand);
487                 exit (1);
488             }
489         }
490     }
491 
492     if (gdb_server.IsConnected())
493     {
494         // After we connected, we need to get an initial ack from...
495         if (gdb_server.HandshakeWithClient(&error))
496         {
497             // We'll use a half a second timeout interval so that an exit conditions can
498             // be checked that often.
499             const uint32_t TIMEOUT_USEC = 500000;
500 
501             bool interrupt = false;
502             bool done = false;
503             while (!interrupt && !done && (g_sighup_received_count < 2))
504             {
505                 const GDBRemoteCommunication::PacketResult result = gdb_server.GetPacketAndSendResponse (TIMEOUT_USEC, error, interrupt, done);
506                 if ((result != GDBRemoteCommunication::PacketResult::Success) &&
507                     (result != GDBRemoteCommunication::PacketResult::ErrorReplyTimeout))
508                 {
509                     // We're bailing out - we only support successful handling and timeouts.
510                     fprintf(stderr, "leaving packet loop due to PacketResult %d\n", result);
511                     break;
512                 }
513             }
514 
515             if (error.Fail())
516             {
517                 fprintf(stderr, "error: %s\n", error.AsCString());
518             }
519         }
520         else
521         {
522             fprintf(stderr, "error: handshake with client failed\n");
523         }
524     }
525     else
526     {
527         fprintf (stderr, "no connection information provided, unable to run\n");
528         display_usage (progname, subcommand);
529         exit (1);
530     }
531 }
532 
533 //----------------------------------------------------------------------
534 // main
535 //----------------------------------------------------------------------
536 int
537 main_gdbserver (int argc, char *argv[])
538 {
539 #ifndef _WIN32
540     // Setup signal handlers first thing.
541     signal (SIGPIPE, signal_handler);
542     signal (SIGHUP, signal_handler);
543 #endif
544 #ifdef __linux__
545     // Block delivery of SIGCHLD on linux. NativeProcessLinux will read it using signalfd.
546     sigset_t set;
547     sigemptyset(&set);
548     sigaddset(&set, SIGCHLD);
549     pthread_sigmask(SIG_BLOCK, &set, NULL);
550 #endif
551 
552     const char *progname = argv[0];
553     const char *subcommand = argv[1];
554     argc--;
555     argv++;
556     int long_option_index = 0;
557     StreamSP log_stream_sp;
558     Args log_args;
559     Error error;
560     int ch;
561     std::string platform_name;
562     std::string attach_target;
563     std::string named_pipe_path;
564     int unnamed_pipe_fd = -1;
565     bool reverse_connect = false;
566 
567     lldb::DebuggerSP debugger_sp = Debugger::CreateInstance ();
568 
569     debugger_sp->SetInputFileHandle(stdin, false);
570     debugger_sp->SetOutputFileHandle(stdout, false);
571     debugger_sp->SetErrorFileHandle(stderr, false);
572 
573     // ProcessLaunchInfo launch_info;
574     ProcessAttachInfo attach_info;
575 
576     bool show_usage = false;
577     int option_error = 0;
578 #if __GLIBC__
579     optind = 0;
580 #else
581     optreset = 1;
582     optind = 1;
583 #endif
584 
585     std::string short_options(OptionParser::GetShortOptionString(g_long_options));
586 
587     std::vector<std::string> lldb_commands;
588 
589     while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
590     {
591         switch (ch)
592         {
593         case 0:   // Any optional that auto set themselves will return 0
594             break;
595 
596         case 'l': // Set Log File
597             if (optarg && optarg[0])
598             {
599                 if ((strcasecmp(optarg, "stdout") == 0) || (strcmp(optarg, "/dev/stdout") == 0))
600                 {
601                     log_stream_sp.reset (new StreamFile (stdout, false));
602                 }
603                 else if ((strcasecmp(optarg, "stderr") == 0) || (strcmp(optarg, "/dev/stderr") == 0))
604                 {
605                     log_stream_sp.reset (new StreamFile (stderr, false));
606                 }
607                 else
608                 {
609                     FILE *log_file = fopen(optarg, "w");
610                     if (log_file)
611                     {
612                         setlinebuf(log_file);
613                         log_stream_sp.reset (new StreamFile (log_file, true));
614                     }
615                     else
616                     {
617                         const char *errno_str = strerror(errno);
618                         fprintf (stderr, "Failed to open log file '%s' for writing: errno = %i (%s)", optarg, errno, errno_str ? errno_str : "unknown error");
619                     }
620 
621                 }
622             }
623             break;
624 
625         case 'f': // Log Flags
626             if (optarg && optarg[0])
627                 log_args.AppendArgument(optarg);
628             break;
629 
630         case 'c': // lldb commands
631             if (optarg && optarg[0])
632                 lldb_commands.push_back(optarg);
633             break;
634 
635         case 'p': // platform name
636             if (optarg && optarg[0])
637                 platform_name = optarg;
638             break;
639 
640         case 'N': // named pipe
641             if (optarg && optarg[0])
642                 named_pipe_path = optarg;
643             break;
644 
645         case 'U': // unnamed pipe
646             if (optarg && optarg[0])
647                 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
648 
649         case 'r':
650             // Do nothing, native regs is the default these days
651             break;
652 
653         case 'R':
654             reverse_connect = true;
655             break;
656 
657 #ifndef _WIN32
658         case 'S':
659             // Put llgs into a new session. Terminals group processes
660             // into sessions and when a special terminal key sequences
661             // (like control+c) are typed they can cause signals to go out to
662             // all processes in a session. Using this --setsid (-S) option
663             // will cause debugserver to run in its own sessions and be free
664             // from such issues.
665             //
666             // This is useful when llgs is spawned from a command
667             // line application that uses llgs to do the debugging,
668             // yet that application doesn't want llgs receiving the
669             // signals sent to the session (i.e. dying when anyone hits ^C).
670             {
671                 const ::pid_t new_sid = setsid();
672                 if (new_sid == -1)
673                 {
674                     const char *errno_str = strerror(errno);
675                     fprintf (stderr, "failed to set new session id for %s (%s)\n", LLGS_PROGRAM_NAME, errno_str ? errno_str : "<no error string>");
676                 }
677             }
678             break;
679 #endif
680 
681         case 'a': // attach {pid|process_name}
682             if (optarg && optarg[0])
683                 attach_target = optarg;
684                 break;
685 
686         case 'h':   /* fall-through is intentional */
687         case '?':
688             show_usage = true;
689             break;
690         }
691     }
692 
693     if (show_usage || option_error)
694     {
695         display_usage(progname, subcommand);
696         exit(option_error);
697     }
698 
699     if (log_stream_sp)
700     {
701         if (log_args.GetArgumentCount() == 0)
702             log_args.AppendArgument("default");
703         ProcessGDBRemoteLog::EnableLog (log_stream_sp, 0,log_args.GetConstArgumentVector(), log_stream_sp.get());
704     }
705     Log *log(lldb_private::GetLogIfAnyCategoriesSet (GDBR_LOG_VERBOSE));
706     if (log)
707     {
708         log->Printf ("lldb-server launch");
709         for (int i = 0; i < argc; i++)
710         {
711             log->Printf ("argv[%i] = '%s'", i, argv[i]);
712         }
713     }
714 
715     // Skip any options we consumed with getopt_long_only.
716     argc -= optind;
717     argv += optind;
718 
719     if (argc == 0)
720     {
721         display_usage(progname, subcommand);
722         exit(255);
723     }
724 
725     // Run any commands requested.
726     run_lldb_commands (debugger_sp, lldb_commands);
727 
728     // Setup the platform that GDBRemoteCommunicationServerLLGS will use.
729     lldb::PlatformSP platform_sp = setup_platform (platform_name);
730 
731     GDBRemoteCommunicationServerLLGS gdb_server (platform_sp, debugger_sp);
732 
733     const char *const host_and_port = argv[0];
734     argc -= 1;
735     argv += 1;
736 
737     // Any arguments left over are for the the program that we need to launch. If there
738     // are no arguments, then the GDB server will start up and wait for an 'A' packet
739     // to launch a program, or a vAttach packet to attach to an existing process, unless
740     // explicitly asked to attach with the --attach={pid|program_name} form.
741     if (!attach_target.empty ())
742         handle_attach (gdb_server, attach_target);
743     else if (argc > 0)
744         handle_launch (gdb_server, argc, argv);
745 
746     // Print version info.
747     printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
748 
749     ConnectToRemote(gdb_server, reverse_connect,
750                     host_and_port, progname, subcommand,
751                     named_pipe_path.c_str(), unnamed_pipe_fd);
752 
753     fprintf(stderr, "lldb-server exiting...\n");
754 
755     return 0;
756 }
757