xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp (revision f6aab3d83b51b91c24247ad2c2573574de475a82)
1dda28197Spatrick //===-- GDBRemoteCommunication.cpp ----------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick 
9061da546Spatrick #include "GDBRemoteCommunication.h"
10061da546Spatrick 
11be691f3bSpatrick #include <climits>
12be691f3bSpatrick #include <cstring>
13061da546Spatrick #include <future>
14061da546Spatrick #include <sys/stat.h>
15061da546Spatrick 
16061da546Spatrick #include "lldb/Core/StreamFile.h"
17061da546Spatrick #include "lldb/Host/Config.h"
18061da546Spatrick #include "lldb/Host/ConnectionFileDescriptor.h"
19061da546Spatrick #include "lldb/Host/FileSystem.h"
20061da546Spatrick #include "lldb/Host/Host.h"
21061da546Spatrick #include "lldb/Host/HostInfo.h"
22061da546Spatrick #include "lldb/Host/Pipe.h"
23061da546Spatrick #include "lldb/Host/ProcessLaunchInfo.h"
24061da546Spatrick #include "lldb/Host/Socket.h"
25061da546Spatrick #include "lldb/Host/ThreadLauncher.h"
26061da546Spatrick #include "lldb/Host/common/TCPSocket.h"
27061da546Spatrick #include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
28061da546Spatrick #include "lldb/Target/Platform.h"
29061da546Spatrick #include "lldb/Utility/Event.h"
30061da546Spatrick #include "lldb/Utility/FileSpec.h"
31061da546Spatrick #include "lldb/Utility/Log.h"
32061da546Spatrick #include "lldb/Utility/RegularExpression.h"
33061da546Spatrick #include "lldb/Utility/StreamString.h"
34061da546Spatrick #include "llvm/ADT/SmallString.h"
35061da546Spatrick #include "llvm/Support/ScopedPrinter.h"
36061da546Spatrick 
37061da546Spatrick #include "ProcessGDBRemoteLog.h"
38061da546Spatrick 
39061da546Spatrick #if defined(__APPLE__)
40061da546Spatrick #define DEBUGSERVER_BASENAME "debugserver"
41061da546Spatrick #elif defined(_WIN32)
42061da546Spatrick #define DEBUGSERVER_BASENAME "lldb-server.exe"
43061da546Spatrick #else
44061da546Spatrick #define DEBUGSERVER_BASENAME "lldb-server"
45061da546Spatrick #endif
46061da546Spatrick 
47061da546Spatrick #if defined(HAVE_LIBCOMPRESSION)
48061da546Spatrick #include <compression.h>
49061da546Spatrick #endif
50061da546Spatrick 
51be691f3bSpatrick #if LLVM_ENABLE_ZLIB
52061da546Spatrick #include <zlib.h>
53061da546Spatrick #endif
54061da546Spatrick 
55061da546Spatrick using namespace lldb;
56061da546Spatrick using namespace lldb_private;
57061da546Spatrick using namespace lldb_private::process_gdb_remote;
58061da546Spatrick 
59061da546Spatrick // GDBRemoteCommunication constructor
GDBRemoteCommunication()60*f6aab3d8Srobert GDBRemoteCommunication::GDBRemoteCommunication()
61*f6aab3d8Srobert     : Communication(),
62061da546Spatrick #ifdef LLDB_CONFIGURATION_DEBUG
63061da546Spatrick       m_packet_timeout(1000),
64061da546Spatrick #else
65061da546Spatrick       m_packet_timeout(1),
66061da546Spatrick #endif
67061da546Spatrick       m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
68*f6aab3d8Srobert       m_send_acks(true), m_is_platform(false),
69*f6aab3d8Srobert       m_compression_type(CompressionType::None), m_listen_url() {
70061da546Spatrick }
71061da546Spatrick 
72061da546Spatrick // Destructor
~GDBRemoteCommunication()73061da546Spatrick GDBRemoteCommunication::~GDBRemoteCommunication() {
74061da546Spatrick   if (IsConnected()) {
75061da546Spatrick     Disconnect();
76061da546Spatrick   }
77061da546Spatrick 
78061da546Spatrick #if defined(HAVE_LIBCOMPRESSION)
79061da546Spatrick   if (m_decompression_scratch)
80061da546Spatrick     free (m_decompression_scratch);
81061da546Spatrick #endif
82061da546Spatrick }
83061da546Spatrick 
CalculcateChecksum(llvm::StringRef payload)84061da546Spatrick char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
85061da546Spatrick   int checksum = 0;
86061da546Spatrick 
87061da546Spatrick   for (char c : payload)
88061da546Spatrick     checksum += c;
89061da546Spatrick 
90061da546Spatrick   return checksum & 255;
91061da546Spatrick }
92061da546Spatrick 
SendAck()93061da546Spatrick size_t GDBRemoteCommunication::SendAck() {
94*f6aab3d8Srobert   Log *log = GetLog(GDBRLog::Packets);
95061da546Spatrick   ConnectionStatus status = eConnectionStatusSuccess;
96061da546Spatrick   char ch = '+';
97*f6aab3d8Srobert   const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
98061da546Spatrick   LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
99061da546Spatrick   m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
100061da546Spatrick   return bytes_written;
101061da546Spatrick }
102061da546Spatrick 
SendNack()103061da546Spatrick size_t GDBRemoteCommunication::SendNack() {
104*f6aab3d8Srobert   Log *log = GetLog(GDBRLog::Packets);
105061da546Spatrick   ConnectionStatus status = eConnectionStatusSuccess;
106061da546Spatrick   char ch = '-';
107*f6aab3d8Srobert   const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
108061da546Spatrick   LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
109061da546Spatrick   m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
110061da546Spatrick   return bytes_written;
111061da546Spatrick }
112061da546Spatrick 
113061da546Spatrick GDBRemoteCommunication::PacketResult
SendPacketNoLock(llvm::StringRef payload)114061da546Spatrick GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
115061da546Spatrick   StreamString packet(0, 4, eByteOrderBig);
116061da546Spatrick   packet.PutChar('$');
117061da546Spatrick   packet.Write(payload.data(), payload.size());
118061da546Spatrick   packet.PutChar('#');
119061da546Spatrick   packet.PutHex8(CalculcateChecksum(payload));
120dda28197Spatrick   std::string packet_str = std::string(packet.GetString());
121061da546Spatrick 
122061da546Spatrick   return SendRawPacketNoLock(packet_str);
123061da546Spatrick }
124061da546Spatrick 
125061da546Spatrick GDBRemoteCommunication::PacketResult
SendNotificationPacketNoLock(llvm::StringRef notify_type,std::deque<std::string> & queue,llvm::StringRef payload)126*f6aab3d8Srobert GDBRemoteCommunication::SendNotificationPacketNoLock(
127*f6aab3d8Srobert     llvm::StringRef notify_type, std::deque<std::string> &queue,
128*f6aab3d8Srobert     llvm::StringRef payload) {
129*f6aab3d8Srobert   PacketResult ret = PacketResult::Success;
130*f6aab3d8Srobert 
131*f6aab3d8Srobert   // If there are no notification in the queue, send the notification
132*f6aab3d8Srobert   // packet.
133*f6aab3d8Srobert   if (queue.empty()) {
134*f6aab3d8Srobert     StreamString packet(0, 4, eByteOrderBig);
135*f6aab3d8Srobert     packet.PutChar('%');
136*f6aab3d8Srobert     packet.Write(notify_type.data(), notify_type.size());
137*f6aab3d8Srobert     packet.PutChar(':');
138*f6aab3d8Srobert     packet.Write(payload.data(), payload.size());
139*f6aab3d8Srobert     packet.PutChar('#');
140*f6aab3d8Srobert     packet.PutHex8(CalculcateChecksum(payload));
141*f6aab3d8Srobert     ret = SendRawPacketNoLock(packet.GetString(), true);
142*f6aab3d8Srobert   }
143*f6aab3d8Srobert 
144*f6aab3d8Srobert   queue.push_back(payload.str());
145*f6aab3d8Srobert   return ret;
146*f6aab3d8Srobert }
147*f6aab3d8Srobert 
148*f6aab3d8Srobert GDBRemoteCommunication::PacketResult
SendRawPacketNoLock(llvm::StringRef packet,bool skip_ack)149061da546Spatrick GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
150061da546Spatrick                                             bool skip_ack) {
151061da546Spatrick   if (IsConnected()) {
152*f6aab3d8Srobert     Log *log = GetLog(GDBRLog::Packets);
153061da546Spatrick     ConnectionStatus status = eConnectionStatusSuccess;
154061da546Spatrick     const char *packet_data = packet.data();
155061da546Spatrick     const size_t packet_length = packet.size();
156*f6aab3d8Srobert     size_t bytes_written = WriteAll(packet_data, packet_length, status, nullptr);
157061da546Spatrick     if (log) {
158061da546Spatrick       size_t binary_start_offset = 0;
159061da546Spatrick       if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
160061da546Spatrick           0) {
161061da546Spatrick         const char *first_comma = strchr(packet_data, ',');
162061da546Spatrick         if (first_comma) {
163061da546Spatrick           const char *second_comma = strchr(first_comma + 1, ',');
164061da546Spatrick           if (second_comma)
165061da546Spatrick             binary_start_offset = second_comma - packet_data + 1;
166061da546Spatrick         }
167061da546Spatrick       }
168061da546Spatrick 
169061da546Spatrick       // If logging was just enabled and we have history, then dump out what we
170061da546Spatrick       // have to the log so we get the historical context. The Dump() call that
171061da546Spatrick       // logs all of the packet will set a boolean so that we don't dump this
172061da546Spatrick       // more than once
173061da546Spatrick       if (!m_history.DidDumpToLog())
174061da546Spatrick         m_history.Dump(log);
175061da546Spatrick 
176061da546Spatrick       if (binary_start_offset) {
177061da546Spatrick         StreamString strm;
178061da546Spatrick         // Print non binary data header
179061da546Spatrick         strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
180061da546Spatrick                     (int)binary_start_offset, packet_data);
181061da546Spatrick         const uint8_t *p;
182061da546Spatrick         // Print binary data exactly as sent
183061da546Spatrick         for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
184061da546Spatrick              ++p)
185061da546Spatrick           strm.Printf("\\x%2.2x", *p);
186061da546Spatrick         // Print the checksum
187061da546Spatrick         strm.Printf("%*s", (int)3, p);
188061da546Spatrick         log->PutString(strm.GetString());
189061da546Spatrick       } else
190061da546Spatrick         LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %.*s",
191061da546Spatrick                   (uint64_t)bytes_written, (int)packet_length, packet_data);
192061da546Spatrick     }
193061da546Spatrick 
194061da546Spatrick     m_history.AddPacket(packet.str(), packet_length,
195061da546Spatrick                         GDBRemotePacket::ePacketTypeSend, bytes_written);
196061da546Spatrick 
197061da546Spatrick     if (bytes_written == packet_length) {
198061da546Spatrick       if (!skip_ack && GetSendAcks())
199061da546Spatrick         return GetAck();
200061da546Spatrick       else
201061da546Spatrick         return PacketResult::Success;
202061da546Spatrick     } else {
203061da546Spatrick       LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,
204061da546Spatrick                 packet_data);
205061da546Spatrick     }
206061da546Spatrick   }
207061da546Spatrick   return PacketResult::ErrorSendFailed;
208061da546Spatrick }
209061da546Spatrick 
GetAck()210061da546Spatrick GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
211061da546Spatrick   StringExtractorGDBRemote packet;
212*f6aab3d8Srobert   PacketResult result = WaitForPacketNoLock(packet, GetPacketTimeout(), false);
213061da546Spatrick   if (result == PacketResult::Success) {
214061da546Spatrick     if (packet.GetResponseType() ==
215061da546Spatrick         StringExtractorGDBRemote::ResponseType::eAck)
216061da546Spatrick       return PacketResult::Success;
217061da546Spatrick     else
218061da546Spatrick       return PacketResult::ErrorSendAck;
219061da546Spatrick   }
220061da546Spatrick   return result;
221061da546Spatrick }
222061da546Spatrick 
223061da546Spatrick GDBRemoteCommunication::PacketResult
ReadPacket(StringExtractorGDBRemote & response,Timeout<std::micro> timeout,bool sync_on_timeout)224061da546Spatrick GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
225061da546Spatrick                                    Timeout<std::micro> timeout,
226061da546Spatrick                                    bool sync_on_timeout) {
227*f6aab3d8Srobert   using ResponseType = StringExtractorGDBRemote::ResponseType;
228*f6aab3d8Srobert 
229*f6aab3d8Srobert   Log *log = GetLog(GDBRLog::Packets);
230*f6aab3d8Srobert   for (;;) {
231*f6aab3d8Srobert     PacketResult result =
232*f6aab3d8Srobert         WaitForPacketNoLock(response, timeout, sync_on_timeout);
233*f6aab3d8Srobert     if (result != PacketResult::Success ||
234*f6aab3d8Srobert         (response.GetResponseType() != ResponseType::eAck &&
235*f6aab3d8Srobert          response.GetResponseType() != ResponseType::eNack))
236*f6aab3d8Srobert       return result;
237*f6aab3d8Srobert     LLDB_LOG(log, "discarding spurious `{0}` packet", response.GetStringRef());
238061da546Spatrick   }
239061da546Spatrick }
240061da546Spatrick 
241061da546Spatrick GDBRemoteCommunication::PacketResult
WaitForPacketNoLock(StringExtractorGDBRemote & packet,Timeout<std::micro> timeout,bool sync_on_timeout)242061da546Spatrick GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
243061da546Spatrick                                             Timeout<std::micro> timeout,
244061da546Spatrick                                             bool sync_on_timeout) {
245061da546Spatrick   uint8_t buffer[8192];
246061da546Spatrick   Status error;
247061da546Spatrick 
248*f6aab3d8Srobert   Log *log = GetLog(GDBRLog::Packets);
249061da546Spatrick 
250061da546Spatrick   // Check for a packet from our cache first without trying any reading...
251061da546Spatrick   if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
252061da546Spatrick     return PacketResult::Success;
253061da546Spatrick 
254061da546Spatrick   bool timed_out = false;
255061da546Spatrick   bool disconnected = false;
256061da546Spatrick   while (IsConnected() && !timed_out) {
257061da546Spatrick     lldb::ConnectionStatus status = eConnectionStatusNoConnection;
258061da546Spatrick     size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
259061da546Spatrick 
260061da546Spatrick     LLDB_LOGV(log,
261061da546Spatrick               "Read(buffer, sizeof(buffer), timeout = {0}, "
262061da546Spatrick               "status = {1}, error = {2}) => bytes_read = {3}",
263be691f3bSpatrick               timeout, Communication::ConnectionStatusAsString(status), error,
264061da546Spatrick               bytes_read);
265061da546Spatrick 
266061da546Spatrick     if (bytes_read > 0) {
267061da546Spatrick       if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
268061da546Spatrick         return PacketResult::Success;
269061da546Spatrick     } else {
270061da546Spatrick       switch (status) {
271061da546Spatrick       case eConnectionStatusTimedOut:
272061da546Spatrick       case eConnectionStatusInterrupted:
273061da546Spatrick         if (sync_on_timeout) {
274061da546Spatrick           /// Sync the remote GDB server and make sure we get a response that
275061da546Spatrick           /// corresponds to what we send.
276061da546Spatrick           ///
277061da546Spatrick           /// Sends a "qEcho" packet and makes sure it gets the exact packet
278061da546Spatrick           /// echoed back. If the qEcho packet isn't supported, we send a qC
279061da546Spatrick           /// packet and make sure we get a valid thread ID back. We use the
280061da546Spatrick           /// "qC" packet since its response if very unique: is responds with
281061da546Spatrick           /// "QC%x" where %x is the thread ID of the current thread. This
282061da546Spatrick           /// makes the response unique enough from other packet responses to
283061da546Spatrick           /// ensure we are back on track.
284061da546Spatrick           ///
285061da546Spatrick           /// This packet is needed after we time out sending a packet so we
286061da546Spatrick           /// can ensure that we are getting the response for the packet we
287061da546Spatrick           /// are sending. There are no sequence IDs in the GDB remote
288061da546Spatrick           /// protocol (there used to be, but they are not supported anymore)
289061da546Spatrick           /// so if you timeout sending packet "abc", you might then send
290061da546Spatrick           /// packet "cde" and get the response for the previous "abc" packet.
291061da546Spatrick           /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
292061da546Spatrick           /// many responses for packets can look like responses for other
293061da546Spatrick           /// packets. So if we timeout, we need to ensure that we can get
294061da546Spatrick           /// back on track. If we can't get back on track, we must
295061da546Spatrick           /// disconnect.
296061da546Spatrick           bool sync_success = false;
297061da546Spatrick           bool got_actual_response = false;
298061da546Spatrick           // We timed out, we need to sync back up with the
299061da546Spatrick           char echo_packet[32];
300061da546Spatrick           int echo_packet_len = 0;
301061da546Spatrick           RegularExpression response_regex;
302061da546Spatrick 
303061da546Spatrick           if (m_supports_qEcho == eLazyBoolYes) {
304061da546Spatrick             echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
305061da546Spatrick                                          "qEcho:%u", ++m_echo_number);
306061da546Spatrick             std::string regex_str = "^";
307061da546Spatrick             regex_str += echo_packet;
308061da546Spatrick             regex_str += "$";
309061da546Spatrick             response_regex = RegularExpression(regex_str);
310061da546Spatrick           } else {
311061da546Spatrick             echo_packet_len =
312061da546Spatrick                 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
313061da546Spatrick             response_regex =
314061da546Spatrick                 RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
315061da546Spatrick           }
316061da546Spatrick 
317061da546Spatrick           PacketResult echo_packet_result =
318061da546Spatrick               SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
319061da546Spatrick           if (echo_packet_result == PacketResult::Success) {
320061da546Spatrick             const uint32_t max_retries = 3;
321061da546Spatrick             uint32_t successful_responses = 0;
322061da546Spatrick             for (uint32_t i = 0; i < max_retries; ++i) {
323061da546Spatrick               StringExtractorGDBRemote echo_response;
324061da546Spatrick               echo_packet_result =
325061da546Spatrick                   WaitForPacketNoLock(echo_response, timeout, false);
326061da546Spatrick               if (echo_packet_result == PacketResult::Success) {
327061da546Spatrick                 ++successful_responses;
328061da546Spatrick                 if (response_regex.Execute(echo_response.GetStringRef())) {
329061da546Spatrick                   sync_success = true;
330061da546Spatrick                   break;
331061da546Spatrick                 } else if (successful_responses == 1) {
332061da546Spatrick                   // We got something else back as the first successful
333061da546Spatrick                   // response, it probably is the  response to the packet we
334061da546Spatrick                   // actually wanted, so copy it over if this is the first
335061da546Spatrick                   // success and continue to try to get the qEcho response
336061da546Spatrick                   packet = echo_response;
337061da546Spatrick                   got_actual_response = true;
338061da546Spatrick                 }
339061da546Spatrick               } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
340061da546Spatrick                 continue; // Packet timed out, continue waiting for a response
341061da546Spatrick               else
342061da546Spatrick                 break; // Something else went wrong getting the packet back, we
343061da546Spatrick                        // failed and are done trying
344061da546Spatrick             }
345061da546Spatrick           }
346061da546Spatrick 
347061da546Spatrick           // We weren't able to sync back up with the server, we must abort
348061da546Spatrick           // otherwise all responses might not be from the right packets...
349061da546Spatrick           if (sync_success) {
350061da546Spatrick             // We timed out, but were able to recover
351061da546Spatrick             if (got_actual_response) {
352061da546Spatrick               // We initially timed out, but we did get a response that came in
353061da546Spatrick               // before the successful reply to our qEcho packet, so lets say
354061da546Spatrick               // everything is fine...
355061da546Spatrick               return PacketResult::Success;
356061da546Spatrick             }
357061da546Spatrick           } else {
358061da546Spatrick             disconnected = true;
359061da546Spatrick             Disconnect();
360061da546Spatrick           }
361061da546Spatrick         }
362061da546Spatrick         timed_out = true;
363061da546Spatrick         break;
364061da546Spatrick       case eConnectionStatusSuccess:
365061da546Spatrick         // printf ("status = success but error = %s\n",
366061da546Spatrick         // error.AsCString("<invalid>"));
367061da546Spatrick         break;
368061da546Spatrick 
369061da546Spatrick       case eConnectionStatusEndOfFile:
370061da546Spatrick       case eConnectionStatusNoConnection:
371061da546Spatrick       case eConnectionStatusLostConnection:
372061da546Spatrick       case eConnectionStatusError:
373061da546Spatrick         disconnected = true;
374061da546Spatrick         Disconnect();
375061da546Spatrick         break;
376061da546Spatrick       }
377061da546Spatrick     }
378061da546Spatrick   }
379061da546Spatrick   packet.Clear();
380061da546Spatrick   if (disconnected)
381061da546Spatrick     return PacketResult::ErrorDisconnected;
382061da546Spatrick   if (timed_out)
383061da546Spatrick     return PacketResult::ErrorReplyTimeout;
384061da546Spatrick   else
385061da546Spatrick     return PacketResult::ErrorReplyFailed;
386061da546Spatrick }
387061da546Spatrick 
DecompressPacket()388061da546Spatrick bool GDBRemoteCommunication::DecompressPacket() {
389*f6aab3d8Srobert   Log *log = GetLog(GDBRLog::Packets);
390061da546Spatrick 
391061da546Spatrick   if (!CompressionIsEnabled())
392061da546Spatrick     return true;
393061da546Spatrick 
394061da546Spatrick   size_t pkt_size = m_bytes.size();
395061da546Spatrick 
396061da546Spatrick   // Smallest possible compressed packet is $N#00 - an uncompressed empty
397061da546Spatrick   // reply, most commonly indicating an unsupported packet.  Anything less than
398061da546Spatrick   // 5 characters, it's definitely not a compressed packet.
399061da546Spatrick   if (pkt_size < 5)
400061da546Spatrick     return true;
401061da546Spatrick 
402061da546Spatrick   if (m_bytes[0] != '$' && m_bytes[0] != '%')
403061da546Spatrick     return true;
404061da546Spatrick   if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
405061da546Spatrick     return true;
406061da546Spatrick 
407061da546Spatrick   size_t hash_mark_idx = m_bytes.find('#');
408061da546Spatrick   if (hash_mark_idx == std::string::npos)
409061da546Spatrick     return true;
410061da546Spatrick   if (hash_mark_idx + 2 >= m_bytes.size())
411061da546Spatrick     return true;
412061da546Spatrick 
413061da546Spatrick   if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
414061da546Spatrick       !::isxdigit(m_bytes[hash_mark_idx + 2]))
415061da546Spatrick     return true;
416061da546Spatrick 
417061da546Spatrick   size_t content_length =
418061da546Spatrick       pkt_size -
419061da546Spatrick       5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
420061da546Spatrick   size_t content_start = 2; // The first character of the
421061da546Spatrick                             // compressed/not-compressed text of the packet
422061da546Spatrick   size_t checksum_idx =
423061da546Spatrick       hash_mark_idx +
424061da546Spatrick       1; // The first character of the two hex checksum characters
425061da546Spatrick 
426061da546Spatrick   // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
427061da546Spatrick   // multiple packets. size_of_first_packet is the size of the initial packet
428061da546Spatrick   // which we'll replace with the decompressed version of, leaving the rest of
429061da546Spatrick   // m_bytes unmodified.
430061da546Spatrick   size_t size_of_first_packet = hash_mark_idx + 3;
431061da546Spatrick 
432061da546Spatrick   // Compressed packets ("$C") start with a base10 number which is the size of
433061da546Spatrick   // the uncompressed payload, then a : and then the compressed data.  e.g.
434061da546Spatrick   // $C1024:<binary>#00 Update content_start and content_length to only include
435061da546Spatrick   // the <binary> part of the packet.
436061da546Spatrick 
437061da546Spatrick   uint64_t decompressed_bufsize = ULONG_MAX;
438061da546Spatrick   if (m_bytes[1] == 'C') {
439061da546Spatrick     size_t i = content_start;
440061da546Spatrick     while (i < hash_mark_idx && isdigit(m_bytes[i]))
441061da546Spatrick       i++;
442061da546Spatrick     if (i < hash_mark_idx && m_bytes[i] == ':') {
443061da546Spatrick       i++;
444061da546Spatrick       content_start = i;
445061da546Spatrick       content_length = hash_mark_idx - content_start;
446061da546Spatrick       std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
447061da546Spatrick       errno = 0;
448061da546Spatrick       decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
449061da546Spatrick       if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
450061da546Spatrick         m_bytes.erase(0, size_of_first_packet);
451061da546Spatrick         return false;
452061da546Spatrick       }
453061da546Spatrick     }
454061da546Spatrick   }
455061da546Spatrick 
456061da546Spatrick   if (GetSendAcks()) {
457061da546Spatrick     char packet_checksum_cstr[3];
458061da546Spatrick     packet_checksum_cstr[0] = m_bytes[checksum_idx];
459061da546Spatrick     packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
460061da546Spatrick     packet_checksum_cstr[2] = '\0';
461061da546Spatrick     long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
462061da546Spatrick 
463061da546Spatrick     long actual_checksum = CalculcateChecksum(
464061da546Spatrick         llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
465061da546Spatrick     bool success = packet_checksum == actual_checksum;
466061da546Spatrick     if (!success) {
467061da546Spatrick       LLDB_LOGF(log,
468061da546Spatrick                 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
469061da546Spatrick                 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
470061da546Spatrick                 (uint8_t)actual_checksum);
471061da546Spatrick     }
472061da546Spatrick     // Send the ack or nack if needed
473061da546Spatrick     if (!success) {
474061da546Spatrick       SendNack();
475061da546Spatrick       m_bytes.erase(0, size_of_first_packet);
476061da546Spatrick       return false;
477061da546Spatrick     } else {
478061da546Spatrick       SendAck();
479061da546Spatrick     }
480061da546Spatrick   }
481061da546Spatrick 
482061da546Spatrick   if (m_bytes[1] == 'N') {
483061da546Spatrick     // This packet was not compressed -- delete the 'N' character at the start
484061da546Spatrick     // and the packet may be processed as-is.
485061da546Spatrick     m_bytes.erase(1, 1);
486061da546Spatrick     return true;
487061da546Spatrick   }
488061da546Spatrick 
489061da546Spatrick   // Reverse the gdb-remote binary escaping that was done to the compressed
490061da546Spatrick   // text to guard characters like '$', '#', '}', etc.
491061da546Spatrick   std::vector<uint8_t> unescaped_content;
492061da546Spatrick   unescaped_content.reserve(content_length);
493061da546Spatrick   size_t i = content_start;
494061da546Spatrick   while (i < hash_mark_idx) {
495061da546Spatrick     if (m_bytes[i] == '}') {
496061da546Spatrick       i++;
497061da546Spatrick       unescaped_content.push_back(m_bytes[i] ^ 0x20);
498061da546Spatrick     } else {
499061da546Spatrick       unescaped_content.push_back(m_bytes[i]);
500061da546Spatrick     }
501061da546Spatrick     i++;
502061da546Spatrick   }
503061da546Spatrick 
504061da546Spatrick   uint8_t *decompressed_buffer = nullptr;
505061da546Spatrick   size_t decompressed_bytes = 0;
506061da546Spatrick 
507061da546Spatrick   if (decompressed_bufsize != ULONG_MAX) {
508061da546Spatrick     decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
509061da546Spatrick     if (decompressed_buffer == nullptr) {
510061da546Spatrick       m_bytes.erase(0, size_of_first_packet);
511061da546Spatrick       return false;
512061da546Spatrick     }
513061da546Spatrick   }
514061da546Spatrick 
515061da546Spatrick #if defined(HAVE_LIBCOMPRESSION)
516061da546Spatrick   if (m_compression_type == CompressionType::ZlibDeflate ||
517061da546Spatrick       m_compression_type == CompressionType::LZFSE ||
518061da546Spatrick       m_compression_type == CompressionType::LZ4 ||
519061da546Spatrick       m_compression_type == CompressionType::LZMA) {
520061da546Spatrick     compression_algorithm compression_type;
521061da546Spatrick     if (m_compression_type == CompressionType::LZFSE)
522061da546Spatrick       compression_type = COMPRESSION_LZFSE;
523061da546Spatrick     else if (m_compression_type == CompressionType::ZlibDeflate)
524061da546Spatrick       compression_type = COMPRESSION_ZLIB;
525061da546Spatrick     else if (m_compression_type == CompressionType::LZ4)
526061da546Spatrick       compression_type = COMPRESSION_LZ4_RAW;
527061da546Spatrick     else if (m_compression_type == CompressionType::LZMA)
528061da546Spatrick       compression_type = COMPRESSION_LZMA;
529061da546Spatrick 
530061da546Spatrick     if (m_decompression_scratch_type != m_compression_type) {
531061da546Spatrick       if (m_decompression_scratch) {
532061da546Spatrick         free (m_decompression_scratch);
533061da546Spatrick         m_decompression_scratch = nullptr;
534061da546Spatrick       }
535061da546Spatrick       size_t scratchbuf_size = 0;
536061da546Spatrick       if (m_compression_type == CompressionType::LZFSE)
537061da546Spatrick         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
538061da546Spatrick       else if (m_compression_type == CompressionType::LZ4)
539061da546Spatrick         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
540061da546Spatrick       else if (m_compression_type == CompressionType::ZlibDeflate)
541061da546Spatrick         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
542061da546Spatrick       else if (m_compression_type == CompressionType::LZMA)
543061da546Spatrick         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
544061da546Spatrick       else if (m_compression_type == CompressionType::LZFSE)
545061da546Spatrick         scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
546061da546Spatrick       if (scratchbuf_size > 0) {
547061da546Spatrick         m_decompression_scratch = (void*) malloc (scratchbuf_size);
548061da546Spatrick         m_decompression_scratch_type = m_compression_type;
549061da546Spatrick       }
550061da546Spatrick     }
551061da546Spatrick 
552061da546Spatrick     if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
553061da546Spatrick       decompressed_bytes = compression_decode_buffer(
554061da546Spatrick           decompressed_buffer, decompressed_bufsize,
555061da546Spatrick           (uint8_t *)unescaped_content.data(), unescaped_content.size(),
556061da546Spatrick           m_decompression_scratch, compression_type);
557061da546Spatrick     }
558061da546Spatrick   }
559061da546Spatrick #endif
560061da546Spatrick 
561be691f3bSpatrick #if LLVM_ENABLE_ZLIB
562061da546Spatrick   if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
563061da546Spatrick       decompressed_buffer != nullptr &&
564061da546Spatrick       m_compression_type == CompressionType::ZlibDeflate) {
565061da546Spatrick     z_stream stream;
566061da546Spatrick     memset(&stream, 0, sizeof(z_stream));
567061da546Spatrick     stream.next_in = (Bytef *)unescaped_content.data();
568061da546Spatrick     stream.avail_in = (uInt)unescaped_content.size();
569061da546Spatrick     stream.total_in = 0;
570061da546Spatrick     stream.next_out = (Bytef *)decompressed_buffer;
571061da546Spatrick     stream.avail_out = decompressed_bufsize;
572061da546Spatrick     stream.total_out = 0;
573061da546Spatrick     stream.zalloc = Z_NULL;
574061da546Spatrick     stream.zfree = Z_NULL;
575061da546Spatrick     stream.opaque = Z_NULL;
576061da546Spatrick 
577061da546Spatrick     if (inflateInit2(&stream, -15) == Z_OK) {
578061da546Spatrick       int status = inflate(&stream, Z_NO_FLUSH);
579061da546Spatrick       inflateEnd(&stream);
580061da546Spatrick       if (status == Z_STREAM_END) {
581061da546Spatrick         decompressed_bytes = stream.total_out;
582061da546Spatrick       }
583061da546Spatrick     }
584061da546Spatrick   }
585061da546Spatrick #endif
586061da546Spatrick 
587061da546Spatrick   if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
588061da546Spatrick     if (decompressed_buffer)
589061da546Spatrick       free(decompressed_buffer);
590061da546Spatrick     m_bytes.erase(0, size_of_first_packet);
591061da546Spatrick     return false;
592061da546Spatrick   }
593061da546Spatrick 
594061da546Spatrick   std::string new_packet;
595061da546Spatrick   new_packet.reserve(decompressed_bytes + 6);
596061da546Spatrick   new_packet.push_back(m_bytes[0]);
597061da546Spatrick   new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
598061da546Spatrick   new_packet.push_back('#');
599061da546Spatrick   if (GetSendAcks()) {
600061da546Spatrick     uint8_t decompressed_checksum = CalculcateChecksum(
601061da546Spatrick         llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
602061da546Spatrick     char decompressed_checksum_str[3];
603061da546Spatrick     snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
604061da546Spatrick     new_packet.append(decompressed_checksum_str);
605061da546Spatrick   } else {
606061da546Spatrick     new_packet.push_back('0');
607061da546Spatrick     new_packet.push_back('0');
608061da546Spatrick   }
609061da546Spatrick 
610061da546Spatrick   m_bytes.replace(0, size_of_first_packet, new_packet.data(),
611061da546Spatrick                   new_packet.size());
612061da546Spatrick 
613061da546Spatrick   free(decompressed_buffer);
614061da546Spatrick   return true;
615061da546Spatrick }
616061da546Spatrick 
617061da546Spatrick GDBRemoteCommunication::PacketType
CheckForPacket(const uint8_t * src,size_t src_len,StringExtractorGDBRemote & packet)618061da546Spatrick GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
619061da546Spatrick                                        StringExtractorGDBRemote &packet) {
620061da546Spatrick   // Put the packet data into the buffer in a thread safe fashion
621061da546Spatrick   std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
622061da546Spatrick 
623*f6aab3d8Srobert   Log *log = GetLog(GDBRLog::Packets);
624061da546Spatrick 
625061da546Spatrick   if (src && src_len > 0) {
626061da546Spatrick     if (log && log->GetVerbose()) {
627061da546Spatrick       StreamString s;
628061da546Spatrick       LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
629061da546Spatrick                 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
630061da546Spatrick     }
631061da546Spatrick     m_bytes.append((const char *)src, src_len);
632061da546Spatrick   }
633061da546Spatrick 
634061da546Spatrick   bool isNotifyPacket = false;
635061da546Spatrick 
636061da546Spatrick   // Parse up the packets into gdb remote packets
637061da546Spatrick   if (!m_bytes.empty()) {
638061da546Spatrick     // end_idx must be one past the last valid packet byte. Start it off with
639061da546Spatrick     // an invalid value that is the same as the current index.
640061da546Spatrick     size_t content_start = 0;
641061da546Spatrick     size_t content_length = 0;
642061da546Spatrick     size_t total_length = 0;
643061da546Spatrick     size_t checksum_idx = std::string::npos;
644061da546Spatrick 
645061da546Spatrick     // Size of packet before it is decompressed, for logging purposes
646061da546Spatrick     size_t original_packet_size = m_bytes.size();
647061da546Spatrick     if (CompressionIsEnabled()) {
648061da546Spatrick       if (!DecompressPacket()) {
649061da546Spatrick         packet.Clear();
650061da546Spatrick         return GDBRemoteCommunication::PacketType::Standard;
651061da546Spatrick       }
652061da546Spatrick     }
653061da546Spatrick 
654061da546Spatrick     switch (m_bytes[0]) {
655061da546Spatrick     case '+':                            // Look for ack
656061da546Spatrick     case '-':                            // Look for cancel
657061da546Spatrick     case '\x03':                         // ^C to halt target
658061da546Spatrick       content_length = total_length = 1; // The command is one byte long...
659061da546Spatrick       break;
660061da546Spatrick 
661061da546Spatrick     case '%': // Async notify packet
662061da546Spatrick       isNotifyPacket = true;
663*f6aab3d8Srobert       [[fallthrough]];
664061da546Spatrick 
665061da546Spatrick     case '$':
666061da546Spatrick       // Look for a standard gdb packet?
667061da546Spatrick       {
668061da546Spatrick         size_t hash_pos = m_bytes.find('#');
669061da546Spatrick         if (hash_pos != std::string::npos) {
670061da546Spatrick           if (hash_pos + 2 < m_bytes.size()) {
671061da546Spatrick             checksum_idx = hash_pos + 1;
672061da546Spatrick             // Skip the dollar sign
673061da546Spatrick             content_start = 1;
674061da546Spatrick             // Don't include the # in the content or the $ in the content
675061da546Spatrick             // length
676061da546Spatrick             content_length = hash_pos - 1;
677061da546Spatrick 
678061da546Spatrick             total_length =
679061da546Spatrick                 hash_pos + 3; // Skip the # and the two hex checksum bytes
680061da546Spatrick           } else {
681061da546Spatrick             // Checksum bytes aren't all here yet
682061da546Spatrick             content_length = std::string::npos;
683061da546Spatrick           }
684061da546Spatrick         }
685061da546Spatrick       }
686061da546Spatrick       break;
687061da546Spatrick 
688061da546Spatrick     default: {
689061da546Spatrick       // We have an unexpected byte and we need to flush all bad data that is
690061da546Spatrick       // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
691061da546Spatrick       // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
692061da546Spatrick       // header) or of course, the end of the data in m_bytes...
693061da546Spatrick       const size_t bytes_len = m_bytes.size();
694061da546Spatrick       bool done = false;
695061da546Spatrick       uint32_t idx;
696061da546Spatrick       for (idx = 1; !done && idx < bytes_len; ++idx) {
697061da546Spatrick         switch (m_bytes[idx]) {
698061da546Spatrick         case '+':
699061da546Spatrick         case '-':
700061da546Spatrick         case '\x03':
701061da546Spatrick         case '%':
702061da546Spatrick         case '$':
703061da546Spatrick           done = true;
704061da546Spatrick           break;
705061da546Spatrick 
706061da546Spatrick         default:
707061da546Spatrick           break;
708061da546Spatrick         }
709061da546Spatrick       }
710061da546Spatrick       LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
711061da546Spatrick                 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
712061da546Spatrick       m_bytes.erase(0, idx - 1);
713061da546Spatrick     } break;
714061da546Spatrick     }
715061da546Spatrick 
716061da546Spatrick     if (content_length == std::string::npos) {
717061da546Spatrick       packet.Clear();
718061da546Spatrick       return GDBRemoteCommunication::PacketType::Invalid;
719061da546Spatrick     } else if (total_length > 0) {
720061da546Spatrick 
721061da546Spatrick       // We have a valid packet...
722061da546Spatrick       assert(content_length <= m_bytes.size());
723061da546Spatrick       assert(total_length <= m_bytes.size());
724061da546Spatrick       assert(content_length <= total_length);
725061da546Spatrick       size_t content_end = content_start + content_length;
726061da546Spatrick 
727061da546Spatrick       bool success = true;
728061da546Spatrick       if (log) {
729061da546Spatrick         // If logging was just enabled and we have history, then dump out what
730061da546Spatrick         // we have to the log so we get the historical context. The Dump() call
731061da546Spatrick         // that logs all of the packet will set a boolean so that we don't dump
732061da546Spatrick         // this more than once
733061da546Spatrick         if (!m_history.DidDumpToLog())
734061da546Spatrick           m_history.Dump(log);
735061da546Spatrick 
736061da546Spatrick         bool binary = false;
737061da546Spatrick         // Only detect binary for packets that start with a '$' and have a
738061da546Spatrick         // '#CC' checksum
739061da546Spatrick         if (m_bytes[0] == '$' && total_length > 4) {
740061da546Spatrick           for (size_t i = 0; !binary && i < total_length; ++i) {
741061da546Spatrick             unsigned char c = m_bytes[i];
742dda28197Spatrick             if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
743061da546Spatrick               binary = true;
744061da546Spatrick             }
745061da546Spatrick           }
746061da546Spatrick         }
747061da546Spatrick         if (binary) {
748061da546Spatrick           StreamString strm;
749061da546Spatrick           // Packet header...
750061da546Spatrick           if (CompressionIsEnabled())
751061da546Spatrick             strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
752061da546Spatrick                         (uint64_t)original_packet_size, (uint64_t)total_length,
753061da546Spatrick                         m_bytes[0]);
754061da546Spatrick           else
755061da546Spatrick             strm.Printf("<%4" PRIu64 "> read packet: %c",
756061da546Spatrick                         (uint64_t)total_length, m_bytes[0]);
757061da546Spatrick           for (size_t i = content_start; i < content_end; ++i) {
758061da546Spatrick             // Remove binary escaped bytes when displaying the packet...
759061da546Spatrick             const char ch = m_bytes[i];
760061da546Spatrick             if (ch == 0x7d) {
761061da546Spatrick               // 0x7d is the escape character.  The next character is to be
762061da546Spatrick               // XOR'd with 0x20.
763061da546Spatrick               const char escapee = m_bytes[++i] ^ 0x20;
764061da546Spatrick               strm.Printf("%2.2x", escapee);
765061da546Spatrick             } else {
766061da546Spatrick               strm.Printf("%2.2x", (uint8_t)ch);
767061da546Spatrick             }
768061da546Spatrick           }
769061da546Spatrick           // Packet footer...
770061da546Spatrick           strm.Printf("%c%c%c", m_bytes[total_length - 3],
771061da546Spatrick                       m_bytes[total_length - 2], m_bytes[total_length - 1]);
772061da546Spatrick           log->PutString(strm.GetString());
773061da546Spatrick         } else {
774061da546Spatrick           if (CompressionIsEnabled())
775061da546Spatrick             LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
776061da546Spatrick                       (uint64_t)original_packet_size, (uint64_t)total_length,
777061da546Spatrick                       (int)(total_length), m_bytes.c_str());
778061da546Spatrick           else
779061da546Spatrick             LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
780061da546Spatrick                       (uint64_t)total_length, (int)(total_length),
781061da546Spatrick                       m_bytes.c_str());
782061da546Spatrick         }
783061da546Spatrick       }
784061da546Spatrick 
785061da546Spatrick       m_history.AddPacket(m_bytes, total_length,
786061da546Spatrick                           GDBRemotePacket::ePacketTypeRecv, total_length);
787061da546Spatrick 
788061da546Spatrick       // Copy the packet from m_bytes to packet_str expanding the run-length
789dda28197Spatrick       // encoding in the process.
790dda28197Spatrick       std ::string packet_str =
791dda28197Spatrick           ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
792061da546Spatrick       packet = StringExtractorGDBRemote(packet_str);
793061da546Spatrick 
794061da546Spatrick       if (m_bytes[0] == '$' || m_bytes[0] == '%') {
795061da546Spatrick         assert(checksum_idx < m_bytes.size());
796061da546Spatrick         if (::isxdigit(m_bytes[checksum_idx + 0]) ||
797061da546Spatrick             ::isxdigit(m_bytes[checksum_idx + 1])) {
798061da546Spatrick           if (GetSendAcks()) {
799061da546Spatrick             const char *packet_checksum_cstr = &m_bytes[checksum_idx];
800061da546Spatrick             char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
801061da546Spatrick             char actual_checksum = CalculcateChecksum(
802061da546Spatrick                 llvm::StringRef(m_bytes).slice(content_start, content_end));
803061da546Spatrick             success = packet_checksum == actual_checksum;
804061da546Spatrick             if (!success) {
805061da546Spatrick               LLDB_LOGF(log,
806061da546Spatrick                         "error: checksum mismatch: %.*s expected 0x%2.2x, "
807061da546Spatrick                         "got 0x%2.2x",
808061da546Spatrick                         (int)(total_length), m_bytes.c_str(),
809061da546Spatrick                         (uint8_t)packet_checksum, (uint8_t)actual_checksum);
810061da546Spatrick             }
811061da546Spatrick             // Send the ack or nack if needed
812061da546Spatrick             if (!success)
813061da546Spatrick               SendNack();
814061da546Spatrick             else
815061da546Spatrick               SendAck();
816061da546Spatrick           }
817061da546Spatrick         } else {
818061da546Spatrick           success = false;
819061da546Spatrick           LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
820061da546Spatrick                     m_bytes.c_str());
821061da546Spatrick         }
822061da546Spatrick       }
823061da546Spatrick 
824061da546Spatrick       m_bytes.erase(0, total_length);
825061da546Spatrick       packet.SetFilePos(0);
826061da546Spatrick 
827061da546Spatrick       if (isNotifyPacket)
828061da546Spatrick         return GDBRemoteCommunication::PacketType::Notify;
829061da546Spatrick       else
830061da546Spatrick         return GDBRemoteCommunication::PacketType::Standard;
831061da546Spatrick     }
832061da546Spatrick   }
833061da546Spatrick   packet.Clear();
834061da546Spatrick   return GDBRemoteCommunication::PacketType::Invalid;
835061da546Spatrick }
836061da546Spatrick 
StartListenThread(const char * hostname,uint16_t port)837061da546Spatrick Status GDBRemoteCommunication::StartListenThread(const char *hostname,
838061da546Spatrick                                                  uint16_t port) {
839061da546Spatrick   if (m_listen_thread.IsJoinable())
840061da546Spatrick     return Status("listen thread already running");
841061da546Spatrick 
842061da546Spatrick   char listen_url[512];
843061da546Spatrick   if (hostname && hostname[0])
844061da546Spatrick     snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
845061da546Spatrick   else
846061da546Spatrick     snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
847061da546Spatrick   m_listen_url = listen_url;
848dda28197Spatrick   SetConnection(std::make_unique<ConnectionFileDescriptor>());
849061da546Spatrick   llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
850*f6aab3d8Srobert       listen_url, [this] { return GDBRemoteCommunication::ListenThread(); });
851061da546Spatrick   if (!listen_thread)
852061da546Spatrick     return Status(listen_thread.takeError());
853061da546Spatrick   m_listen_thread = *listen_thread;
854061da546Spatrick 
855061da546Spatrick   return Status();
856061da546Spatrick }
857061da546Spatrick 
JoinListenThread()858061da546Spatrick bool GDBRemoteCommunication::JoinListenThread() {
859061da546Spatrick   if (m_listen_thread.IsJoinable())
860061da546Spatrick     m_listen_thread.Join(nullptr);
861061da546Spatrick   return true;
862061da546Spatrick }
863061da546Spatrick 
ListenThread()864*f6aab3d8Srobert lldb::thread_result_t GDBRemoteCommunication::ListenThread() {
865061da546Spatrick   Status error;
866061da546Spatrick   ConnectionFileDescriptor *connection =
867*f6aab3d8Srobert       (ConnectionFileDescriptor *)GetConnection();
868061da546Spatrick 
869061da546Spatrick   if (connection) {
870061da546Spatrick     // Do the listen on another thread so we can continue on...
871*f6aab3d8Srobert     if (connection->Connect(
872*f6aab3d8Srobert             m_listen_url.c_str(),
873*f6aab3d8Srobert             [this](llvm::StringRef port_str) {
874*f6aab3d8Srobert               uint16_t port = 0;
875*f6aab3d8Srobert               llvm::to_integer(port_str, port, 10);
876*f6aab3d8Srobert               m_port_promise.set_value(port);
877*f6aab3d8Srobert             },
878*f6aab3d8Srobert             &error) != eConnectionStatusSuccess)
879*f6aab3d8Srobert       SetConnection(nullptr);
880061da546Spatrick   }
881061da546Spatrick   return {};
882061da546Spatrick }
883061da546Spatrick 
StartDebugserverProcess(const char * url,Platform * platform,ProcessLaunchInfo & launch_info,uint16_t * port,const Args * inferior_args,int pass_comm_fd)884061da546Spatrick Status GDBRemoteCommunication::StartDebugserverProcess(
885061da546Spatrick     const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
886061da546Spatrick     uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
887*f6aab3d8Srobert   Log *log = GetLog(GDBRLog::Process);
888061da546Spatrick   LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
889061da546Spatrick             __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
890061da546Spatrick 
891061da546Spatrick   Status error;
892061da546Spatrick   // If we locate debugserver, keep that located version around
893061da546Spatrick   static FileSpec g_debugserver_file_spec;
894061da546Spatrick 
895061da546Spatrick   char debugserver_path[PATH_MAX];
896061da546Spatrick   FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
897061da546Spatrick 
898061da546Spatrick   Environment host_env = Host::GetEnvironment();
899061da546Spatrick 
900061da546Spatrick   // Always check to see if we have an environment override for the path to the
901061da546Spatrick   // debugserver to use and use it if we do.
902061da546Spatrick   std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
903061da546Spatrick   if (!env_debugserver_path.empty()) {
904061da546Spatrick     debugserver_file_spec.SetFile(env_debugserver_path,
905061da546Spatrick                                   FileSpec::Style::native);
906061da546Spatrick     LLDB_LOGF(log,
907061da546Spatrick               "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
908061da546Spatrick               "from environment variable: %s",
909061da546Spatrick               __FUNCTION__, env_debugserver_path.c_str());
910061da546Spatrick   } else
911061da546Spatrick     debugserver_file_spec = g_debugserver_file_spec;
912061da546Spatrick   bool debugserver_exists =
913061da546Spatrick       FileSystem::Instance().Exists(debugserver_file_spec);
914061da546Spatrick   if (!debugserver_exists) {
915061da546Spatrick     // The debugserver binary is in the LLDB.framework/Resources directory.
916061da546Spatrick     debugserver_file_spec = HostInfo::GetSupportExeDir();
917061da546Spatrick     if (debugserver_file_spec) {
918061da546Spatrick       debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
919061da546Spatrick       debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
920061da546Spatrick       if (debugserver_exists) {
921061da546Spatrick         LLDB_LOGF(log,
922061da546Spatrick                   "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
923061da546Spatrick                   __FUNCTION__, debugserver_file_spec.GetPath().c_str());
924061da546Spatrick 
925061da546Spatrick         g_debugserver_file_spec = debugserver_file_spec;
926061da546Spatrick       } else {
927061da546Spatrick         if (platform)
928061da546Spatrick           debugserver_file_spec =
929061da546Spatrick               platform->LocateExecutable(DEBUGSERVER_BASENAME);
930061da546Spatrick         else
931061da546Spatrick           debugserver_file_spec.Clear();
932061da546Spatrick         if (debugserver_file_spec) {
933061da546Spatrick           // Platform::LocateExecutable() wouldn't return a path if it doesn't
934061da546Spatrick           // exist
935061da546Spatrick           debugserver_exists = true;
936061da546Spatrick         } else {
937061da546Spatrick           LLDB_LOGF(log,
938061da546Spatrick                     "GDBRemoteCommunication::%s() could not find "
939061da546Spatrick                     "gdb-remote stub exe '%s'",
940061da546Spatrick                     __FUNCTION__, debugserver_file_spec.GetPath().c_str());
941061da546Spatrick         }
942061da546Spatrick         // Don't cache the platform specific GDB server binary as it could
943061da546Spatrick         // change from platform to platform
944061da546Spatrick         g_debugserver_file_spec.Clear();
945061da546Spatrick       }
946061da546Spatrick     }
947061da546Spatrick   }
948061da546Spatrick 
949061da546Spatrick   if (debugserver_exists) {
950061da546Spatrick     debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
951061da546Spatrick 
952061da546Spatrick     Args &debugserver_args = launch_info.GetArguments();
953061da546Spatrick     debugserver_args.Clear();
954061da546Spatrick 
955061da546Spatrick     // Start args with "debugserver /file/path -r --"
956061da546Spatrick     debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
957061da546Spatrick 
958061da546Spatrick #if !defined(__APPLE__)
959061da546Spatrick     // First argument to lldb-server must be mode in which to run.
960061da546Spatrick     debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
961061da546Spatrick #endif
962061da546Spatrick 
963061da546Spatrick     // If a url is supplied then use it
964061da546Spatrick     if (url)
965061da546Spatrick       debugserver_args.AppendArgument(llvm::StringRef(url));
966061da546Spatrick 
967061da546Spatrick     if (pass_comm_fd >= 0) {
968061da546Spatrick       StreamString fd_arg;
969061da546Spatrick       fd_arg.Printf("--fd=%i", pass_comm_fd);
970061da546Spatrick       debugserver_args.AppendArgument(fd_arg.GetString());
971061da546Spatrick       // Send "pass_comm_fd" down to the inferior so it can use it to
972061da546Spatrick       // communicate back with this process
973061da546Spatrick       launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
974061da546Spatrick     }
975061da546Spatrick 
976061da546Spatrick     // use native registers, not the GDB registers
977061da546Spatrick     debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
978061da546Spatrick 
979061da546Spatrick     if (launch_info.GetLaunchInSeparateProcessGroup()) {
980061da546Spatrick       debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
981061da546Spatrick     }
982061da546Spatrick 
983061da546Spatrick     llvm::SmallString<128> named_pipe_path;
984061da546Spatrick     // socket_pipe is used by debug server to communicate back either
985061da546Spatrick     // TCP port or domain socket name which it listens on.
986061da546Spatrick     // The second purpose of the pipe to serve as a synchronization point -
987061da546Spatrick     // once data is written to the pipe, debug server is up and running.
988061da546Spatrick     Pipe socket_pipe;
989061da546Spatrick 
990061da546Spatrick     // port is null when debug server should listen on domain socket - we're
991061da546Spatrick     // not interested in port value but rather waiting for debug server to
992061da546Spatrick     // become available.
993061da546Spatrick     if (pass_comm_fd == -1) {
994061da546Spatrick       if (url) {
995061da546Spatrick // Create a temporary file to get the stdout/stderr and redirect the output of
996061da546Spatrick // the command into this file. We will later read this file if all goes well
997061da546Spatrick // and fill the data into "command_output_ptr"
998061da546Spatrick #if defined(__APPLE__)
999061da546Spatrick         // Binding to port zero, we need to figure out what port it ends up
1000061da546Spatrick         // using using a named pipe...
1001061da546Spatrick         error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1002061da546Spatrick                                                  false, named_pipe_path);
1003061da546Spatrick         if (error.Fail()) {
1004061da546Spatrick           LLDB_LOGF(log,
1005061da546Spatrick                     "GDBRemoteCommunication::%s() "
1006061da546Spatrick                     "named pipe creation failed: %s",
1007061da546Spatrick                     __FUNCTION__, error.AsCString());
1008061da546Spatrick           return error;
1009061da546Spatrick         }
1010061da546Spatrick         debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1011061da546Spatrick         debugserver_args.AppendArgument(named_pipe_path);
1012061da546Spatrick #else
1013061da546Spatrick         // Binding to port zero, we need to figure out what port it ends up
1014061da546Spatrick         // using using an unnamed pipe...
1015061da546Spatrick         error = socket_pipe.CreateNew(true);
1016061da546Spatrick         if (error.Fail()) {
1017061da546Spatrick           LLDB_LOGF(log,
1018061da546Spatrick                     "GDBRemoteCommunication::%s() "
1019061da546Spatrick                     "unnamed pipe creation failed: %s",
1020061da546Spatrick                     __FUNCTION__, error.AsCString());
1021061da546Spatrick           return error;
1022061da546Spatrick         }
1023061da546Spatrick         pipe_t write = socket_pipe.GetWritePipe();
1024061da546Spatrick         debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1025061da546Spatrick         debugserver_args.AppendArgument(llvm::to_string(write));
1026061da546Spatrick         launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1027061da546Spatrick #endif
1028061da546Spatrick       } else {
1029061da546Spatrick         // No host and port given, so lets listen on our end and make the
1030061da546Spatrick         // debugserver connect to us..
1031061da546Spatrick         error = StartListenThread("127.0.0.1", 0);
1032061da546Spatrick         if (error.Fail()) {
1033061da546Spatrick           LLDB_LOGF(log,
1034061da546Spatrick                     "GDBRemoteCommunication::%s() unable to start listen "
1035061da546Spatrick                     "thread: %s",
1036061da546Spatrick                     __FUNCTION__, error.AsCString());
1037061da546Spatrick           return error;
1038061da546Spatrick         }
1039061da546Spatrick 
1040061da546Spatrick         // Wait for 10 seconds to resolve the bound port
1041*f6aab3d8Srobert         std::future<uint16_t> port_future = m_port_promise.get_future();
1042*f6aab3d8Srobert         uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==
1043*f6aab3d8Srobert                                  std::future_status::ready
1044*f6aab3d8Srobert                              ? port_future.get()
1045*f6aab3d8Srobert                              : 0;
1046061da546Spatrick         if (port_ > 0) {
1047061da546Spatrick           char port_cstr[32];
1048061da546Spatrick           snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1049061da546Spatrick           // Send the host and port down that debugserver and specify an option
1050061da546Spatrick           // so that it connects back to the port we are listening to in this
1051061da546Spatrick           // process
1052061da546Spatrick           debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1053061da546Spatrick           debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1054061da546Spatrick           if (port)
1055061da546Spatrick             *port = port_;
1056061da546Spatrick         } else {
1057061da546Spatrick           error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1058061da546Spatrick           LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",
1059061da546Spatrick                     __FUNCTION__, error.AsCString());
1060061da546Spatrick           return error;
1061061da546Spatrick         }
1062061da546Spatrick       }
1063061da546Spatrick     }
1064061da546Spatrick     std::string env_debugserver_log_file =
1065061da546Spatrick         host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1066061da546Spatrick     if (!env_debugserver_log_file.empty()) {
1067061da546Spatrick       debugserver_args.AppendArgument(
1068061da546Spatrick           llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
1069061da546Spatrick     }
1070061da546Spatrick 
1071061da546Spatrick #if defined(__APPLE__)
1072061da546Spatrick     const char *env_debugserver_log_flags =
1073061da546Spatrick         getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1074061da546Spatrick     if (env_debugserver_log_flags) {
1075061da546Spatrick       debugserver_args.AppendArgument(
1076061da546Spatrick           llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
1077061da546Spatrick     }
1078061da546Spatrick #else
1079061da546Spatrick     std::string env_debugserver_log_channels =
1080061da546Spatrick         host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1081061da546Spatrick     if (!env_debugserver_log_channels.empty()) {
1082061da546Spatrick       debugserver_args.AppendArgument(
1083061da546Spatrick           llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1084061da546Spatrick               .str());
1085061da546Spatrick     }
1086061da546Spatrick #endif
1087061da546Spatrick 
1088061da546Spatrick     // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1089061da546Spatrick     // env var doesn't come back.
1090061da546Spatrick     uint32_t env_var_index = 1;
1091061da546Spatrick     bool has_env_var;
1092061da546Spatrick     do {
1093061da546Spatrick       char env_var_name[64];
1094061da546Spatrick       snprintf(env_var_name, sizeof(env_var_name),
1095061da546Spatrick                "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1096061da546Spatrick       std::string extra_arg = host_env.lookup(env_var_name);
1097061da546Spatrick       has_env_var = !extra_arg.empty();
1098061da546Spatrick 
1099061da546Spatrick       if (has_env_var) {
1100061da546Spatrick         debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1101061da546Spatrick         LLDB_LOGF(log,
1102061da546Spatrick                   "GDBRemoteCommunication::%s adding env var %s contents "
1103061da546Spatrick                   "to stub command line (%s)",
1104061da546Spatrick                   __FUNCTION__, env_var_name, extra_arg.c_str());
1105061da546Spatrick       }
1106061da546Spatrick     } while (has_env_var);
1107061da546Spatrick 
1108061da546Spatrick     if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1109061da546Spatrick       debugserver_args.AppendArgument(llvm::StringRef("--"));
1110061da546Spatrick       debugserver_args.AppendArguments(*inferior_args);
1111061da546Spatrick     }
1112061da546Spatrick 
1113061da546Spatrick     // Copy the current environment to the gdbserver/debugserver instance
1114061da546Spatrick     launch_info.GetEnvironment() = host_env;
1115061da546Spatrick 
1116061da546Spatrick     // Close STDIN, STDOUT and STDERR.
1117061da546Spatrick     launch_info.AppendCloseFileAction(STDIN_FILENO);
1118061da546Spatrick     launch_info.AppendCloseFileAction(STDOUT_FILENO);
1119061da546Spatrick     launch_info.AppendCloseFileAction(STDERR_FILENO);
1120061da546Spatrick 
1121061da546Spatrick     // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1122061da546Spatrick     launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1123061da546Spatrick     launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1124061da546Spatrick     launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1125061da546Spatrick 
1126061da546Spatrick     if (log) {
1127061da546Spatrick       StreamString string_stream;
1128061da546Spatrick       Platform *const platform = nullptr;
1129061da546Spatrick       launch_info.Dump(string_stream, platform);
1130061da546Spatrick       LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",
1131061da546Spatrick                 string_stream.GetData());
1132061da546Spatrick     }
1133061da546Spatrick     error = Host::LaunchProcess(launch_info);
1134061da546Spatrick 
1135061da546Spatrick     if (error.Success() &&
1136061da546Spatrick         (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1137061da546Spatrick         pass_comm_fd == -1) {
1138061da546Spatrick       if (named_pipe_path.size() > 0) {
1139061da546Spatrick         error = socket_pipe.OpenAsReader(named_pipe_path, false);
1140061da546Spatrick         if (error.Fail())
1141061da546Spatrick           LLDB_LOGF(log,
1142061da546Spatrick                     "GDBRemoteCommunication::%s() "
1143061da546Spatrick                     "failed to open named pipe %s for reading: %s",
1144061da546Spatrick                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1145061da546Spatrick       }
1146061da546Spatrick 
1147061da546Spatrick       if (socket_pipe.CanWrite())
1148061da546Spatrick         socket_pipe.CloseWriteFileDescriptor();
1149061da546Spatrick       if (socket_pipe.CanRead()) {
1150061da546Spatrick         char port_cstr[PATH_MAX] = {0};
1151061da546Spatrick         port_cstr[0] = '\0';
1152061da546Spatrick         size_t num_bytes = sizeof(port_cstr);
1153061da546Spatrick         // Read port from pipe with 10 second timeout.
1154061da546Spatrick         error = socket_pipe.ReadWithTimeout(
1155061da546Spatrick             port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1156061da546Spatrick         if (error.Success() && (port != nullptr)) {
1157061da546Spatrick           assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1158*f6aab3d8Srobert           uint16_t child_port = 0;
1159*f6aab3d8Srobert           // FIXME: improve error handling
1160*f6aab3d8Srobert           llvm::to_integer(port_cstr, child_port);
1161061da546Spatrick           if (*port == 0 || *port == child_port) {
1162061da546Spatrick             *port = child_port;
1163061da546Spatrick             LLDB_LOGF(log,
1164061da546Spatrick                       "GDBRemoteCommunication::%s() "
1165061da546Spatrick                       "debugserver listens %u port",
1166061da546Spatrick                       __FUNCTION__, *port);
1167061da546Spatrick           } else {
1168061da546Spatrick             LLDB_LOGF(log,
1169061da546Spatrick                       "GDBRemoteCommunication::%s() "
1170061da546Spatrick                       "debugserver listening on port "
1171061da546Spatrick                       "%d but requested port was %d",
1172061da546Spatrick                       __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));
1173061da546Spatrick           }
1174061da546Spatrick         } else {
1175061da546Spatrick           LLDB_LOGF(log,
1176061da546Spatrick                     "GDBRemoteCommunication::%s() "
1177061da546Spatrick                     "failed to read a port value from pipe %s: %s",
1178061da546Spatrick                     __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1179061da546Spatrick         }
1180061da546Spatrick         socket_pipe.Close();
1181061da546Spatrick       }
1182061da546Spatrick 
1183061da546Spatrick       if (named_pipe_path.size() > 0) {
1184061da546Spatrick         const auto err = socket_pipe.Delete(named_pipe_path);
1185061da546Spatrick         if (err.Fail()) {
1186061da546Spatrick           LLDB_LOGF(log,
1187061da546Spatrick                     "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1188061da546Spatrick                     __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
1189061da546Spatrick         }
1190061da546Spatrick       }
1191061da546Spatrick 
1192061da546Spatrick       // Make sure we actually connect with the debugserver...
1193061da546Spatrick       JoinListenThread();
1194061da546Spatrick     }
1195061da546Spatrick   } else {
1196061da546Spatrick     error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1197061da546Spatrick   }
1198061da546Spatrick 
1199061da546Spatrick   if (error.Fail()) {
1200061da546Spatrick     LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1201061da546Spatrick               error.AsCString());
1202061da546Spatrick   }
1203061da546Spatrick 
1204061da546Spatrick   return error;
1205061da546Spatrick }
1206061da546Spatrick 
DumpHistory(Stream & strm)1207061da546Spatrick void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1208061da546Spatrick 
1209061da546Spatrick llvm::Error
ConnectLocally(GDBRemoteCommunication & client,GDBRemoteCommunication & server)1210061da546Spatrick GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1211061da546Spatrick                                        GDBRemoteCommunication &server) {
1212061da546Spatrick   const bool child_processes_inherit = false;
1213061da546Spatrick   const int backlog = 5;
1214061da546Spatrick   TCPSocket listen_socket(true, child_processes_inherit);
1215061da546Spatrick   if (llvm::Error error =
1216be691f3bSpatrick           listen_socket.Listen("localhost:0", backlog).ToError())
1217061da546Spatrick     return error;
1218061da546Spatrick 
1219*f6aab3d8Srobert   Socket *accept_socket = nullptr;
1220061da546Spatrick   std::future<Status> accept_status = std::async(
1221061da546Spatrick       std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1222061da546Spatrick 
1223061da546Spatrick   llvm::SmallString<32> remote_addr;
1224061da546Spatrick   llvm::raw_svector_ostream(remote_addr)
1225be691f3bSpatrick       << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1226061da546Spatrick 
1227061da546Spatrick   std::unique_ptr<ConnectionFileDescriptor> conn_up(
1228061da546Spatrick       new ConnectionFileDescriptor());
1229061da546Spatrick   Status status;
1230061da546Spatrick   if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1231061da546Spatrick     return llvm::createStringError(llvm::inconvertibleErrorCode(),
1232061da546Spatrick                                    "Unable to connect: %s", status.AsCString());
1233061da546Spatrick 
1234dda28197Spatrick   client.SetConnection(std::move(conn_up));
1235061da546Spatrick   if (llvm::Error error = accept_status.get().ToError())
1236061da546Spatrick     return error;
1237061da546Spatrick 
1238dda28197Spatrick   server.SetConnection(
1239dda28197Spatrick       std::make_unique<ConnectionFileDescriptor>(accept_socket));
1240061da546Spatrick   return llvm::Error::success();
1241061da546Spatrick }
1242061da546Spatrick 
ScopedTimeout(GDBRemoteCommunication & gdb_comm,std::chrono::seconds timeout)1243061da546Spatrick GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1244061da546Spatrick     GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1245*f6aab3d8Srobert     : m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {
1246061da546Spatrick   auto curr_timeout = gdb_comm.GetPacketTimeout();
1247061da546Spatrick   // Only update the timeout if the timeout is greater than the current
1248061da546Spatrick   // timeout. If the current timeout is larger, then just use that.
1249061da546Spatrick   if (curr_timeout < timeout) {
1250061da546Spatrick     m_timeout_modified = true;
1251061da546Spatrick     m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1252061da546Spatrick   }
1253061da546Spatrick }
1254061da546Spatrick 
~ScopedTimeout()1255061da546Spatrick GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1256061da546Spatrick   // Only restore the timeout if we set it in the constructor.
1257061da546Spatrick   if (m_timeout_modified)
1258061da546Spatrick     m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1259061da546Spatrick }
1260061da546Spatrick 
format(const GDBRemoteCommunication::PacketResult & result,raw_ostream & Stream,StringRef Style)1261061da546Spatrick void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1262061da546Spatrick     const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1263061da546Spatrick     StringRef Style) {
1264061da546Spatrick   using PacketResult = GDBRemoteCommunication::PacketResult;
1265061da546Spatrick 
1266061da546Spatrick   switch (result) {
1267061da546Spatrick   case PacketResult::Success:
1268061da546Spatrick     Stream << "Success";
1269061da546Spatrick     break;
1270061da546Spatrick   case PacketResult::ErrorSendFailed:
1271061da546Spatrick     Stream << "ErrorSendFailed";
1272061da546Spatrick     break;
1273061da546Spatrick   case PacketResult::ErrorSendAck:
1274061da546Spatrick     Stream << "ErrorSendAck";
1275061da546Spatrick     break;
1276061da546Spatrick   case PacketResult::ErrorReplyFailed:
1277061da546Spatrick     Stream << "ErrorReplyFailed";
1278061da546Spatrick     break;
1279061da546Spatrick   case PacketResult::ErrorReplyTimeout:
1280061da546Spatrick     Stream << "ErrorReplyTimeout";
1281061da546Spatrick     break;
1282061da546Spatrick   case PacketResult::ErrorReplyInvalid:
1283061da546Spatrick     Stream << "ErrorReplyInvalid";
1284061da546Spatrick     break;
1285061da546Spatrick   case PacketResult::ErrorReplyAck:
1286061da546Spatrick     Stream << "ErrorReplyAck";
1287061da546Spatrick     break;
1288061da546Spatrick   case PacketResult::ErrorDisconnected:
1289061da546Spatrick     Stream << "ErrorDisconnected";
1290061da546Spatrick     break;
1291061da546Spatrick   case PacketResult::ErrorNoSequenceLock:
1292061da546Spatrick     Stream << "ErrorNoSequenceLock";
1293061da546Spatrick     break;
1294061da546Spatrick   }
1295061da546Spatrick }
1296dda28197Spatrick 
ExpandRLE(std::string packet)1297dda28197Spatrick std::string GDBRemoteCommunication::ExpandRLE(std::string packet) {
1298dda28197Spatrick   // Reserve enough byte for the most common case (no RLE used).
1299dda28197Spatrick   std::string decoded;
1300dda28197Spatrick   decoded.reserve(packet.size());
1301dda28197Spatrick   for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1302dda28197Spatrick     if (*c == '*') {
1303dda28197Spatrick       // '*' indicates RLE. Next character will give us the repeat count and
1304dda28197Spatrick       // previous character is what is to be repeated.
1305dda28197Spatrick       char char_to_repeat = decoded.back();
1306dda28197Spatrick       // Number of time the previous character is repeated.
1307dda28197Spatrick       int repeat_count = *++c + 3 - ' ';
1308dda28197Spatrick       // We have the char_to_repeat and repeat_count. Now push it in the
1309dda28197Spatrick       // packet.
1310dda28197Spatrick       for (int i = 0; i < repeat_count; ++i)
1311dda28197Spatrick         decoded.push_back(char_to_repeat);
1312dda28197Spatrick     } else if (*c == 0x7d) {
1313dda28197Spatrick       // 0x7d is the escape character.  The next character is to be XOR'd with
1314dda28197Spatrick       // 0x20.
1315dda28197Spatrick       char escapee = *++c ^ 0x20;
1316dda28197Spatrick       decoded.push_back(escapee);
1317dda28197Spatrick     } else {
1318dda28197Spatrick       decoded.push_back(*c);
1319dda28197Spatrick     }
1320dda28197Spatrick   }
1321dda28197Spatrick   return decoded;
1322dda28197Spatrick }
1323