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 #include "GDBRemoteCommunication.h"
11 
12 #include <limits.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 
16 #include "lldb/Core/StreamFile.h"
17 #include "lldb/Host/ConnectionFileDescriptor.h"
18 #include "lldb/Host/FileSystem.h"
19 #include "lldb/Host/Host.h"
20 #include "lldb/Host/HostInfo.h"
21 #include "lldb/Host/Pipe.h"
22 #include "lldb/Host/Socket.h"
23 #include "lldb/Host/StringConvert.h"
24 #include "lldb/Host/ThreadLauncher.h"
25 #include "lldb/Target/Platform.h"
26 #include "lldb/Target/Process.h"
27 #include "lldb/Utility/FileSpec.h"
28 #include "lldb/Utility/Log.h"
29 #include "lldb/Utility/RegularExpression.h"
30 #include "lldb/Utility/StreamString.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/Support/ScopedPrinter.h"
33 
34 #include "ProcessGDBRemoteLog.h"
35 
36 #if defined(__APPLE__)
37 #define DEBUGSERVER_BASENAME "debugserver"
38 #else
39 #define DEBUGSERVER_BASENAME "lldb-server"
40 #endif
41 
42 #if defined(HAVE_LIBCOMPRESSION)
43 #include <compression.h>
44 #endif
45 
46 #if defined(HAVE_LIBZ)
47 #include <zlib.h>
48 #endif
49 
50 using namespace lldb;
51 using namespace lldb_private;
52 using namespace lldb_private::process_gdb_remote;
53 
54 GDBRemoteCommunication::History::History(uint32_t size)
55     : m_packets(), m_curr_idx(0), m_total_packet_count(0),
56       m_dumped_to_log(false) {
57   m_packets.resize(size);
58 }
59 
60 GDBRemoteCommunication::History::~History() {}
61 
62 void GDBRemoteCommunication::History::AddPacket(char packet_char,
63                                                 PacketType type,
64                                                 uint32_t bytes_transmitted) {
65   const size_t size = m_packets.size();
66   if (size > 0) {
67     const uint32_t idx = GetNextIndex();
68     m_packets[idx].packet.assign(1, packet_char);
69     m_packets[idx].type = type;
70     m_packets[idx].bytes_transmitted = bytes_transmitted;
71     m_packets[idx].packet_idx = m_total_packet_count;
72     m_packets[idx].tid = llvm::get_threadid();
73   }
74 }
75 
76 void GDBRemoteCommunication::History::AddPacket(const std::string &src,
77                                                 uint32_t src_len,
78                                                 PacketType type,
79                                                 uint32_t bytes_transmitted) {
80   const size_t size = m_packets.size();
81   if (size > 0) {
82     const uint32_t idx = GetNextIndex();
83     m_packets[idx].packet.assign(src, 0, src_len);
84     m_packets[idx].type = type;
85     m_packets[idx].bytes_transmitted = bytes_transmitted;
86     m_packets[idx].packet_idx = m_total_packet_count;
87     m_packets[idx].tid = llvm::get_threadid();
88   }
89 }
90 
91 void GDBRemoteCommunication::History::Dump(Stream &strm) const {
92   const uint32_t size = GetNumPacketsInHistory();
93   const uint32_t first_idx = GetFirstSavedPacketIndex();
94   const uint32_t stop_idx = m_curr_idx + size;
95   for (uint32_t i = first_idx; i < stop_idx; ++i) {
96     const uint32_t idx = NormalizeIndex(i);
97     const Entry &entry = m_packets[idx];
98     if (entry.type == ePacketTypeInvalid || entry.packet.empty())
99       break;
100     strm.Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
101                 entry.packet_idx, entry.tid, entry.bytes_transmitted,
102                 (entry.type == ePacketTypeSend) ? "send" : "read",
103                 entry.packet.c_str());
104   }
105 }
106 
107 void GDBRemoteCommunication::History::Dump(Log *log) const {
108   if (log && !m_dumped_to_log) {
109     m_dumped_to_log = true;
110     const uint32_t size = GetNumPacketsInHistory();
111     const uint32_t first_idx = GetFirstSavedPacketIndex();
112     const uint32_t stop_idx = m_curr_idx + size;
113     for (uint32_t i = first_idx; i < stop_idx; ++i) {
114       const uint32_t idx = NormalizeIndex(i);
115       const Entry &entry = m_packets[idx];
116       if (entry.type == ePacketTypeInvalid || entry.packet.empty())
117         break;
118       log->Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
119                   entry.packet_idx, entry.tid, entry.bytes_transmitted,
120                   (entry.type == ePacketTypeSend) ? "send" : "read",
121                   entry.packet.c_str());
122     }
123   }
124 }
125 
126 //----------------------------------------------------------------------
127 // GDBRemoteCommunication constructor
128 //----------------------------------------------------------------------
129 GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
130                                                const char *listener_name)
131     : Communication(comm_name),
132 #ifdef LLDB_CONFIGURATION_DEBUG
133       m_packet_timeout(1000),
134 #else
135       m_packet_timeout(1),
136 #endif
137       m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
138       m_send_acks(true), m_compression_type(CompressionType::None),
139       m_listen_url() {
140 }
141 
142 //----------------------------------------------------------------------
143 // Destructor
144 //----------------------------------------------------------------------
145 GDBRemoteCommunication::~GDBRemoteCommunication() {
146   if (IsConnected()) {
147     Disconnect();
148   }
149 
150   // Stop the communications read thread which is used to parse all incoming
151   // packets.  This function will block until the read thread returns.
152   if (m_read_thread_enabled)
153     StopReadThread();
154 }
155 
156 char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
157   int checksum = 0;
158 
159   for (char c : payload)
160     checksum += c;
161 
162   return checksum & 255;
163 }
164 
165 size_t GDBRemoteCommunication::SendAck() {
166   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
167   ConnectionStatus status = eConnectionStatusSuccess;
168   char ch = '+';
169   const size_t bytes_written = Write(&ch, 1, status, NULL);
170   if (log)
171     log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
172   m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
173   return bytes_written;
174 }
175 
176 size_t GDBRemoteCommunication::SendNack() {
177   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
178   ConnectionStatus status = eConnectionStatusSuccess;
179   char ch = '-';
180   const size_t bytes_written = Write(&ch, 1, status, NULL);
181   if (log)
182     log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
183   m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
184   return bytes_written;
185 }
186 
187 GDBRemoteCommunication::PacketResult
188 GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
189   if (IsConnected()) {
190     StreamString packet(0, 4, eByteOrderBig);
191 
192     packet.PutChar('$');
193     packet.Write(payload.data(), payload.size());
194     packet.PutChar('#');
195     packet.PutHex8(CalculcateChecksum(payload));
196 
197     Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
198     ConnectionStatus status = eConnectionStatusSuccess;
199     // TODO: Don't shimmy through a std::string, just use StringRef.
200     std::string packet_str = packet.GetString();
201     const char *packet_data = packet_str.c_str();
202     const size_t packet_length = packet.GetSize();
203     size_t bytes_written = Write(packet_data, packet_length, status, NULL);
204     if (log) {
205       size_t binary_start_offset = 0;
206       if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
207           0) {
208         const char *first_comma = strchr(packet_data, ',');
209         if (first_comma) {
210           const char *second_comma = strchr(first_comma + 1, ',');
211           if (second_comma)
212             binary_start_offset = second_comma - packet_data + 1;
213         }
214       }
215 
216       // If logging was just enabled and we have history, then dump out what we
217       // have to the log so we get the historical context. The Dump() call that
218       // logs all of the packet will set a boolean so that we don't dump this
219       // more than once
220       if (!m_history.DidDumpToLog())
221         m_history.Dump(log);
222 
223       if (binary_start_offset) {
224         StreamString strm;
225         // Print non binary data header
226         strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
227                     (int)binary_start_offset, packet_data);
228         const uint8_t *p;
229         // Print binary data exactly as sent
230         for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
231              ++p)
232           strm.Printf("\\x%2.2x", *p);
233         // Print the checksum
234         strm.Printf("%*s", (int)3, p);
235         log->PutString(strm.GetString());
236       } else
237         log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
238                     (int)packet_length, packet_data);
239     }
240 
241     m_history.AddPacket(packet.GetString(), packet_length,
242                         History::ePacketTypeSend, bytes_written);
243 
244     if (bytes_written == packet_length) {
245       if (GetSendAcks())
246         return GetAck();
247       else
248         return PacketResult::Success;
249     } else {
250       if (log)
251         log->Printf("error: failed to send packet: %.*s", (int)packet_length,
252                     packet_data);
253     }
254   }
255   return PacketResult::ErrorSendFailed;
256 }
257 
258 GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
259   StringExtractorGDBRemote packet;
260   PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
261   if (result == PacketResult::Success) {
262     if (packet.GetResponseType() ==
263         StringExtractorGDBRemote::ResponseType::eAck)
264       return PacketResult::Success;
265     else
266       return PacketResult::ErrorSendAck;
267   }
268   return result;
269 }
270 
271 GDBRemoteCommunication::PacketResult
272 GDBRemoteCommunication::ReadPacketWithOutputSupport(
273     StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
274     bool sync_on_timeout,
275     llvm::function_ref<void(llvm::StringRef)> output_callback) {
276   auto result = ReadPacket(response, timeout, sync_on_timeout);
277   while (result == PacketResult::Success && response.IsNormalResponse() &&
278          response.PeekChar() == 'O') {
279     response.GetChar();
280     std::string output;
281     if (response.GetHexByteString(output))
282       output_callback(output);
283     result = ReadPacket(response, timeout, sync_on_timeout);
284   }
285   return result;
286 }
287 
288 GDBRemoteCommunication::PacketResult
289 GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
290                                    Timeout<std::micro> timeout,
291                                    bool sync_on_timeout) {
292   if (m_read_thread_enabled)
293     return PopPacketFromQueue(response, timeout);
294   else
295     return WaitForPacketNoLock(response, timeout, sync_on_timeout);
296 }
297 
298 // This function is called when a packet is requested.
299 // A whole packet is popped from the packet queue and returned to the caller.
300 // Packets are placed into this queue from the communication read thread. See
301 // GDBRemoteCommunication::AppendBytesToCache.
302 GDBRemoteCommunication::PacketResult
303 GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
304                                            Timeout<std::micro> timeout) {
305   auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
306   // lock down the packet queue
307   std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
308 
309   if (!timeout)
310     m_condition_queue_not_empty.wait(lock, pred);
311   else {
312     if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
313       return PacketResult::ErrorReplyTimeout;
314     if (!IsConnected())
315       return PacketResult::ErrorDisconnected;
316   }
317 
318   // get the front element of the queue
319   response = m_packet_queue.front();
320 
321   // remove the front element
322   m_packet_queue.pop();
323 
324   // we got a packet
325   return PacketResult::Success;
326 }
327 
328 GDBRemoteCommunication::PacketResult
329 GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
330                                             Timeout<std::micro> timeout,
331                                             bool sync_on_timeout) {
332   uint8_t buffer[8192];
333   Status error;
334 
335   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
336 
337   // Check for a packet from our cache first without trying any reading...
338   if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
339     return PacketResult::Success;
340 
341   bool timed_out = false;
342   bool disconnected = false;
343   while (IsConnected() && !timed_out) {
344     lldb::ConnectionStatus status = eConnectionStatusNoConnection;
345     size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
346 
347     LLDB_LOGV(log,
348               "Read(buffer, sizeof(buffer), timeout = {0}, "
349               "status = {1}, error = {2}) => bytes_read = {3}",
350               timeout, Communication::ConnectionStatusAsCString(status), error,
351               bytes_read);
352 
353     if (bytes_read > 0) {
354       if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
355         return PacketResult::Success;
356     } else {
357       switch (status) {
358       case eConnectionStatusTimedOut:
359       case eConnectionStatusInterrupted:
360         if (sync_on_timeout) {
361           //------------------------------------------------------------------
362           /// Sync the remote GDB server and make sure we get a response that
363           /// corresponds to what we send.
364           ///
365           /// Sends a "qEcho" packet and makes sure it gets the exact packet
366           /// echoed back. If the qEcho packet isn't supported, we send a qC
367           /// packet and make sure we get a valid thread ID back. We use the
368           /// "qC" packet since its response if very unique: is responds with
369           /// "QC%x" where %x is the thread ID of the current thread. This
370           /// makes the response unique enough from other packet responses to
371           /// ensure we are back on track.
372           ///
373           /// This packet is needed after we time out sending a packet so we
374           /// can ensure that we are getting the response for the packet we
375           /// are sending. There are no sequence IDs in the GDB remote
376           /// protocol (there used to be, but they are not supported anymore)
377           /// so if you timeout sending packet "abc", you might then send
378           /// packet "cde" and get the response for the previous "abc" packet.
379           /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
380           /// many responses for packets can look like responses for other
381           /// packets. So if we timeout, we need to ensure that we can get
382           /// back on track. If we can't get back on track, we must
383           /// disconnect.
384           //------------------------------------------------------------------
385           bool sync_success = false;
386           bool got_actual_response = false;
387           // We timed out, we need to sync back up with the
388           char echo_packet[32];
389           int echo_packet_len = 0;
390           RegularExpression response_regex;
391 
392           if (m_supports_qEcho == eLazyBoolYes) {
393             echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
394                                          "qEcho:%u", ++m_echo_number);
395             std::string regex_str = "^";
396             regex_str += echo_packet;
397             regex_str += "$";
398             response_regex.Compile(regex_str);
399           } else {
400             echo_packet_len =
401                 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
402             response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
403           }
404 
405           PacketResult echo_packet_result =
406               SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
407           if (echo_packet_result == PacketResult::Success) {
408             const uint32_t max_retries = 3;
409             uint32_t successful_responses = 0;
410             for (uint32_t i = 0; i < max_retries; ++i) {
411               StringExtractorGDBRemote echo_response;
412               echo_packet_result =
413                   WaitForPacketNoLock(echo_response, timeout, false);
414               if (echo_packet_result == PacketResult::Success) {
415                 ++successful_responses;
416                 if (response_regex.Execute(echo_response.GetStringRef())) {
417                   sync_success = true;
418                   break;
419                 } else if (successful_responses == 1) {
420                   // We got something else back as the first successful
421                   // response, it probably is the  response to the packet we
422                   // actually wanted, so copy it over if this is the first
423                   // success and continue to try to get the qEcho response
424                   packet = echo_response;
425                   got_actual_response = true;
426                 }
427               } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
428                 continue; // Packet timed out, continue waiting for a response
429               else
430                 break; // Something else went wrong getting the packet back, we
431                        // failed and are done trying
432             }
433           }
434 
435           // We weren't able to sync back up with the server, we must abort
436           // otherwise all responses might not be from the right packets...
437           if (sync_success) {
438             // We timed out, but were able to recover
439             if (got_actual_response) {
440               // We initially timed out, but we did get a response that came in
441               // before the successful reply to our qEcho packet, so lets say
442               // everything is fine...
443               return PacketResult::Success;
444             }
445           } else {
446             disconnected = true;
447             Disconnect();
448           }
449         }
450         timed_out = true;
451         break;
452       case eConnectionStatusSuccess:
453         // printf ("status = success but error = %s\n",
454         // error.AsCString("<invalid>"));
455         break;
456 
457       case eConnectionStatusEndOfFile:
458       case eConnectionStatusNoConnection:
459       case eConnectionStatusLostConnection:
460       case eConnectionStatusError:
461         disconnected = true;
462         Disconnect();
463         break;
464       }
465     }
466   }
467   packet.Clear();
468   if (disconnected)
469     return PacketResult::ErrorDisconnected;
470   if (timed_out)
471     return PacketResult::ErrorReplyTimeout;
472   else
473     return PacketResult::ErrorReplyFailed;
474 }
475 
476 bool GDBRemoteCommunication::DecompressPacket() {
477   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
478 
479   if (!CompressionIsEnabled())
480     return true;
481 
482   size_t pkt_size = m_bytes.size();
483 
484   // Smallest possible compressed packet is $N#00 - an uncompressed empty
485   // reply, most commonly indicating an unsupported packet.  Anything less than
486   // 5 characters, it's definitely not a compressed packet.
487   if (pkt_size < 5)
488     return true;
489 
490   if (m_bytes[0] != '$' && m_bytes[0] != '%')
491     return true;
492   if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
493     return true;
494 
495   size_t hash_mark_idx = m_bytes.find('#');
496   if (hash_mark_idx == std::string::npos)
497     return true;
498   if (hash_mark_idx + 2 >= m_bytes.size())
499     return true;
500 
501   if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
502       !::isxdigit(m_bytes[hash_mark_idx + 2]))
503     return true;
504 
505   size_t content_length =
506       pkt_size -
507       5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
508   size_t content_start = 2; // The first character of the
509                             // compressed/not-compressed text of the packet
510   size_t checksum_idx =
511       hash_mark_idx +
512       1; // The first character of the two hex checksum characters
513 
514   // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
515   // multiple packets. size_of_first_packet is the size of the initial packet
516   // which we'll replace with the decompressed version of, leaving the rest of
517   // m_bytes unmodified.
518   size_t size_of_first_packet = hash_mark_idx + 3;
519 
520   // Compressed packets ("$C") start with a base10 number which is the size of
521   // the uncompressed payload, then a : and then the compressed data.  e.g.
522   // $C1024:<binary>#00 Update content_start and content_length to only include
523   // the <binary> part of the packet.
524 
525   uint64_t decompressed_bufsize = ULONG_MAX;
526   if (m_bytes[1] == 'C') {
527     size_t i = content_start;
528     while (i < hash_mark_idx && isdigit(m_bytes[i]))
529       i++;
530     if (i < hash_mark_idx && m_bytes[i] == ':') {
531       i++;
532       content_start = i;
533       content_length = hash_mark_idx - content_start;
534       std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
535       errno = 0;
536       decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
537       if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
538         m_bytes.erase(0, size_of_first_packet);
539         return false;
540       }
541     }
542   }
543 
544   if (GetSendAcks()) {
545     char packet_checksum_cstr[3];
546     packet_checksum_cstr[0] = m_bytes[checksum_idx];
547     packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
548     packet_checksum_cstr[2] = '\0';
549     long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
550 
551     long actual_checksum = CalculcateChecksum(
552         llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
553     bool success = packet_checksum == actual_checksum;
554     if (!success) {
555       if (log)
556         log->Printf(
557             "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
558             (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
559             (uint8_t)actual_checksum);
560     }
561     // Send the ack or nack if needed
562     if (!success) {
563       SendNack();
564       m_bytes.erase(0, size_of_first_packet);
565       return false;
566     } else {
567       SendAck();
568     }
569   }
570 
571   if (m_bytes[1] == 'N') {
572     // This packet was not compressed -- delete the 'N' character at the start
573     // and the packet may be processed as-is.
574     m_bytes.erase(1, 1);
575     return true;
576   }
577 
578   // Reverse the gdb-remote binary escaping that was done to the compressed
579   // text to guard characters like '$', '#', '}', etc.
580   std::vector<uint8_t> unescaped_content;
581   unescaped_content.reserve(content_length);
582   size_t i = content_start;
583   while (i < hash_mark_idx) {
584     if (m_bytes[i] == '}') {
585       i++;
586       unescaped_content.push_back(m_bytes[i] ^ 0x20);
587     } else {
588       unescaped_content.push_back(m_bytes[i]);
589     }
590     i++;
591   }
592 
593   uint8_t *decompressed_buffer = nullptr;
594   size_t decompressed_bytes = 0;
595 
596   if (decompressed_bufsize != ULONG_MAX) {
597     decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1);
598     if (decompressed_buffer == nullptr) {
599       m_bytes.erase(0, size_of_first_packet);
600       return false;
601     }
602   }
603 
604 #if defined(HAVE_LIBCOMPRESSION)
605   // libcompression is weak linked so check that compression_decode_buffer() is
606   // available
607   if (m_compression_type == CompressionType::ZlibDeflate ||
608       m_compression_type == CompressionType::LZFSE ||
609       m_compression_type == CompressionType::LZ4) {
610     compression_algorithm compression_type;
611     if (m_compression_type == CompressionType::LZFSE)
612       compression_type = COMPRESSION_LZFSE;
613     else if (m_compression_type == CompressionType::ZlibDeflate)
614       compression_type = COMPRESSION_ZLIB;
615     else if (m_compression_type == CompressionType::LZ4)
616       compression_type = COMPRESSION_LZ4_RAW;
617     else if (m_compression_type == CompressionType::LZMA)
618       compression_type = COMPRESSION_LZMA;
619 
620     // If we have the expected size of the decompressed payload, we can
621     // allocate the right-sized buffer and do it.  If we don't have that
622     // information, we'll need to try decoding into a big buffer and if the
623     // buffer wasn't big enough, increase it and try again.
624 
625     if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
626       decompressed_bytes = compression_decode_buffer(
627           decompressed_buffer, decompressed_bufsize + 10,
628           (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL,
629           compression_type);
630     }
631   }
632 #endif
633 
634 #if defined(HAVE_LIBZ)
635   if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
636       decompressed_buffer != nullptr &&
637       m_compression_type == CompressionType::ZlibDeflate) {
638     z_stream stream;
639     memset(&stream, 0, sizeof(z_stream));
640     stream.next_in = (Bytef *)unescaped_content.data();
641     stream.avail_in = (uInt)unescaped_content.size();
642     stream.total_in = 0;
643     stream.next_out = (Bytef *)decompressed_buffer;
644     stream.avail_out = decompressed_bufsize;
645     stream.total_out = 0;
646     stream.zalloc = Z_NULL;
647     stream.zfree = Z_NULL;
648     stream.opaque = Z_NULL;
649 
650     if (inflateInit2(&stream, -15) == Z_OK) {
651       int status = inflate(&stream, Z_NO_FLUSH);
652       inflateEnd(&stream);
653       if (status == Z_STREAM_END) {
654         decompressed_bytes = stream.total_out;
655       }
656     }
657   }
658 #endif
659 
660   if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
661     if (decompressed_buffer)
662       free(decompressed_buffer);
663     m_bytes.erase(0, size_of_first_packet);
664     return false;
665   }
666 
667   std::string new_packet;
668   new_packet.reserve(decompressed_bytes + 6);
669   new_packet.push_back(m_bytes[0]);
670   new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
671   new_packet.push_back('#');
672   if (GetSendAcks()) {
673     uint8_t decompressed_checksum = CalculcateChecksum(
674         llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
675     char decompressed_checksum_str[3];
676     snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
677     new_packet.append(decompressed_checksum_str);
678   } else {
679     new_packet.push_back('0');
680     new_packet.push_back('0');
681   }
682 
683   m_bytes.replace(0, size_of_first_packet, new_packet.data(),
684                   new_packet.size());
685 
686   free(decompressed_buffer);
687   return true;
688 }
689 
690 GDBRemoteCommunication::PacketType
691 GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
692                                        StringExtractorGDBRemote &packet) {
693   // Put the packet data into the buffer in a thread safe fashion
694   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
695 
696   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
697 
698   if (src && src_len > 0) {
699     if (log && log->GetVerbose()) {
700       StreamString s;
701       log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
702                   __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
703     }
704     m_bytes.append((const char *)src, src_len);
705   }
706 
707   bool isNotifyPacket = false;
708 
709   // Parse up the packets into gdb remote packets
710   if (!m_bytes.empty()) {
711     // end_idx must be one past the last valid packet byte. Start it off with
712     // an invalid value that is the same as the current index.
713     size_t content_start = 0;
714     size_t content_length = 0;
715     size_t total_length = 0;
716     size_t checksum_idx = std::string::npos;
717 
718     // Size of packet before it is decompressed, for logging purposes
719     size_t original_packet_size = m_bytes.size();
720     if (CompressionIsEnabled()) {
721       if (DecompressPacket() == false) {
722         packet.Clear();
723         return GDBRemoteCommunication::PacketType::Standard;
724       }
725     }
726 
727     switch (m_bytes[0]) {
728     case '+':                            // Look for ack
729     case '-':                            // Look for cancel
730     case '\x03':                         // ^C to halt target
731       content_length = total_length = 1; // The command is one byte long...
732       break;
733 
734     case '%': // Async notify packet
735       isNotifyPacket = true;
736       LLVM_FALLTHROUGH;
737 
738     case '$':
739       // Look for a standard gdb packet?
740       {
741         size_t hash_pos = m_bytes.find('#');
742         if (hash_pos != std::string::npos) {
743           if (hash_pos + 2 < m_bytes.size()) {
744             checksum_idx = hash_pos + 1;
745             // Skip the dollar sign
746             content_start = 1;
747             // Don't include the # in the content or the $ in the content
748             // length
749             content_length = hash_pos - 1;
750 
751             total_length =
752                 hash_pos + 3; // Skip the # and the two hex checksum bytes
753           } else {
754             // Checksum bytes aren't all here yet
755             content_length = std::string::npos;
756           }
757         }
758       }
759       break;
760 
761     default: {
762       // We have an unexpected byte and we need to flush all bad data that is
763       // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
764       // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
765       // header) or of course, the end of the data in m_bytes...
766       const size_t bytes_len = m_bytes.size();
767       bool done = false;
768       uint32_t idx;
769       for (idx = 1; !done && idx < bytes_len; ++idx) {
770         switch (m_bytes[idx]) {
771         case '+':
772         case '-':
773         case '\x03':
774         case '%':
775         case '$':
776           done = true;
777           break;
778 
779         default:
780           break;
781         }
782       }
783       if (log)
784         log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
785                     __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
786       m_bytes.erase(0, idx - 1);
787     } break;
788     }
789 
790     if (content_length == std::string::npos) {
791       packet.Clear();
792       return GDBRemoteCommunication::PacketType::Invalid;
793     } else if (total_length > 0) {
794 
795       // We have a valid packet...
796       assert(content_length <= m_bytes.size());
797       assert(total_length <= m_bytes.size());
798       assert(content_length <= total_length);
799       size_t content_end = content_start + content_length;
800 
801       bool success = true;
802       std::string &packet_str = packet.GetStringRef();
803       if (log) {
804         // If logging was just enabled and we have history, then dump out what
805         // we have to the log so we get the historical context. The Dump() call
806         // that logs all of the packet will set a boolean so that we don't dump
807         // this more than once
808         if (!m_history.DidDumpToLog())
809           m_history.Dump(log);
810 
811         bool binary = false;
812         // Only detect binary for packets that start with a '$' and have a
813         // '#CC' checksum
814         if (m_bytes[0] == '$' && total_length > 4) {
815           for (size_t i = 0; !binary && i < total_length; ++i) {
816             unsigned char c = m_bytes[i];
817             if (isprint(c) == 0 && isspace(c) == 0) {
818               binary = true;
819             }
820           }
821         }
822         if (binary) {
823           StreamString strm;
824           // Packet header...
825           if (CompressionIsEnabled())
826             strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
827                         (uint64_t)original_packet_size, (uint64_t)total_length,
828                         m_bytes[0]);
829           else
830             strm.Printf("<%4" PRIu64 "> read packet: %c",
831                         (uint64_t)total_length, m_bytes[0]);
832           for (size_t i = content_start; i < content_end; ++i) {
833             // Remove binary escaped bytes when displaying the packet...
834             const char ch = m_bytes[i];
835             if (ch == 0x7d) {
836               // 0x7d is the escape character.  The next character is to be
837               // XOR'd with 0x20.
838               const char escapee = m_bytes[++i] ^ 0x20;
839               strm.Printf("%2.2x", escapee);
840             } else {
841               strm.Printf("%2.2x", (uint8_t)ch);
842             }
843           }
844           // Packet footer...
845           strm.Printf("%c%c%c", m_bytes[total_length - 3],
846                       m_bytes[total_length - 2], m_bytes[total_length - 1]);
847           log->PutString(strm.GetString());
848         } else {
849           if (CompressionIsEnabled())
850             log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
851                         (uint64_t)original_packet_size, (uint64_t)total_length,
852                         (int)(total_length), m_bytes.c_str());
853           else
854             log->Printf("<%4" PRIu64 "> read packet: %.*s",
855                         (uint64_t)total_length, (int)(total_length),
856                         m_bytes.c_str());
857         }
858       }
859 
860       m_history.AddPacket(m_bytes, total_length, History::ePacketTypeRecv,
861                           total_length);
862 
863       // Clear packet_str in case there is some existing data in it.
864       packet_str.clear();
865       // Copy the packet from m_bytes to packet_str expanding the run-length
866       // encoding in the process. Reserve enough byte for the most common case
867       // (no RLE used)
868       packet_str.reserve(m_bytes.length());
869       for (std::string::const_iterator c = m_bytes.begin() + content_start;
870            c != m_bytes.begin() + content_end; ++c) {
871         if (*c == '*') {
872           // '*' indicates RLE. Next character will give us the repeat count
873           // and previous character is what is to be repeated.
874           char char_to_repeat = packet_str.back();
875           // Number of time the previous character is repeated
876           int repeat_count = *++c + 3 - ' ';
877           // We have the char_to_repeat and repeat_count. Now push it in the
878           // packet.
879           for (int i = 0; i < repeat_count; ++i)
880             packet_str.push_back(char_to_repeat);
881         } else if (*c == 0x7d) {
882           // 0x7d is the escape character.  The next character is to be XOR'd
883           // with 0x20.
884           char escapee = *++c ^ 0x20;
885           packet_str.push_back(escapee);
886         } else {
887           packet_str.push_back(*c);
888         }
889       }
890 
891       if (m_bytes[0] == '$' || m_bytes[0] == '%') {
892         assert(checksum_idx < m_bytes.size());
893         if (::isxdigit(m_bytes[checksum_idx + 0]) ||
894             ::isxdigit(m_bytes[checksum_idx + 1])) {
895           if (GetSendAcks()) {
896             const char *packet_checksum_cstr = &m_bytes[checksum_idx];
897             char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
898             char actual_checksum = CalculcateChecksum(
899                 llvm::StringRef(m_bytes).slice(content_start, content_end));
900             success = packet_checksum == actual_checksum;
901             if (!success) {
902               if (log)
903                 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
904                             "got 0x%2.2x",
905                             (int)(total_length), m_bytes.c_str(),
906                             (uint8_t)packet_checksum, (uint8_t)actual_checksum);
907             }
908             // Send the ack or nack if needed
909             if (!success)
910               SendNack();
911             else
912               SendAck();
913           }
914         } else {
915           success = false;
916           if (log)
917             log->Printf("error: invalid checksum in packet: '%s'\n",
918                         m_bytes.c_str());
919         }
920       }
921 
922       m_bytes.erase(0, total_length);
923       packet.SetFilePos(0);
924 
925       if (isNotifyPacket)
926         return GDBRemoteCommunication::PacketType::Notify;
927       else
928         return GDBRemoteCommunication::PacketType::Standard;
929     }
930   }
931   packet.Clear();
932   return GDBRemoteCommunication::PacketType::Invalid;
933 }
934 
935 Status GDBRemoteCommunication::StartListenThread(const char *hostname,
936                                                  uint16_t port) {
937   Status error;
938   if (m_listen_thread.IsJoinable()) {
939     error.SetErrorString("listen thread already running");
940   } else {
941     char listen_url[512];
942     if (hostname && hostname[0])
943       snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
944                port);
945     else
946       snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
947     m_listen_url = listen_url;
948     SetConnection(new ConnectionFileDescriptor());
949     m_listen_thread = ThreadLauncher::LaunchThread(
950         listen_url, GDBRemoteCommunication::ListenThread, this, &error);
951   }
952   return error;
953 }
954 
955 bool GDBRemoteCommunication::JoinListenThread() {
956   if (m_listen_thread.IsJoinable())
957     m_listen_thread.Join(nullptr);
958   return true;
959 }
960 
961 lldb::thread_result_t
962 GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
963   GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
964   Status error;
965   ConnectionFileDescriptor *connection =
966       (ConnectionFileDescriptor *)comm->GetConnection();
967 
968   if (connection) {
969     // Do the listen on another thread so we can continue on...
970     if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
971         eConnectionStatusSuccess)
972       comm->SetConnection(NULL);
973   }
974   return NULL;
975 }
976 
977 Status GDBRemoteCommunication::StartDebugserverProcess(
978     const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
979     uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
980   Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
981   if (log)
982     log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
983                 __FUNCTION__, url ? url : "<empty>",
984                 port ? *port : uint16_t(0));
985 
986   Status error;
987   // If we locate debugserver, keep that located version around
988   static FileSpec g_debugserver_file_spec;
989 
990   char debugserver_path[PATH_MAX];
991   FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
992 
993   // Always check to see if we have an environment override for the path to the
994   // debugserver to use and use it if we do.
995   const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
996   if (env_debugserver_path) {
997     debugserver_file_spec.SetFile(env_debugserver_path,
998                                   FileSpec::Style::native);
999     if (log)
1000       log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
1001                   "from environment variable: %s",
1002                   __FUNCTION__, env_debugserver_path);
1003   } else
1004     debugserver_file_spec = g_debugserver_file_spec;
1005   bool debugserver_exists =
1006       FileSystem::Instance().Exists(debugserver_file_spec);
1007   if (!debugserver_exists) {
1008     // The debugserver binary is in the LLDB.framework/Resources directory.
1009     debugserver_file_spec = HostInfo::GetSupportExeDir();
1010     if (debugserver_file_spec) {
1011       debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
1012       debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
1013       if (debugserver_exists) {
1014         if (log)
1015           log->Printf(
1016               "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
1017               __FUNCTION__, debugserver_file_spec.GetPath().c_str());
1018 
1019         g_debugserver_file_spec = debugserver_file_spec;
1020       } else {
1021         debugserver_file_spec =
1022             platform->LocateExecutable(DEBUGSERVER_BASENAME);
1023         if (debugserver_file_spec) {
1024           // Platform::LocateExecutable() wouldn't return a path if it doesn't
1025           // exist
1026           debugserver_exists = true;
1027         } else {
1028           if (log)
1029             log->Printf("GDBRemoteCommunication::%s() could not find "
1030                         "gdb-remote stub exe '%s'",
1031                         __FUNCTION__, debugserver_file_spec.GetPath().c_str());
1032         }
1033         // Don't cache the platform specific GDB server binary as it could
1034         // change from platform to platform
1035         g_debugserver_file_spec.Clear();
1036       }
1037     }
1038   }
1039 
1040   if (debugserver_exists) {
1041     debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
1042 
1043     Args &debugserver_args = launch_info.GetArguments();
1044     debugserver_args.Clear();
1045     char arg_cstr[PATH_MAX];
1046 
1047     // Start args with "debugserver /file/path -r --"
1048     debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
1049 
1050 #if !defined(__APPLE__)
1051     // First argument to lldb-server must be mode in which to run.
1052     debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
1053 #endif
1054 
1055     // If a url is supplied then use it
1056     if (url)
1057       debugserver_args.AppendArgument(llvm::StringRef(url));
1058 
1059     if (pass_comm_fd >= 0) {
1060       StreamString fd_arg;
1061       fd_arg.Printf("--fd=%i", pass_comm_fd);
1062       debugserver_args.AppendArgument(fd_arg.GetString());
1063       // Send "pass_comm_fd" down to the inferior so it can use it to
1064       // communicate back with this process
1065       launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1066     }
1067 
1068     // use native registers, not the GDB registers
1069     debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
1070 
1071     if (launch_info.GetLaunchInSeparateProcessGroup()) {
1072       debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
1073     }
1074 
1075     llvm::SmallString<PATH_MAX> named_pipe_path;
1076     // socket_pipe is used by debug server to communicate back either
1077     // TCP port or domain socket name which it listens on.
1078     // The second purpose of the pipe to serve as a synchronization point -
1079     // once data is written to the pipe, debug server is up and running.
1080     Pipe socket_pipe;
1081 
1082     // port is null when debug server should listen on domain socket - we're
1083     // not interested in port value but rather waiting for debug server to
1084     // become available.
1085     if (pass_comm_fd == -1) {
1086       if (url) {
1087 // Create a temporary file to get the stdout/stderr and redirect the output of
1088 // the command into this file. We will later read this file if all goes well
1089 // and fill the data into "command_output_ptr"
1090 #if defined(__APPLE__)
1091         // Binding to port zero, we need to figure out what port it ends up
1092         // using using a named pipe...
1093         error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1094                                                  false, named_pipe_path);
1095         if (error.Fail()) {
1096           if (log)
1097             log->Printf("GDBRemoteCommunication::%s() "
1098                         "named pipe creation failed: %s",
1099                         __FUNCTION__, error.AsCString());
1100           return error;
1101         }
1102         debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1103         debugserver_args.AppendArgument(named_pipe_path);
1104 #else
1105         // Binding to port zero, we need to figure out what port it ends up
1106         // using using an unnamed pipe...
1107         error = socket_pipe.CreateNew(true);
1108         if (error.Fail()) {
1109           if (log)
1110             log->Printf("GDBRemoteCommunication::%s() "
1111                         "unnamed pipe creation failed: %s",
1112                         __FUNCTION__, error.AsCString());
1113           return error;
1114         }
1115         int write_fd = socket_pipe.GetWriteFileDescriptor();
1116         debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1117         debugserver_args.AppendArgument(llvm::to_string(write_fd));
1118         launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1119 #endif
1120       } else {
1121         // No host and port given, so lets listen on our end and make the
1122         // debugserver connect to us..
1123         error = StartListenThread("127.0.0.1", 0);
1124         if (error.Fail()) {
1125           if (log)
1126             log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1127                         "thread: %s",
1128                         __FUNCTION__, error.AsCString());
1129           return error;
1130         }
1131 
1132         ConnectionFileDescriptor *connection =
1133             (ConnectionFileDescriptor *)GetConnection();
1134         // Wait for 10 seconds to resolve the bound port
1135         uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
1136         if (port_ > 0) {
1137           char port_cstr[32];
1138           snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1139           // Send the host and port down that debugserver and specify an option
1140           // so that it connects back to the port we are listening to in this
1141           // process
1142           debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1143           debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1144           if (port)
1145             *port = port_;
1146         } else {
1147           error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1148           if (log)
1149             log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1150                         error.AsCString());
1151           return error;
1152         }
1153       }
1154     }
1155 
1156     const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1157     if (env_debugserver_log_file) {
1158       ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1159                  env_debugserver_log_file);
1160       debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1161     }
1162 
1163 #if defined(__APPLE__)
1164     const char *env_debugserver_log_flags =
1165         getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1166     if (env_debugserver_log_flags) {
1167       ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1168                  env_debugserver_log_flags);
1169       debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1170     }
1171 #else
1172     const char *env_debugserver_log_channels =
1173         getenv("LLDB_SERVER_LOG_CHANNELS");
1174     if (env_debugserver_log_channels) {
1175       ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1176                  env_debugserver_log_channels);
1177       debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
1178     }
1179 #endif
1180 
1181     // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1182     // env var doesn't come back.
1183     uint32_t env_var_index = 1;
1184     bool has_env_var;
1185     do {
1186       char env_var_name[64];
1187       snprintf(env_var_name, sizeof(env_var_name),
1188                "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1189       const char *extra_arg = getenv(env_var_name);
1190       has_env_var = extra_arg != nullptr;
1191 
1192       if (has_env_var) {
1193         debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1194         if (log)
1195           log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1196                       "to stub command line (%s)",
1197                       __FUNCTION__, env_var_name, extra_arg);
1198       }
1199     } while (has_env_var);
1200 
1201     if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1202       debugserver_args.AppendArgument(llvm::StringRef("--"));
1203       debugserver_args.AppendArguments(*inferior_args);
1204     }
1205 
1206     // Copy the current environment to the gdbserver/debugserver instance
1207     launch_info.GetEnvironment() = Host::GetEnvironment();
1208 
1209     // Close STDIN, STDOUT and STDERR.
1210     launch_info.AppendCloseFileAction(STDIN_FILENO);
1211     launch_info.AppendCloseFileAction(STDOUT_FILENO);
1212     launch_info.AppendCloseFileAction(STDERR_FILENO);
1213 
1214     // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1215     launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1216     launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1217     launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1218 
1219     if (log) {
1220       StreamString string_stream;
1221       Platform *const platform = nullptr;
1222       launch_info.Dump(string_stream, platform);
1223       log->Printf("launch info for gdb-remote stub:\n%s",
1224                   string_stream.GetData());
1225     }
1226     error = Host::LaunchProcess(launch_info);
1227 
1228     if (error.Success() &&
1229         (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1230         pass_comm_fd == -1) {
1231       if (named_pipe_path.size() > 0) {
1232         error = socket_pipe.OpenAsReader(named_pipe_path, false);
1233         if (error.Fail())
1234           if (log)
1235             log->Printf("GDBRemoteCommunication::%s() "
1236                         "failed to open named pipe %s for reading: %s",
1237                         __FUNCTION__, named_pipe_path.c_str(),
1238                         error.AsCString());
1239       }
1240 
1241       if (socket_pipe.CanWrite())
1242         socket_pipe.CloseWriteFileDescriptor();
1243       if (socket_pipe.CanRead()) {
1244         char port_cstr[PATH_MAX] = {0};
1245         port_cstr[0] = '\0';
1246         size_t num_bytes = sizeof(port_cstr);
1247         // Read port from pipe with 10 second timeout.
1248         error = socket_pipe.ReadWithTimeout(
1249             port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1250         if (error.Success() && (port != nullptr)) {
1251           assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1252           uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1253           if (*port == 0 || *port == child_port) {
1254             *port = child_port;
1255             if (log)
1256               log->Printf("GDBRemoteCommunication::%s() "
1257                           "debugserver listens %u port",
1258                           __FUNCTION__, *port);
1259           } else {
1260             if (log)
1261               log->Printf("GDBRemoteCommunication::%s() "
1262                           "debugserver listening on port "
1263                           "%d but requested port was %d",
1264                           __FUNCTION__, (uint32_t)child_port,
1265                           (uint32_t)(*port));
1266           }
1267         } else {
1268           if (log)
1269             log->Printf("GDBRemoteCommunication::%s() "
1270                         "failed to read a port value from pipe %s: %s",
1271                         __FUNCTION__, named_pipe_path.c_str(),
1272                         error.AsCString());
1273         }
1274         socket_pipe.Close();
1275       }
1276 
1277       if (named_pipe_path.size() > 0) {
1278         const auto err = socket_pipe.Delete(named_pipe_path);
1279         if (err.Fail()) {
1280           if (log)
1281             log->Printf(
1282                 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1283                 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1284         }
1285       }
1286 
1287       // Make sure we actually connect with the debugserver...
1288       JoinListenThread();
1289     }
1290   } else {
1291     error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1292   }
1293 
1294   if (error.Fail()) {
1295     if (log)
1296       log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1297                   error.AsCString());
1298   }
1299 
1300   return error;
1301 }
1302 
1303 void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1304 
1305 GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1306     GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1307   : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1308     auto curr_timeout = gdb_comm.GetPacketTimeout();
1309     // Only update the timeout if the timeout is greater than the current
1310     // timeout. If the current timeout is larger, then just use that.
1311     if (curr_timeout < timeout) {
1312       m_timeout_modified = true;
1313       m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1314     }
1315 }
1316 
1317 GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1318   // Only restore the timeout if we set it in the constructor.
1319   if (m_timeout_modified)
1320     m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1321 }
1322 
1323 // This function is called via the Communications class read thread when bytes
1324 // become available for this connection. This function will consume all
1325 // incoming bytes and try to parse whole packets as they become available. Full
1326 // packets are placed in a queue, so that all packet requests can simply pop
1327 // from this queue. Async notification packets will be dispatched immediately
1328 // to the ProcessGDBRemote Async thread via an event.
1329 void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1330                                                 size_t len, bool broadcast,
1331                                                 lldb::ConnectionStatus status) {
1332   StringExtractorGDBRemote packet;
1333 
1334   while (true) {
1335     PacketType type = CheckForPacket(bytes, len, packet);
1336 
1337     // scrub the data so we do not pass it back to CheckForPacket on future
1338     // passes of the loop
1339     bytes = nullptr;
1340     len = 0;
1341 
1342     // we may have received no packet so lets bail out
1343     if (type == PacketType::Invalid)
1344       break;
1345 
1346     if (type == PacketType::Standard) {
1347       // scope for the mutex
1348       {
1349         // lock down the packet queue
1350         std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1351         // push a new packet into the queue
1352         m_packet_queue.push(packet);
1353         // Signal condition variable that we have a packet
1354         m_condition_queue_not_empty.notify_one();
1355       }
1356     }
1357 
1358     if (type == PacketType::Notify) {
1359       // put this packet into an event
1360       const char *pdata = packet.GetStringRef().c_str();
1361 
1362       // as the communication class, we are a broadcaster and the async thread
1363       // is tuned to listen to us
1364       BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1365                      new EventDataBytes(pdata));
1366     }
1367   }
1368 }
1369 
1370 void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1371     const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1372     StringRef Style) {
1373   using PacketResult = GDBRemoteCommunication::PacketResult;
1374 
1375   switch (result) {
1376   case PacketResult::Success:
1377     Stream << "Success";
1378     break;
1379   case PacketResult::ErrorSendFailed:
1380     Stream << "ErrorSendFailed";
1381     break;
1382   case PacketResult::ErrorSendAck:
1383     Stream << "ErrorSendAck";
1384     break;
1385   case PacketResult::ErrorReplyFailed:
1386     Stream << "ErrorReplyFailed";
1387     break;
1388   case PacketResult::ErrorReplyTimeout:
1389     Stream << "ErrorReplyTimeout";
1390     break;
1391   case PacketResult::ErrorReplyInvalid:
1392     Stream << "ErrorReplyInvalid";
1393     break;
1394   case PacketResult::ErrorReplyAck:
1395     Stream << "ErrorReplyAck";
1396     break;
1397   case PacketResult::ErrorDisconnected:
1398     Stream << "ErrorDisconnected";
1399     break;
1400   case PacketResult::ErrorNoSequenceLock:
1401     Stream << "ErrorNoSequenceLock";
1402     break;
1403   }
1404 }
1405