blob: b630fae87c3a07aec810dee7b922b0bbfda4a206 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chris Lattner30fdc8d2010-06-08 16:52:24 +000010#include "GDBRemoteCommunication.h"
11
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000012#include <future>
Johnny Chena5663552011-05-13 20:07:25 +000013#include <limits.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000014#include <string.h>
Greg Clayton91a9b2472013-12-04 19:19:12 +000015#include <sys/stat.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000016
Greg Claytonc1422c12012-04-09 22:46:21 +000017#include "lldb/Core/StreamFile.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000018#include "lldb/Host/ConnectionFileDescriptor.h"
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +000019#include "lldb/Host/FileSystem.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000020#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000021#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000022#include "lldb/Host/Pipe.h"
Zachary Turner98688922014-08-06 18:16:26 +000023#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000024#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000025#include "lldb/Host/ThreadLauncher.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000026#include "lldb/Host/common/TCPSocket.h"
27#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
Greg Clayton6988abc2015-10-19 20:44:01 +000028#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000029#include "lldb/Target/Process.h"
Zachary Turner5713a052017-03-22 18:40:07 +000030#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000031#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000032#include "lldb/Utility/RegularExpression.h"
33#include "lldb/Utility/StreamString.h"
Oleksiy Vyalov4536c452015-02-05 16:29:12 +000034#include "llvm/ADT/SmallString.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000035#include "llvm/Support/ScopedPrinter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "ProcessGDBRemoteLog.h"
38
Todd Fiala015d8182014-07-22 23:41:36 +000039#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +000040#define DEBUGSERVER_BASENAME "debugserver"
Todd Fiala015d8182014-07-22 23:41:36 +000041#else
Kate Stoneb9c1b512016-09-06 20:57:50 +000042#define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000043#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000044
Jason Molenda4a793c82018-12-18 23:02:50 +000045#if defined(__APPLE__)
46#define HAVE_LIBCOMPRESSION
Jason Molenda91ffe0a2015-06-18 21:46:06 +000047#include <compression.h>
48#endif
49
Kate Stoneb9c1b512016-09-06 20:57:50 +000050#if defined(HAVE_LIBZ)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000051#include <zlib.h>
52#endif
53
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054using namespace lldb;
55using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000056using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057
58//----------------------------------------------------------------------
59// GDBRemoteCommunication constructor
60//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000061GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
62 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000063 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +000064#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000065 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +000066#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000067 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +000068#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
70 m_send_acks(true), m_compression_type(CompressionType::None),
Jason Molenda4a793c82018-12-18 23:02:50 +000071 m_listen_url(), m_decompression_scratch_type(CompressionType::None),
Raphael Isemann0e3299d2019-01-08 22:55:02 +000072 m_decompression_scratch(nullptr) {
73 // Unused unless HAVE_LIBCOMPRESSION is defined.
74 (void)m_decompression_scratch_type;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000075}
76
77//----------------------------------------------------------------------
78// Destructor
79//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000080GDBRemoteCommunication::~GDBRemoteCommunication() {
81 if (IsConnected()) {
82 Disconnect();
83 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +000084
Jason Molenda8460bb02018-12-18 23:45:45 +000085 if (m_decompression_scratch)
86 free (m_decompression_scratch);
87
Adrian Prantl05097242018-04-30 16:49:04 +000088 // Stop the communications read thread which is used to parse all incoming
89 // packets. This function will block until the read thread returns.
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 if (m_read_thread_enabled)
91 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000092}
93
Kate Stoneb9c1b512016-09-06 20:57:50 +000094char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
95 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000096
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 for (char c : payload)
98 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +000099
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000101}
102
Kate Stoneb9c1b512016-09-06 20:57:50 +0000103size_t GDBRemoteCommunication::SendAck() {
104 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
105 ConnectionStatus status = eConnectionStatusSuccess;
106 char ch = '+';
107 const size_t bytes_written = Write(&ch, 1, status, NULL);
108 if (log)
109 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000110 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
111 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000112 return bytes_written;
113}
114
115size_t GDBRemoteCommunication::SendNack() {
116 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
117 ConnectionStatus status = eConnectionStatusSuccess;
118 char ch = '-';
119 const size_t bytes_written = Write(&ch, 1, status, NULL);
120 if (log)
121 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000122 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
123 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000124 return bytes_written;
125}
126
127GDBRemoteCommunication::PacketResult
128GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 StreamString packet(0, 4, eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 packet.PutChar('$');
131 packet.Write(payload.data(), payload.size());
132 packet.PutChar('#');
133 packet.PutHex8(CalculcateChecksum(payload));
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000134 std::string packet_str = packet.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000136 return SendRawPacketNoLock(packet_str);
137}
138
139GDBRemoteCommunication::PacketResult
140GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
141 bool skip_ack) {
142 if (IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000144 ConnectionStatus status = eConnectionStatusSuccess;
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000145 const char *packet_data = packet.data();
146 const size_t packet_length = packet.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 size_t bytes_written = Write(packet_data, packet_length, status, NULL);
148 if (log) {
149 size_t binary_start_offset = 0;
150 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
151 0) {
152 const char *first_comma = strchr(packet_data, ',');
153 if (first_comma) {
154 const char *second_comma = strchr(first_comma + 1, ',');
155 if (second_comma)
156 binary_start_offset = second_comma - packet_data + 1;
Greg Claytonc1422c12012-04-09 22:46:21 +0000157 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000159
Adrian Prantl05097242018-04-30 16:49:04 +0000160 // If logging was just enabled and we have history, then dump out what we
161 // have to the log so we get the historical context. The Dump() call that
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 // logs all of the packet will set a boolean so that we don't dump this
Adrian Prantl05097242018-04-30 16:49:04 +0000163 // more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 if (!m_history.DidDumpToLog())
165 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167 if (binary_start_offset) {
168 StreamString strm;
169 // Print non binary data header
170 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
171 (int)binary_start_offset, packet_data);
172 const uint8_t *p;
173 // Print binary data exactly as sent
174 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
175 ++p)
176 strm.Printf("\\x%2.2x", *p);
177 // Print the checksum
178 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000179 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180 } else
181 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
182 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000183 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000184
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000185 m_history.AddPacket(packet.str(), packet_length,
186 GDBRemoteCommunicationHistory::ePacketTypeSend,
187 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188
189 if (bytes_written == packet_length) {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000190 if (!skip_ack && GetSendAcks())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191 return GetAck();
192 else
193 return PacketResult::Success;
194 } else {
195 if (log)
196 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
197 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000198 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 }
200 return PacketResult::ErrorSendFailed;
201}
202
203GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
204 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000205 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 if (result == PacketResult::Success) {
207 if (packet.GetResponseType() ==
208 StringExtractorGDBRemote::ResponseType::eAck)
209 return PacketResult::Success;
210 else
211 return PacketResult::ErrorSendAck;
212 }
213 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000214}
215
Greg Clayton3dedae12013-12-06 21:45:27 +0000216GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000217GDBRemoteCommunication::ReadPacketWithOutputSupport(
218 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
219 bool sync_on_timeout,
220 llvm::function_ref<void(llvm::StringRef)> output_callback) {
221 auto result = ReadPacket(response, timeout, sync_on_timeout);
222 while (result == PacketResult::Success && response.IsNormalResponse() &&
223 response.PeekChar() == 'O') {
224 response.GetChar();
225 std::string output;
226 if (response.GetHexByteString(output))
227 output_callback(output);
228 result = ReadPacket(response, timeout, sync_on_timeout);
229 }
230 return result;
231}
232
233GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000235 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000236 bool sync_on_timeout) {
237 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000238 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000240 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000241}
242
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000243// This function is called when a packet is requested.
244// A whole packet is popped from the packet queue and returned to the caller.
Adrian Prantl05097242018-04-30 16:49:04 +0000245// Packets are placed into this queue from the communication read thread. See
246// GDBRemoteCommunication::AppendBytesToCache.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000247GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000249 Timeout<std::micro> timeout) {
250 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
251 // lock down the packet queue
252 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000253
Pavel Labath1eff73c2016-11-24 10:54:49 +0000254 if (!timeout)
255 m_condition_queue_not_empty.wait(lock, pred);
256 else {
257 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
258 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 if (!IsConnected())
260 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000261 }
262
Pavel Labath1eff73c2016-11-24 10:54:49 +0000263 // get the front element of the queue
264 response = m_packet_queue.front();
265
266 // remove the front element
267 m_packet_queue.pop();
268
269 // we got a packet
270 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000272
273GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000274GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
275 Timeout<std::micro> timeout,
276 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000278 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000279
Pavel Labathe8a7b982017-02-06 19:31:09 +0000280 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000281
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282 // Check for a packet from our cache first without trying any reading...
283 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
284 return PacketResult::Success;
285
286 bool timed_out = false;
287 bool disconnected = false;
288 while (IsConnected() && !timed_out) {
289 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000290 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291
Pavel Labathe8a7b982017-02-06 19:31:09 +0000292 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000293 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000294 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000295 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000296 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297
298 if (bytes_read > 0) {
299 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000300 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 } else {
302 switch (status) {
303 case eConnectionStatusTimedOut:
304 case eConnectionStatusInterrupted:
305 if (sync_on_timeout) {
306 //------------------------------------------------------------------
307 /// Sync the remote GDB server and make sure we get a response that
308 /// corresponds to what we send.
309 ///
310 /// Sends a "qEcho" packet and makes sure it gets the exact packet
311 /// echoed back. If the qEcho packet isn't supported, we send a qC
312 /// packet and make sure we get a valid thread ID back. We use the
313 /// "qC" packet since its response if very unique: is responds with
314 /// "QC%x" where %x is the thread ID of the current thread. This
315 /// makes the response unique enough from other packet responses to
316 /// ensure we are back on track.
317 ///
318 /// This packet is needed after we time out sending a packet so we
319 /// can ensure that we are getting the response for the packet we
320 /// are sending. There are no sequence IDs in the GDB remote
321 /// protocol (there used to be, but they are not supported anymore)
322 /// so if you timeout sending packet "abc", you might then send
323 /// packet "cde" and get the response for the previous "abc" packet.
324 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
325 /// many responses for packets can look like responses for other
326 /// packets. So if we timeout, we need to ensure that we can get
327 /// back on track. If we can't get back on track, we must
328 /// disconnect.
329 //------------------------------------------------------------------
330 bool sync_success = false;
331 bool got_actual_response = false;
332 // We timed out, we need to sync back up with the
333 char echo_packet[32];
334 int echo_packet_len = 0;
335 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000336
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 if (m_supports_qEcho == eLazyBoolYes) {
338 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
339 "qEcho:%u", ++m_echo_number);
340 std::string regex_str = "^";
341 regex_str += echo_packet;
342 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000343 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 } else {
345 echo_packet_len =
346 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000347 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 }
Greg Clayton644247c2011-07-07 01:59:51 +0000349
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 PacketResult echo_packet_result =
351 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
352 if (echo_packet_result == PacketResult::Success) {
353 const uint32_t max_retries = 3;
354 uint32_t successful_responses = 0;
355 for (uint32_t i = 0; i < max_retries; ++i) {
356 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000357 echo_packet_result =
358 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 if (echo_packet_result == PacketResult::Success) {
360 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000361 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 sync_success = true;
363 break;
364 } else if (successful_responses == 1) {
365 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000366 // response, it probably is the response to the packet we
367 // actually wanted, so copy it over if this is the first
368 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 packet = echo_response;
370 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000371 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
373 continue; // Packet timed out, continue waiting for a response
374 else
375 break; // Something else went wrong getting the packet back, we
376 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 }
379
380 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000381 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 if (sync_success) {
383 // We timed out, but were able to recover
384 if (got_actual_response) {
385 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000386 // before the successful reply to our qEcho packet, so lets say
387 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 return PacketResult::Success;
389 }
390 } else {
391 disconnected = true;
392 Disconnect();
393 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 timed_out = true;
396 break;
397 case eConnectionStatusSuccess:
398 // printf ("status = success but error = %s\n",
399 // error.AsCString("<invalid>"));
400 break;
401
402 case eConnectionStatusEndOfFile:
403 case eConnectionStatusNoConnection:
404 case eConnectionStatusLostConnection:
405 case eConnectionStatusError:
406 disconnected = true;
407 Disconnect();
408 break;
409 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411 }
412 packet.Clear();
413 if (disconnected)
414 return PacketResult::ErrorDisconnected;
415 if (timed_out)
416 return PacketResult::ErrorReplyTimeout;
417 else
418 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000419}
420
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421bool GDBRemoteCommunication::DecompressPacket() {
422 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000423
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000425 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000426
427 size_t pkt_size = m_bytes.size();
428
Adrian Prantl05097242018-04-30 16:49:04 +0000429 // Smallest possible compressed packet is $N#00 - an uncompressed empty
430 // reply, most commonly indicating an unsupported packet. Anything less than
431 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000432 if (pkt_size < 5)
433 return true;
434
435 if (m_bytes[0] != '$' && m_bytes[0] != '%')
436 return true;
437 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
438 return true;
439
440 size_t hash_mark_idx = m_bytes.find('#');
441 if (hash_mark_idx == std::string::npos)
442 return true;
443 if (hash_mark_idx + 2 >= m_bytes.size())
444 return true;
445
446 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
447 !::isxdigit(m_bytes[hash_mark_idx + 2]))
448 return true;
449
450 size_t content_length =
451 pkt_size -
452 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
453 size_t content_start = 2; // The first character of the
454 // compressed/not-compressed text of the packet
455 size_t checksum_idx =
456 hash_mark_idx +
457 1; // The first character of the two hex checksum characters
458
459 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000460 // multiple packets. size_of_first_packet is the size of the initial packet
461 // which we'll replace with the decompressed version of, leaving the rest of
462 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 size_t size_of_first_packet = hash_mark_idx + 3;
464
465 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000466 // the uncompressed payload, then a : and then the compressed data. e.g.
467 // $C1024:<binary>#00 Update content_start and content_length to only include
468 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469
470 uint64_t decompressed_bufsize = ULONG_MAX;
471 if (m_bytes[1] == 'C') {
472 size_t i = content_start;
473 while (i < hash_mark_idx && isdigit(m_bytes[i]))
474 i++;
475 if (i < hash_mark_idx && m_bytes[i] == ':') {
476 i++;
477 content_start = i;
478 content_length = hash_mark_idx - content_start;
479 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
480 errno = 0;
481 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
482 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
483 m_bytes.erase(0, size_of_first_packet);
484 return false;
485 }
486 }
487 }
488
489 if (GetSendAcks()) {
490 char packet_checksum_cstr[3];
491 packet_checksum_cstr[0] = m_bytes[checksum_idx];
492 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
493 packet_checksum_cstr[2] = '\0';
494 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
495
496 long actual_checksum = CalculcateChecksum(
497 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
498 bool success = packet_checksum == actual_checksum;
499 if (!success) {
500 if (log)
501 log->Printf(
502 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
503 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
504 (uint8_t)actual_checksum);
505 }
506 // Send the ack or nack if needed
507 if (!success) {
508 SendNack();
509 m_bytes.erase(0, size_of_first_packet);
510 return false;
511 } else {
512 SendAck();
513 }
514 }
515
516 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000517 // This packet was not compressed -- delete the 'N' character at the start
518 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000519 m_bytes.erase(1, 1);
520 return true;
521 }
522
Adrian Prantl05097242018-04-30 16:49:04 +0000523 // Reverse the gdb-remote binary escaping that was done to the compressed
524 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000525 std::vector<uint8_t> unescaped_content;
526 unescaped_content.reserve(content_length);
527 size_t i = content_start;
528 while (i < hash_mark_idx) {
529 if (m_bytes[i] == '}') {
530 i++;
531 unescaped_content.push_back(m_bytes[i] ^ 0x20);
532 } else {
533 unescaped_content.push_back(m_bytes[i]);
534 }
535 i++;
536 }
537
538 uint8_t *decompressed_buffer = nullptr;
539 size_t decompressed_bytes = 0;
540
541 if (decompressed_bufsize != ULONG_MAX) {
Jason Molenda4a793c82018-12-18 23:02:50 +0000542 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 if (decompressed_buffer == nullptr) {
544 m_bytes.erase(0, size_of_first_packet);
545 return false;
546 }
547 }
548
549#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +0000550 if (m_compression_type == CompressionType::ZlibDeflate ||
551 m_compression_type == CompressionType::LZFSE ||
Jason Molenda4a793c82018-12-18 23:02:50 +0000552 m_compression_type == CompressionType::LZ4 ||
553 m_compression_type == CompressionType::LZMA) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000555 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000556 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000557 else if (m_compression_type == CompressionType::ZlibDeflate)
558 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000559 else if (m_compression_type == CompressionType::LZ4)
560 compression_type = COMPRESSION_LZ4_RAW;
561 else if (m_compression_type == CompressionType::LZMA)
562 compression_type = COMPRESSION_LZMA;
563
Jason Molenda4a793c82018-12-18 23:02:50 +0000564 if (m_decompression_scratch_type != m_compression_type) {
565 if (m_decompression_scratch) {
566 free (m_decompression_scratch);
567 m_decompression_scratch = nullptr;
568 }
569 size_t scratchbuf_size = 0;
570 if (m_compression_type == CompressionType::LZFSE)
571 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
572 else if (m_compression_type == CompressionType::LZ4)
573 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
574 else if (m_compression_type == CompressionType::ZlibDeflate)
575 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
576 else if (m_compression_type == CompressionType::LZMA)
577 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
578 else if (m_compression_type == CompressionType::LZFSE)
579 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
580 if (scratchbuf_size > 0) {
581 m_decompression_scratch = (void*) malloc (scratchbuf_size);
582 m_decompression_scratch_type = m_compression_type;
583 }
584 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000585
586 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
587 decompressed_bytes = compression_decode_buffer(
Jason Molenda4a793c82018-12-18 23:02:50 +0000588 decompressed_buffer, decompressed_bufsize,
589 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
590 m_decompression_scratch, compression_type);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000591 }
592 }
593#endif
594
595#if defined(HAVE_LIBZ)
596 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
597 decompressed_buffer != nullptr &&
598 m_compression_type == CompressionType::ZlibDeflate) {
599 z_stream stream;
600 memset(&stream, 0, sizeof(z_stream));
601 stream.next_in = (Bytef *)unescaped_content.data();
602 stream.avail_in = (uInt)unescaped_content.size();
603 stream.total_in = 0;
604 stream.next_out = (Bytef *)decompressed_buffer;
605 stream.avail_out = decompressed_bufsize;
606 stream.total_out = 0;
607 stream.zalloc = Z_NULL;
608 stream.zfree = Z_NULL;
609 stream.opaque = Z_NULL;
610
611 if (inflateInit2(&stream, -15) == Z_OK) {
612 int status = inflate(&stream, Z_NO_FLUSH);
613 inflateEnd(&stream);
614 if (status == Z_STREAM_END) {
615 decompressed_bytes = stream.total_out;
616 }
617 }
618 }
619#endif
620
621 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
622 if (decompressed_buffer)
623 free(decompressed_buffer);
624 m_bytes.erase(0, size_of_first_packet);
625 return false;
626 }
627
628 std::string new_packet;
629 new_packet.reserve(decompressed_bytes + 6);
630 new_packet.push_back(m_bytes[0]);
631 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
632 new_packet.push_back('#');
633 if (GetSendAcks()) {
634 uint8_t decompressed_checksum = CalculcateChecksum(
635 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
636 char decompressed_checksum_str[3];
637 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
638 new_packet.append(decompressed_checksum_str);
639 } else {
640 new_packet.push_back('0');
641 new_packet.push_back('0');
642 }
643
644 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
645 new_packet.size());
646
647 free(decompressed_buffer);
648 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000649}
650
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000651GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000652GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
653 StringExtractorGDBRemote &packet) {
654 // Put the packet data into the buffer in a thread safe fashion
655 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000656
Kate Stoneb9c1b512016-09-06 20:57:50 +0000657 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000658
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 if (src && src_len > 0) {
660 if (log && log->GetVerbose()) {
661 StreamString s;
662 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
663 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
664 }
665 m_bytes.append((const char *)src, src_len);
666 }
667
668 bool isNotifyPacket = false;
669
670 // Parse up the packets into gdb remote packets
671 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000672 // end_idx must be one past the last valid packet byte. Start it off with
673 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 size_t content_start = 0;
675 size_t content_length = 0;
676 size_t total_length = 0;
677 size_t checksum_idx = std::string::npos;
678
679 // Size of packet before it is decompressed, for logging purposes
680 size_t original_packet_size = m_bytes.size();
681 if (CompressionIsEnabled()) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000682 if (!DecompressPacket()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000683 packet.Clear();
684 return GDBRemoteCommunication::PacketType::Standard;
685 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000686 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 switch (m_bytes[0]) {
689 case '+': // Look for ack
690 case '-': // Look for cancel
691 case '\x03': // ^C to halt target
692 content_length = total_length = 1; // The command is one byte long...
693 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 case '%': // Async notify packet
696 isNotifyPacket = true;
697 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000698
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 case '$':
700 // Look for a standard gdb packet?
701 {
702 size_t hash_pos = m_bytes.find('#');
703 if (hash_pos != std::string::npos) {
704 if (hash_pos + 2 < m_bytes.size()) {
705 checksum_idx = hash_pos + 1;
706 // Skip the dollar sign
707 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000708 // Don't include the # in the content or the $ in the content
709 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 content_length = hash_pos - 1;
711
712 total_length =
713 hash_pos + 3; // Skip the # and the two hex checksum bytes
714 } else {
715 // Checksum bytes aren't all here yet
716 content_length = std::string::npos;
717 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000718 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 }
720 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000721
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000723 // We have an unexpected byte and we need to flush all bad data that is
724 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
725 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
726 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 const size_t bytes_len = m_bytes.size();
728 bool done = false;
729 uint32_t idx;
730 for (idx = 1; !done && idx < bytes_len; ++idx) {
731 switch (m_bytes[idx]) {
732 case '+':
733 case '-':
734 case '\x03':
735 case '%':
736 case '$':
737 done = true;
738 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000739
Kate Stoneb9c1b512016-09-06 20:57:50 +0000740 default:
741 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 }
744 if (log)
745 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
746 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
747 m_bytes.erase(0, idx - 1);
748 } break;
749 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000750
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 if (content_length == std::string::npos) {
752 packet.Clear();
753 return GDBRemoteCommunication::PacketType::Invalid;
754 } else if (total_length > 0) {
755
756 // We have a valid packet...
757 assert(content_length <= m_bytes.size());
758 assert(total_length <= m_bytes.size());
759 assert(content_length <= total_length);
760 size_t content_end = content_start + content_length;
761
762 bool success = true;
763 std::string &packet_str = packet.GetStringRef();
764 if (log) {
765 // If logging was just enabled and we have history, then dump out what
766 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000767 // that logs all of the packet will set a boolean so that we don't dump
768 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 if (!m_history.DidDumpToLog())
770 m_history.Dump(log);
771
772 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000773 // Only detect binary for packets that start with a '$' and have a
774 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 if (m_bytes[0] == '$' && total_length > 4) {
776 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000777 unsigned char c = m_bytes[i];
778 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 binary = true;
780 }
781 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000782 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 if (binary) {
784 StreamString strm;
785 // Packet header...
786 if (CompressionIsEnabled())
787 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
788 (uint64_t)original_packet_size, (uint64_t)total_length,
789 m_bytes[0]);
790 else
791 strm.Printf("<%4" PRIu64 "> read packet: %c",
792 (uint64_t)total_length, m_bytes[0]);
793 for (size_t i = content_start; i < content_end; ++i) {
794 // Remove binary escaped bytes when displaying the packet...
795 const char ch = m_bytes[i];
796 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000797 // 0x7d is the escape character. The next character is to be
798 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000799 const char escapee = m_bytes[++i] ^ 0x20;
800 strm.Printf("%2.2x", escapee);
801 } else {
802 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000803 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000804 }
805 // Packet footer...
806 strm.Printf("%c%c%c", m_bytes[total_length - 3],
807 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000808 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809 } else {
810 if (CompressionIsEnabled())
811 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
812 (uint64_t)original_packet_size, (uint64_t)total_length,
813 (int)(total_length), m_bytes.c_str());
814 else
815 log->Printf("<%4" PRIu64 "> read packet: %.*s",
816 (uint64_t)total_length, (int)(total_length),
817 m_bytes.c_str());
818 }
819 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000820
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000821 m_history.AddPacket(m_bytes, total_length,
822 GDBRemoteCommunicationHistory::ePacketTypeRecv,
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000823 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000824
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 // Clear packet_str in case there is some existing data in it.
826 packet_str.clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000827 // Copy the packet from m_bytes to packet_str expanding the run-length
828 // encoding in the process. Reserve enough byte for the most common case
829 // (no RLE used)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 packet_str.reserve(m_bytes.length());
831 for (std::string::const_iterator c = m_bytes.begin() + content_start;
832 c != m_bytes.begin() + content_end; ++c) {
833 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000834 // '*' indicates RLE. Next character will give us the repeat count
835 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000836 char char_to_repeat = packet_str.back();
837 // Number of time the previous character is repeated
838 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000839 // We have the char_to_repeat and repeat_count. Now push it in the
840 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 for (int i = 0; i < repeat_count; ++i)
842 packet_str.push_back(char_to_repeat);
843 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000844 // 0x7d is the escape character. The next character is to be XOR'd
845 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 char escapee = *++c ^ 0x20;
847 packet_str.push_back(escapee);
848 } else {
849 packet_str.push_back(*c);
850 }
851 }
852
853 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
854 assert(checksum_idx < m_bytes.size());
855 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
856 ::isxdigit(m_bytes[checksum_idx + 1])) {
857 if (GetSendAcks()) {
858 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
859 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
Pavel Labath5a841232018-03-28 10:19:10 +0000860 char actual_checksum = CalculcateChecksum(
861 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 success = packet_checksum == actual_checksum;
863 if (!success) {
864 if (log)
865 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
866 "got 0x%2.2x",
867 (int)(total_length), m_bytes.c_str(),
868 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000869 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000870 // Send the ack or nack if needed
871 if (!success)
872 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000873 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 SendAck();
875 }
876 } else {
877 success = false;
878 if (log)
879 log->Printf("error: invalid checksum in packet: '%s'\n",
880 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000881 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 }
883
884 m_bytes.erase(0, total_length);
885 packet.SetFilePos(0);
886
887 if (isNotifyPacket)
888 return GDBRemoteCommunication::PacketType::Notify;
889 else
890 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 }
893 packet.Clear();
894 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000895}
896
Zachary Turner97206d52017-05-12 04:51:55 +0000897Status GDBRemoteCommunication::StartListenThread(const char *hostname,
898 uint16_t port) {
899 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 if (m_listen_thread.IsJoinable()) {
901 error.SetErrorString("listen thread already running");
902 } else {
903 char listen_url[512];
904 if (hostname && hostname[0])
905 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
906 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000907 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
909 m_listen_url = listen_url;
910 SetConnection(new ConnectionFileDescriptor());
911 m_listen_thread = ThreadLauncher::LaunchThread(
912 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
913 }
914 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000915}
916
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917bool GDBRemoteCommunication::JoinListenThread() {
918 if (m_listen_thread.IsJoinable())
919 m_listen_thread.Join(nullptr);
920 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000921}
922
923lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
925 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000926 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 ConnectionFileDescriptor *connection =
928 (ConnectionFileDescriptor *)comm->GetConnection();
929
930 if (connection) {
931 // Do the listen on another thread so we can continue on...
932 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
933 eConnectionStatusSuccess)
934 comm->SetConnection(NULL);
935 }
936 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000937}
938
Zachary Turner97206d52017-05-12 04:51:55 +0000939Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
941 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
942 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
943 if (log)
944 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
945 __FUNCTION__, url ? url : "<empty>",
946 port ? *port : uint16_t(0));
947
Zachary Turner97206d52017-05-12 04:51:55 +0000948 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 // If we locate debugserver, keep that located version around
950 static FileSpec g_debugserver_file_spec;
951
952 char debugserver_path[PATH_MAX];
953 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
954
Adrian Prantl05097242018-04-30 16:49:04 +0000955 // Always check to see if we have an environment override for the path to the
956 // debugserver to use and use it if we do.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
958 if (env_debugserver_path) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000959 debugserver_file_spec.SetFile(env_debugserver_path,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000960 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +0000961 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
963 "from environment variable: %s",
964 __FUNCTION__, env_debugserver_path);
965 } else
966 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000967 bool debugserver_exists =
968 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +0000970 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +0000971 debugserver_file_spec = HostInfo::GetSupportExeDir();
972 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000974 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +0000976 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 log->Printf(
978 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
979 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +0000980
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 g_debugserver_file_spec = debugserver_file_spec;
982 } else {
983 debugserver_file_spec =
984 platform->LocateExecutable(DEBUGSERVER_BASENAME);
985 if (debugserver_file_spec) {
986 // Platform::LocateExecutable() wouldn't return a path if it doesn't
987 // exist
988 debugserver_exists = true;
989 } else {
990 if (log)
991 log->Printf("GDBRemoteCommunication::%s() could not find "
992 "gdb-remote stub exe '%s'",
993 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +0000994 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +0000996 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 g_debugserver_file_spec.Clear();
998 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000999 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001001
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 if (debugserver_exists) {
1003 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001004
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005 Args &debugserver_args = launch_info.GetArguments();
1006 debugserver_args.Clear();
1007 char arg_cstr[PATH_MAX];
1008
1009 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001010 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001011
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001012#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001014 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001015#endif
1016
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 // If a url is supplied then use it
1018 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001019 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001020
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 if (pass_comm_fd >= 0) {
1022 StreamString fd_arg;
1023 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001024 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025 // Send "pass_comm_fd" down to the inferior so it can use it to
1026 // communicate back with this process
1027 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1028 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001029
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001031 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001032
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001034 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001036
Stella Stamenovab3f44ad2018-12-10 17:23:28 +00001037 llvm::SmallString<128> named_pipe_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001038 // socket_pipe is used by debug server to communicate back either
1039 // TCP port or domain socket name which it listens on.
1040 // The second purpose of the pipe to serve as a synchronization point -
1041 // once data is written to the pipe, debug server is up and running.
1042 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001043
Adrian Prantl05097242018-04-30 16:49:04 +00001044 // port is null when debug server should listen on domain socket - we're
1045 // not interested in port value but rather waiting for debug server to
1046 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001047 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001049// Create a temporary file to get the stdout/stderr and redirect the output of
1050// the command into this file. We will later read this file if all goes well
1051// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001052#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 // Binding to port zero, we need to figure out what port it ends up
1054 // using using a named pipe...
1055 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1056 false, named_pipe_path);
1057 if (error.Fail()) {
1058 if (log)
1059 log->Printf("GDBRemoteCommunication::%s() "
1060 "named pipe creation failed: %s",
1061 __FUNCTION__, error.AsCString());
1062 return error;
1063 }
Sean Callanan1355f472016-09-19 22:06:12 +00001064 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001065 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001066#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 // Binding to port zero, we need to figure out what port it ends up
1068 // using using an unnamed pipe...
1069 error = socket_pipe.CreateNew(true);
1070 if (error.Fail()) {
1071 if (log)
1072 log->Printf("GDBRemoteCommunication::%s() "
1073 "unnamed pipe creation failed: %s",
1074 __FUNCTION__, error.AsCString());
1075 return error;
1076 }
1077 int write_fd = socket_pipe.GetWriteFileDescriptor();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001078 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1079 debugserver_args.AppendArgument(llvm::to_string(write_fd));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001081#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 } else {
1083 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001084 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 error = StartListenThread("127.0.0.1", 0);
1086 if (error.Fail()) {
1087 if (log)
1088 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1089 "thread: %s",
1090 __FUNCTION__, error.AsCString());
1091 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001092 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093
1094 ConnectionFileDescriptor *connection =
1095 (ConnectionFileDescriptor *)GetConnection();
1096 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001097 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001098 if (port_ > 0) {
1099 char port_cstr[32];
1100 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1101 // Send the host and port down that debugserver and specify an option
1102 // so that it connects back to the port we are listening to in this
1103 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001104 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1105 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001106 if (port)
1107 *port = port_;
1108 } else {
1109 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1110 if (log)
1111 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1112 error.AsCString());
1113 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001114 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 }
1116 }
1117
1118 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1119 if (env_debugserver_log_file) {
1120 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1121 env_debugserver_log_file);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001122 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
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) {
1129 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1130 env_debugserver_log_flags);
Sean Callanan1355f472016-09-19 22:06:12 +00001131 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001132 }
Vince Harron9753dd92015-05-10 15:22:09 +00001133#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134 const char *env_debugserver_log_channels =
1135 getenv("LLDB_SERVER_LOG_CHANNELS");
1136 if (env_debugserver_log_channels) {
1137 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1138 env_debugserver_log_channels);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001139 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 }
Vince Harron9753dd92015-05-10 15:22:09 +00001141#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001142
Kate Stoneb9c1b512016-09-06 20:57:50 +00001143 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1144 // env var doesn't come back.
1145 uint32_t env_var_index = 1;
1146 bool has_env_var;
1147 do {
1148 char env_var_name[64];
1149 snprintf(env_var_name, sizeof(env_var_name),
1150 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1151 const char *extra_arg = getenv(env_var_name);
1152 has_env_var = extra_arg != nullptr;
Todd Fiala34ba4262014-08-29 17:10:31 +00001153
Kate Stoneb9c1b512016-09-06 20:57:50 +00001154 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001155 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001156 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1158 "to stub command line (%s)",
1159 __FUNCTION__, env_var_name, extra_arg);
1160 }
1161 } while (has_env_var);
1162
1163 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001164 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 debugserver_args.AppendArguments(*inferior_args);
1166 }
1167
1168 // Copy the current environment to the gdbserver/debugserver instance
Pavel Labath62930e52018-01-10 11:57:31 +00001169 launch_info.GetEnvironment() = Host::GetEnvironment();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170
1171 // Close STDIN, STDOUT and STDERR.
1172 launch_info.AppendCloseFileAction(STDIN_FILENO);
1173 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1174 launch_info.AppendCloseFileAction(STDERR_FILENO);
1175
1176 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1177 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1178 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1179 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1180
1181 if (log) {
1182 StreamString string_stream;
1183 Platform *const platform = nullptr;
1184 launch_info.Dump(string_stream, platform);
1185 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001186 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187 }
1188 error = Host::LaunchProcess(launch_info);
1189
1190 if (error.Success() &&
1191 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1192 pass_comm_fd == -1) {
1193 if (named_pipe_path.size() > 0) {
1194 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1195 if (error.Fail())
1196 if (log)
1197 log->Printf("GDBRemoteCommunication::%s() "
1198 "failed to open named pipe %s for reading: %s",
1199 __FUNCTION__, named_pipe_path.c_str(),
1200 error.AsCString());
1201 }
1202
1203 if (socket_pipe.CanWrite())
1204 socket_pipe.CloseWriteFileDescriptor();
1205 if (socket_pipe.CanRead()) {
1206 char port_cstr[PATH_MAX] = {0};
1207 port_cstr[0] = '\0';
1208 size_t num_bytes = sizeof(port_cstr);
1209 // Read port from pipe with 10 second timeout.
1210 error = socket_pipe.ReadWithTimeout(
1211 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1212 if (error.Success() && (port != nullptr)) {
1213 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001214 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1215 if (*port == 0 || *port == child_port) {
1216 *port = child_port;
1217 if (log)
1218 log->Printf("GDBRemoteCommunication::%s() "
1219 "debugserver listens %u port",
1220 __FUNCTION__, *port);
1221 } else {
1222 if (log)
1223 log->Printf("GDBRemoteCommunication::%s() "
1224 "debugserver listening on port "
1225 "%d but requested port was %d",
1226 __FUNCTION__, (uint32_t)child_port,
1227 (uint32_t)(*port));
1228 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 } else {
1230 if (log)
1231 log->Printf("GDBRemoteCommunication::%s() "
1232 "failed to read a port value from pipe %s: %s",
1233 __FUNCTION__, named_pipe_path.c_str(),
1234 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001235 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 socket_pipe.Close();
1237 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001238
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 if (named_pipe_path.size() > 0) {
1240 const auto err = socket_pipe.Delete(named_pipe_path);
1241 if (err.Fail()) {
1242 if (log)
1243 log->Printf(
1244 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1245 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001246 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 }
1248
1249 // Make sure we actually connect with the debugserver...
1250 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001251 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001252 } else {
1253 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1254 }
Vince Harron8b335672015-05-12 01:10:56 +00001255
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 if (error.Fail()) {
1257 if (log)
1258 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1259 error.AsCString());
1260 }
Vince Harron8b335672015-05-12 01:10:56 +00001261
Kate Stoneb9c1b512016-09-06 20:57:50 +00001262 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001263}
1264
Kate Stoneb9c1b512016-09-06 20:57:50 +00001265void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1266
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001267void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1268 m_history.SetStream(strm);
1269};
1270
1271llvm::Error
1272GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1273 GDBRemoteCommunication &server) {
1274 const bool child_processes_inherit = false;
1275 const int backlog = 5;
1276 TCPSocket listen_socket(true, child_processes_inherit);
1277 if (llvm::Error error =
1278 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1279 return error;
1280
1281 Socket *accept_socket;
1282 std::future<Status> accept_status = std::async(
1283 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1284
1285 llvm::SmallString<32> remote_addr;
1286 llvm::raw_svector_ostream(remote_addr)
1287 << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1288
1289 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1290 new ConnectionFileDescriptor());
1291 if (conn_up->Connect(remote_addr, nullptr) != lldb::eConnectionStatusSuccess)
1292 return llvm::make_error<llvm::StringError>("Unable to connect",
1293 llvm::inconvertibleErrorCode());
1294
1295 client.SetConnection(conn_up.release());
1296 if (llvm::Error error = accept_status.get().ToError())
1297 return error;
1298
1299 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1300 return llvm::Error::success();
1301}
1302
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)
Greg Clayton84577092017-04-17 16:20:22 +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}