blob: 2e0a1a62aa183b0c23c2b8054df4ec164d57407a [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Chris Lattner30fdc8d2010-06-08 16:52:24 +00009#include "GDBRemoteCommunication.h"
10
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000011#include <future>
Johnny Chena5663552011-05-13 20:07:25 +000012#include <limits.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000013#include <string.h>
Greg Clayton91a9b2472013-12-04 19:19:12 +000014#include <sys/stat.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015
Greg Claytonc1422c12012-04-09 22:46:21 +000016#include "lldb/Core/StreamFile.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000017#include "lldb/Host/ConnectionFileDescriptor.h"
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +000018#include "lldb/Host/FileSystem.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000019#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000020#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000021#include "lldb/Host/Pipe.h"
Zachary Turner98688922014-08-06 18:16:26 +000022#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000023#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000024#include "lldb/Host/ThreadLauncher.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000025#include "lldb/Host/common/TCPSocket.h"
26#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
Greg Clayton6988abc2015-10-19 20:44:01 +000027#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000028#include "lldb/Target/Process.h"
Zachary Turner5713a052017-03-22 18:40:07 +000029#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000030#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000031#include "lldb/Utility/RegularExpression.h"
32#include "lldb/Utility/StreamString.h"
Oleksiy Vyalov4536c452015-02-05 16:29:12 +000033#include "llvm/ADT/SmallString.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000034#include "llvm/Support/ScopedPrinter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "ProcessGDBRemoteLog.h"
37
Todd Fiala015d8182014-07-22 23:41:36 +000038#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +000039#define DEBUGSERVER_BASENAME "debugserver"
Todd Fiala015d8182014-07-22 23:41:36 +000040#else
Kate Stoneb9c1b512016-09-06 20:57:50 +000041#define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000042#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000043
Raphael Isemann46508f62019-01-25 08:21:47 +000044#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000045#include <compression.h>
46#endif
47
Kate Stoneb9c1b512016-09-06 20:57:50 +000048#if defined(HAVE_LIBZ)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000049#include <zlib.h>
50#endif
51
Chris Lattner30fdc8d2010-06-08 16:52:24 +000052using namespace lldb;
53using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000054using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000055
56//----------------------------------------------------------------------
57// GDBRemoteCommunication constructor
58//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000059GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
60 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000061 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +000062#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000063 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +000064#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000065 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +000066#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +000067 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
68 m_send_acks(true), m_compression_type(CompressionType::None),
Raphael Isemann46508f62019-01-25 08:21:47 +000069 m_listen_url() {
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070}
71
72//----------------------------------------------------------------------
73// Destructor
74//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000075GDBRemoteCommunication::~GDBRemoteCommunication() {
76 if (IsConnected()) {
77 Disconnect();
78 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +000079
Raphael Isemann46508f62019-01-25 08:21:47 +000080#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda8460bb02018-12-18 23:45:45 +000081 if (m_decompression_scratch)
82 free (m_decompression_scratch);
Raphael Isemann46508f62019-01-25 08:21:47 +000083#endif
Jason Molenda8460bb02018-12-18 23:45:45 +000084
Adrian Prantl05097242018-04-30 16:49:04 +000085 // Stop the communications read thread which is used to parse all incoming
86 // packets. This function will block until the read thread returns.
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 if (m_read_thread_enabled)
88 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089}
90
Kate Stoneb9c1b512016-09-06 20:57:50 +000091char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
92 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 for (char c : payload)
95 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +000096
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000098}
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100size_t GDBRemoteCommunication::SendAck() {
101 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
102 ConnectionStatus status = eConnectionStatusSuccess;
103 char ch = '+';
104 const size_t bytes_written = Write(&ch, 1, status, NULL);
105 if (log)
106 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000107 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
108 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 return bytes_written;
110}
111
112size_t GDBRemoteCommunication::SendNack() {
113 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
114 ConnectionStatus status = eConnectionStatusSuccess;
115 char ch = '-';
116 const size_t bytes_written = Write(&ch, 1, status, NULL);
117 if (log)
118 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000119 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
120 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121 return bytes_written;
122}
123
124GDBRemoteCommunication::PacketResult
125GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
Aaron Smith981e6352019-02-07 18:22:00 +0000126 StreamString packet(0, 4, eByteOrderBig);
127 packet.PutChar('$');
128 packet.Write(payload.data(), payload.size());
129 packet.PutChar('#');
130 packet.PutHex8(CalculcateChecksum(payload));
131 std::string packet_str = packet.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132
Aaron Smith981e6352019-02-07 18:22:00 +0000133 return SendRawPacketNoLock(packet_str);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000134}
135
136GDBRemoteCommunication::PacketResult
137GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
138 bool skip_ack) {
139 if (IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000141 ConnectionStatus status = eConnectionStatusSuccess;
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000142 const char *packet_data = packet.data();
143 const size_t packet_length = packet.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000144 size_t bytes_written = Write(packet_data, packet_length, status, NULL);
145 if (log) {
146 size_t binary_start_offset = 0;
147 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
148 0) {
149 const char *first_comma = strchr(packet_data, ',');
150 if (first_comma) {
151 const char *second_comma = strchr(first_comma + 1, ',');
152 if (second_comma)
153 binary_start_offset = second_comma - packet_data + 1;
Greg Claytonc1422c12012-04-09 22:46:21 +0000154 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000156
Adrian Prantl05097242018-04-30 16:49:04 +0000157 // If logging was just enabled and we have history, then dump out what we
158 // have to the log so we get the historical context. The Dump() call that
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159 // logs all of the packet will set a boolean so that we don't dump this
Adrian Prantl05097242018-04-30 16:49:04 +0000160 // more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 if (!m_history.DidDumpToLog())
162 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000163
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 if (binary_start_offset) {
165 StreamString strm;
166 // Print non binary data header
167 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
168 (int)binary_start_offset, packet_data);
169 const uint8_t *p;
170 // Print binary data exactly as sent
171 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
172 ++p)
173 strm.Printf("\\x%2.2x", *p);
174 // Print the checksum
175 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000176 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177 } else
178 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
179 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000180 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000181
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000182 m_history.AddPacket(packet.str(), packet_length,
183 GDBRemoteCommunicationHistory::ePacketTypeSend,
184 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185
186 if (bytes_written == packet_length) {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000187 if (!skip_ack && GetSendAcks())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188 return GetAck();
189 else
190 return PacketResult::Success;
191 } else {
192 if (log)
193 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
194 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000195 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000196 }
197 return PacketResult::ErrorSendFailed;
198}
199
200GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
201 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000202 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000203 if (result == PacketResult::Success) {
204 if (packet.GetResponseType() ==
205 StringExtractorGDBRemote::ResponseType::eAck)
206 return PacketResult::Success;
207 else
208 return PacketResult::ErrorSendAck;
209 }
210 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000211}
212
Greg Clayton3dedae12013-12-06 21:45:27 +0000213GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000214GDBRemoteCommunication::ReadPacketWithOutputSupport(
215 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
216 bool sync_on_timeout,
217 llvm::function_ref<void(llvm::StringRef)> output_callback) {
218 auto result = ReadPacket(response, timeout, sync_on_timeout);
219 while (result == PacketResult::Success && response.IsNormalResponse() &&
220 response.PeekChar() == 'O') {
221 response.GetChar();
222 std::string output;
223 if (response.GetHexByteString(output))
224 output_callback(output);
225 result = ReadPacket(response, timeout, sync_on_timeout);
226 }
227 return result;
228}
229
230GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000231GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000232 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 bool sync_on_timeout) {
234 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000235 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000237 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000238}
239
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000240// This function is called when a packet is requested.
241// A whole packet is popped from the packet queue and returned to the caller.
Adrian Prantl05097242018-04-30 16:49:04 +0000242// Packets are placed into this queue from the communication read thread. See
243// GDBRemoteCommunication::AppendBytesToCache.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000244GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000246 Timeout<std::micro> timeout) {
247 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
248 // lock down the packet queue
249 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000250
Pavel Labath1eff73c2016-11-24 10:54:49 +0000251 if (!timeout)
252 m_condition_queue_not_empty.wait(lock, pred);
253 else {
254 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
255 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 if (!IsConnected())
257 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 }
259
Pavel Labath1eff73c2016-11-24 10:54:49 +0000260 // get the front element of the queue
261 response = m_packet_queue.front();
262
263 // remove the front element
264 m_packet_queue.pop();
265
266 // we got a packet
267 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000269
270GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000271GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
272 Timeout<std::micro> timeout,
273 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000274 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000275 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000276
Pavel Labathe8a7b982017-02-06 19:31:09 +0000277 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000278
Kate Stoneb9c1b512016-09-06 20:57:50 +0000279 // Check for a packet from our cache first without trying any reading...
280 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
281 return PacketResult::Success;
282
283 bool timed_out = false;
284 bool disconnected = false;
285 while (IsConnected() && !timed_out) {
286 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000287 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288
Pavel Labathe8a7b982017-02-06 19:31:09 +0000289 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000290 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000291 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000292 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000293 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294
295 if (bytes_read > 0) {
296 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000297 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 } else {
299 switch (status) {
300 case eConnectionStatusTimedOut:
301 case eConnectionStatusInterrupted:
302 if (sync_on_timeout) {
303 //------------------------------------------------------------------
304 /// Sync the remote GDB server and make sure we get a response that
305 /// corresponds to what we send.
306 ///
307 /// Sends a "qEcho" packet and makes sure it gets the exact packet
308 /// echoed back. If the qEcho packet isn't supported, we send a qC
309 /// packet and make sure we get a valid thread ID back. We use the
310 /// "qC" packet since its response if very unique: is responds with
311 /// "QC%x" where %x is the thread ID of the current thread. This
312 /// makes the response unique enough from other packet responses to
313 /// ensure we are back on track.
314 ///
315 /// This packet is needed after we time out sending a packet so we
316 /// can ensure that we are getting the response for the packet we
317 /// are sending. There are no sequence IDs in the GDB remote
318 /// protocol (there used to be, but they are not supported anymore)
319 /// so if you timeout sending packet "abc", you might then send
320 /// packet "cde" and get the response for the previous "abc" packet.
321 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
322 /// many responses for packets can look like responses for other
323 /// packets. So if we timeout, we need to ensure that we can get
324 /// back on track. If we can't get back on track, we must
325 /// disconnect.
326 //------------------------------------------------------------------
327 bool sync_success = false;
328 bool got_actual_response = false;
329 // We timed out, we need to sync back up with the
330 char echo_packet[32];
331 int echo_packet_len = 0;
332 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000333
Kate Stoneb9c1b512016-09-06 20:57:50 +0000334 if (m_supports_qEcho == eLazyBoolYes) {
335 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
336 "qEcho:%u", ++m_echo_number);
337 std::string regex_str = "^";
338 regex_str += echo_packet;
339 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000340 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 } else {
342 echo_packet_len =
343 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000344 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 }
Greg Clayton644247c2011-07-07 01:59:51 +0000346
Kate Stoneb9c1b512016-09-06 20:57:50 +0000347 PacketResult echo_packet_result =
348 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
349 if (echo_packet_result == PacketResult::Success) {
350 const uint32_t max_retries = 3;
351 uint32_t successful_responses = 0;
352 for (uint32_t i = 0; i < max_retries; ++i) {
353 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000354 echo_packet_result =
355 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356 if (echo_packet_result == PacketResult::Success) {
357 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000358 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 sync_success = true;
360 break;
361 } else if (successful_responses == 1) {
362 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000363 // response, it probably is the response to the packet we
364 // actually wanted, so copy it over if this is the first
365 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 packet = echo_response;
367 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000368 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
370 continue; // Packet timed out, continue waiting for a response
371 else
372 break; // Something else went wrong getting the packet back, we
373 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 }
376
377 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000378 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 if (sync_success) {
380 // We timed out, but were able to recover
381 if (got_actual_response) {
382 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000383 // before the successful reply to our qEcho packet, so lets say
384 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 return PacketResult::Success;
386 }
387 } else {
388 disconnected = true;
389 Disconnect();
390 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000391 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 timed_out = true;
393 break;
394 case eConnectionStatusSuccess:
395 // printf ("status = success but error = %s\n",
396 // error.AsCString("<invalid>"));
397 break;
398
399 case eConnectionStatusEndOfFile:
400 case eConnectionStatusNoConnection:
401 case eConnectionStatusLostConnection:
402 case eConnectionStatusError:
403 disconnected = true;
404 Disconnect();
405 break;
406 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 }
409 packet.Clear();
410 if (disconnected)
411 return PacketResult::ErrorDisconnected;
412 if (timed_out)
413 return PacketResult::ErrorReplyTimeout;
414 else
415 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000416}
417
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418bool GDBRemoteCommunication::DecompressPacket() {
419 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000420
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000422 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423
424 size_t pkt_size = m_bytes.size();
425
Adrian Prantl05097242018-04-30 16:49:04 +0000426 // Smallest possible compressed packet is $N#00 - an uncompressed empty
427 // reply, most commonly indicating an unsupported packet. Anything less than
428 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000429 if (pkt_size < 5)
430 return true;
431
432 if (m_bytes[0] != '$' && m_bytes[0] != '%')
433 return true;
434 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
435 return true;
436
437 size_t hash_mark_idx = m_bytes.find('#');
438 if (hash_mark_idx == std::string::npos)
439 return true;
440 if (hash_mark_idx + 2 >= m_bytes.size())
441 return true;
442
443 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
444 !::isxdigit(m_bytes[hash_mark_idx + 2]))
445 return true;
446
447 size_t content_length =
448 pkt_size -
449 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
450 size_t content_start = 2; // The first character of the
451 // compressed/not-compressed text of the packet
452 size_t checksum_idx =
453 hash_mark_idx +
454 1; // The first character of the two hex checksum characters
455
456 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000457 // multiple packets. size_of_first_packet is the size of the initial packet
458 // which we'll replace with the decompressed version of, leaving the rest of
459 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 size_t size_of_first_packet = hash_mark_idx + 3;
461
462 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000463 // the uncompressed payload, then a : and then the compressed data. e.g.
464 // $C1024:<binary>#00 Update content_start and content_length to only include
465 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466
467 uint64_t decompressed_bufsize = ULONG_MAX;
468 if (m_bytes[1] == 'C') {
469 size_t i = content_start;
470 while (i < hash_mark_idx && isdigit(m_bytes[i]))
471 i++;
472 if (i < hash_mark_idx && m_bytes[i] == ':') {
473 i++;
474 content_start = i;
475 content_length = hash_mark_idx - content_start;
476 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
477 errno = 0;
478 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
479 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
480 m_bytes.erase(0, size_of_first_packet);
481 return false;
482 }
483 }
484 }
485
486 if (GetSendAcks()) {
487 char packet_checksum_cstr[3];
488 packet_checksum_cstr[0] = m_bytes[checksum_idx];
489 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
490 packet_checksum_cstr[2] = '\0';
491 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
492
493 long actual_checksum = CalculcateChecksum(
494 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
495 bool success = packet_checksum == actual_checksum;
496 if (!success) {
497 if (log)
498 log->Printf(
499 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
500 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
501 (uint8_t)actual_checksum);
502 }
503 // Send the ack or nack if needed
504 if (!success) {
505 SendNack();
506 m_bytes.erase(0, size_of_first_packet);
507 return false;
508 } else {
509 SendAck();
510 }
511 }
512
513 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000514 // This packet was not compressed -- delete the 'N' character at the start
515 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 m_bytes.erase(1, 1);
517 return true;
518 }
519
Adrian Prantl05097242018-04-30 16:49:04 +0000520 // Reverse the gdb-remote binary escaping that was done to the compressed
521 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 std::vector<uint8_t> unescaped_content;
523 unescaped_content.reserve(content_length);
524 size_t i = content_start;
525 while (i < hash_mark_idx) {
526 if (m_bytes[i] == '}') {
527 i++;
528 unescaped_content.push_back(m_bytes[i] ^ 0x20);
529 } else {
530 unescaped_content.push_back(m_bytes[i]);
531 }
532 i++;
533 }
534
535 uint8_t *decompressed_buffer = nullptr;
536 size_t decompressed_bytes = 0;
537
538 if (decompressed_bufsize != ULONG_MAX) {
Jason Molenda4a793c82018-12-18 23:02:50 +0000539 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540 if (decompressed_buffer == nullptr) {
541 m_bytes.erase(0, size_of_first_packet);
542 return false;
543 }
544 }
545
546#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +0000547 if (m_compression_type == CompressionType::ZlibDeflate ||
548 m_compression_type == CompressionType::LZFSE ||
Jason Molenda4a793c82018-12-18 23:02:50 +0000549 m_compression_type == CompressionType::LZ4 ||
550 m_compression_type == CompressionType::LZMA) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000552 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000554 else if (m_compression_type == CompressionType::ZlibDeflate)
555 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 else if (m_compression_type == CompressionType::LZ4)
557 compression_type = COMPRESSION_LZ4_RAW;
558 else if (m_compression_type == CompressionType::LZMA)
559 compression_type = COMPRESSION_LZMA;
560
Jason Molenda4a793c82018-12-18 23:02:50 +0000561 if (m_decompression_scratch_type != m_compression_type) {
562 if (m_decompression_scratch) {
563 free (m_decompression_scratch);
564 m_decompression_scratch = nullptr;
565 }
566 size_t scratchbuf_size = 0;
567 if (m_compression_type == CompressionType::LZFSE)
568 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
569 else if (m_compression_type == CompressionType::LZ4)
570 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
571 else if (m_compression_type == CompressionType::ZlibDeflate)
572 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
573 else if (m_compression_type == CompressionType::LZMA)
574 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
575 else if (m_compression_type == CompressionType::LZFSE)
576 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
577 if (scratchbuf_size > 0) {
578 m_decompression_scratch = (void*) malloc (scratchbuf_size);
579 m_decompression_scratch_type = m_compression_type;
580 }
581 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582
583 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
584 decompressed_bytes = compression_decode_buffer(
Jason Molenda4a793c82018-12-18 23:02:50 +0000585 decompressed_buffer, decompressed_bufsize,
586 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
587 m_decompression_scratch, compression_type);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000588 }
589 }
590#endif
591
592#if defined(HAVE_LIBZ)
593 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
594 decompressed_buffer != nullptr &&
595 m_compression_type == CompressionType::ZlibDeflate) {
596 z_stream stream;
597 memset(&stream, 0, sizeof(z_stream));
598 stream.next_in = (Bytef *)unescaped_content.data();
599 stream.avail_in = (uInt)unescaped_content.size();
600 stream.total_in = 0;
601 stream.next_out = (Bytef *)decompressed_buffer;
602 stream.avail_out = decompressed_bufsize;
603 stream.total_out = 0;
604 stream.zalloc = Z_NULL;
605 stream.zfree = Z_NULL;
606 stream.opaque = Z_NULL;
607
608 if (inflateInit2(&stream, -15) == Z_OK) {
609 int status = inflate(&stream, Z_NO_FLUSH);
610 inflateEnd(&stream);
611 if (status == Z_STREAM_END) {
612 decompressed_bytes = stream.total_out;
613 }
614 }
615 }
616#endif
617
618 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
619 if (decompressed_buffer)
620 free(decompressed_buffer);
621 m_bytes.erase(0, size_of_first_packet);
622 return false;
623 }
624
625 std::string new_packet;
626 new_packet.reserve(decompressed_bytes + 6);
627 new_packet.push_back(m_bytes[0]);
628 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
629 new_packet.push_back('#');
630 if (GetSendAcks()) {
631 uint8_t decompressed_checksum = CalculcateChecksum(
632 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
633 char decompressed_checksum_str[3];
634 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
635 new_packet.append(decompressed_checksum_str);
636 } else {
637 new_packet.push_back('0');
638 new_packet.push_back('0');
639 }
640
641 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
642 new_packet.size());
643
644 free(decompressed_buffer);
645 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000646}
647
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000648GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
650 StringExtractorGDBRemote &packet) {
651 // Put the packet data into the buffer in a thread safe fashion
652 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000653
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000655
Kate Stoneb9c1b512016-09-06 20:57:50 +0000656 if (src && src_len > 0) {
657 if (log && log->GetVerbose()) {
658 StreamString s;
659 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
660 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
661 }
662 m_bytes.append((const char *)src, src_len);
663 }
664
665 bool isNotifyPacket = false;
666
667 // Parse up the packets into gdb remote packets
668 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000669 // end_idx must be one past the last valid packet byte. Start it off with
670 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000671 size_t content_start = 0;
672 size_t content_length = 0;
673 size_t total_length = 0;
674 size_t checksum_idx = std::string::npos;
675
676 // Size of packet before it is decompressed, for logging purposes
677 size_t original_packet_size = m_bytes.size();
678 if (CompressionIsEnabled()) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000679 if (!DecompressPacket()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 packet.Clear();
681 return GDBRemoteCommunication::PacketType::Standard;
682 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000683 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000684
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 switch (m_bytes[0]) {
686 case '+': // Look for ack
687 case '-': // Look for cancel
688 case '\x03': // ^C to halt target
689 content_length = total_length = 1; // The command is one byte long...
690 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000691
Kate Stoneb9c1b512016-09-06 20:57:50 +0000692 case '%': // Async notify packet
693 isNotifyPacket = true;
694 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000695
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 case '$':
697 // Look for a standard gdb packet?
698 {
699 size_t hash_pos = m_bytes.find('#');
700 if (hash_pos != std::string::npos) {
701 if (hash_pos + 2 < m_bytes.size()) {
702 checksum_idx = hash_pos + 1;
703 // Skip the dollar sign
704 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000705 // Don't include the # in the content or the $ in the content
706 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000707 content_length = hash_pos - 1;
708
709 total_length =
710 hash_pos + 3; // Skip the # and the two hex checksum bytes
711 } else {
712 // Checksum bytes aren't all here yet
713 content_length = std::string::npos;
714 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000715 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 }
717 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000718
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000720 // We have an unexpected byte and we need to flush all bad data that is
721 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
722 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
723 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000724 const size_t bytes_len = m_bytes.size();
725 bool done = false;
726 uint32_t idx;
727 for (idx = 1; !done && idx < bytes_len; ++idx) {
728 switch (m_bytes[idx]) {
729 case '+':
730 case '-':
731 case '\x03':
732 case '%':
733 case '$':
734 done = true;
735 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000736
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 default:
738 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 }
741 if (log)
742 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
743 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
744 m_bytes.erase(0, idx - 1);
745 } break;
746 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748 if (content_length == std::string::npos) {
749 packet.Clear();
750 return GDBRemoteCommunication::PacketType::Invalid;
751 } else if (total_length > 0) {
752
753 // We have a valid packet...
754 assert(content_length <= m_bytes.size());
755 assert(total_length <= m_bytes.size());
756 assert(content_length <= total_length);
757 size_t content_end = content_start + content_length;
758
759 bool success = true;
760 std::string &packet_str = packet.GetStringRef();
761 if (log) {
762 // If logging was just enabled and we have history, then dump out what
763 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000764 // that logs all of the packet will set a boolean so that we don't dump
765 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766 if (!m_history.DidDumpToLog())
767 m_history.Dump(log);
768
769 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000770 // Only detect binary for packets that start with a '$' and have a
771 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000772 if (m_bytes[0] == '$' && total_length > 4) {
773 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000774 unsigned char c = m_bytes[i];
775 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 binary = true;
777 }
778 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000779 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780 if (binary) {
781 StreamString strm;
782 // Packet header...
783 if (CompressionIsEnabled())
784 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
785 (uint64_t)original_packet_size, (uint64_t)total_length,
786 m_bytes[0]);
787 else
788 strm.Printf("<%4" PRIu64 "> read packet: %c",
789 (uint64_t)total_length, m_bytes[0]);
790 for (size_t i = content_start; i < content_end; ++i) {
791 // Remove binary escaped bytes when displaying the packet...
792 const char ch = m_bytes[i];
793 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000794 // 0x7d is the escape character. The next character is to be
795 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 const char escapee = m_bytes[++i] ^ 0x20;
797 strm.Printf("%2.2x", escapee);
798 } else {
799 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000800 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 }
802 // Packet footer...
803 strm.Printf("%c%c%c", m_bytes[total_length - 3],
804 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000805 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000806 } else {
807 if (CompressionIsEnabled())
808 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
809 (uint64_t)original_packet_size, (uint64_t)total_length,
810 (int)(total_length), m_bytes.c_str());
811 else
812 log->Printf("<%4" PRIu64 "> read packet: %.*s",
813 (uint64_t)total_length, (int)(total_length),
814 m_bytes.c_str());
815 }
816 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000817
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000818 m_history.AddPacket(m_bytes, total_length,
819 GDBRemoteCommunicationHistory::ePacketTypeRecv,
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000820 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000821
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 // Clear packet_str in case there is some existing data in it.
823 packet_str.clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000824 // Copy the packet from m_bytes to packet_str expanding the run-length
825 // encoding in the process. Reserve enough byte for the most common case
826 // (no RLE used)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 packet_str.reserve(m_bytes.length());
828 for (std::string::const_iterator c = m_bytes.begin() + content_start;
829 c != m_bytes.begin() + content_end; ++c) {
830 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000831 // '*' indicates RLE. Next character will give us the repeat count
832 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 char char_to_repeat = packet_str.back();
834 // Number of time the previous character is repeated
835 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000836 // We have the char_to_repeat and repeat_count. Now push it in the
837 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 for (int i = 0; i < repeat_count; ++i)
839 packet_str.push_back(char_to_repeat);
840 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000841 // 0x7d is the escape character. The next character is to be XOR'd
842 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000843 char escapee = *++c ^ 0x20;
844 packet_str.push_back(escapee);
845 } else {
846 packet_str.push_back(*c);
847 }
848 }
849
850 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
851 assert(checksum_idx < m_bytes.size());
852 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
853 ::isxdigit(m_bytes[checksum_idx + 1])) {
854 if (GetSendAcks()) {
855 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
856 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
Pavel Labath5a841232018-03-28 10:19:10 +0000857 char actual_checksum = CalculcateChecksum(
858 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 success = packet_checksum == actual_checksum;
860 if (!success) {
861 if (log)
862 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
863 "got 0x%2.2x",
864 (int)(total_length), m_bytes.c_str(),
865 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000866 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 // Send the ack or nack if needed
868 if (!success)
869 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000870 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 SendAck();
872 }
873 } else {
874 success = false;
875 if (log)
876 log->Printf("error: invalid checksum in packet: '%s'\n",
877 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000878 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000879 }
880
881 m_bytes.erase(0, total_length);
882 packet.SetFilePos(0);
883
884 if (isNotifyPacket)
885 return GDBRemoteCommunication::PacketType::Notify;
886 else
887 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000888 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000889 }
890 packet.Clear();
891 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000892}
893
Zachary Turner97206d52017-05-12 04:51:55 +0000894Status GDBRemoteCommunication::StartListenThread(const char *hostname,
895 uint16_t port) {
896 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000897 if (m_listen_thread.IsJoinable()) {
898 error.SetErrorString("listen thread already running");
899 } else {
900 char listen_url[512];
901 if (hostname && hostname[0])
902 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
903 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000904 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
906 m_listen_url = listen_url;
907 SetConnection(new ConnectionFileDescriptor());
908 m_listen_thread = ThreadLauncher::LaunchThread(
909 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
910 }
911 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000912}
913
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914bool GDBRemoteCommunication::JoinListenThread() {
915 if (m_listen_thread.IsJoinable())
916 m_listen_thread.Join(nullptr);
917 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000918}
919
920lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
922 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000923 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 ConnectionFileDescriptor *connection =
925 (ConnectionFileDescriptor *)comm->GetConnection();
926
927 if (connection) {
928 // Do the listen on another thread so we can continue on...
929 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
930 eConnectionStatusSuccess)
931 comm->SetConnection(NULL);
932 }
933 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000934}
935
Zachary Turner97206d52017-05-12 04:51:55 +0000936Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000937 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
938 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
939 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
940 if (log)
941 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
942 __FUNCTION__, url ? url : "<empty>",
943 port ? *port : uint16_t(0));
944
Zachary Turner97206d52017-05-12 04:51:55 +0000945 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000946 // If we locate debugserver, keep that located version around
947 static FileSpec g_debugserver_file_spec;
948
949 char debugserver_path[PATH_MAX];
950 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
951
Aaron Smith981e6352019-02-07 18:22:00 +0000952 Environment host_env = Host::GetEnvironment();
953
Adrian Prantl05097242018-04-30 16:49:04 +0000954 // Always check to see if we have an environment override for the path to the
955 // debugserver to use and use it if we do.
Aaron Smith981e6352019-02-07 18:22:00 +0000956 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
957 if (!env_debugserver_path.empty()) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000958 debugserver_file_spec.SetFile(env_debugserver_path,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000959 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +0000960 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
962 "from environment variable: %s",
Aaron Smith981e6352019-02-07 18:22:00 +0000963 __FUNCTION__, env_debugserver_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 } else
965 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000966 bool debugserver_exists =
967 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +0000969 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +0000970 debugserver_file_spec = HostInfo::GetSupportExeDir();
971 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000973 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +0000975 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 log->Printf(
977 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
978 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +0000979
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 g_debugserver_file_spec = debugserver_file_spec;
981 } else {
Aaron Smithbc472892019-02-14 08:59:04 +0000982 if (platform)
983 debugserver_file_spec =
984 platform->LocateExecutable(DEBUGSERVER_BASENAME);
985 else
986 debugserver_file_spec.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987 if (debugserver_file_spec) {
988 // Platform::LocateExecutable() wouldn't return a path if it doesn't
989 // exist
990 debugserver_exists = true;
991 } else {
992 if (log)
993 log->Printf("GDBRemoteCommunication::%s() could not find "
994 "gdb-remote stub exe '%s'",
995 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +0000996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +0000998 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 g_debugserver_file_spec.Clear();
1000 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001001 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 if (debugserver_exists) {
1005 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 Args &debugserver_args = launch_info.GetArguments();
1008 debugserver_args.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009
1010 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001011 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001012
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001013#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001015 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001016#endif
1017
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 // If a url is supplied then use it
1019 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001020 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001021
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 if (pass_comm_fd >= 0) {
1023 StreamString fd_arg;
1024 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001025 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 // Send "pass_comm_fd" down to the inferior so it can use it to
1027 // communicate back with this process
1028 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1029 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001030
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001032 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001033
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001035 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001037
Stella Stamenovab3f44ad2018-12-10 17:23:28 +00001038 llvm::SmallString<128> named_pipe_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039 // socket_pipe is used by debug server to communicate back either
1040 // TCP port or domain socket name which it listens on.
1041 // The second purpose of the pipe to serve as a synchronization point -
1042 // once data is written to the pipe, debug server is up and running.
1043 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001044
Adrian Prantl05097242018-04-30 16:49:04 +00001045 // port is null when debug server should listen on domain socket - we're
1046 // not interested in port value but rather waiting for debug server to
1047 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001048 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001050// Create a temporary file to get the stdout/stderr and redirect the output of
1051// the command into this file. We will later read this file if all goes well
1052// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001053#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 // Binding to port zero, we need to figure out what port it ends up
1055 // using using a named pipe...
1056 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1057 false, named_pipe_path);
1058 if (error.Fail()) {
1059 if (log)
1060 log->Printf("GDBRemoteCommunication::%s() "
1061 "named pipe creation failed: %s",
1062 __FUNCTION__, error.AsCString());
1063 return error;
1064 }
Sean Callanan1355f472016-09-19 22:06:12 +00001065 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001066 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001067#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001068 // Binding to port zero, we need to figure out what port it ends up
1069 // using using an unnamed pipe...
1070 error = socket_pipe.CreateNew(true);
1071 if (error.Fail()) {
1072 if (log)
1073 log->Printf("GDBRemoteCommunication::%s() "
1074 "unnamed pipe creation failed: %s",
1075 __FUNCTION__, error.AsCString());
1076 return error;
1077 }
Aaron Smithe55850b2019-01-10 00:46:09 +00001078 pipe_t write = socket_pipe.GetWritePipe();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001079 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
Aaron Smithe55850b2019-01-10 00:46:09 +00001080 debugserver_args.AppendArgument(llvm::to_string(write));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001082#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 } else {
1084 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001085 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001086 error = StartListenThread("127.0.0.1", 0);
1087 if (error.Fail()) {
1088 if (log)
1089 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1090 "thread: %s",
1091 __FUNCTION__, error.AsCString());
1092 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001093 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094
1095 ConnectionFileDescriptor *connection =
1096 (ConnectionFileDescriptor *)GetConnection();
1097 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001098 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 if (port_ > 0) {
1100 char port_cstr[32];
1101 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1102 // Send the host and port down that debugserver and specify an option
1103 // so that it connects back to the port we are listening to in this
1104 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001105 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1106 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 if (port)
1108 *port = port_;
1109 } else {
1110 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1111 if (log)
1112 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1113 error.AsCString());
1114 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001115 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 }
1117 }
Aaron Smith981e6352019-02-07 18:22:00 +00001118 std::string env_debugserver_log_file =
1119 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1120 if (!env_debugserver_log_file.empty()) {
1121 debugserver_args.AppendArgument(
1122 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123 }
1124
Vince Harron9753dd92015-05-10 15:22:09 +00001125#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 const char *env_debugserver_log_flags =
1127 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1128 if (env_debugserver_log_flags) {
Aaron Smith981e6352019-02-07 18:22:00 +00001129 debugserver_args.AppendArgument(
1130 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 }
Vince Harron9753dd92015-05-10 15:22:09 +00001132#else
Aaron Smith981e6352019-02-07 18:22:00 +00001133 std::string env_debugserver_log_channels =
1134 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1135 if (!env_debugserver_log_channels.empty()) {
1136 debugserver_args.AppendArgument(
1137 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1138 .str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139 }
Vince Harron9753dd92015-05-10 15:22:09 +00001140#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001141
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1143 // env var doesn't come back.
1144 uint32_t env_var_index = 1;
1145 bool has_env_var;
1146 do {
1147 char env_var_name[64];
1148 snprintf(env_var_name, sizeof(env_var_name),
1149 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
Aaron Smith981e6352019-02-07 18:22:00 +00001150 std::string extra_arg = host_env.lookup(env_var_name);
1151 has_env_var = !extra_arg.empty();
Todd Fiala34ba4262014-08-29 17:10:31 +00001152
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001154 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001155 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1157 "to stub command line (%s)",
Aaron Smith981e6352019-02-07 18:22:00 +00001158 __FUNCTION__, env_var_name, extra_arg.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 }
1160 } while (has_env_var);
1161
1162 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001163 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 debugserver_args.AppendArguments(*inferior_args);
1165 }
1166
1167 // Copy the current environment to the gdbserver/debugserver instance
Aaron Smith981e6352019-02-07 18:22:00 +00001168 launch_info.GetEnvironment() = host_env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001169
1170 // Close STDIN, STDOUT and STDERR.
1171 launch_info.AppendCloseFileAction(STDIN_FILENO);
1172 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1173 launch_info.AppendCloseFileAction(STDERR_FILENO);
1174
1175 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1176 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1177 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1178 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1179
1180 if (log) {
1181 StreamString string_stream;
1182 Platform *const platform = nullptr;
1183 launch_info.Dump(string_stream, platform);
1184 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001185 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186 }
1187 error = Host::LaunchProcess(launch_info);
1188
1189 if (error.Success() &&
1190 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1191 pass_comm_fd == -1) {
1192 if (named_pipe_path.size() > 0) {
1193 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1194 if (error.Fail())
1195 if (log)
1196 log->Printf("GDBRemoteCommunication::%s() "
1197 "failed to open named pipe %s for reading: %s",
1198 __FUNCTION__, named_pipe_path.c_str(),
1199 error.AsCString());
1200 }
1201
1202 if (socket_pipe.CanWrite())
1203 socket_pipe.CloseWriteFileDescriptor();
1204 if (socket_pipe.CanRead()) {
1205 char port_cstr[PATH_MAX] = {0};
1206 port_cstr[0] = '\0';
1207 size_t num_bytes = sizeof(port_cstr);
1208 // Read port from pipe with 10 second timeout.
1209 error = socket_pipe.ReadWithTimeout(
1210 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1211 if (error.Success() && (port != nullptr)) {
1212 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001213 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1214 if (*port == 0 || *port == child_port) {
1215 *port = child_port;
1216 if (log)
1217 log->Printf("GDBRemoteCommunication::%s() "
1218 "debugserver listens %u port",
1219 __FUNCTION__, *port);
1220 } else {
1221 if (log)
1222 log->Printf("GDBRemoteCommunication::%s() "
1223 "debugserver listening on port "
1224 "%d but requested port was %d",
1225 __FUNCTION__, (uint32_t)child_port,
1226 (uint32_t)(*port));
1227 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001228 } else {
1229 if (log)
1230 log->Printf("GDBRemoteCommunication::%s() "
1231 "failed to read a port value from pipe %s: %s",
1232 __FUNCTION__, named_pipe_path.c_str(),
1233 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001234 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001235 socket_pipe.Close();
1236 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001237
Kate Stoneb9c1b512016-09-06 20:57:50 +00001238 if (named_pipe_path.size() > 0) {
1239 const auto err = socket_pipe.Delete(named_pipe_path);
1240 if (err.Fail()) {
1241 if (log)
1242 log->Printf(
1243 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1244 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001245 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 }
1247
1248 // Make sure we actually connect with the debugserver...
1249 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001250 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251 } else {
1252 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1253 }
Vince Harron8b335672015-05-12 01:10:56 +00001254
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 if (error.Fail()) {
1256 if (log)
1257 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1258 error.AsCString());
1259 }
Vince Harron8b335672015-05-12 01:10:56 +00001260
Kate Stoneb9c1b512016-09-06 20:57:50 +00001261 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001262}
1263
Kate Stoneb9c1b512016-09-06 20:57:50 +00001264void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1265
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001266void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1267 m_history.SetStream(strm);
Zachary Turner52f8f342019-01-29 22:55:21 +00001268}
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001269
1270llvm::Error
1271GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1272 GDBRemoteCommunication &server) {
1273 const bool child_processes_inherit = false;
1274 const int backlog = 5;
1275 TCPSocket listen_socket(true, child_processes_inherit);
1276 if (llvm::Error error =
1277 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1278 return error;
1279
1280 Socket *accept_socket;
1281 std::future<Status> accept_status = std::async(
1282 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1283
1284 llvm::SmallString<32> remote_addr;
1285 llvm::raw_svector_ostream(remote_addr)
1286 << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1287
1288 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1289 new ConnectionFileDescriptor());
Pavel Labath9d723b82019-02-18 10:36:23 +00001290 Status status;
1291 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1292 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1293 "Unable to connect: %s", status.AsCString());
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001294
1295 client.SetConnection(conn_up.release());
1296 if (llvm::Error error = accept_status.get().ToError())
1297 return error;
1298
1299 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1300 return llvm::Error::success();
1301}
1302
Kate Stoneb9c1b512016-09-06 20:57:50 +00001303GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001304 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Aaron Smith981e6352019-02-07 18:22:00 +00001305 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1306 auto curr_timeout = gdb_comm.GetPacketTimeout();
1307 // Only update the timeout if the timeout is greater than the current
1308 // timeout. If the current timeout is larger, then just use that.
1309 if (curr_timeout < timeout) {
1310 m_timeout_modified = true;
1311 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1312 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001313}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001314
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001316 // Only restore the timeout if we set it in the constructor.
1317 if (m_timeout_modified)
1318 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001319}
1320
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001322// become available for this connection. This function will consume all
1323// incoming bytes and try to parse whole packets as they become available. Full
1324// packets are placed in a queue, so that all packet requests can simply pop
1325// from this queue. Async notification packets will be dispatched immediately
1326// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1328 size_t len, bool broadcast,
1329 lldb::ConnectionStatus status) {
1330 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001331
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 while (true) {
1333 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001334
Adrian Prantl05097242018-04-30 16:49:04 +00001335 // scrub the data so we do not pass it back to CheckForPacket on future
1336 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001337 bytes = nullptr;
1338 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001339
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 // we may have received no packet so lets bail out
1341 if (type == PacketType::Invalid)
1342 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 if (type == PacketType::Standard) {
1345 // scope for the mutex
1346 {
1347 // lock down the packet queue
1348 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1349 // push a new packet into the queue
1350 m_packet_queue.push(packet);
1351 // Signal condition variable that we have a packet
1352 m_condition_queue_not_empty.notify_one();
1353 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001354 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001355
1356 if (type == PacketType::Notify) {
1357 // put this packet into an event
1358 const char *pdata = packet.GetStringRef().c_str();
1359
Adrian Prantl05097242018-04-30 16:49:04 +00001360 // as the communication class, we are a broadcaster and the async thread
1361 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001362 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1363 new EventDataBytes(pdata));
1364 }
1365 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001366}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001367
1368void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1369 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1370 StringRef Style) {
1371 using PacketResult = GDBRemoteCommunication::PacketResult;
1372
1373 switch (result) {
1374 case PacketResult::Success:
1375 Stream << "Success";
1376 break;
1377 case PacketResult::ErrorSendFailed:
1378 Stream << "ErrorSendFailed";
1379 break;
1380 case PacketResult::ErrorSendAck:
1381 Stream << "ErrorSendAck";
1382 break;
1383 case PacketResult::ErrorReplyFailed:
1384 Stream << "ErrorReplyFailed";
1385 break;
1386 case PacketResult::ErrorReplyTimeout:
1387 Stream << "ErrorReplyTimeout";
1388 break;
1389 case PacketResult::ErrorReplyInvalid:
1390 Stream << "ErrorReplyInvalid";
1391 break;
1392 case PacketResult::ErrorReplyAck:
1393 Stream << "ErrorReplyAck";
1394 break;
1395 case PacketResult::ErrorDisconnected:
1396 Stream << "ErrorDisconnected";
1397 break;
1398 case PacketResult::ErrorNoSequenceLock:
1399 Stream << "ErrorNoSequenceLock";
1400 break;
1401 }
1402}