blob: 4605bd2e90e4c017b1251ea148a2c1cf34a60ed0 [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
Kate Stoneb9c1b512016-09-06 20:57:50 +000045#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000046#include <compression.h>
47#endif
48
Kate Stoneb9c1b512016-09-06 20:57:50 +000049#if defined(HAVE_LIBZ)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000050#include <zlib.h>
51#endif
52
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053using namespace lldb;
54using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000055using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056
57//----------------------------------------------------------------------
58// GDBRemoteCommunication constructor
59//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000060GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
61 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000062 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +000063#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000064 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +000065#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000066 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +000067#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +000068 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
69 m_send_acks(true), m_compression_type(CompressionType::None),
70 m_listen_url() {
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071}
72
73//----------------------------------------------------------------------
74// Destructor
75//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000076GDBRemoteCommunication::~GDBRemoteCommunication() {
77 if (IsConnected()) {
78 Disconnect();
79 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +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) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000122 StreamString packet(0, 4, eByteOrderBig);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 packet.PutChar('$');
124 packet.Write(payload.data(), payload.size());
125 packet.PutChar('#');
126 packet.PutHex8(CalculcateChecksum(payload));
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000127 std::string packet_str = packet.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000129 return SendRawPacketNoLock(packet_str);
130}
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) {
299 //------------------------------------------------------------------
300 /// Sync the remote GDB server and make sure we get a response that
301 /// corresponds to what we send.
302 ///
303 /// Sends a "qEcho" packet and makes sure it gets the exact packet
304 /// echoed back. If the qEcho packet isn't supported, we send a qC
305 /// packet and make sure we get a valid thread ID back. We use the
306 /// "qC" packet since its response if very unique: is responds with
307 /// "QC%x" where %x is the thread ID of the current thread. This
308 /// makes the response unique enough from other packet responses to
309 /// ensure we are back on track.
310 ///
311 /// This packet is needed after we time out sending a packet so we
312 /// can ensure that we are getting the response for the packet we
313 /// are sending. There are no sequence IDs in the GDB remote
314 /// protocol (there used to be, but they are not supported anymore)
315 /// so if you timeout sending packet "abc", you might then send
316 /// packet "cde" and get the response for the previous "abc" packet.
317 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
318 /// many responses for packets can look like responses for other
319 /// packets. So if we timeout, we need to ensure that we can get
320 /// back on track. If we can't get back on track, we must
321 /// disconnect.
322 //------------------------------------------------------------------
323 bool sync_success = false;
324 bool got_actual_response = false;
325 // We timed out, we need to sync back up with the
326 char echo_packet[32];
327 int echo_packet_len = 0;
328 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000329
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330 if (m_supports_qEcho == eLazyBoolYes) {
331 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
332 "qEcho:%u", ++m_echo_number);
333 std::string regex_str = "^";
334 regex_str += echo_packet;
335 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000336 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000337 } else {
338 echo_packet_len =
339 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000340 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 }
Greg Clayton644247c2011-07-07 01:59:51 +0000342
Kate Stoneb9c1b512016-09-06 20:57:50 +0000343 PacketResult echo_packet_result =
344 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
345 if (echo_packet_result == PacketResult::Success) {
346 const uint32_t max_retries = 3;
347 uint32_t successful_responses = 0;
348 for (uint32_t i = 0; i < max_retries; ++i) {
349 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000350 echo_packet_result =
351 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 if (echo_packet_result == PacketResult::Success) {
353 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000354 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 sync_success = true;
356 break;
357 } else if (successful_responses == 1) {
358 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000359 // response, it probably is the response to the packet we
360 // actually wanted, so copy it over if this is the first
361 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 packet = echo_response;
363 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000364 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
366 continue; // Packet timed out, continue waiting for a response
367 else
368 break; // Something else went wrong getting the packet back, we
369 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000370 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 }
372
373 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000374 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000375 if (sync_success) {
376 // We timed out, but were able to recover
377 if (got_actual_response) {
378 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000379 // before the successful reply to our qEcho packet, so lets say
380 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 return PacketResult::Success;
382 }
383 } else {
384 disconnected = true;
385 Disconnect();
386 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 timed_out = true;
389 break;
390 case eConnectionStatusSuccess:
391 // printf ("status = success but error = %s\n",
392 // error.AsCString("<invalid>"));
393 break;
394
395 case eConnectionStatusEndOfFile:
396 case eConnectionStatusNoConnection:
397 case eConnectionStatusLostConnection:
398 case eConnectionStatusError:
399 disconnected = true;
400 Disconnect();
401 break;
402 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000403 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404 }
405 packet.Clear();
406 if (disconnected)
407 return PacketResult::ErrorDisconnected;
408 if (timed_out)
409 return PacketResult::ErrorReplyTimeout;
410 else
411 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412}
413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414bool GDBRemoteCommunication::DecompressPacket() {
415 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000418 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000419
420 size_t pkt_size = m_bytes.size();
421
Adrian Prantl05097242018-04-30 16:49:04 +0000422 // Smallest possible compressed packet is $N#00 - an uncompressed empty
423 // reply, most commonly indicating an unsupported packet. Anything less than
424 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000425 if (pkt_size < 5)
426 return true;
427
428 if (m_bytes[0] != '$' && m_bytes[0] != '%')
429 return true;
430 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
431 return true;
432
433 size_t hash_mark_idx = m_bytes.find('#');
434 if (hash_mark_idx == std::string::npos)
435 return true;
436 if (hash_mark_idx + 2 >= m_bytes.size())
437 return true;
438
439 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
440 !::isxdigit(m_bytes[hash_mark_idx + 2]))
441 return true;
442
443 size_t content_length =
444 pkt_size -
445 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
446 size_t content_start = 2; // The first character of the
447 // compressed/not-compressed text of the packet
448 size_t checksum_idx =
449 hash_mark_idx +
450 1; // The first character of the two hex checksum characters
451
452 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000453 // multiple packets. size_of_first_packet is the size of the initial packet
454 // which we'll replace with the decompressed version of, leaving the rest of
455 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000456 size_t size_of_first_packet = hash_mark_idx + 3;
457
458 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000459 // the uncompressed payload, then a : and then the compressed data. e.g.
460 // $C1024:<binary>#00 Update content_start and content_length to only include
461 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000462
463 uint64_t decompressed_bufsize = ULONG_MAX;
464 if (m_bytes[1] == 'C') {
465 size_t i = content_start;
466 while (i < hash_mark_idx && isdigit(m_bytes[i]))
467 i++;
468 if (i < hash_mark_idx && m_bytes[i] == ':') {
469 i++;
470 content_start = i;
471 content_length = hash_mark_idx - content_start;
472 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
473 errno = 0;
474 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
475 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
476 m_bytes.erase(0, size_of_first_packet);
477 return false;
478 }
479 }
480 }
481
482 if (GetSendAcks()) {
483 char packet_checksum_cstr[3];
484 packet_checksum_cstr[0] = m_bytes[checksum_idx];
485 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
486 packet_checksum_cstr[2] = '\0';
487 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
488
489 long actual_checksum = CalculcateChecksum(
490 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
491 bool success = packet_checksum == actual_checksum;
492 if (!success) {
493 if (log)
494 log->Printf(
495 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
496 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
497 (uint8_t)actual_checksum);
498 }
499 // Send the ack or nack if needed
500 if (!success) {
501 SendNack();
502 m_bytes.erase(0, size_of_first_packet);
503 return false;
504 } else {
505 SendAck();
506 }
507 }
508
509 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000510 // This packet was not compressed -- delete the 'N' character at the start
511 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000512 m_bytes.erase(1, 1);
513 return true;
514 }
515
Adrian Prantl05097242018-04-30 16:49:04 +0000516 // Reverse the gdb-remote binary escaping that was done to the compressed
517 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000518 std::vector<uint8_t> unescaped_content;
519 unescaped_content.reserve(content_length);
520 size_t i = content_start;
521 while (i < hash_mark_idx) {
522 if (m_bytes[i] == '}') {
523 i++;
524 unescaped_content.push_back(m_bytes[i] ^ 0x20);
525 } else {
526 unescaped_content.push_back(m_bytes[i]);
527 }
528 i++;
529 }
530
531 uint8_t *decompressed_buffer = nullptr;
532 size_t decompressed_bytes = 0;
533
534 if (decompressed_bufsize != ULONG_MAX) {
535 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1);
536 if (decompressed_buffer == nullptr) {
537 m_bytes.erase(0, size_of_first_packet);
538 return false;
539 }
540 }
541
542#if defined(HAVE_LIBCOMPRESSION)
543 // libcompression is weak linked so check that compression_decode_buffer() is
544 // available
Vedant Kumar606908a2017-12-06 19:21:10 +0000545 if (m_compression_type == CompressionType::ZlibDeflate ||
546 m_compression_type == CompressionType::LZFSE ||
547 m_compression_type == CompressionType::LZ4) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000549 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000550 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000551 else if (m_compression_type == CompressionType::ZlibDeflate)
552 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000553 else if (m_compression_type == CompressionType::LZ4)
554 compression_type = COMPRESSION_LZ4_RAW;
555 else if (m_compression_type == CompressionType::LZMA)
556 compression_type = COMPRESSION_LZMA;
557
Adrian Prantl05097242018-04-30 16:49:04 +0000558 // If we have the expected size of the decompressed payload, we can
559 // allocate the right-sized buffer and do it. If we don't have that
560 // information, we'll need to try decoding into a big buffer and if the
561 // buffer wasn't big enough, increase it and try again.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000562
563 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
564 decompressed_bytes = compression_decode_buffer(
565 decompressed_buffer, decompressed_bufsize + 10,
566 (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL,
567 compression_type);
568 }
569 }
570#endif
571
572#if defined(HAVE_LIBZ)
573 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
574 decompressed_buffer != nullptr &&
575 m_compression_type == CompressionType::ZlibDeflate) {
576 z_stream stream;
577 memset(&stream, 0, sizeof(z_stream));
578 stream.next_in = (Bytef *)unescaped_content.data();
579 stream.avail_in = (uInt)unescaped_content.size();
580 stream.total_in = 0;
581 stream.next_out = (Bytef *)decompressed_buffer;
582 stream.avail_out = decompressed_bufsize;
583 stream.total_out = 0;
584 stream.zalloc = Z_NULL;
585 stream.zfree = Z_NULL;
586 stream.opaque = Z_NULL;
587
588 if (inflateInit2(&stream, -15) == Z_OK) {
589 int status = inflate(&stream, Z_NO_FLUSH);
590 inflateEnd(&stream);
591 if (status == Z_STREAM_END) {
592 decompressed_bytes = stream.total_out;
593 }
594 }
595 }
596#endif
597
598 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
599 if (decompressed_buffer)
600 free(decompressed_buffer);
601 m_bytes.erase(0, size_of_first_packet);
602 return false;
603 }
604
605 std::string new_packet;
606 new_packet.reserve(decompressed_bytes + 6);
607 new_packet.push_back(m_bytes[0]);
608 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
609 new_packet.push_back('#');
610 if (GetSendAcks()) {
611 uint8_t decompressed_checksum = CalculcateChecksum(
612 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
613 char decompressed_checksum_str[3];
614 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
615 new_packet.append(decompressed_checksum_str);
616 } else {
617 new_packet.push_back('0');
618 new_packet.push_back('0');
619 }
620
621 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
622 new_packet.size());
623
624 free(decompressed_buffer);
625 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000626}
627
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000628GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000629GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
630 StringExtractorGDBRemote &packet) {
631 // Put the packet data into the buffer in a thread safe fashion
632 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000633
Kate Stoneb9c1b512016-09-06 20:57:50 +0000634 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000635
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 if (src && src_len > 0) {
637 if (log && log->GetVerbose()) {
638 StreamString s;
639 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
640 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
641 }
642 m_bytes.append((const char *)src, src_len);
643 }
644
645 bool isNotifyPacket = false;
646
647 // Parse up the packets into gdb remote packets
648 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000649 // end_idx must be one past the last valid packet byte. Start it off with
650 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 size_t content_start = 0;
652 size_t content_length = 0;
653 size_t total_length = 0;
654 size_t checksum_idx = std::string::npos;
655
656 // Size of packet before it is decompressed, for logging purposes
657 size_t original_packet_size = m_bytes.size();
658 if (CompressionIsEnabled()) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000659 if (!DecompressPacket()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 packet.Clear();
661 return GDBRemoteCommunication::PacketType::Standard;
662 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000663 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000664
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 switch (m_bytes[0]) {
666 case '+': // Look for ack
667 case '-': // Look for cancel
668 case '\x03': // ^C to halt target
669 content_length = total_length = 1; // The command is one byte long...
670 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 case '%': // Async notify packet
673 isNotifyPacket = true;
674 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000675
Kate Stoneb9c1b512016-09-06 20:57:50 +0000676 case '$':
677 // Look for a standard gdb packet?
678 {
679 size_t hash_pos = m_bytes.find('#');
680 if (hash_pos != std::string::npos) {
681 if (hash_pos + 2 < m_bytes.size()) {
682 checksum_idx = hash_pos + 1;
683 // Skip the dollar sign
684 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000685 // Don't include the # in the content or the $ in the content
686 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 content_length = hash_pos - 1;
688
689 total_length =
690 hash_pos + 3; // Skip the # and the two hex checksum bytes
691 } else {
692 // Checksum bytes aren't all here yet
693 content_length = std::string::npos;
694 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000695 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 }
697 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000698
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000700 // We have an unexpected byte and we need to flush all bad data that is
701 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
702 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
703 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 const size_t bytes_len = m_bytes.size();
705 bool done = false;
706 uint32_t idx;
707 for (idx = 1; !done && idx < bytes_len; ++idx) {
708 switch (m_bytes[idx]) {
709 case '+':
710 case '-':
711 case '\x03':
712 case '%':
713 case '$':
714 done = true;
715 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000716
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 default:
718 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000719 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000720 }
721 if (log)
722 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
723 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
724 m_bytes.erase(0, idx - 1);
725 } break;
726 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000727
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 if (content_length == std::string::npos) {
729 packet.Clear();
730 return GDBRemoteCommunication::PacketType::Invalid;
731 } else if (total_length > 0) {
732
733 // We have a valid packet...
734 assert(content_length <= m_bytes.size());
735 assert(total_length <= m_bytes.size());
736 assert(content_length <= total_length);
737 size_t content_end = content_start + content_length;
738
739 bool success = true;
740 std::string &packet_str = packet.GetStringRef();
741 if (log) {
742 // If logging was just enabled and we have history, then dump out what
743 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000744 // that logs all of the packet will set a boolean so that we don't dump
745 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000746 if (!m_history.DidDumpToLog())
747 m_history.Dump(log);
748
749 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000750 // Only detect binary for packets that start with a '$' and have a
751 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 if (m_bytes[0] == '$' && total_length > 4) {
753 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000754 unsigned char c = m_bytes[i];
755 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 binary = true;
757 }
758 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000759 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 if (binary) {
761 StreamString strm;
762 // Packet header...
763 if (CompressionIsEnabled())
764 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
765 (uint64_t)original_packet_size, (uint64_t)total_length,
766 m_bytes[0]);
767 else
768 strm.Printf("<%4" PRIu64 "> read packet: %c",
769 (uint64_t)total_length, m_bytes[0]);
770 for (size_t i = content_start; i < content_end; ++i) {
771 // Remove binary escaped bytes when displaying the packet...
772 const char ch = m_bytes[i];
773 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000774 // 0x7d is the escape character. The next character is to be
775 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776 const char escapee = m_bytes[++i] ^ 0x20;
777 strm.Printf("%2.2x", escapee);
778 } else {
779 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000780 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 }
782 // Packet footer...
783 strm.Printf("%c%c%c", m_bytes[total_length - 3],
784 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000785 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 } else {
787 if (CompressionIsEnabled())
788 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
789 (uint64_t)original_packet_size, (uint64_t)total_length,
790 (int)(total_length), m_bytes.c_str());
791 else
792 log->Printf("<%4" PRIu64 "> read packet: %.*s",
793 (uint64_t)total_length, (int)(total_length),
794 m_bytes.c_str());
795 }
796 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000797
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000798 m_history.AddPacket(m_bytes, total_length,
799 GDBRemoteCommunicationHistory::ePacketTypeRecv,
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000800 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000801
Kate Stoneb9c1b512016-09-06 20:57:50 +0000802 // Clear packet_str in case there is some existing data in it.
803 packet_str.clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000804 // Copy the packet from m_bytes to packet_str expanding the run-length
805 // encoding in the process. Reserve enough byte for the most common case
806 // (no RLE used)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 packet_str.reserve(m_bytes.length());
808 for (std::string::const_iterator c = m_bytes.begin() + content_start;
809 c != m_bytes.begin() + content_end; ++c) {
810 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000811 // '*' indicates RLE. Next character will give us the repeat count
812 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 char char_to_repeat = packet_str.back();
814 // Number of time the previous character is repeated
815 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000816 // We have the char_to_repeat and repeat_count. Now push it in the
817 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 for (int i = 0; i < repeat_count; ++i)
819 packet_str.push_back(char_to_repeat);
820 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000821 // 0x7d is the escape character. The next character is to be XOR'd
822 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 char escapee = *++c ^ 0x20;
824 packet_str.push_back(escapee);
825 } else {
826 packet_str.push_back(*c);
827 }
828 }
829
830 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
831 assert(checksum_idx < m_bytes.size());
832 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
833 ::isxdigit(m_bytes[checksum_idx + 1])) {
834 if (GetSendAcks()) {
835 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
836 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
Pavel Labath5a841232018-03-28 10:19:10 +0000837 char actual_checksum = CalculcateChecksum(
838 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000839 success = packet_checksum == actual_checksum;
840 if (!success) {
841 if (log)
842 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
843 "got 0x%2.2x",
844 (int)(total_length), m_bytes.c_str(),
845 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000846 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 // Send the ack or nack if needed
848 if (!success)
849 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000850 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 SendAck();
852 }
853 } else {
854 success = false;
855 if (log)
856 log->Printf("error: invalid checksum in packet: '%s'\n",
857 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000858 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000859 }
860
861 m_bytes.erase(0, total_length);
862 packet.SetFilePos(0);
863
864 if (isNotifyPacket)
865 return GDBRemoteCommunication::PacketType::Notify;
866 else
867 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000868 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000869 }
870 packet.Clear();
871 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000872}
873
Zachary Turner97206d52017-05-12 04:51:55 +0000874Status GDBRemoteCommunication::StartListenThread(const char *hostname,
875 uint16_t port) {
876 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 if (m_listen_thread.IsJoinable()) {
878 error.SetErrorString("listen thread already running");
879 } else {
880 char listen_url[512];
881 if (hostname && hostname[0])
882 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
883 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000884 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
886 m_listen_url = listen_url;
887 SetConnection(new ConnectionFileDescriptor());
888 m_listen_thread = ThreadLauncher::LaunchThread(
889 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
890 }
891 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000892}
893
Kate Stoneb9c1b512016-09-06 20:57:50 +0000894bool GDBRemoteCommunication::JoinListenThread() {
895 if (m_listen_thread.IsJoinable())
896 m_listen_thread.Join(nullptr);
897 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000898}
899
900lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000901GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
902 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000903 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 ConnectionFileDescriptor *connection =
905 (ConnectionFileDescriptor *)comm->GetConnection();
906
907 if (connection) {
908 // Do the listen on another thread so we can continue on...
909 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
910 eConnectionStatusSuccess)
911 comm->SetConnection(NULL);
912 }
913 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000914}
915
Zachary Turner97206d52017-05-12 04:51:55 +0000916Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
918 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
919 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
920 if (log)
921 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
922 __FUNCTION__, url ? url : "<empty>",
923 port ? *port : uint16_t(0));
924
Zachary Turner97206d52017-05-12 04:51:55 +0000925 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 // If we locate debugserver, keep that located version around
927 static FileSpec g_debugserver_file_spec;
928
929 char debugserver_path[PATH_MAX];
930 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
931
Adrian Prantl05097242018-04-30 16:49:04 +0000932 // Always check to see if we have an environment override for the path to the
933 // debugserver to use and use it if we do.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
935 if (env_debugserver_path) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000936 debugserver_file_spec.SetFile(env_debugserver_path,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000937 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +0000938 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000939 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
940 "from environment variable: %s",
941 __FUNCTION__, env_debugserver_path);
942 } else
943 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000944 bool debugserver_exists =
945 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000946 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +0000947 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +0000948 debugserver_file_spec = HostInfo::GetSupportExeDir();
949 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000951 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +0000953 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000954 log->Printf(
955 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
956 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +0000957
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958 g_debugserver_file_spec = debugserver_file_spec;
959 } else {
960 debugserver_file_spec =
961 platform->LocateExecutable(DEBUGSERVER_BASENAME);
962 if (debugserver_file_spec) {
963 // Platform::LocateExecutable() wouldn't return a path if it doesn't
964 // exist
965 debugserver_exists = true;
966 } else {
967 if (log)
968 log->Printf("GDBRemoteCommunication::%s() could not find "
969 "gdb-remote stub exe '%s'",
970 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +0000971 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +0000973 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 g_debugserver_file_spec.Clear();
975 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000976 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000978
Kate Stoneb9c1b512016-09-06 20:57:50 +0000979 if (debugserver_exists) {
980 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000981
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 Args &debugserver_args = launch_info.GetArguments();
983 debugserver_args.Clear();
984 char arg_cstr[PATH_MAX];
985
986 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000987 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +0000988
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000989#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000991 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000992#endif
993
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 // If a url is supplied then use it
995 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000996 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +0000997
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 if (pass_comm_fd >= 0) {
999 StreamString fd_arg;
1000 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001001 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 // Send "pass_comm_fd" down to the inferior so it can use it to
1003 // communicate back with this process
1004 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1005 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001006
Kate Stoneb9c1b512016-09-06 20:57:50 +00001007 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001008 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001009
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001011 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001013
Stella Stamenovab3f44ad2018-12-10 17:23:28 +00001014 llvm::SmallString<128> named_pipe_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 // socket_pipe is used by debug server to communicate back either
1016 // TCP port or domain socket name which it listens on.
1017 // The second purpose of the pipe to serve as a synchronization point -
1018 // once data is written to the pipe, debug server is up and running.
1019 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001020
Adrian Prantl05097242018-04-30 16:49:04 +00001021 // port is null when debug server should listen on domain socket - we're
1022 // not interested in port value but rather waiting for debug server to
1023 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001024 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001026// Create a temporary file to get the stdout/stderr and redirect the output of
1027// the command into this file. We will later read this file if all goes well
1028// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001029#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 // Binding to port zero, we need to figure out what port it ends up
1031 // using using a named pipe...
1032 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1033 false, named_pipe_path);
1034 if (error.Fail()) {
1035 if (log)
1036 log->Printf("GDBRemoteCommunication::%s() "
1037 "named pipe creation failed: %s",
1038 __FUNCTION__, error.AsCString());
1039 return error;
1040 }
Sean Callanan1355f472016-09-19 22:06:12 +00001041 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001042 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001043#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 // Binding to port zero, we need to figure out what port it ends up
1045 // using using an unnamed pipe...
1046 error = socket_pipe.CreateNew(true);
1047 if (error.Fail()) {
1048 if (log)
1049 log->Printf("GDBRemoteCommunication::%s() "
1050 "unnamed pipe creation failed: %s",
1051 __FUNCTION__, error.AsCString());
1052 return error;
1053 }
1054 int write_fd = socket_pipe.GetWriteFileDescriptor();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001055 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1056 debugserver_args.AppendArgument(llvm::to_string(write_fd));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001058#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 } else {
1060 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001061 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 error = StartListenThread("127.0.0.1", 0);
1063 if (error.Fail()) {
1064 if (log)
1065 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1066 "thread: %s",
1067 __FUNCTION__, error.AsCString());
1068 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001069 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070
1071 ConnectionFileDescriptor *connection =
1072 (ConnectionFileDescriptor *)GetConnection();
1073 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001074 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 if (port_ > 0) {
1076 char port_cstr[32];
1077 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1078 // Send the host and port down that debugserver and specify an option
1079 // so that it connects back to the port we are listening to in this
1080 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001081 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1082 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 if (port)
1084 *port = port_;
1085 } else {
1086 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1087 if (log)
1088 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1089 error.AsCString());
1090 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001091 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001092 }
1093 }
1094
1095 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1096 if (env_debugserver_log_file) {
1097 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1098 env_debugserver_log_file);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001099 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001100 }
1101
Vince Harron9753dd92015-05-10 15:22:09 +00001102#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 const char *env_debugserver_log_flags =
1104 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1105 if (env_debugserver_log_flags) {
1106 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1107 env_debugserver_log_flags);
Sean Callanan1355f472016-09-19 22:06:12 +00001108 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 }
Vince Harron9753dd92015-05-10 15:22:09 +00001110#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 const char *env_debugserver_log_channels =
1112 getenv("LLDB_SERVER_LOG_CHANNELS");
1113 if (env_debugserver_log_channels) {
1114 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1115 env_debugserver_log_channels);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001116 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117 }
Vince Harron9753dd92015-05-10 15:22:09 +00001118#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001119
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1121 // env var doesn't come back.
1122 uint32_t env_var_index = 1;
1123 bool has_env_var;
1124 do {
1125 char env_var_name[64];
1126 snprintf(env_var_name, sizeof(env_var_name),
1127 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1128 const char *extra_arg = getenv(env_var_name);
1129 has_env_var = extra_arg != nullptr;
Todd Fiala34ba4262014-08-29 17:10:31 +00001130
Kate Stoneb9c1b512016-09-06 20:57:50 +00001131 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001132 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001133 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1135 "to stub command line (%s)",
1136 __FUNCTION__, env_var_name, extra_arg);
1137 }
1138 } while (has_env_var);
1139
1140 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001141 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 debugserver_args.AppendArguments(*inferior_args);
1143 }
1144
1145 // Copy the current environment to the gdbserver/debugserver instance
Pavel Labath62930e52018-01-10 11:57:31 +00001146 launch_info.GetEnvironment() = Host::GetEnvironment();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147
1148 // Close STDIN, STDOUT and STDERR.
1149 launch_info.AppendCloseFileAction(STDIN_FILENO);
1150 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1151 launch_info.AppendCloseFileAction(STDERR_FILENO);
1152
1153 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1154 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1155 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1156 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1157
1158 if (log) {
1159 StreamString string_stream;
1160 Platform *const platform = nullptr;
1161 launch_info.Dump(string_stream, platform);
1162 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001163 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 }
1165 error = Host::LaunchProcess(launch_info);
1166
1167 if (error.Success() &&
1168 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1169 pass_comm_fd == -1) {
1170 if (named_pipe_path.size() > 0) {
1171 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1172 if (error.Fail())
1173 if (log)
1174 log->Printf("GDBRemoteCommunication::%s() "
1175 "failed to open named pipe %s for reading: %s",
1176 __FUNCTION__, named_pipe_path.c_str(),
1177 error.AsCString());
1178 }
1179
1180 if (socket_pipe.CanWrite())
1181 socket_pipe.CloseWriteFileDescriptor();
1182 if (socket_pipe.CanRead()) {
1183 char port_cstr[PATH_MAX] = {0};
1184 port_cstr[0] = '\0';
1185 size_t num_bytes = sizeof(port_cstr);
1186 // Read port from pipe with 10 second timeout.
1187 error = socket_pipe.ReadWithTimeout(
1188 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1189 if (error.Success() && (port != nullptr)) {
1190 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001191 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1192 if (*port == 0 || *port == child_port) {
1193 *port = child_port;
1194 if (log)
1195 log->Printf("GDBRemoteCommunication::%s() "
1196 "debugserver listens %u port",
1197 __FUNCTION__, *port);
1198 } else {
1199 if (log)
1200 log->Printf("GDBRemoteCommunication::%s() "
1201 "debugserver listening on port "
1202 "%d but requested port was %d",
1203 __FUNCTION__, (uint32_t)child_port,
1204 (uint32_t)(*port));
1205 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 } else {
1207 if (log)
1208 log->Printf("GDBRemoteCommunication::%s() "
1209 "failed to read a port value from pipe %s: %s",
1210 __FUNCTION__, named_pipe_path.c_str(),
1211 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001212 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001213 socket_pipe.Close();
1214 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001215
Kate Stoneb9c1b512016-09-06 20:57:50 +00001216 if (named_pipe_path.size() > 0) {
1217 const auto err = socket_pipe.Delete(named_pipe_path);
1218 if (err.Fail()) {
1219 if (log)
1220 log->Printf(
1221 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1222 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001223 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224 }
1225
1226 // Make sure we actually connect with the debugserver...
1227 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001228 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 } else {
1230 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1231 }
Vince Harron8b335672015-05-12 01:10:56 +00001232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 if (error.Fail()) {
1234 if (log)
1235 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1236 error.AsCString());
1237 }
Vince Harron8b335672015-05-12 01:10:56 +00001238
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001240}
1241
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1243
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001244void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1245 m_history.SetStream(strm);
1246};
1247
1248llvm::Error
1249GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1250 GDBRemoteCommunication &server) {
1251 const bool child_processes_inherit = false;
1252 const int backlog = 5;
1253 TCPSocket listen_socket(true, child_processes_inherit);
1254 if (llvm::Error error =
1255 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1256 return error;
1257
1258 Socket *accept_socket;
1259 std::future<Status> accept_status = std::async(
1260 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1261
1262 llvm::SmallString<32> remote_addr;
1263 llvm::raw_svector_ostream(remote_addr)
1264 << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1265
1266 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1267 new ConnectionFileDescriptor());
1268 if (conn_up->Connect(remote_addr, nullptr) != lldb::eConnectionStatusSuccess)
1269 return llvm::make_error<llvm::StringError>("Unable to connect",
1270 llvm::inconvertibleErrorCode());
1271
1272 client.SetConnection(conn_up.release());
1273 if (llvm::Error error = accept_status.get().ToError())
1274 return error;
1275
1276 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1277 return llvm::Error::success();
1278}
1279
Kate Stoneb9c1b512016-09-06 20:57:50 +00001280GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001281 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Greg Clayton84577092017-04-17 16:20:22 +00001282 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1283 auto curr_timeout = gdb_comm.GetPacketTimeout();
1284 // Only update the timeout if the timeout is greater than the current
1285 // timeout. If the current timeout is larger, then just use that.
1286 if (curr_timeout < timeout) {
1287 m_timeout_modified = true;
1288 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1289 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001290}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001291
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001293 // Only restore the timeout if we set it in the constructor.
1294 if (m_timeout_modified)
1295 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001296}
1297
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001299// become available for this connection. This function will consume all
1300// incoming bytes and try to parse whole packets as they become available. Full
1301// packets are placed in a queue, so that all packet requests can simply pop
1302// from this queue. Async notification packets will be dispatched immediately
1303// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1305 size_t len, bool broadcast,
1306 lldb::ConnectionStatus status) {
1307 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001308
Kate Stoneb9c1b512016-09-06 20:57:50 +00001309 while (true) {
1310 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001311
Adrian Prantl05097242018-04-30 16:49:04 +00001312 // scrub the data so we do not pass it back to CheckForPacket on future
1313 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 bytes = nullptr;
1315 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 // we may have received no packet so lets bail out
1318 if (type == PacketType::Invalid)
1319 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001320
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321 if (type == PacketType::Standard) {
1322 // scope for the mutex
1323 {
1324 // lock down the packet queue
1325 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1326 // push a new packet into the queue
1327 m_packet_queue.push(packet);
1328 // Signal condition variable that we have a packet
1329 m_condition_queue_not_empty.notify_one();
1330 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001331 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332
1333 if (type == PacketType::Notify) {
1334 // put this packet into an event
1335 const char *pdata = packet.GetStringRef().c_str();
1336
Adrian Prantl05097242018-04-30 16:49:04 +00001337 // as the communication class, we are a broadcaster and the async thread
1338 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1340 new EventDataBytes(pdata));
1341 }
1342 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001343}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001344
1345void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1346 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1347 StringRef Style) {
1348 using PacketResult = GDBRemoteCommunication::PacketResult;
1349
1350 switch (result) {
1351 case PacketResult::Success:
1352 Stream << "Success";
1353 break;
1354 case PacketResult::ErrorSendFailed:
1355 Stream << "ErrorSendFailed";
1356 break;
1357 case PacketResult::ErrorSendAck:
1358 Stream << "ErrorSendAck";
1359 break;
1360 case PacketResult::ErrorReplyFailed:
1361 Stream << "ErrorReplyFailed";
1362 break;
1363 case PacketResult::ErrorReplyTimeout:
1364 Stream << "ErrorReplyTimeout";
1365 break;
1366 case PacketResult::ErrorReplyInvalid:
1367 Stream << "ErrorReplyInvalid";
1368 break;
1369 case PacketResult::ErrorReplyAck:
1370 Stream << "ErrorReplyAck";
1371 break;
1372 case PacketResult::ErrorDisconnected:
1373 Stream << "ErrorDisconnected";
1374 break;
1375 case PacketResult::ErrorNoSequenceLock:
1376 Stream << "ErrorNoSequenceLock";
1377 break;
1378 }
1379}