blob: c5a449783bd44e1588648471777eba86897ebb74 [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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056// GDBRemoteCommunication constructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000057GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
58 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000059 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +000060#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000061 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +000062#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000063 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +000064#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +000065 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
66 m_send_acks(true), m_compression_type(CompressionType::None),
Raphael Isemann46508f62019-01-25 08:21:47 +000067 m_listen_url() {
Chris Lattner30fdc8d2010-06-08 16:52:24 +000068}
69
Chris Lattner30fdc8d2010-06-08 16:52:24 +000070// Destructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000071GDBRemoteCommunication::~GDBRemoteCommunication() {
72 if (IsConnected()) {
73 Disconnect();
74 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +000075
Raphael Isemann46508f62019-01-25 08:21:47 +000076#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda8460bb02018-12-18 23:45:45 +000077 if (m_decompression_scratch)
78 free (m_decompression_scratch);
Raphael Isemann46508f62019-01-25 08:21:47 +000079#endif
Jason Molenda8460bb02018-12-18 23:45:45 +000080
Adrian Prantl05097242018-04-30 16:49:04 +000081 // Stop the communications read thread which is used to parse all incoming
82 // packets. This function will block until the read thread returns.
Kate Stoneb9c1b512016-09-06 20:57:50 +000083 if (m_read_thread_enabled)
84 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000085}
86
Kate Stoneb9c1b512016-09-06 20:57:50 +000087char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
88 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089
Kate Stoneb9c1b512016-09-06 20:57:50 +000090 for (char c : payload)
91 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +000092
Kate Stoneb9c1b512016-09-06 20:57:50 +000093 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000094}
95
Kate Stoneb9c1b512016-09-06 20:57:50 +000096size_t GDBRemoteCommunication::SendAck() {
97 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
98 ConnectionStatus status = eConnectionStatusSuccess;
99 char ch = '+';
100 const size_t bytes_written = Write(&ch, 1, status, NULL);
101 if (log)
102 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000103 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
104 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 return bytes_written;
106}
107
108size_t GDBRemoteCommunication::SendNack() {
109 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
110 ConnectionStatus status = eConnectionStatusSuccess;
111 char ch = '-';
112 const size_t bytes_written = Write(&ch, 1, status, NULL);
113 if (log)
114 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000115 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
116 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 return bytes_written;
118}
119
120GDBRemoteCommunication::PacketResult
121GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
Aaron Smith981e6352019-02-07 18:22:00 +0000122 StreamString packet(0, 4, eByteOrderBig);
123 packet.PutChar('$');
124 packet.Write(payload.data(), payload.size());
125 packet.PutChar('#');
126 packet.PutHex8(CalculcateChecksum(payload));
127 std::string packet_str = packet.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128
Aaron Smith981e6352019-02-07 18:22:00 +0000129 return SendRawPacketNoLock(packet_str);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000130}
131
132GDBRemoteCommunication::PacketResult
133GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
134 bool skip_ack) {
135 if (IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000137 ConnectionStatus status = eConnectionStatusSuccess;
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000138 const char *packet_data = packet.data();
139 const size_t packet_length = packet.size();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 size_t bytes_written = Write(packet_data, packet_length, status, NULL);
141 if (log) {
142 size_t binary_start_offset = 0;
143 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
144 0) {
145 const char *first_comma = strchr(packet_data, ',');
146 if (first_comma) {
147 const char *second_comma = strchr(first_comma + 1, ',');
148 if (second_comma)
149 binary_start_offset = second_comma - packet_data + 1;
Greg Claytonc1422c12012-04-09 22:46:21 +0000150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000152
Adrian Prantl05097242018-04-30 16:49:04 +0000153 // If logging was just enabled and we have history, then dump out what we
154 // have to the log so we get the historical context. The Dump() call that
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 // logs all of the packet will set a boolean so that we don't dump this
Adrian Prantl05097242018-04-30 16:49:04 +0000156 // more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 if (!m_history.DidDumpToLog())
158 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 if (binary_start_offset) {
161 StreamString strm;
162 // Print non binary data header
163 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
164 (int)binary_start_offset, packet_data);
165 const uint8_t *p;
166 // Print binary data exactly as sent
167 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
168 ++p)
169 strm.Printf("\\x%2.2x", *p);
170 // Print the checksum
171 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000172 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 } else
174 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
175 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000176 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000177
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000178 m_history.AddPacket(packet.str(), packet_length,
179 GDBRemoteCommunicationHistory::ePacketTypeSend,
180 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181
182 if (bytes_written == packet_length) {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000183 if (!skip_ack && GetSendAcks())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184 return GetAck();
185 else
186 return PacketResult::Success;
187 } else {
188 if (log)
189 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
190 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000191 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192 }
193 return PacketResult::ErrorSendFailed;
194}
195
196GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
197 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000198 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199 if (result == PacketResult::Success) {
200 if (packet.GetResponseType() ==
201 StringExtractorGDBRemote::ResponseType::eAck)
202 return PacketResult::Success;
203 else
204 return PacketResult::ErrorSendAck;
205 }
206 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207}
208
Greg Clayton3dedae12013-12-06 21:45:27 +0000209GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000210GDBRemoteCommunication::ReadPacketWithOutputSupport(
211 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
212 bool sync_on_timeout,
213 llvm::function_ref<void(llvm::StringRef)> output_callback) {
214 auto result = ReadPacket(response, timeout, sync_on_timeout);
215 while (result == PacketResult::Success && response.IsNormalResponse() &&
216 response.PeekChar() == 'O') {
217 response.GetChar();
218 std::string output;
219 if (response.GetHexByteString(output))
220 output_callback(output);
221 result = ReadPacket(response, timeout, sync_on_timeout);
222 }
223 return result;
224}
225
226GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000228 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 bool sync_on_timeout) {
230 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000231 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000232 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000233 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000234}
235
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000236// This function is called when a packet is requested.
237// A whole packet is popped from the packet queue and returned to the caller.
Adrian Prantl05097242018-04-30 16:49:04 +0000238// Packets are placed into this queue from the communication read thread. See
239// GDBRemoteCommunication::AppendBytesToCache.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000240GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000241GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000242 Timeout<std::micro> timeout) {
243 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
244 // lock down the packet queue
245 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000246
Pavel Labath1eff73c2016-11-24 10:54:49 +0000247 if (!timeout)
248 m_condition_queue_not_empty.wait(lock, pred);
249 else {
250 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
251 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 if (!IsConnected())
253 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 }
255
Pavel Labath1eff73c2016-11-24 10:54:49 +0000256 // get the front element of the queue
257 response = m_packet_queue.front();
258
259 // remove the front element
260 m_packet_queue.pop();
261
262 // we got a packet
263 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000265
266GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000267GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
268 Timeout<std::micro> timeout,
269 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000270 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000271 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272
Pavel Labathe8a7b982017-02-06 19:31:09 +0000273 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000274
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 // Check for a packet from our cache first without trying any reading...
276 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
277 return PacketResult::Success;
278
279 bool timed_out = false;
280 bool disconnected = false;
281 while (IsConnected() && !timed_out) {
282 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000283 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000284
Pavel Labathe8a7b982017-02-06 19:31:09 +0000285 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000286 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000287 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000288 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000289 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000290
291 if (bytes_read > 0) {
292 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000293 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 } else {
295 switch (status) {
296 case eConnectionStatusTimedOut:
297 case eConnectionStatusInterrupted:
298 if (sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000299 /// Sync the remote GDB server and make sure we get a response that
300 /// corresponds to what we send.
301 ///
302 /// Sends a "qEcho" packet and makes sure it gets the exact packet
303 /// echoed back. If the qEcho packet isn't supported, we send a qC
304 /// packet and make sure we get a valid thread ID back. We use the
305 /// "qC" packet since its response if very unique: is responds with
306 /// "QC%x" where %x is the thread ID of the current thread. This
307 /// makes the response unique enough from other packet responses to
308 /// ensure we are back on track.
309 ///
310 /// This packet is needed after we time out sending a packet so we
311 /// can ensure that we are getting the response for the packet we
312 /// are sending. There are no sequence IDs in the GDB remote
313 /// protocol (there used to be, but they are not supported anymore)
314 /// so if you timeout sending packet "abc", you might then send
315 /// packet "cde" and get the response for the previous "abc" packet.
316 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
317 /// many responses for packets can look like responses for other
318 /// packets. So if we timeout, we need to ensure that we can get
319 /// back on track. If we can't get back on track, we must
320 /// disconnect.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 bool sync_success = false;
322 bool got_actual_response = false;
323 // We timed out, we need to sync back up with the
324 char echo_packet[32];
325 int echo_packet_len = 0;
326 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 if (m_supports_qEcho == eLazyBoolYes) {
329 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
330 "qEcho:%u", ++m_echo_number);
331 std::string regex_str = "^";
332 regex_str += echo_packet;
333 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000334 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 } else {
336 echo_packet_len =
337 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000338 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000339 }
Greg Clayton644247c2011-07-07 01:59:51 +0000340
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 PacketResult echo_packet_result =
342 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
343 if (echo_packet_result == PacketResult::Success) {
344 const uint32_t max_retries = 3;
345 uint32_t successful_responses = 0;
346 for (uint32_t i = 0; i < max_retries; ++i) {
347 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000348 echo_packet_result =
349 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350 if (echo_packet_result == PacketResult::Success) {
351 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000352 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000353 sync_success = true;
354 break;
355 } else if (successful_responses == 1) {
356 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000357 // response, it probably is the response to the packet we
358 // actually wanted, so copy it over if this is the first
359 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 packet = echo_response;
361 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000362 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
364 continue; // Packet timed out, continue waiting for a response
365 else
366 break; // Something else went wrong getting the packet back, we
367 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000368 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369 }
370
371 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000372 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373 if (sync_success) {
374 // We timed out, but were able to recover
375 if (got_actual_response) {
376 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000377 // before the successful reply to our qEcho packet, so lets say
378 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000379 return PacketResult::Success;
380 }
381 } else {
382 disconnected = true;
383 Disconnect();
384 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000386 timed_out = true;
387 break;
388 case eConnectionStatusSuccess:
389 // printf ("status = success but error = %s\n",
390 // error.AsCString("<invalid>"));
391 break;
392
393 case eConnectionStatusEndOfFile:
394 case eConnectionStatusNoConnection:
395 case eConnectionStatusLostConnection:
396 case eConnectionStatusError:
397 disconnected = true;
398 Disconnect();
399 break;
400 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000401 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 }
403 packet.Clear();
404 if (disconnected)
405 return PacketResult::ErrorDisconnected;
406 if (timed_out)
407 return PacketResult::ErrorReplyTimeout;
408 else
409 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410}
411
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412bool GDBRemoteCommunication::DecompressPacket() {
413 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000414
Kate Stoneb9c1b512016-09-06 20:57:50 +0000415 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000416 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417
418 size_t pkt_size = m_bytes.size();
419
Adrian Prantl05097242018-04-30 16:49:04 +0000420 // Smallest possible compressed packet is $N#00 - an uncompressed empty
421 // reply, most commonly indicating an unsupported packet. Anything less than
422 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000423 if (pkt_size < 5)
424 return true;
425
426 if (m_bytes[0] != '$' && m_bytes[0] != '%')
427 return true;
428 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
429 return true;
430
431 size_t hash_mark_idx = m_bytes.find('#');
432 if (hash_mark_idx == std::string::npos)
433 return true;
434 if (hash_mark_idx + 2 >= m_bytes.size())
435 return true;
436
437 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
438 !::isxdigit(m_bytes[hash_mark_idx + 2]))
439 return true;
440
441 size_t content_length =
442 pkt_size -
443 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
444 size_t content_start = 2; // The first character of the
445 // compressed/not-compressed text of the packet
446 size_t checksum_idx =
447 hash_mark_idx +
448 1; // The first character of the two hex checksum characters
449
450 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000451 // multiple packets. size_of_first_packet is the size of the initial packet
452 // which we'll replace with the decompressed version of, leaving the rest of
453 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 size_t size_of_first_packet = hash_mark_idx + 3;
455
456 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000457 // the uncompressed payload, then a : and then the compressed data. e.g.
458 // $C1024:<binary>#00 Update content_start and content_length to only include
459 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460
461 uint64_t decompressed_bufsize = ULONG_MAX;
462 if (m_bytes[1] == 'C') {
463 size_t i = content_start;
464 while (i < hash_mark_idx && isdigit(m_bytes[i]))
465 i++;
466 if (i < hash_mark_idx && m_bytes[i] == ':') {
467 i++;
468 content_start = i;
469 content_length = hash_mark_idx - content_start;
470 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
471 errno = 0;
472 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
473 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
474 m_bytes.erase(0, size_of_first_packet);
475 return false;
476 }
477 }
478 }
479
480 if (GetSendAcks()) {
481 char packet_checksum_cstr[3];
482 packet_checksum_cstr[0] = m_bytes[checksum_idx];
483 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
484 packet_checksum_cstr[2] = '\0';
485 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
486
487 long actual_checksum = CalculcateChecksum(
488 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
489 bool success = packet_checksum == actual_checksum;
490 if (!success) {
491 if (log)
492 log->Printf(
493 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
494 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
495 (uint8_t)actual_checksum);
496 }
497 // Send the ack or nack if needed
498 if (!success) {
499 SendNack();
500 m_bytes.erase(0, size_of_first_packet);
501 return false;
502 } else {
503 SendAck();
504 }
505 }
506
507 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000508 // This packet was not compressed -- delete the 'N' character at the start
509 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000510 m_bytes.erase(1, 1);
511 return true;
512 }
513
Adrian Prantl05097242018-04-30 16:49:04 +0000514 // Reverse the gdb-remote binary escaping that was done to the compressed
515 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000516 std::vector<uint8_t> unescaped_content;
517 unescaped_content.reserve(content_length);
518 size_t i = content_start;
519 while (i < hash_mark_idx) {
520 if (m_bytes[i] == '}') {
521 i++;
522 unescaped_content.push_back(m_bytes[i] ^ 0x20);
523 } else {
524 unescaped_content.push_back(m_bytes[i]);
525 }
526 i++;
527 }
528
529 uint8_t *decompressed_buffer = nullptr;
530 size_t decompressed_bytes = 0;
531
532 if (decompressed_bufsize != ULONG_MAX) {
Jason Molenda4a793c82018-12-18 23:02:50 +0000533 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 if (decompressed_buffer == nullptr) {
535 m_bytes.erase(0, size_of_first_packet);
536 return false;
537 }
538 }
539
540#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +0000541 if (m_compression_type == CompressionType::ZlibDeflate ||
542 m_compression_type == CompressionType::LZFSE ||
Jason Molenda4a793c82018-12-18 23:02:50 +0000543 m_compression_type == CompressionType::LZ4 ||
544 m_compression_type == CompressionType::LZMA) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000546 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000548 else if (m_compression_type == CompressionType::ZlibDeflate)
549 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 else if (m_compression_type == CompressionType::LZ4)
551 compression_type = COMPRESSION_LZ4_RAW;
552 else if (m_compression_type == CompressionType::LZMA)
553 compression_type = COMPRESSION_LZMA;
554
Jason Molenda4a793c82018-12-18 23:02:50 +0000555 if (m_decompression_scratch_type != m_compression_type) {
556 if (m_decompression_scratch) {
557 free (m_decompression_scratch);
558 m_decompression_scratch = nullptr;
559 }
560 size_t scratchbuf_size = 0;
561 if (m_compression_type == CompressionType::LZFSE)
562 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
563 else if (m_compression_type == CompressionType::LZ4)
564 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
565 else if (m_compression_type == CompressionType::ZlibDeflate)
566 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
567 else if (m_compression_type == CompressionType::LZMA)
568 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
569 else if (m_compression_type == CompressionType::LZFSE)
570 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
571 if (scratchbuf_size > 0) {
572 m_decompression_scratch = (void*) malloc (scratchbuf_size);
573 m_decompression_scratch_type = m_compression_type;
574 }
575 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000576
577 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
578 decompressed_bytes = compression_decode_buffer(
Jason Molenda4a793c82018-12-18 23:02:50 +0000579 decompressed_buffer, decompressed_bufsize,
580 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
581 m_decompression_scratch, compression_type);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000582 }
583 }
584#endif
585
586#if defined(HAVE_LIBZ)
587 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
588 decompressed_buffer != nullptr &&
589 m_compression_type == CompressionType::ZlibDeflate) {
590 z_stream stream;
591 memset(&stream, 0, sizeof(z_stream));
592 stream.next_in = (Bytef *)unescaped_content.data();
593 stream.avail_in = (uInt)unescaped_content.size();
594 stream.total_in = 0;
595 stream.next_out = (Bytef *)decompressed_buffer;
596 stream.avail_out = decompressed_bufsize;
597 stream.total_out = 0;
598 stream.zalloc = Z_NULL;
599 stream.zfree = Z_NULL;
600 stream.opaque = Z_NULL;
601
602 if (inflateInit2(&stream, -15) == Z_OK) {
603 int status = inflate(&stream, Z_NO_FLUSH);
604 inflateEnd(&stream);
605 if (status == Z_STREAM_END) {
606 decompressed_bytes = stream.total_out;
607 }
608 }
609 }
610#endif
611
612 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
613 if (decompressed_buffer)
614 free(decompressed_buffer);
615 m_bytes.erase(0, size_of_first_packet);
616 return false;
617 }
618
619 std::string new_packet;
620 new_packet.reserve(decompressed_bytes + 6);
621 new_packet.push_back(m_bytes[0]);
622 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
623 new_packet.push_back('#');
624 if (GetSendAcks()) {
625 uint8_t decompressed_checksum = CalculcateChecksum(
626 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
627 char decompressed_checksum_str[3];
628 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
629 new_packet.append(decompressed_checksum_str);
630 } else {
631 new_packet.push_back('0');
632 new_packet.push_back('0');
633 }
634
635 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
636 new_packet.size());
637
638 free(decompressed_buffer);
639 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000640}
641
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000642GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000643GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
644 StringExtractorGDBRemote &packet) {
645 // Put the packet data into the buffer in a thread safe fashion
646 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000647
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 if (src && src_len > 0) {
651 if (log && log->GetVerbose()) {
652 StreamString s;
653 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
654 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
655 }
656 m_bytes.append((const char *)src, src_len);
657 }
658
659 bool isNotifyPacket = false;
660
661 // Parse up the packets into gdb remote packets
662 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000663 // end_idx must be one past the last valid packet byte. Start it off with
664 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 size_t content_start = 0;
666 size_t content_length = 0;
667 size_t total_length = 0;
668 size_t checksum_idx = std::string::npos;
669
670 // Size of packet before it is decompressed, for logging purposes
671 size_t original_packet_size = m_bytes.size();
672 if (CompressionIsEnabled()) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000673 if (!DecompressPacket()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 packet.Clear();
675 return GDBRemoteCommunication::PacketType::Standard;
676 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000677 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 switch (m_bytes[0]) {
680 case '+': // Look for ack
681 case '-': // Look for cancel
682 case '\x03': // ^C to halt target
683 content_length = total_length = 1; // The command is one byte long...
684 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000685
Kate Stoneb9c1b512016-09-06 20:57:50 +0000686 case '%': // Async notify packet
687 isNotifyPacket = true;
688 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000689
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690 case '$':
691 // Look for a standard gdb packet?
692 {
693 size_t hash_pos = m_bytes.find('#');
694 if (hash_pos != std::string::npos) {
695 if (hash_pos + 2 < m_bytes.size()) {
696 checksum_idx = hash_pos + 1;
697 // Skip the dollar sign
698 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000699 // Don't include the # in the content or the $ in the content
700 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 content_length = hash_pos - 1;
702
703 total_length =
704 hash_pos + 3; // Skip the # and the two hex checksum bytes
705 } else {
706 // Checksum bytes aren't all here yet
707 content_length = std::string::npos;
708 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000709 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 }
711 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000712
Kate Stoneb9c1b512016-09-06 20:57:50 +0000713 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000714 // We have an unexpected byte and we need to flush all bad data that is
715 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
716 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
717 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 const size_t bytes_len = m_bytes.size();
719 bool done = false;
720 uint32_t idx;
721 for (idx = 1; !done && idx < bytes_len; ++idx) {
722 switch (m_bytes[idx]) {
723 case '+':
724 case '-':
725 case '\x03':
726 case '%':
727 case '$':
728 done = true;
729 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 default:
732 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000733 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 }
735 if (log)
736 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
737 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
738 m_bytes.erase(0, idx - 1);
739 } break;
740 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 if (content_length == std::string::npos) {
743 packet.Clear();
744 return GDBRemoteCommunication::PacketType::Invalid;
745 } else if (total_length > 0) {
746
747 // We have a valid packet...
748 assert(content_length <= m_bytes.size());
749 assert(total_length <= m_bytes.size());
750 assert(content_length <= total_length);
751 size_t content_end = content_start + content_length;
752
753 bool success = true;
754 std::string &packet_str = packet.GetStringRef();
755 if (log) {
756 // If logging was just enabled and we have history, then dump out what
757 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000758 // that logs all of the packet will set a boolean so that we don't dump
759 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 if (!m_history.DidDumpToLog())
761 m_history.Dump(log);
762
763 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000764 // Only detect binary for packets that start with a '$' and have a
765 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766 if (m_bytes[0] == '$' && total_length > 4) {
767 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000768 unsigned char c = m_bytes[i];
769 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 binary = true;
771 }
772 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000773 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774 if (binary) {
775 StreamString strm;
776 // Packet header...
777 if (CompressionIsEnabled())
778 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
779 (uint64_t)original_packet_size, (uint64_t)total_length,
780 m_bytes[0]);
781 else
782 strm.Printf("<%4" PRIu64 "> read packet: %c",
783 (uint64_t)total_length, m_bytes[0]);
784 for (size_t i = content_start; i < content_end; ++i) {
785 // Remove binary escaped bytes when displaying the packet...
786 const char ch = m_bytes[i];
787 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000788 // 0x7d is the escape character. The next character is to be
789 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 const char escapee = m_bytes[++i] ^ 0x20;
791 strm.Printf("%2.2x", escapee);
792 } else {
793 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000794 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000795 }
796 // Packet footer...
797 strm.Printf("%c%c%c", m_bytes[total_length - 3],
798 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000799 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 } else {
801 if (CompressionIsEnabled())
802 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
803 (uint64_t)original_packet_size, (uint64_t)total_length,
804 (int)(total_length), m_bytes.c_str());
805 else
806 log->Printf("<%4" PRIu64 "> read packet: %.*s",
807 (uint64_t)total_length, (int)(total_length),
808 m_bytes.c_str());
809 }
810 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000811
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000812 m_history.AddPacket(m_bytes, total_length,
813 GDBRemoteCommunicationHistory::ePacketTypeRecv,
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000814 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000815
Kate Stoneb9c1b512016-09-06 20:57:50 +0000816 // Clear packet_str in case there is some existing data in it.
817 packet_str.clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000818 // Copy the packet from m_bytes to packet_str expanding the run-length
819 // encoding in the process. Reserve enough byte for the most common case
820 // (no RLE used)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 packet_str.reserve(m_bytes.length());
822 for (std::string::const_iterator c = m_bytes.begin() + content_start;
823 c != m_bytes.begin() + content_end; ++c) {
824 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000825 // '*' indicates RLE. Next character will give us the repeat count
826 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 char char_to_repeat = packet_str.back();
828 // Number of time the previous character is repeated
829 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000830 // We have the char_to_repeat and repeat_count. Now push it in the
831 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000832 for (int i = 0; i < repeat_count; ++i)
833 packet_str.push_back(char_to_repeat);
834 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000835 // 0x7d is the escape character. The next character is to be XOR'd
836 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000837 char escapee = *++c ^ 0x20;
838 packet_str.push_back(escapee);
839 } else {
840 packet_str.push_back(*c);
841 }
842 }
843
844 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
845 assert(checksum_idx < m_bytes.size());
846 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
847 ::isxdigit(m_bytes[checksum_idx + 1])) {
848 if (GetSendAcks()) {
849 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
850 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
Pavel Labath5a841232018-03-28 10:19:10 +0000851 char actual_checksum = CalculcateChecksum(
852 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000853 success = packet_checksum == actual_checksum;
854 if (!success) {
855 if (log)
856 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
857 "got 0x%2.2x",
858 (int)(total_length), m_bytes.c_str(),
859 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000860 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000861 // Send the ack or nack if needed
862 if (!success)
863 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000864 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 SendAck();
866 }
867 } else {
868 success = false;
869 if (log)
870 log->Printf("error: invalid checksum in packet: '%s'\n",
871 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000873 }
874
875 m_bytes.erase(0, total_length);
876 packet.SetFilePos(0);
877
878 if (isNotifyPacket)
879 return GDBRemoteCommunication::PacketType::Notify;
880 else
881 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000882 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 }
884 packet.Clear();
885 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000886}
887
Zachary Turner97206d52017-05-12 04:51:55 +0000888Status GDBRemoteCommunication::StartListenThread(const char *hostname,
889 uint16_t port) {
890 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891 if (m_listen_thread.IsJoinable()) {
892 error.SetErrorString("listen thread already running");
893 } else {
894 char listen_url[512];
895 if (hostname && hostname[0])
896 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
897 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000898 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000899 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
900 m_listen_url = listen_url;
901 SetConnection(new ConnectionFileDescriptor());
902 m_listen_thread = ThreadLauncher::LaunchThread(
903 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
904 }
905 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000906}
907
Kate Stoneb9c1b512016-09-06 20:57:50 +0000908bool GDBRemoteCommunication::JoinListenThread() {
909 if (m_listen_thread.IsJoinable())
910 m_listen_thread.Join(nullptr);
911 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000912}
913
914lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
916 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000917 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918 ConnectionFileDescriptor *connection =
919 (ConnectionFileDescriptor *)comm->GetConnection();
920
921 if (connection) {
922 // Do the listen on another thread so we can continue on...
923 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
924 eConnectionStatusSuccess)
925 comm->SetConnection(NULL);
926 }
927 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000928}
929
Zachary Turner97206d52017-05-12 04:51:55 +0000930Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
932 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
933 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
934 if (log)
935 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
936 __FUNCTION__, url ? url : "<empty>",
937 port ? *port : uint16_t(0));
938
Zachary Turner97206d52017-05-12 04:51:55 +0000939 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 // If we locate debugserver, keep that located version around
941 static FileSpec g_debugserver_file_spec;
942
943 char debugserver_path[PATH_MAX];
944 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
945
Aaron Smith981e6352019-02-07 18:22:00 +0000946 Environment host_env = Host::GetEnvironment();
947
Adrian Prantl05097242018-04-30 16:49:04 +0000948 // Always check to see if we have an environment override for the path to the
949 // debugserver to use and use it if we do.
Aaron Smith981e6352019-02-07 18:22:00 +0000950 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
951 if (!env_debugserver_path.empty()) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000952 debugserver_file_spec.SetFile(env_debugserver_path,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000953 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +0000954 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
956 "from environment variable: %s",
Aaron Smith981e6352019-02-07 18:22:00 +0000957 __FUNCTION__, env_debugserver_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958 } else
959 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000960 bool debugserver_exists =
961 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000962 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +0000963 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +0000964 debugserver_file_spec = HostInfo::GetSupportExeDir();
965 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000967 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +0000969 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 log->Printf(
971 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
972 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +0000973
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 g_debugserver_file_spec = debugserver_file_spec;
975 } else {
Aaron Smithbc472892019-02-14 08:59:04 +0000976 if (platform)
977 debugserver_file_spec =
978 platform->LocateExecutable(DEBUGSERVER_BASENAME);
979 else
980 debugserver_file_spec.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 if (debugserver_file_spec) {
982 // Platform::LocateExecutable() wouldn't return a path if it doesn't
983 // exist
984 debugserver_exists = true;
985 } else {
986 if (log)
987 log->Printf("GDBRemoteCommunication::%s() could not find "
988 "gdb-remote stub exe '%s'",
989 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +0000990 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +0000992 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 g_debugserver_file_spec.Clear();
994 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000995 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000997
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 if (debugserver_exists) {
999 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001000
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 Args &debugserver_args = launch_info.GetArguments();
1002 debugserver_args.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003
1004 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001005 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001006
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001007#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001009 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001010#endif
1011
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 // If a url is supplied then use it
1013 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001014 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001015
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 if (pass_comm_fd >= 0) {
1017 StreamString fd_arg;
1018 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001019 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 // Send "pass_comm_fd" down to the inferior so it can use it to
1021 // communicate back with this process
1022 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1023 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001024
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001026 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001027
Kate Stoneb9c1b512016-09-06 20:57:50 +00001028 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001029 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001031
Stella Stamenovab3f44ad2018-12-10 17:23:28 +00001032 llvm::SmallString<128> named_pipe_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033 // socket_pipe is used by debug server to communicate back either
1034 // TCP port or domain socket name which it listens on.
1035 // The second purpose of the pipe to serve as a synchronization point -
1036 // once data is written to the pipe, debug server is up and running.
1037 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001038
Adrian Prantl05097242018-04-30 16:49:04 +00001039 // port is null when debug server should listen on domain socket - we're
1040 // not interested in port value but rather waiting for debug server to
1041 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001042 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001043 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001044// Create a temporary file to get the stdout/stderr and redirect the output of
1045// the command into this file. We will later read this file if all goes well
1046// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001047#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001048 // Binding to port zero, we need to figure out what port it ends up
1049 // using using a named pipe...
1050 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1051 false, named_pipe_path);
1052 if (error.Fail()) {
1053 if (log)
1054 log->Printf("GDBRemoteCommunication::%s() "
1055 "named pipe creation failed: %s",
1056 __FUNCTION__, error.AsCString());
1057 return error;
1058 }
Sean Callanan1355f472016-09-19 22:06:12 +00001059 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001060 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001061#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 // Binding to port zero, we need to figure out what port it ends up
1063 // using using an unnamed pipe...
1064 error = socket_pipe.CreateNew(true);
1065 if (error.Fail()) {
1066 if (log)
1067 log->Printf("GDBRemoteCommunication::%s() "
1068 "unnamed pipe creation failed: %s",
1069 __FUNCTION__, error.AsCString());
1070 return error;
1071 }
Aaron Smithe55850b2019-01-10 00:46:09 +00001072 pipe_t write = socket_pipe.GetWritePipe();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001073 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
Aaron Smithe55850b2019-01-10 00:46:09 +00001074 debugserver_args.AppendArgument(llvm::to_string(write));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001076#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 } else {
1078 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001079 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080 error = StartListenThread("127.0.0.1", 0);
1081 if (error.Fail()) {
1082 if (log)
1083 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1084 "thread: %s",
1085 __FUNCTION__, error.AsCString());
1086 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001087 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088
1089 ConnectionFileDescriptor *connection =
1090 (ConnectionFileDescriptor *)GetConnection();
1091 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001092 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 if (port_ > 0) {
1094 char port_cstr[32];
1095 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1096 // Send the host and port down that debugserver and specify an option
1097 // so that it connects back to the port we are listening to in this
1098 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001099 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1100 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 if (port)
1102 *port = port_;
1103 } else {
1104 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1105 if (log)
1106 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1107 error.AsCString());
1108 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001109 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001110 }
1111 }
Aaron Smith981e6352019-02-07 18:22:00 +00001112 std::string env_debugserver_log_file =
1113 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1114 if (!env_debugserver_log_file.empty()) {
1115 debugserver_args.AppendArgument(
1116 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 }
1118
Vince Harron9753dd92015-05-10 15:22:09 +00001119#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 const char *env_debugserver_log_flags =
1121 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1122 if (env_debugserver_log_flags) {
Aaron Smith981e6352019-02-07 18:22:00 +00001123 debugserver_args.AppendArgument(
1124 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 }
Vince Harron9753dd92015-05-10 15:22:09 +00001126#else
Aaron Smith981e6352019-02-07 18:22:00 +00001127 std::string env_debugserver_log_channels =
1128 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1129 if (!env_debugserver_log_channels.empty()) {
1130 debugserver_args.AppendArgument(
1131 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1132 .str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133 }
Vince Harron9753dd92015-05-10 15:22:09 +00001134#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001135
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1137 // env var doesn't come back.
1138 uint32_t env_var_index = 1;
1139 bool has_env_var;
1140 do {
1141 char env_var_name[64];
1142 snprintf(env_var_name, sizeof(env_var_name),
1143 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
Aaron Smith981e6352019-02-07 18:22:00 +00001144 std::string extra_arg = host_env.lookup(env_var_name);
1145 has_env_var = !extra_arg.empty();
Todd Fiala34ba4262014-08-29 17:10:31 +00001146
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001148 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001149 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001150 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1151 "to stub command line (%s)",
Aaron Smith981e6352019-02-07 18:22:00 +00001152 __FUNCTION__, env_var_name, extra_arg.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001153 }
1154 } while (has_env_var);
1155
1156 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001157 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001158 debugserver_args.AppendArguments(*inferior_args);
1159 }
1160
1161 // Copy the current environment to the gdbserver/debugserver instance
Aaron Smith981e6352019-02-07 18:22:00 +00001162 launch_info.GetEnvironment() = host_env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163
1164 // Close STDIN, STDOUT and STDERR.
1165 launch_info.AppendCloseFileAction(STDIN_FILENO);
1166 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1167 launch_info.AppendCloseFileAction(STDERR_FILENO);
1168
1169 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1170 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1171 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1172 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1173
1174 if (log) {
1175 StreamString string_stream;
1176 Platform *const platform = nullptr;
1177 launch_info.Dump(string_stream, platform);
1178 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001179 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180 }
1181 error = Host::LaunchProcess(launch_info);
1182
1183 if (error.Success() &&
1184 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1185 pass_comm_fd == -1) {
1186 if (named_pipe_path.size() > 0) {
1187 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1188 if (error.Fail())
1189 if (log)
1190 log->Printf("GDBRemoteCommunication::%s() "
1191 "failed to open named pipe %s for reading: %s",
1192 __FUNCTION__, named_pipe_path.c_str(),
1193 error.AsCString());
1194 }
1195
1196 if (socket_pipe.CanWrite())
1197 socket_pipe.CloseWriteFileDescriptor();
1198 if (socket_pipe.CanRead()) {
1199 char port_cstr[PATH_MAX] = {0};
1200 port_cstr[0] = '\0';
1201 size_t num_bytes = sizeof(port_cstr);
1202 // Read port from pipe with 10 second timeout.
1203 error = socket_pipe.ReadWithTimeout(
1204 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1205 if (error.Success() && (port != nullptr)) {
1206 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001207 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1208 if (*port == 0 || *port == child_port) {
1209 *port = child_port;
1210 if (log)
1211 log->Printf("GDBRemoteCommunication::%s() "
1212 "debugserver listens %u port",
1213 __FUNCTION__, *port);
1214 } else {
1215 if (log)
1216 log->Printf("GDBRemoteCommunication::%s() "
1217 "debugserver listening on port "
1218 "%d but requested port was %d",
1219 __FUNCTION__, (uint32_t)child_port,
1220 (uint32_t)(*port));
1221 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001222 } else {
1223 if (log)
1224 log->Printf("GDBRemoteCommunication::%s() "
1225 "failed to read a port value from pipe %s: %s",
1226 __FUNCTION__, named_pipe_path.c_str(),
1227 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001228 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 socket_pipe.Close();
1230 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001231
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232 if (named_pipe_path.size() > 0) {
1233 const auto err = socket_pipe.Delete(named_pipe_path);
1234 if (err.Fail()) {
1235 if (log)
1236 log->Printf(
1237 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1238 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001239 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001240 }
1241
1242 // Make sure we actually connect with the debugserver...
1243 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001244 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001245 } else {
1246 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1247 }
Vince Harron8b335672015-05-12 01:10:56 +00001248
Kate Stoneb9c1b512016-09-06 20:57:50 +00001249 if (error.Fail()) {
1250 if (log)
1251 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1252 error.AsCString());
1253 }
Vince Harron8b335672015-05-12 01:10:56 +00001254
Kate Stoneb9c1b512016-09-06 20:57:50 +00001255 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001256}
1257
Kate Stoneb9c1b512016-09-06 20:57:50 +00001258void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1259
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001260void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1261 m_history.SetStream(strm);
Zachary Turner52f8f342019-01-29 22:55:21 +00001262}
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001263
1264llvm::Error
1265GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1266 GDBRemoteCommunication &server) {
1267 const bool child_processes_inherit = false;
1268 const int backlog = 5;
1269 TCPSocket listen_socket(true, child_processes_inherit);
1270 if (llvm::Error error =
1271 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1272 return error;
1273
1274 Socket *accept_socket;
1275 std::future<Status> accept_status = std::async(
1276 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1277
1278 llvm::SmallString<32> remote_addr;
1279 llvm::raw_svector_ostream(remote_addr)
Michal Gornye39ec432019-03-03 12:42:43 +00001280 << "connect://127.0.0.1:" << listen_socket.GetLocalPortNumber();
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001281
1282 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1283 new ConnectionFileDescriptor());
Pavel Labath9d723b82019-02-18 10:36:23 +00001284 Status status;
1285 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1286 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1287 "Unable to connect: %s", status.AsCString());
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001288
1289 client.SetConnection(conn_up.release());
1290 if (llvm::Error error = accept_status.get().ToError())
1291 return error;
1292
1293 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1294 return llvm::Error::success();
1295}
1296
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001298 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Aaron Smith981e6352019-02-07 18:22:00 +00001299 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1300 auto curr_timeout = gdb_comm.GetPacketTimeout();
1301 // Only update the timeout if the timeout is greater than the current
1302 // timeout. If the current timeout is larger, then just use that.
1303 if (curr_timeout < timeout) {
1304 m_timeout_modified = true;
1305 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1306 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001307}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001308
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001310 // Only restore the timeout if we set it in the constructor.
1311 if (m_timeout_modified)
1312 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001313}
1314
Kate Stoneb9c1b512016-09-06 20:57:50 +00001315// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001316// become available for this connection. This function will consume all
1317// incoming bytes and try to parse whole packets as they become available. Full
1318// packets are placed in a queue, so that all packet requests can simply pop
1319// from this queue. Async notification packets will be dispatched immediately
1320// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1322 size_t len, bool broadcast,
1323 lldb::ConnectionStatus status) {
1324 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001325
Kate Stoneb9c1b512016-09-06 20:57:50 +00001326 while (true) {
1327 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001328
Adrian Prantl05097242018-04-30 16:49:04 +00001329 // scrub the data so we do not pass it back to CheckForPacket on future
1330 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331 bytes = nullptr;
1332 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001333
Kate Stoneb9c1b512016-09-06 20:57:50 +00001334 // we may have received no packet so lets bail out
1335 if (type == PacketType::Invalid)
1336 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001337
Kate Stoneb9c1b512016-09-06 20:57:50 +00001338 if (type == PacketType::Standard) {
1339 // scope for the mutex
1340 {
1341 // lock down the packet queue
1342 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1343 // push a new packet into the queue
1344 m_packet_queue.push(packet);
1345 // Signal condition variable that we have a packet
1346 m_condition_queue_not_empty.notify_one();
1347 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001348 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001349
1350 if (type == PacketType::Notify) {
1351 // put this packet into an event
1352 const char *pdata = packet.GetStringRef().c_str();
1353
Adrian Prantl05097242018-04-30 16:49:04 +00001354 // as the communication class, we are a broadcaster and the async thread
1355 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1357 new EventDataBytes(pdata));
1358 }
1359 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001360}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001361
1362void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1363 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1364 StringRef Style) {
1365 using PacketResult = GDBRemoteCommunication::PacketResult;
1366
1367 switch (result) {
1368 case PacketResult::Success:
1369 Stream << "Success";
1370 break;
1371 case PacketResult::ErrorSendFailed:
1372 Stream << "ErrorSendFailed";
1373 break;
1374 case PacketResult::ErrorSendAck:
1375 Stream << "ErrorSendAck";
1376 break;
1377 case PacketResult::ErrorReplyFailed:
1378 Stream << "ErrorReplyFailed";
1379 break;
1380 case PacketResult::ErrorReplyTimeout:
1381 Stream << "ErrorReplyTimeout";
1382 break;
1383 case PacketResult::ErrorReplyInvalid:
1384 Stream << "ErrorReplyInvalid";
1385 break;
1386 case PacketResult::ErrorReplyAck:
1387 Stream << "ErrorReplyAck";
1388 break;
1389 case PacketResult::ErrorDisconnected:
1390 Stream << "ErrorDisconnected";
1391 break;
1392 case PacketResult::ErrorNoSequenceLock:
1393 Stream << "ErrorNoSequenceLock";
1394 break;
1395 }
1396}