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