xref: /llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp (revision 06f09b58f7d712a047fc1a52f86b3d4177b13844)
1 //===-- GDBRemoteCommunication.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 
11 #include "GDBRemoteCommunication.h"
12 
13 // C Includes
14 #include <limits.h>
15 #include <string.h>
16 #include <sys/stat.h>
17 
18 // C++ Includes
19 // Other libraries and framework includes
20 #include "lldb/Core/ConnectionFileDescriptor.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/StreamFile.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Host/FileSpec.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/TimeValue.h"
27 #include "lldb/Target/Process.h"
28 
29 // Project includes
30 #include "ProcessGDBRemoteLog.h"
31 
32 #define DEBUGSERVER_BASENAME    "debugserver"
33 
34 using namespace lldb;
35 using namespace lldb_private;
36 
37 GDBRemoteCommunication::History::History (uint32_t size) :
38     m_packets(),
39     m_curr_idx (0),
40     m_total_packet_count (0),
41     m_dumped_to_log (false)
42 {
43     m_packets.resize(size);
44 }
45 
46 GDBRemoteCommunication::History::~History ()
47 {
48 }
49 
50 void
51 GDBRemoteCommunication::History::AddPacket (char packet_char,
52                                             PacketType type,
53                                             uint32_t bytes_transmitted)
54 {
55     const size_t size = m_packets.size();
56     if (size > 0)
57     {
58         const uint32_t idx = GetNextIndex();
59         m_packets[idx].packet.assign (1, packet_char);
60         m_packets[idx].type = type;
61         m_packets[idx].bytes_transmitted = bytes_transmitted;
62         m_packets[idx].packet_idx = m_total_packet_count;
63         m_packets[idx].tid = Host::GetCurrentThreadID();
64     }
65 }
66 
67 void
68 GDBRemoteCommunication::History::AddPacket (const std::string &src,
69                                             uint32_t src_len,
70                                             PacketType type,
71                                             uint32_t bytes_transmitted)
72 {
73     const size_t size = m_packets.size();
74     if (size > 0)
75     {
76         const uint32_t idx = GetNextIndex();
77         m_packets[idx].packet.assign (src, 0, src_len);
78         m_packets[idx].type = type;
79         m_packets[idx].bytes_transmitted = bytes_transmitted;
80         m_packets[idx].packet_idx = m_total_packet_count;
81         m_packets[idx].tid = Host::GetCurrentThreadID();
82     }
83 }
84 
85 void
86 GDBRemoteCommunication::History::Dump (lldb_private::Stream &strm) const
87 {
88     const uint32_t size = GetNumPacketsInHistory ();
89     const uint32_t first_idx = GetFirstSavedPacketIndex ();
90     const uint32_t stop_idx = m_curr_idx + size;
91     for (uint32_t i = first_idx;  i < stop_idx; ++i)
92     {
93         const uint32_t idx = NormalizeIndex (i);
94         const Entry &entry = m_packets[idx];
95         if (entry.type == ePacketTypeInvalid || entry.packet.empty())
96             break;
97         strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
98                      entry.packet_idx,
99                      entry.tid,
100                      entry.bytes_transmitted,
101                      (entry.type == ePacketTypeSend) ? "send" : "read",
102                      entry.packet.c_str());
103     }
104 }
105 
106 void
107 GDBRemoteCommunication::History::Dump (lldb_private::Log *log) const
108 {
109     if (log && !m_dumped_to_log)
110     {
111         m_dumped_to_log = true;
112         const uint32_t size = GetNumPacketsInHistory ();
113         const uint32_t first_idx = GetFirstSavedPacketIndex ();
114         const uint32_t stop_idx = m_curr_idx + size;
115         for (uint32_t i = first_idx;  i < stop_idx; ++i)
116         {
117             const uint32_t idx = NormalizeIndex (i);
118             const Entry &entry = m_packets[idx];
119             if (entry.type == ePacketTypeInvalid || entry.packet.empty())
120                 break;
121             log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
122                          entry.packet_idx,
123                          entry.tid,
124                          entry.bytes_transmitted,
125                          (entry.type == ePacketTypeSend) ? "send" : "read",
126                          entry.packet.c_str());
127         }
128     }
129 }
130 
131 //----------------------------------------------------------------------
132 // GDBRemoteCommunication constructor
133 //----------------------------------------------------------------------
134 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
135                                                const char *listener_name,
136                                                bool is_platform) :
137     Communication(comm_name),
138 #ifdef LLDB_CONFIGURATION_DEBUG
139     m_packet_timeout (1000),
140 #else
141     m_packet_timeout (1),
142 #endif
143     m_sequence_mutex (Mutex::eMutexTypeRecursive),
144     m_public_is_running (false),
145     m_private_is_running (false),
146     m_history (512),
147     m_send_acks (true),
148     m_is_platform (is_platform),
149     m_listen_thread (LLDB_INVALID_HOST_THREAD),
150     m_listen_url ()
151 {
152 }
153 
154 //----------------------------------------------------------------------
155 // Destructor
156 //----------------------------------------------------------------------
157 GDBRemoteCommunication::~GDBRemoteCommunication()
158 {
159     if (IsConnected())
160     {
161         Disconnect();
162     }
163 }
164 
165 char
166 GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
167 {
168     int checksum = 0;
169 
170     for (size_t i = 0; i < payload_length; ++i)
171         checksum += payload[i];
172 
173     return checksum & 255;
174 }
175 
176 size_t
177 GDBRemoteCommunication::SendAck ()
178 {
179     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
180     ConnectionStatus status = eConnectionStatusSuccess;
181     char ch = '+';
182     const size_t bytes_written = Write (&ch, 1, status, NULL);
183     if (log)
184         log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
185     m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
186     return bytes_written;
187 }
188 
189 size_t
190 GDBRemoteCommunication::SendNack ()
191 {
192     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
193     ConnectionStatus status = eConnectionStatusSuccess;
194     char ch = '-';
195     const size_t bytes_written = Write (&ch, 1, status, NULL);
196     if (log)
197         log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
198     m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
199     return bytes_written;
200 }
201 
202 GDBRemoteCommunication::PacketResult
203 GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
204 {
205     Mutex::Locker locker(m_sequence_mutex);
206     return SendPacketNoLock (payload, payload_length);
207 }
208 
209 GDBRemoteCommunication::PacketResult
210 GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
211 {
212     if (IsConnected())
213     {
214         StreamString packet(0, 4, eByteOrderBig);
215 
216         packet.PutChar('$');
217         packet.Write (payload, payload_length);
218         packet.PutChar('#');
219         packet.PutHex8(CalculcateChecksum (payload, payload_length));
220 
221         Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
222         ConnectionStatus status = eConnectionStatusSuccess;
223         size_t bytes_written = Write (packet.GetData(), packet.GetSize(), status, NULL);
224         if (log)
225         {
226             // If logging was just enabled and we have history, then dump out what
227             // we have to the log so we get the historical context. The Dump() call that
228             // logs all of the packet will set a boolean so that we don't dump this more
229             // than once
230             if (!m_history.DidDumpToLog ())
231                 m_history.Dump (log);
232 
233             log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet.GetSize(), packet.GetData());
234         }
235 
236         m_history.AddPacket (packet.GetString(), packet.GetSize(), History::ePacketTypeSend, bytes_written);
237 
238 
239         if (bytes_written == packet.GetSize())
240         {
241             if (GetSendAcks ())
242                 return GetAck ();
243             else
244                 return PacketResult::Success;
245         }
246         else
247         {
248             if (log)
249                 log->Printf ("error: failed to send packet: %.*s", (int)packet.GetSize(), packet.GetData());
250         }
251     }
252     return PacketResult::ErrorSendFailed;
253 }
254 
255 GDBRemoteCommunication::PacketResult
256 GDBRemoteCommunication::GetAck ()
257 {
258     StringExtractorGDBRemote packet;
259     PacketResult result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ());
260     if (result == PacketResult::Success)
261     {
262         if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
263             return PacketResult::Success;
264         else
265             return PacketResult::ErrorSendAck;
266     }
267     return result;
268 }
269 
270 bool
271 GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
272 {
273     if (IsRunning())
274         return locker.TryLock (m_sequence_mutex, failure_message);
275 
276     locker.Lock (m_sequence_mutex);
277     return true;
278 }
279 
280 
281 bool
282 GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
283 {
284     return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
285 }
286 
287 GDBRemoteCommunication::PacketResult
288 GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
289 {
290     uint8_t buffer[8192];
291     Error error;
292 
293     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
294 
295     // Check for a packet from our cache first without trying any reading...
296     if (CheckForPacket (NULL, 0, packet))
297         return PacketResult::Success;
298 
299     bool timed_out = false;
300     bool disconnected = false;
301     while (IsConnected() && !timed_out)
302     {
303         lldb::ConnectionStatus status = eConnectionStatusNoConnection;
304         size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
305 
306         if (log)
307             log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %" PRIu64,
308                          __PRETTY_FUNCTION__,
309                          timeout_usec,
310                          Communication::ConnectionStatusAsCString (status),
311                          error.AsCString(),
312                          (uint64_t)bytes_read);
313 
314         if (bytes_read > 0)
315         {
316             if (CheckForPacket (buffer, bytes_read, packet))
317                 return PacketResult::Success;
318         }
319         else
320         {
321             switch (status)
322             {
323             case eConnectionStatusTimedOut:
324             case eConnectionStatusInterrupted:
325                 timed_out = true;
326                 break;
327             case eConnectionStatusSuccess:
328                 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
329                 break;
330 
331             case eConnectionStatusEndOfFile:
332             case eConnectionStatusNoConnection:
333             case eConnectionStatusLostConnection:
334             case eConnectionStatusError:
335                 disconnected = true;
336                 Disconnect();
337                 break;
338             }
339         }
340     }
341     packet.Clear ();
342     if (disconnected)
343         return PacketResult::ErrorDisconnected;
344     if (timed_out)
345         return PacketResult::ErrorReplyTimeout;
346     else
347         return PacketResult::ErrorReplyFailed;
348 }
349 
350 bool
351 GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
352 {
353     // Put the packet data into the buffer in a thread safe fashion
354     Mutex::Locker locker(m_bytes_mutex);
355 
356     Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
357 
358     if (src && src_len > 0)
359     {
360         if (log && log->GetVerbose())
361         {
362             StreamString s;
363             log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
364                          __FUNCTION__,
365                          (uint32_t)src_len,
366                          (uint32_t)src_len,
367                          src);
368         }
369         m_bytes.append ((const char *)src, src_len);
370     }
371 
372     // Parse up the packets into gdb remote packets
373     if (!m_bytes.empty())
374     {
375         // end_idx must be one past the last valid packet byte. Start
376         // it off with an invalid value that is the same as the current
377         // index.
378         size_t content_start = 0;
379         size_t content_length = 0;
380         size_t total_length = 0;
381         size_t checksum_idx = std::string::npos;
382 
383         switch (m_bytes[0])
384         {
385             case '+':       // Look for ack
386             case '-':       // Look for cancel
387             case '\x03':    // ^C to halt target
388                 content_length = total_length = 1;  // The command is one byte long...
389                 break;
390 
391             case '$':
392                 // Look for a standard gdb packet?
393                 {
394                     size_t hash_pos = m_bytes.find('#');
395                     if (hash_pos != std::string::npos)
396                     {
397                         if (hash_pos + 2 < m_bytes.size())
398                         {
399                             checksum_idx = hash_pos + 1;
400                             // Skip the dollar sign
401                             content_start = 1;
402                             // Don't include the # in the content or the $ in the content length
403                             content_length = hash_pos - 1;
404 
405                             total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
406                         }
407                         else
408                         {
409                             // Checksum bytes aren't all here yet
410                             content_length = std::string::npos;
411                         }
412                     }
413                 }
414                 break;
415 
416             default:
417                 {
418                     // We have an unexpected byte and we need to flush all bad
419                     // data that is in m_bytes, so we need to find the first
420                     // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
421                     // or '$' character (start of packet header) or of course,
422                     // the end of the data in m_bytes...
423                     const size_t bytes_len = m_bytes.size();
424                     bool done = false;
425                     uint32_t idx;
426                     for (idx = 1; !done && idx < bytes_len; ++idx)
427                     {
428                         switch (m_bytes[idx])
429                         {
430                         case '+':
431                         case '-':
432                         case '\x03':
433                         case '$':
434                             done = true;
435                             break;
436 
437                         default:
438                             break;
439                         }
440                     }
441                     if (log)
442                         log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
443                                      __FUNCTION__, idx, idx, m_bytes.c_str());
444                     m_bytes.erase(0, idx);
445                 }
446                 break;
447         }
448 
449         if (content_length == std::string::npos)
450         {
451             packet.Clear();
452             return false;
453         }
454         else if (total_length > 0)
455         {
456 
457             // We have a valid packet...
458             assert (content_length <= m_bytes.size());
459             assert (total_length <= m_bytes.size());
460             assert (content_length <= total_length);
461             const size_t content_end = content_start + content_length;
462 
463             bool success = true;
464             std::string &packet_str = packet.GetStringRef();
465 
466 
467             if (log)
468             {
469                 // If logging was just enabled and we have history, then dump out what
470                 // we have to the log so we get the historical context. The Dump() call that
471                 // logs all of the packet will set a boolean so that we don't dump this more
472                 // than once
473                 if (!m_history.DidDumpToLog ())
474                     m_history.Dump (log);
475 
476                 bool binary = false;
477                 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
478                 if (m_bytes[0] == '$' && total_length > 4)
479                 {
480                     for (size_t i=0; !binary && i<total_length; ++i)
481                     {
482                         if (isprint(m_bytes[i]) == 0)
483                             binary = true;
484                     }
485                 }
486                 if (binary)
487                 {
488                     StreamString strm;
489                     // Packet header...
490                     strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
491                     for (size_t i=content_start; i<content_end; ++i)
492                     {
493                         // Remove binary escaped bytes when displaying the packet...
494                         const char ch = m_bytes[i];
495                         if (ch == 0x7d)
496                         {
497                             // 0x7d is the escape character.  The next character is to
498                             // be XOR'd with 0x20.
499                             const char escapee = m_bytes[++i] ^ 0x20;
500                             strm.Printf("%2.2x", escapee);
501                         }
502                         else
503                         {
504                             strm.Printf("%2.2x", (uint8_t)ch);
505                         }
506                     }
507                     // Packet footer...
508                     strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
509                     log->PutCString(strm.GetString().c_str());
510                 }
511                 else
512                 {
513                     log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
514                 }
515             }
516 
517             m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
518 
519             // Clear packet_str in case there is some existing data in it.
520             packet_str.clear();
521             // Copy the packet from m_bytes to packet_str expanding the
522             // run-length encoding in the process.
523             // Reserve enough byte for the most common case (no RLE used)
524             packet_str.reserve(m_bytes.length());
525             for (std::string::const_iterator c = m_bytes.begin() + content_start; c != m_bytes.begin() + content_end; ++c)
526             {
527                 if (*c == '*')
528                 {
529                     // '*' indicates RLE. Next character will give us the
530                     // repeat count and previous character is what is to be
531                     // repeated.
532                     char char_to_repeat = packet_str.back();
533                     // Number of time the previous character is repeated
534                     int repeat_count = *++c + 3 - ' ';
535                     // We have the char_to_repeat and repeat_count. Now push
536                     // it in the packet.
537                     for (int i = 0; i < repeat_count; ++i)
538                         packet_str.push_back(char_to_repeat);
539                 }
540                 else if (*c == 0x7d)
541                 {
542                     // 0x7d is the escape character.  The next character is to
543                     // be XOR'd with 0x20.
544                     char escapee = *++c ^ 0x20;
545                     packet_str.push_back(escapee);
546                 }
547                 else
548                 {
549                     packet_str.push_back(*c);
550                 }
551             }
552 
553             if (m_bytes[0] == '$')
554             {
555                 assert (checksum_idx < m_bytes.size());
556                 if (::isxdigit (m_bytes[checksum_idx+0]) ||
557                     ::isxdigit (m_bytes[checksum_idx+1]))
558                 {
559                     if (GetSendAcks ())
560                     {
561                         const char *packet_checksum_cstr = &m_bytes[checksum_idx];
562                         char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
563                         char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
564                         success = packet_checksum == actual_checksum;
565                         if (!success)
566                         {
567                             if (log)
568                                 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
569                                              (int)(total_length),
570                                              m_bytes.c_str(),
571                                              (uint8_t)packet_checksum,
572                                              (uint8_t)actual_checksum);
573                         }
574                         // Send the ack or nack if needed
575                         if (!success)
576                             SendNack();
577                         else
578                             SendAck();
579                     }
580                 }
581                 else
582                 {
583                     success = false;
584                     if (log)
585                         log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
586                 }
587             }
588 
589             m_bytes.erase(0, total_length);
590             packet.SetFilePos(0);
591             return success;
592         }
593     }
594     packet.Clear();
595     return false;
596 }
597 
598 Error
599 GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
600 {
601     Error error;
602     if (IS_VALID_LLDB_HOST_THREAD(m_listen_thread))
603     {
604         error.SetErrorString("listen thread already running");
605     }
606     else
607     {
608         char listen_url[512];
609         if (hostname && hostname[0])
610             snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
611         else
612             snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
613         m_listen_url = listen_url;
614         SetConnection(new ConnectionFileDescriptor());
615         m_listen_thread = Host::ThreadCreate (listen_url, GDBRemoteCommunication::ListenThread, this, &error);
616     }
617     return error;
618 }
619 
620 bool
621 GDBRemoteCommunication::JoinListenThread ()
622 {
623     if (IS_VALID_LLDB_HOST_THREAD(m_listen_thread))
624     {
625         Host::ThreadJoin(m_listen_thread, NULL, NULL);
626         m_listen_thread = LLDB_INVALID_HOST_THREAD;
627     }
628     return true;
629 }
630 
631 lldb::thread_result_t
632 GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
633 {
634     GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
635     Error error;
636     ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
637 
638     if (connection)
639     {
640         // Do the listen on another thread so we can continue on...
641         if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
642             comm->SetConnection(NULL);
643     }
644     return NULL;
645 }
646 
647 Error
648 GDBRemoteCommunication::StartDebugserverProcess (const char *hostname,
649                                                  uint16_t in_port,
650                                                  lldb_private::ProcessLaunchInfo &launch_info,
651                                                  uint16_t &out_port)
652 {
653     out_port = in_port;
654     Error error;
655     // If we locate debugserver, keep that located version around
656     static FileSpec g_debugserver_file_spec;
657 
658     char debugserver_path[PATH_MAX];
659     FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
660 
661     // Always check to see if we have an environment override for the path
662     // to the debugserver to use and use it if we do.
663     const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
664     if (env_debugserver_path)
665         debugserver_file_spec.SetFile (env_debugserver_path, false);
666     else
667         debugserver_file_spec = g_debugserver_file_spec;
668     bool debugserver_exists = debugserver_file_spec.Exists();
669     if (!debugserver_exists)
670     {
671         // The debugserver binary is in the LLDB.framework/Resources
672         // directory.
673         if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
674         {
675             debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
676             debugserver_exists = debugserver_file_spec.Exists();
677             if (debugserver_exists)
678             {
679                 g_debugserver_file_spec = debugserver_file_spec;
680             }
681             else
682             {
683                 g_debugserver_file_spec.Clear();
684                 debugserver_file_spec.Clear();
685             }
686         }
687     }
688 
689     if (debugserver_exists)
690     {
691         debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
692 
693         Args &debugserver_args = launch_info.GetArguments();
694         debugserver_args.Clear();
695         char arg_cstr[PATH_MAX];
696 
697         // Start args with "debugserver /file/path -r --"
698         debugserver_args.AppendArgument(debugserver_path);
699 
700         // If a host and port is supplied then use it
701         char host_and_port[128];
702         if (hostname)
703         {
704             snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port);
705             debugserver_args.AppendArgument(host_and_port);
706         }
707         else
708         {
709             host_and_port[0] = '\0';
710         }
711 
712         // use native registers, not the GDB registers
713         debugserver_args.AppendArgument("--native-regs");
714         // make debugserver run in its own session so signals generated by
715         // special terminal key sequences (^C) don't affect debugserver
716         debugserver_args.AppendArgument("--setsid");
717 
718         char named_pipe_path[PATH_MAX];
719         named_pipe_path[0] = '\0';
720 
721         bool listen = false;
722         if (host_and_port[0])
723         {
724             // Create a temporary file to get the stdout/stderr and redirect the
725             // output of the command into this file. We will later read this file
726             // if all goes well and fill the data into "command_output_ptr"
727 
728             if (in_port == 0)
729             {
730                 // Binding to port zero, we need to figure out what port it ends up
731                 // using using a named pipe...
732                 FileSpec tmpdir_file_spec;
733                 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
734                 {
735                     tmpdir_file_spec.GetFilename().SetCString("debugserver-named-pipe.XXXXXX");
736                     strncpy(named_pipe_path, tmpdir_file_spec.GetPath().c_str(), sizeof(named_pipe_path));
737                 }
738                 else
739                 {
740                     strncpy(named_pipe_path, "/tmp/debugserver-named-pipe.XXXXXX", sizeof(named_pipe_path));
741                 }
742 
743                 if (::mktemp (named_pipe_path))
744                 {
745 #if defined(_WIN32)
746                     if ( false )
747 #else
748                     if (::mkfifo(named_pipe_path, 0600) == 0)
749 #endif
750                     {
751                         debugserver_args.AppendArgument("--named-pipe");
752                         debugserver_args.AppendArgument(named_pipe_path);
753                     }
754                 }
755             }
756             else
757             {
758                 listen = true;
759             }
760         }
761         else
762         {
763             // No host and port given, so lets listen on our end and make the debugserver
764             // connect to us..
765             error = StartListenThread ("127.0.0.1", 0);
766             if (error.Fail())
767                 return error;
768 
769             ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
770             // Wait for 10 seconds to resolve the bound port
771             out_port = connection->GetBoundPort(10);
772             if (out_port > 0)
773             {
774                 char port_cstr[32];
775                 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", out_port);
776                 // Send the host and port down that debugserver and specify an option
777                 // so that it connects back to the port we are listening to in this process
778                 debugserver_args.AppendArgument("--reverse-connect");
779                 debugserver_args.AppendArgument(port_cstr);
780             }
781             else
782             {
783                 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
784                 return error;
785             }
786         }
787 
788 
789         const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
790         if (env_debugserver_log_file)
791         {
792             ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
793             debugserver_args.AppendArgument(arg_cstr);
794         }
795 
796         const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
797         if (env_debugserver_log_flags)
798         {
799             ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
800             debugserver_args.AppendArgument(arg_cstr);
801         }
802 
803         // Close STDIN, STDOUT and STDERR. We might need to redirect them
804         // to "/dev/null" if we run into any problems.
805         launch_info.AppendCloseFileAction (STDIN_FILENO);
806         launch_info.AppendCloseFileAction (STDOUT_FILENO);
807         launch_info.AppendCloseFileAction (STDERR_FILENO);
808 
809         error = Host::LaunchProcess(launch_info);
810 
811         if (error.Success() && launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
812         {
813             if (named_pipe_path[0])
814             {
815                 File name_pipe_file;
816                 error = name_pipe_file.Open(named_pipe_path, File::eOpenOptionRead);
817                 if (error.Success())
818                 {
819                     char port_cstr[256];
820                     port_cstr[0] = '\0';
821                     size_t num_bytes = sizeof(port_cstr);
822                     error = name_pipe_file.Read(port_cstr, num_bytes);
823                     assert (error.Success());
824                     assert (num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
825                     out_port = Args::StringToUInt32(port_cstr, 0);
826                     name_pipe_file.Close();
827                 }
828                 Host::Unlink(named_pipe_path);
829             }
830             else if (listen)
831             {
832 
833             }
834             else
835             {
836                 // Make sure we actually connect with the debugserver...
837                 JoinListenThread();
838             }
839         }
840     }
841     else
842     {
843         error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
844     }
845     return error;
846 }
847 
848 void
849 GDBRemoteCommunication::DumpHistory(Stream &strm)
850 {
851     m_history.Dump (strm);
852 }
853