blob: c3f0d5dc2ee40fb1207d7a6e804c17779285e97a [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
12// C Includes
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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017// C++ Includes
18// Other libraries and framework includes
Greg Claytonc1422c12012-04-09 22:46:21 +000019#include "lldb/Core/StreamFile.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000020#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000021#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000022#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000023#include "lldb/Host/Pipe.h"
Zachary Turner98688922014-08-06 18:16:26 +000024#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000025#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000026#include "lldb/Host/ThreadLauncher.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
36// Project includes
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
Kate Stoneb9c1b512016-09-06 20:57:50 +000057GDBRemoteCommunication::History::History(uint32_t size)
58 : m_packets(), m_curr_idx(0), m_total_packet_count(0),
59 m_dumped_to_log(false) {
60 m_packets.resize(size);
Greg Claytonc1422c12012-04-09 22:46:21 +000061}
62
Kate Stoneb9c1b512016-09-06 20:57:50 +000063GDBRemoteCommunication::History::~History() {}
64
65void GDBRemoteCommunication::History::AddPacket(char packet_char,
66 PacketType type,
67 uint32_t bytes_transmitted) {
68 const size_t size = m_packets.size();
69 if (size > 0) {
70 const uint32_t idx = GetNextIndex();
71 m_packets[idx].packet.assign(1, packet_char);
72 m_packets[idx].type = type;
73 m_packets[idx].bytes_transmitted = bytes_transmitted;
74 m_packets[idx].packet_idx = m_total_packet_count;
Zachary Turnered96be92017-03-04 01:31:06 +000075 m_packets[idx].tid = llvm::get_threadid();
Kate Stoneb9c1b512016-09-06 20:57:50 +000076 }
Greg Claytonc1422c12012-04-09 22:46:21 +000077}
78
Kate Stoneb9c1b512016-09-06 20:57:50 +000079void GDBRemoteCommunication::History::AddPacket(const std::string &src,
80 uint32_t src_len,
81 PacketType type,
82 uint32_t bytes_transmitted) {
83 const size_t size = m_packets.size();
84 if (size > 0) {
85 const uint32_t idx = GetNextIndex();
86 m_packets[idx].packet.assign(src, 0, src_len);
87 m_packets[idx].type = type;
88 m_packets[idx].bytes_transmitted = bytes_transmitted;
89 m_packets[idx].packet_idx = m_total_packet_count;
Zachary Turnered96be92017-03-04 01:31:06 +000090 m_packets[idx].tid = llvm::get_threadid();
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 }
Greg Claytond451c1a2012-04-13 21:24:18 +000092}
93
Kate Stoneb9c1b512016-09-06 20:57:50 +000094void GDBRemoteCommunication::History::Dump(Stream &strm) const {
95 const uint32_t size = GetNumPacketsInHistory();
96 const uint32_t first_idx = GetFirstSavedPacketIndex();
97 const uint32_t stop_idx = m_curr_idx + size;
98 for (uint32_t i = first_idx; i < stop_idx; ++i) {
99 const uint32_t idx = NormalizeIndex(i);
100 const Entry &entry = m_packets[idx];
101 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
102 break;
103 strm.Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
104 entry.packet_idx, entry.tid, entry.bytes_transmitted,
105 (entry.type == ePacketTypeSend) ? "send" : "read",
106 entry.packet.c_str());
107 }
Greg Claytond451c1a2012-04-13 21:24:18 +0000108}
109
Kate Stoneb9c1b512016-09-06 20:57:50 +0000110void GDBRemoteCommunication::History::Dump(Log *log) const {
111 if (log && !m_dumped_to_log) {
112 m_dumped_to_log = true;
113 const uint32_t size = GetNumPacketsInHistory();
114 const uint32_t first_idx = GetFirstSavedPacketIndex();
Greg Claytonc1422c12012-04-09 22:46:21 +0000115 const uint32_t stop_idx = m_curr_idx + size;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 for (uint32_t i = first_idx; i < stop_idx; ++i) {
117 const uint32_t idx = NormalizeIndex(i);
118 const Entry &entry = m_packets[idx];
119 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
120 break;
121 log->Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
122 entry.packet_idx, entry.tid, entry.bytes_transmitted,
123 (entry.type == ePacketTypeSend) ? "send" : "read",
124 entry.packet.c_str());
Greg Claytonc1422c12012-04-09 22:46:21 +0000125 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000127}
128
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000129//----------------------------------------------------------------------
130// GDBRemoteCommunication constructor
131//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000132GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
133 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000134 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000135#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000136 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000137#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000138 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000139#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000140 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
141 m_send_acks(true), m_compression_type(CompressionType::None),
142 m_listen_url() {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000143}
144
145//----------------------------------------------------------------------
146// Destructor
147//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148GDBRemoteCommunication::~GDBRemoteCommunication() {
149 if (IsConnected()) {
150 Disconnect();
151 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 // Stop the communications read thread which is used to parse all
154 // incoming packets. This function will block until the read
155 // thread returns.
156 if (m_read_thread_enabled)
157 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000158}
159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
161 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000162
Kate Stoneb9c1b512016-09-06 20:57:50 +0000163 for (char c : payload)
164 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +0000165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000167}
168
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169size_t GDBRemoteCommunication::SendAck() {
170 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
171 ConnectionStatus status = eConnectionStatusSuccess;
172 char ch = '+';
173 const size_t bytes_written = Write(&ch, 1, status, NULL);
174 if (log)
175 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
176 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
177 return bytes_written;
178}
179
180size_t GDBRemoteCommunication::SendNack() {
181 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
182 ConnectionStatus status = eConnectionStatusSuccess;
183 char ch = '-';
184 const size_t bytes_written = Write(&ch, 1, status, NULL);
185 if (log)
186 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
187 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
188 return bytes_written;
189}
190
191GDBRemoteCommunication::PacketResult
192GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
193 if (IsConnected()) {
194 StreamString packet(0, 4, eByteOrderBig);
195
196 packet.PutChar('$');
197 packet.Write(payload.data(), payload.size());
198 packet.PutChar('#');
199 packet.PutHex8(CalculcateChecksum(payload));
200
201 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000202 ConnectionStatus status = eConnectionStatusSuccess;
Zachary Turnerc1564272016-11-16 21:15:24 +0000203 // TODO: Don't shimmy through a std::string, just use StringRef.
204 std::string packet_str = packet.GetString();
205 const char *packet_data = packet_str.c_str();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206 const size_t packet_length = packet.GetSize();
207 size_t bytes_written = Write(packet_data, packet_length, status, NULL);
208 if (log) {
209 size_t binary_start_offset = 0;
210 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
211 0) {
212 const char *first_comma = strchr(packet_data, ',');
213 if (first_comma) {
214 const char *second_comma = strchr(first_comma + 1, ',');
215 if (second_comma)
216 binary_start_offset = second_comma - packet_data + 1;
Greg Claytonc1422c12012-04-09 22:46:21 +0000217 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000218 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220 // If logging was just enabled and we have history, then dump out what
221 // we have to the log so we get the historical context. The Dump() call
222 // that
223 // logs all of the packet will set a boolean so that we don't dump this
224 // more
225 // than once
226 if (!m_history.DidDumpToLog())
227 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000228
Kate Stoneb9c1b512016-09-06 20:57:50 +0000229 if (binary_start_offset) {
230 StreamString strm;
231 // Print non binary data header
232 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
233 (int)binary_start_offset, packet_data);
234 const uint8_t *p;
235 // Print binary data exactly as sent
236 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
237 ++p)
238 strm.Printf("\\x%2.2x", *p);
239 // Print the checksum
240 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000241 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242 } else
243 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
244 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000245 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000246
Kate Stoneb9c1b512016-09-06 20:57:50 +0000247 m_history.AddPacket(packet.GetString(), packet_length,
248 History::ePacketTypeSend, bytes_written);
249
250 if (bytes_written == packet_length) {
251 if (GetSendAcks())
252 return GetAck();
253 else
254 return PacketResult::Success;
255 } else {
256 if (log)
257 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
258 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000259 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000260 }
261 return PacketResult::ErrorSendFailed;
262}
263
264GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
265 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000266 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000267 if (result == PacketResult::Success) {
268 if (packet.GetResponseType() ==
269 StringExtractorGDBRemote::ResponseType::eAck)
270 return PacketResult::Success;
271 else
272 return PacketResult::ErrorSendAck;
273 }
274 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275}
276
Greg Clayton3dedae12013-12-06 21:45:27 +0000277GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000279 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000280 bool sync_on_timeout) {
281 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000282 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000283 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000284 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000285}
286
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000287// This function is called when a packet is requested.
288// A whole packet is popped from the packet queue and returned to the caller.
289// Packets are placed into this queue from the communication read thread.
290// See GDBRemoteCommunication::AppendBytesToCache.
291GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000293 Timeout<std::micro> timeout) {
294 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
295 // lock down the packet queue
296 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000297
Pavel Labath1eff73c2016-11-24 10:54:49 +0000298 if (!timeout)
299 m_condition_queue_not_empty.wait(lock, pred);
300 else {
301 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
302 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000303 if (!IsConnected())
304 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000305 }
306
Pavel Labath1eff73c2016-11-24 10:54:49 +0000307 // get the front element of the queue
308 response = m_packet_queue.front();
309
310 // remove the front element
311 m_packet_queue.pop();
312
313 // we got a packet
314 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000316
317GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000318GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
319 Timeout<std::micro> timeout,
320 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000321 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000322 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323
Pavel Labathe8a7b982017-02-06 19:31:09 +0000324 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 // Check for a packet from our cache first without trying any reading...
327 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
328 return PacketResult::Success;
329
330 bool timed_out = false;
331 bool disconnected = false;
332 while (IsConnected() && !timed_out) {
333 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000334 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335
Pavel Labathe8a7b982017-02-06 19:31:09 +0000336 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000337 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000338 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000339 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000340 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341
342 if (bytes_read > 0) {
343 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000344 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345 } else {
346 switch (status) {
347 case eConnectionStatusTimedOut:
348 case eConnectionStatusInterrupted:
349 if (sync_on_timeout) {
350 //------------------------------------------------------------------
351 /// Sync the remote GDB server and make sure we get a response that
352 /// corresponds to what we send.
353 ///
354 /// Sends a "qEcho" packet and makes sure it gets the exact packet
355 /// echoed back. If the qEcho packet isn't supported, we send a qC
356 /// packet and make sure we get a valid thread ID back. We use the
357 /// "qC" packet since its response if very unique: is responds with
358 /// "QC%x" where %x is the thread ID of the current thread. This
359 /// makes the response unique enough from other packet responses to
360 /// ensure we are back on track.
361 ///
362 /// This packet is needed after we time out sending a packet so we
363 /// can ensure that we are getting the response for the packet we
364 /// are sending. There are no sequence IDs in the GDB remote
365 /// protocol (there used to be, but they are not supported anymore)
366 /// so if you timeout sending packet "abc", you might then send
367 /// packet "cde" and get the response for the previous "abc" packet.
368 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
369 /// many responses for packets can look like responses for other
370 /// packets. So if we timeout, we need to ensure that we can get
371 /// back on track. If we can't get back on track, we must
372 /// disconnect.
373 //------------------------------------------------------------------
374 bool sync_success = false;
375 bool got_actual_response = false;
376 // We timed out, we need to sync back up with the
377 char echo_packet[32];
378 int echo_packet_len = 0;
379 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380
Kate Stoneb9c1b512016-09-06 20:57:50 +0000381 if (m_supports_qEcho == eLazyBoolYes) {
382 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
383 "qEcho:%u", ++m_echo_number);
384 std::string regex_str = "^";
385 regex_str += echo_packet;
386 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000387 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000388 } else {
389 echo_packet_len =
390 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000391 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000392 }
Greg Clayton644247c2011-07-07 01:59:51 +0000393
Kate Stoneb9c1b512016-09-06 20:57:50 +0000394 PacketResult echo_packet_result =
395 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
396 if (echo_packet_result == PacketResult::Success) {
397 const uint32_t max_retries = 3;
398 uint32_t successful_responses = 0;
399 for (uint32_t i = 0; i < max_retries; ++i) {
400 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000401 echo_packet_result =
402 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 if (echo_packet_result == PacketResult::Success) {
404 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000405 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 sync_success = true;
407 break;
408 } else if (successful_responses == 1) {
409 // We got something else back as the first successful
410 // response, it probably is
411 // the response to the packet we actually wanted, so copy it
412 // over if this
413 // is the first success and continue to try to get the qEcho
414 // response
415 packet = echo_response;
416 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000417 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
419 continue; // Packet timed out, continue waiting for a response
420 else
421 break; // Something else went wrong getting the packet back, we
422 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000423 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 }
425
426 // We weren't able to sync back up with the server, we must abort
427 // otherwise
428 // all responses might not be from the right packets...
429 if (sync_success) {
430 // We timed out, but were able to recover
431 if (got_actual_response) {
432 // We initially timed out, but we did get a response that came in
433 // before the successful
434 // reply to our qEcho packet, so lets say everything is fine...
435 return PacketResult::Success;
436 }
437 } else {
438 disconnected = true;
439 Disconnect();
440 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000441 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 timed_out = true;
443 break;
444 case eConnectionStatusSuccess:
445 // printf ("status = success but error = %s\n",
446 // error.AsCString("<invalid>"));
447 break;
448
449 case eConnectionStatusEndOfFile:
450 case eConnectionStatusNoConnection:
451 case eConnectionStatusLostConnection:
452 case eConnectionStatusError:
453 disconnected = true;
454 Disconnect();
455 break;
456 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000457 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000458 }
459 packet.Clear();
460 if (disconnected)
461 return PacketResult::ErrorDisconnected;
462 if (timed_out)
463 return PacketResult::ErrorReplyTimeout;
464 else
465 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000466}
467
Kate Stoneb9c1b512016-09-06 20:57:50 +0000468bool GDBRemoteCommunication::DecompressPacket() {
469 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000470
Kate Stoneb9c1b512016-09-06 20:57:50 +0000471 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000472 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000473
474 size_t pkt_size = m_bytes.size();
475
476 // Smallest possible compressed packet is $N#00 - an uncompressed empty reply,
477 // most commonly indicating
478 // an unsupported packet. Anything less than 5 characters, it's definitely
479 // not a compressed packet.
480 if (pkt_size < 5)
481 return true;
482
483 if (m_bytes[0] != '$' && m_bytes[0] != '%')
484 return true;
485 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
486 return true;
487
488 size_t hash_mark_idx = m_bytes.find('#');
489 if (hash_mark_idx == std::string::npos)
490 return true;
491 if (hash_mark_idx + 2 >= m_bytes.size())
492 return true;
493
494 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
495 !::isxdigit(m_bytes[hash_mark_idx + 2]))
496 return true;
497
498 size_t content_length =
499 pkt_size -
500 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
501 size_t content_start = 2; // The first character of the
502 // compressed/not-compressed text of the packet
503 size_t checksum_idx =
504 hash_mark_idx +
505 1; // The first character of the two hex checksum characters
506
507 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
508 // multiple packets.
509 // size_of_first_packet is the size of the initial packet which we'll replace
510 // with the decompressed
511 // version of, leaving the rest of m_bytes unmodified.
512 size_t size_of_first_packet = hash_mark_idx + 3;
513
514 // Compressed packets ("$C") start with a base10 number which is the size of
515 // the uncompressed payload,
516 // then a : and then the compressed data. e.g. $C1024:<binary>#00
517 // Update content_start and content_length to only include the <binary> part
518 // of the packet.
519
520 uint64_t decompressed_bufsize = ULONG_MAX;
521 if (m_bytes[1] == 'C') {
522 size_t i = content_start;
523 while (i < hash_mark_idx && isdigit(m_bytes[i]))
524 i++;
525 if (i < hash_mark_idx && m_bytes[i] == ':') {
526 i++;
527 content_start = i;
528 content_length = hash_mark_idx - content_start;
529 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
530 errno = 0;
531 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
532 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
533 m_bytes.erase(0, size_of_first_packet);
534 return false;
535 }
536 }
537 }
538
539 if (GetSendAcks()) {
540 char packet_checksum_cstr[3];
541 packet_checksum_cstr[0] = m_bytes[checksum_idx];
542 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
543 packet_checksum_cstr[2] = '\0';
544 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
545
546 long actual_checksum = CalculcateChecksum(
547 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
548 bool success = packet_checksum == actual_checksum;
549 if (!success) {
550 if (log)
551 log->Printf(
552 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
553 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
554 (uint8_t)actual_checksum);
555 }
556 // Send the ack or nack if needed
557 if (!success) {
558 SendNack();
559 m_bytes.erase(0, size_of_first_packet);
560 return false;
561 } else {
562 SendAck();
563 }
564 }
565
566 if (m_bytes[1] == 'N') {
567 // This packet was not compressed -- delete the 'N' character at the
568 // start and the packet may be processed as-is.
569 m_bytes.erase(1, 1);
570 return true;
571 }
572
573 // Reverse the gdb-remote binary escaping that was done to the compressed text
574 // to
575 // guard characters like '$', '#', '}', etc.
576 std::vector<uint8_t> unescaped_content;
577 unescaped_content.reserve(content_length);
578 size_t i = content_start;
579 while (i < hash_mark_idx) {
580 if (m_bytes[i] == '}') {
581 i++;
582 unescaped_content.push_back(m_bytes[i] ^ 0x20);
583 } else {
584 unescaped_content.push_back(m_bytes[i]);
585 }
586 i++;
587 }
588
589 uint8_t *decompressed_buffer = nullptr;
590 size_t decompressed_bytes = 0;
591
592 if (decompressed_bufsize != ULONG_MAX) {
593 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1);
594 if (decompressed_buffer == nullptr) {
595 m_bytes.erase(0, size_of_first_packet);
596 return false;
597 }
598 }
599
600#if defined(HAVE_LIBCOMPRESSION)
601 // libcompression is weak linked so check that compression_decode_buffer() is
602 // available
603 if (compression_decode_buffer != NULL &&
604 (m_compression_type == CompressionType::ZlibDeflate ||
605 m_compression_type == CompressionType::LZFSE ||
606 m_compression_type == CompressionType::LZ4)) {
607 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000608 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000610 else if (m_compression_type == CompressionType::ZlibDeflate)
611 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000612 else if (m_compression_type == CompressionType::LZ4)
613 compression_type = COMPRESSION_LZ4_RAW;
614 else if (m_compression_type == CompressionType::LZMA)
615 compression_type = COMPRESSION_LZMA;
616
617 // If we have the expected size of the decompressed payload, we can allocate
618 // the right-sized buffer and do it. If we don't have that information,
619 // we'll
620 // need to try decoding into a big buffer and if the buffer wasn't big
621 // enough,
622 // increase it and try again.
623
624 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
625 decompressed_bytes = compression_decode_buffer(
626 decompressed_buffer, decompressed_bufsize + 10,
627 (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL,
628 compression_type);
629 }
630 }
631#endif
632
633#if defined(HAVE_LIBZ)
634 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
635 decompressed_buffer != nullptr &&
636 m_compression_type == CompressionType::ZlibDeflate) {
637 z_stream stream;
638 memset(&stream, 0, sizeof(z_stream));
639 stream.next_in = (Bytef *)unescaped_content.data();
640 stream.avail_in = (uInt)unescaped_content.size();
641 stream.total_in = 0;
642 stream.next_out = (Bytef *)decompressed_buffer;
643 stream.avail_out = decompressed_bufsize;
644 stream.total_out = 0;
645 stream.zalloc = Z_NULL;
646 stream.zfree = Z_NULL;
647 stream.opaque = Z_NULL;
648
649 if (inflateInit2(&stream, -15) == Z_OK) {
650 int status = inflate(&stream, Z_NO_FLUSH);
651 inflateEnd(&stream);
652 if (status == Z_STREAM_END) {
653 decompressed_bytes = stream.total_out;
654 }
655 }
656 }
657#endif
658
659 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
660 if (decompressed_buffer)
661 free(decompressed_buffer);
662 m_bytes.erase(0, size_of_first_packet);
663 return false;
664 }
665
666 std::string new_packet;
667 new_packet.reserve(decompressed_bytes + 6);
668 new_packet.push_back(m_bytes[0]);
669 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
670 new_packet.push_back('#');
671 if (GetSendAcks()) {
672 uint8_t decompressed_checksum = CalculcateChecksum(
673 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
674 char decompressed_checksum_str[3];
675 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
676 new_packet.append(decompressed_checksum_str);
677 } else {
678 new_packet.push_back('0');
679 new_packet.push_back('0');
680 }
681
682 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
683 new_packet.size());
684
685 free(decompressed_buffer);
686 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000687}
688
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000689GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000690GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
691 StringExtractorGDBRemote &packet) {
692 // Put the packet data into the buffer in a thread safe fashion
693 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000696
Kate Stoneb9c1b512016-09-06 20:57:50 +0000697 if (src && src_len > 0) {
698 if (log && log->GetVerbose()) {
699 StreamString s;
700 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
701 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
702 }
703 m_bytes.append((const char *)src, src_len);
704 }
705
706 bool isNotifyPacket = false;
707
708 // Parse up the packets into gdb remote packets
709 if (!m_bytes.empty()) {
710 // end_idx must be one past the last valid packet byte. Start
711 // it off with an invalid value that is the same as the current
712 // index.
713 size_t content_start = 0;
714 size_t content_length = 0;
715 size_t total_length = 0;
716 size_t checksum_idx = std::string::npos;
717
718 // Size of packet before it is decompressed, for logging purposes
719 size_t original_packet_size = m_bytes.size();
720 if (CompressionIsEnabled()) {
721 if (DecompressPacket() == false) {
722 packet.Clear();
723 return GDBRemoteCommunication::PacketType::Standard;
724 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000725 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000726
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 switch (m_bytes[0]) {
728 case '+': // Look for ack
729 case '-': // Look for cancel
730 case '\x03': // ^C to halt target
731 content_length = total_length = 1; // The command is one byte long...
732 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000733
Kate Stoneb9c1b512016-09-06 20:57:50 +0000734 case '%': // Async notify packet
735 isNotifyPacket = true;
736 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000737
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 case '$':
739 // Look for a standard gdb packet?
740 {
741 size_t hash_pos = m_bytes.find('#');
742 if (hash_pos != std::string::npos) {
743 if (hash_pos + 2 < m_bytes.size()) {
744 checksum_idx = hash_pos + 1;
745 // Skip the dollar sign
746 content_start = 1;
747 // Don't include the # in the content or the $ in the content length
748 content_length = hash_pos - 1;
749
750 total_length =
751 hash_pos + 3; // Skip the # and the two hex checksum bytes
752 } else {
753 // Checksum bytes aren't all here yet
754 content_length = std::string::npos;
755 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000756 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000757 }
758 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000759
Kate Stoneb9c1b512016-09-06 20:57:50 +0000760 default: {
761 // We have an unexpected byte and we need to flush all bad
762 // data that is in m_bytes, so we need to find the first
763 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
764 // or '$' character (start of packet header) or of course,
765 // the end of the data in m_bytes...
766 const size_t bytes_len = m_bytes.size();
767 bool done = false;
768 uint32_t idx;
769 for (idx = 1; !done && idx < bytes_len; ++idx) {
770 switch (m_bytes[idx]) {
771 case '+':
772 case '-':
773 case '\x03':
774 case '%':
775 case '$':
776 done = true;
777 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779 default:
780 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782 }
783 if (log)
784 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
785 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
786 m_bytes.erase(0, idx - 1);
787 } break;
788 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000789
Kate Stoneb9c1b512016-09-06 20:57:50 +0000790 if (content_length == std::string::npos) {
791 packet.Clear();
792 return GDBRemoteCommunication::PacketType::Invalid;
793 } else if (total_length > 0) {
794
795 // We have a valid packet...
796 assert(content_length <= m_bytes.size());
797 assert(total_length <= m_bytes.size());
798 assert(content_length <= total_length);
799 size_t content_end = content_start + content_length;
800
801 bool success = true;
802 std::string &packet_str = packet.GetStringRef();
803 if (log) {
804 // If logging was just enabled and we have history, then dump out what
805 // we have to the log so we get the historical context. The Dump() call
806 // that
807 // logs all of the packet will set a boolean so that we don't dump this
808 // more
809 // than once
810 if (!m_history.DidDumpToLog())
811 m_history.Dump(log);
812
813 bool binary = false;
814 // Only detect binary for packets that start with a '$' and have a '#CC'
815 // checksum
816 if (m_bytes[0] == '$' && total_length > 4) {
817 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000818 unsigned char c = m_bytes[i];
819 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000820 binary = true;
821 }
822 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000823 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 if (binary) {
825 StreamString strm;
826 // Packet header...
827 if (CompressionIsEnabled())
828 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
829 (uint64_t)original_packet_size, (uint64_t)total_length,
830 m_bytes[0]);
831 else
832 strm.Printf("<%4" PRIu64 "> read packet: %c",
833 (uint64_t)total_length, m_bytes[0]);
834 for (size_t i = content_start; i < content_end; ++i) {
835 // Remove binary escaped bytes when displaying the packet...
836 const char ch = m_bytes[i];
837 if (ch == 0x7d) {
838 // 0x7d is the escape character. The next character is to
839 // be XOR'd with 0x20.
840 const char escapee = m_bytes[++i] ^ 0x20;
841 strm.Printf("%2.2x", escapee);
842 } else {
843 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000844 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 }
846 // Packet footer...
847 strm.Printf("%c%c%c", m_bytes[total_length - 3],
848 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000849 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000850 } else {
851 if (CompressionIsEnabled())
852 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
853 (uint64_t)original_packet_size, (uint64_t)total_length,
854 (int)(total_length), m_bytes.c_str());
855 else
856 log->Printf("<%4" PRIu64 "> read packet: %.*s",
857 (uint64_t)total_length, (int)(total_length),
858 m_bytes.c_str());
859 }
860 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000861
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000862 m_history.AddPacket(m_bytes, total_length, History::ePacketTypeRecv,
863 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000864
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 // Clear packet_str in case there is some existing data in it.
866 packet_str.clear();
867 // Copy the packet from m_bytes to packet_str expanding the
868 // run-length encoding in the process.
869 // Reserve enough byte for the most common case (no RLE used)
870 packet_str.reserve(m_bytes.length());
871 for (std::string::const_iterator c = m_bytes.begin() + content_start;
872 c != m_bytes.begin() + content_end; ++c) {
873 if (*c == '*') {
874 // '*' indicates RLE. Next character will give us the
875 // repeat count and previous character is what is to be
876 // repeated.
877 char char_to_repeat = packet_str.back();
878 // Number of time the previous character is repeated
879 int repeat_count = *++c + 3 - ' ';
880 // We have the char_to_repeat and repeat_count. Now push
881 // it in the packet.
882 for (int i = 0; i < repeat_count; ++i)
883 packet_str.push_back(char_to_repeat);
884 } else if (*c == 0x7d) {
885 // 0x7d is the escape character. The next character is to
886 // be XOR'd with 0x20.
887 char escapee = *++c ^ 0x20;
888 packet_str.push_back(escapee);
889 } else {
890 packet_str.push_back(*c);
891 }
892 }
893
894 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
895 assert(checksum_idx < m_bytes.size());
896 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
897 ::isxdigit(m_bytes[checksum_idx + 1])) {
898 if (GetSendAcks()) {
899 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
900 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
901 char actual_checksum = CalculcateChecksum(packet_str);
902 success = packet_checksum == actual_checksum;
903 if (!success) {
904 if (log)
905 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
906 "got 0x%2.2x",
907 (int)(total_length), m_bytes.c_str(),
908 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000909 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910 // Send the ack or nack if needed
911 if (!success)
912 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000913 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000914 SendAck();
915 }
916 } else {
917 success = false;
918 if (log)
919 log->Printf("error: invalid checksum in packet: '%s'\n",
920 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000921 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000922 }
923
924 m_bytes.erase(0, total_length);
925 packet.SetFilePos(0);
926
927 if (isNotifyPacket)
928 return GDBRemoteCommunication::PacketType::Notify;
929 else
930 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 }
933 packet.Clear();
934 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000935}
936
Zachary Turner97206d52017-05-12 04:51:55 +0000937Status GDBRemoteCommunication::StartListenThread(const char *hostname,
938 uint16_t port) {
939 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000940 if (m_listen_thread.IsJoinable()) {
941 error.SetErrorString("listen thread already running");
942 } else {
943 char listen_url[512];
944 if (hostname && hostname[0])
945 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
946 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000947 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
949 m_listen_url = listen_url;
950 SetConnection(new ConnectionFileDescriptor());
951 m_listen_thread = ThreadLauncher::LaunchThread(
952 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
953 }
954 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000955}
956
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957bool GDBRemoteCommunication::JoinListenThread() {
958 if (m_listen_thread.IsJoinable())
959 m_listen_thread.Join(nullptr);
960 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000961}
962
963lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
965 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000966 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967 ConnectionFileDescriptor *connection =
968 (ConnectionFileDescriptor *)comm->GetConnection();
969
970 if (connection) {
971 // Do the listen on another thread so we can continue on...
972 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
973 eConnectionStatusSuccess)
974 comm->SetConnection(NULL);
975 }
976 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000977}
978
Zachary Turner97206d52017-05-12 04:51:55 +0000979Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000980 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
981 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
982 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
983 if (log)
984 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
985 __FUNCTION__, url ? url : "<empty>",
986 port ? *port : uint16_t(0));
987
Zachary Turner97206d52017-05-12 04:51:55 +0000988 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 // If we locate debugserver, keep that located version around
990 static FileSpec g_debugserver_file_spec;
991
992 char debugserver_path[PATH_MAX];
993 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
994
995 // Always check to see if we have an environment override for the path
996 // to the debugserver to use and use it if we do.
997 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
998 if (env_debugserver_path) {
999 debugserver_file_spec.SetFile(env_debugserver_path, false);
Todd Fiala015d8182014-07-22 23:41:36 +00001000 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
1002 "from environment variable: %s",
1003 __FUNCTION__, env_debugserver_path);
1004 } else
1005 debugserver_file_spec = g_debugserver_file_spec;
1006 bool debugserver_exists = debugserver_file_spec.Exists();
1007 if (!debugserver_exists) {
1008 // The debugserver binary is in the LLDB.framework/Resources
1009 // directory.
1010 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir,
1011 debugserver_file_spec)) {
1012 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
1013 debugserver_exists = debugserver_file_spec.Exists();
1014 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +00001015 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001016 log->Printf(
1017 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
1018 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +00001019
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 g_debugserver_file_spec = debugserver_file_spec;
1021 } else {
1022 debugserver_file_spec =
1023 platform->LocateExecutable(DEBUGSERVER_BASENAME);
1024 if (debugserver_file_spec) {
1025 // Platform::LocateExecutable() wouldn't return a path if it doesn't
1026 // exist
1027 debugserver_exists = true;
1028 } else {
1029 if (log)
1030 log->Printf("GDBRemoteCommunication::%s() could not find "
1031 "gdb-remote stub exe '%s'",
1032 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +00001033 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 // Don't cache the platform specific GDB server binary as it could
1035 // change
1036 // from platform to platform
1037 g_debugserver_file_spec.Clear();
1038 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001039 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001041
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 if (debugserver_exists) {
1043 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001044
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 Args &debugserver_args = launch_info.GetArguments();
1046 debugserver_args.Clear();
1047 char arg_cstr[PATH_MAX];
1048
1049 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001050 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001051
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001052#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001053 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001054 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001055#endif
1056
Kate Stoneb9c1b512016-09-06 20:57:50 +00001057 // If a url is supplied then use it
1058 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001059 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001060
Kate Stoneb9c1b512016-09-06 20:57:50 +00001061 if (pass_comm_fd >= 0) {
1062 StreamString fd_arg;
1063 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001064 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 // Send "pass_comm_fd" down to the inferior so it can use it to
1066 // communicate back with this process
1067 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1068 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001069
Kate Stoneb9c1b512016-09-06 20:57:50 +00001070 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001071 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001072
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001074 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 llvm::SmallString<PATH_MAX> named_pipe_path;
1078 // socket_pipe is used by debug server to communicate back either
1079 // TCP port or domain socket name which it listens on.
1080 // The second purpose of the pipe to serve as a synchronization point -
1081 // once data is written to the pipe, debug server is up and running.
1082 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001083
Kate Stoneb9c1b512016-09-06 20:57:50 +00001084 // port is null when debug server should listen on domain socket -
1085 // we're not interested in port value but rather waiting for debug server
1086 // to become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001087 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001088 if (url) {
1089// Create a temporary file to get the stdout/stderr and redirect the
1090// output of the command into this file. We will later read this file
1091// if all goes well and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001092#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 // Binding to port zero, we need to figure out what port it ends up
1094 // using using a named pipe...
1095 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1096 false, named_pipe_path);
1097 if (error.Fail()) {
1098 if (log)
1099 log->Printf("GDBRemoteCommunication::%s() "
1100 "named pipe creation failed: %s",
1101 __FUNCTION__, error.AsCString());
1102 return error;
1103 }
Sean Callanan1355f472016-09-19 22:06:12 +00001104 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001105 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001106#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001107 // Binding to port zero, we need to figure out what port it ends up
1108 // using using an unnamed pipe...
1109 error = socket_pipe.CreateNew(true);
1110 if (error.Fail()) {
1111 if (log)
1112 log->Printf("GDBRemoteCommunication::%s() "
1113 "unnamed pipe creation failed: %s",
1114 __FUNCTION__, error.AsCString());
1115 return error;
1116 }
1117 int write_fd = socket_pipe.GetWriteFileDescriptor();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001118 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1119 debugserver_args.AppendArgument(llvm::to_string(write_fd));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001120 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001121#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 } else {
1123 // No host and port given, so lets listen on our end and make the
1124 // debugserver
1125 // connect to us..
1126 error = StartListenThread("127.0.0.1", 0);
1127 if (error.Fail()) {
1128 if (log)
1129 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1130 "thread: %s",
1131 __FUNCTION__, error.AsCString());
1132 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001133 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134
1135 ConnectionFileDescriptor *connection =
1136 (ConnectionFileDescriptor *)GetConnection();
1137 // Wait for 10 seconds to resolve the bound port
1138 uint16_t port_ = connection->GetListeningPort(10);
1139 if (port_ > 0) {
1140 char port_cstr[32];
1141 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1142 // Send the host and port down that debugserver and specify an option
1143 // so that it connects back to the port we are listening to in this
1144 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001145 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1146 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001147 if (port)
1148 *port = port_;
1149 } else {
1150 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1151 if (log)
1152 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1153 error.AsCString());
1154 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001155 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001156 }
1157 }
1158
1159 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1160 if (env_debugserver_log_file) {
1161 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1162 env_debugserver_log_file);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001163 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164 }
1165
Vince Harron9753dd92015-05-10 15:22:09 +00001166#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167 const char *env_debugserver_log_flags =
1168 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1169 if (env_debugserver_log_flags) {
1170 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1171 env_debugserver_log_flags);
Sean Callanan1355f472016-09-19 22:06:12 +00001172 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 }
Vince Harron9753dd92015-05-10 15:22:09 +00001174#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001175 const char *env_debugserver_log_channels =
1176 getenv("LLDB_SERVER_LOG_CHANNELS");
1177 if (env_debugserver_log_channels) {
1178 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1179 env_debugserver_log_channels);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001180 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 }
Vince Harron9753dd92015-05-10 15:22:09 +00001182#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001183
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1185 // env var doesn't come back.
1186 uint32_t env_var_index = 1;
1187 bool has_env_var;
1188 do {
1189 char env_var_name[64];
1190 snprintf(env_var_name, sizeof(env_var_name),
1191 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1192 const char *extra_arg = getenv(env_var_name);
1193 has_env_var = extra_arg != nullptr;
Todd Fiala34ba4262014-08-29 17:10:31 +00001194
Kate Stoneb9c1b512016-09-06 20:57:50 +00001195 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001196 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001197 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1199 "to stub command line (%s)",
1200 __FUNCTION__, env_var_name, extra_arg);
1201 }
1202 } while (has_env_var);
1203
1204 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001205 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001206 debugserver_args.AppendArguments(*inferior_args);
1207 }
1208
1209 // Copy the current environment to the gdbserver/debugserver instance
1210 StringList env;
1211 if (Host::GetEnvironment(env)) {
1212 for (size_t i = 0; i < env.GetSize(); ++i)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001213 launch_info.GetEnvironmentEntries().AppendArgument(env[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001214 }
1215
1216 // Close STDIN, STDOUT and STDERR.
1217 launch_info.AppendCloseFileAction(STDIN_FILENO);
1218 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1219 launch_info.AppendCloseFileAction(STDERR_FILENO);
1220
1221 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1222 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1223 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1224 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1225
1226 if (log) {
1227 StreamString string_stream;
1228 Platform *const platform = nullptr;
1229 launch_info.Dump(string_stream, platform);
1230 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001231 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232 }
1233 error = Host::LaunchProcess(launch_info);
1234
1235 if (error.Success() &&
1236 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1237 pass_comm_fd == -1) {
1238 if (named_pipe_path.size() > 0) {
1239 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1240 if (error.Fail())
1241 if (log)
1242 log->Printf("GDBRemoteCommunication::%s() "
1243 "failed to open named pipe %s for reading: %s",
1244 __FUNCTION__, named_pipe_path.c_str(),
1245 error.AsCString());
1246 }
1247
1248 if (socket_pipe.CanWrite())
1249 socket_pipe.CloseWriteFileDescriptor();
1250 if (socket_pipe.CanRead()) {
1251 char port_cstr[PATH_MAX] = {0};
1252 port_cstr[0] = '\0';
1253 size_t num_bytes = sizeof(port_cstr);
1254 // Read port from pipe with 10 second timeout.
1255 error = socket_pipe.ReadWithTimeout(
1256 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1257 if (error.Success() && (port != nullptr)) {
1258 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001259 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1260 if (*port == 0 || *port == child_port) {
1261 *port = child_port;
1262 if (log)
1263 log->Printf("GDBRemoteCommunication::%s() "
1264 "debugserver listens %u port",
1265 __FUNCTION__, *port);
1266 } else {
1267 if (log)
1268 log->Printf("GDBRemoteCommunication::%s() "
1269 "debugserver listening on port "
1270 "%d but requested port was %d",
1271 __FUNCTION__, (uint32_t)child_port,
1272 (uint32_t)(*port));
1273 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001274 } else {
1275 if (log)
1276 log->Printf("GDBRemoteCommunication::%s() "
1277 "failed to read a port value from pipe %s: %s",
1278 __FUNCTION__, named_pipe_path.c_str(),
1279 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001280 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 socket_pipe.Close();
1282 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001283
Kate Stoneb9c1b512016-09-06 20:57:50 +00001284 if (named_pipe_path.size() > 0) {
1285 const auto err = socket_pipe.Delete(named_pipe_path);
1286 if (err.Fail()) {
1287 if (log)
1288 log->Printf(
1289 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1290 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001291 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292 }
1293
1294 // Make sure we actually connect with the debugserver...
1295 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001296 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 } else {
1298 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1299 }
Vince Harron8b335672015-05-12 01:10:56 +00001300
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 if (error.Fail()) {
1302 if (log)
1303 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1304 error.AsCString());
1305 }
Vince Harron8b335672015-05-12 01:10:56 +00001306
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001308}
1309
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1311
1312GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001313 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Greg Clayton84577092017-04-17 16:20:22 +00001314 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1315 auto curr_timeout = gdb_comm.GetPacketTimeout();
1316 // Only update the timeout if the timeout is greater than the current
1317 // timeout. If the current timeout is larger, then just use that.
1318 if (curr_timeout < timeout) {
1319 m_timeout_modified = true;
1320 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1321 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001322}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001323
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001325 // Only restore the timeout if we set it in the constructor.
1326 if (m_timeout_modified)
1327 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001328}
1329
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330// This function is called via the Communications class read thread when bytes
1331// become available
1332// for this connection. This function will consume all incoming bytes and try to
1333// parse whole
1334// packets as they become available. Full packets are placed in a queue, so that
1335// all packet
1336// requests can simply pop from this queue. Async notification packets will be
1337// dispatched
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001338// immediately to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1340 size_t len, bool broadcast,
1341 lldb::ConnectionStatus status) {
1342 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 while (true) {
1345 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001346
Kate Stoneb9c1b512016-09-06 20:57:50 +00001347 // scrub the data so we do not pass it back to CheckForPacket
1348 // on future passes of the loop
1349 bytes = nullptr;
1350 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001351
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352 // we may have received no packet so lets bail out
1353 if (type == PacketType::Invalid)
1354 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001355
Kate Stoneb9c1b512016-09-06 20:57:50 +00001356 if (type == PacketType::Standard) {
1357 // scope for the mutex
1358 {
1359 // lock down the packet queue
1360 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1361 // push a new packet into the queue
1362 m_packet_queue.push(packet);
1363 // Signal condition variable that we have a packet
1364 m_condition_queue_not_empty.notify_one();
1365 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001366 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001367
1368 if (type == PacketType::Notify) {
1369 // put this packet into an event
1370 const char *pdata = packet.GetStringRef().c_str();
1371
1372 // as the communication class, we are a broadcaster and the
1373 // async thread is tuned to listen to us
1374 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1375 new EventDataBytes(pdata));
1376 }
1377 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001378}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001379
1380void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1381 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1382 StringRef Style) {
1383 using PacketResult = GDBRemoteCommunication::PacketResult;
1384
1385 switch (result) {
1386 case PacketResult::Success:
1387 Stream << "Success";
1388 break;
1389 case PacketResult::ErrorSendFailed:
1390 Stream << "ErrorSendFailed";
1391 break;
1392 case PacketResult::ErrorSendAck:
1393 Stream << "ErrorSendAck";
1394 break;
1395 case PacketResult::ErrorReplyFailed:
1396 Stream << "ErrorReplyFailed";
1397 break;
1398 case PacketResult::ErrorReplyTimeout:
1399 Stream << "ErrorReplyTimeout";
1400 break;
1401 case PacketResult::ErrorReplyInvalid:
1402 Stream << "ErrorReplyInvalid";
1403 break;
1404 case PacketResult::ErrorReplyAck:
1405 Stream << "ErrorReplyAck";
1406 break;
1407 case PacketResult::ErrorDisconnected:
1408 Stream << "ErrorDisconnected";
1409 break;
1410 case PacketResult::ErrorNoSequenceLock:
1411 Stream << "ErrorNoSequenceLock";
1412 break;
1413 }
1414}