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