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