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