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