blob: 14f0553147974c9969137229ac572d9e661ece50 [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
Adrian Prantl05097242018-04-30 16:49:04 +0000153 // Stop the communications read thread which is used to parse all incoming
154 // packets. This function will block until the read thread returns.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 if (m_read_thread_enabled)
156 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000157}
158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
160 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162 for (char c : payload)
163 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +0000164
Kate Stoneb9c1b512016-09-06 20:57:50 +0000165 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000166}
167
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168size_t GDBRemoteCommunication::SendAck() {
169 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
170 ConnectionStatus status = eConnectionStatusSuccess;
171 char ch = '+';
172 const size_t bytes_written = Write(&ch, 1, status, NULL);
173 if (log)
174 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
175 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
176 return bytes_written;
177}
178
179size_t GDBRemoteCommunication::SendNack() {
180 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
181 ConnectionStatus status = eConnectionStatusSuccess;
182 char ch = '-';
183 const size_t bytes_written = Write(&ch, 1, status, NULL);
184 if (log)
185 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
186 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
187 return bytes_written;
188}
189
190GDBRemoteCommunication::PacketResult
191GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
192 if (IsConnected()) {
193 StreamString packet(0, 4, eByteOrderBig);
194
195 packet.PutChar('$');
196 packet.Write(payload.data(), payload.size());
197 packet.PutChar('#');
198 packet.PutHex8(CalculcateChecksum(payload));
199
200 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000201 ConnectionStatus status = eConnectionStatusSuccess;
Zachary Turnerc1564272016-11-16 21:15:24 +0000202 // TODO: Don't shimmy through a std::string, just use StringRef.
203 std::string packet_str = packet.GetString();
204 const char *packet_data = packet_str.c_str();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205 const size_t packet_length = packet.GetSize();
206 size_t bytes_written = Write(packet_data, packet_length, status, NULL);
207 if (log) {
208 size_t binary_start_offset = 0;
209 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
210 0) {
211 const char *first_comma = strchr(packet_data, ',');
212 if (first_comma) {
213 const char *second_comma = strchr(first_comma + 1, ',');
214 if (second_comma)
215 binary_start_offset = second_comma - packet_data + 1;
Greg Claytonc1422c12012-04-09 22:46:21 +0000216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000217 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000218
Adrian Prantl05097242018-04-30 16:49:04 +0000219 // If logging was just enabled and we have history, then dump out what we
220 // have to the log so we get the historical context. The Dump() call that
Kate Stoneb9c1b512016-09-06 20:57:50 +0000221 // logs all of the packet will set a boolean so that we don't dump this
Adrian Prantl05097242018-04-30 16:49:04 +0000222 // more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223 if (!m_history.DidDumpToLog())
224 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226 if (binary_start_offset) {
227 StreamString strm;
228 // Print non binary data header
229 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
230 (int)binary_start_offset, packet_data);
231 const uint8_t *p;
232 // Print binary data exactly as sent
233 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
234 ++p)
235 strm.Printf("\\x%2.2x", *p);
236 // Print the checksum
237 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000238 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239 } else
240 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
241 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000242 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000243
Kate Stoneb9c1b512016-09-06 20:57:50 +0000244 m_history.AddPacket(packet.GetString(), packet_length,
245 History::ePacketTypeSend, bytes_written);
246
247 if (bytes_written == packet_length) {
248 if (GetSendAcks())
249 return GetAck();
250 else
251 return PacketResult::Success;
252 } else {
253 if (log)
254 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
255 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000256 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 }
258 return PacketResult::ErrorSendFailed;
259}
260
261GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
262 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000263 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000264 if (result == PacketResult::Success) {
265 if (packet.GetResponseType() ==
266 StringExtractorGDBRemote::ResponseType::eAck)
267 return PacketResult::Success;
268 else
269 return PacketResult::ErrorSendAck;
270 }
271 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272}
273
Greg Clayton3dedae12013-12-06 21:45:27 +0000274GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000275GDBRemoteCommunication::ReadPacketWithOutputSupport(
276 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
277 bool sync_on_timeout,
278 llvm::function_ref<void(llvm::StringRef)> output_callback) {
279 auto result = ReadPacket(response, timeout, sync_on_timeout);
280 while (result == PacketResult::Success && response.IsNormalResponse() &&
281 response.PeekChar() == 'O') {
282 response.GetChar();
283 std::string output;
284 if (response.GetHexByteString(output))
285 output_callback(output);
286 result = ReadPacket(response, timeout, sync_on_timeout);
287 }
288 return result;
289}
290
291GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000293 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 bool sync_on_timeout) {
295 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000296 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000298 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000299}
300
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000301// This function is called when a packet is requested.
302// A whole packet is popped from the packet queue and returned to the caller.
Adrian Prantl05097242018-04-30 16:49:04 +0000303// Packets are placed into this queue from the communication read thread. See
304// GDBRemoteCommunication::AppendBytesToCache.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000305GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000306GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000307 Timeout<std::micro> timeout) {
308 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
309 // lock down the packet queue
310 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000311
Pavel Labath1eff73c2016-11-24 10:54:49 +0000312 if (!timeout)
313 m_condition_queue_not_empty.wait(lock, pred);
314 else {
315 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
316 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000317 if (!IsConnected())
318 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 }
320
Pavel Labath1eff73c2016-11-24 10:54:49 +0000321 // get the front element of the queue
322 response = m_packet_queue.front();
323
324 // remove the front element
325 m_packet_queue.pop();
326
327 // we got a packet
328 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000330
331GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000332GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
333 Timeout<std::micro> timeout,
334 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000336 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337
Pavel Labathe8a7b982017-02-06 19:31:09 +0000338 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000339
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 // Check for a packet from our cache first without trying any reading...
341 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
342 return PacketResult::Success;
343
344 bool timed_out = false;
345 bool disconnected = false;
346 while (IsConnected() && !timed_out) {
347 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000348 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349
Pavel Labathe8a7b982017-02-06 19:31:09 +0000350 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000351 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000352 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000353 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000354 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355
356 if (bytes_read > 0) {
357 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000358 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 } else {
360 switch (status) {
361 case eConnectionStatusTimedOut:
362 case eConnectionStatusInterrupted:
363 if (sync_on_timeout) {
364 //------------------------------------------------------------------
365 /// Sync the remote GDB server and make sure we get a response that
366 /// corresponds to what we send.
367 ///
368 /// Sends a "qEcho" packet and makes sure it gets the exact packet
369 /// echoed back. If the qEcho packet isn't supported, we send a qC
370 /// packet and make sure we get a valid thread ID back. We use the
371 /// "qC" packet since its response if very unique: is responds with
372 /// "QC%x" where %x is the thread ID of the current thread. This
373 /// makes the response unique enough from other packet responses to
374 /// ensure we are back on track.
375 ///
376 /// This packet is needed after we time out sending a packet so we
377 /// can ensure that we are getting the response for the packet we
378 /// are sending. There are no sequence IDs in the GDB remote
379 /// protocol (there used to be, but they are not supported anymore)
380 /// so if you timeout sending packet "abc", you might then send
381 /// packet "cde" and get the response for the previous "abc" packet.
382 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
383 /// many responses for packets can look like responses for other
384 /// packets. So if we timeout, we need to ensure that we can get
385 /// back on track. If we can't get back on track, we must
386 /// disconnect.
387 //------------------------------------------------------------------
388 bool sync_success = false;
389 bool got_actual_response = false;
390 // We timed out, we need to sync back up with the
391 char echo_packet[32];
392 int echo_packet_len = 0;
393 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395 if (m_supports_qEcho == eLazyBoolYes) {
396 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
397 "qEcho:%u", ++m_echo_number);
398 std::string regex_str = "^";
399 regex_str += echo_packet;
400 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000401 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402 } else {
403 echo_packet_len =
404 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000405 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000406 }
Greg Clayton644247c2011-07-07 01:59:51 +0000407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408 PacketResult echo_packet_result =
409 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
410 if (echo_packet_result == PacketResult::Success) {
411 const uint32_t max_retries = 3;
412 uint32_t successful_responses = 0;
413 for (uint32_t i = 0; i < max_retries; ++i) {
414 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000415 echo_packet_result =
416 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417 if (echo_packet_result == PacketResult::Success) {
418 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000419 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000420 sync_success = true;
421 break;
422 } else if (successful_responses == 1) {
423 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000424 // response, it probably is the response to the packet we
425 // actually wanted, so copy it over if this is the first
426 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000427 packet = echo_response;
428 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000429 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000430 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
431 continue; // Packet timed out, continue waiting for a response
432 else
433 break; // Something else went wrong getting the packet back, we
434 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000435 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000436 }
437
438 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000439 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000440 if (sync_success) {
441 // We timed out, but were able to recover
442 if (got_actual_response) {
443 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000444 // before the successful reply to our qEcho packet, so lets say
445 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000446 return PacketResult::Success;
447 }
448 } else {
449 disconnected = true;
450 Disconnect();
451 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000452 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 timed_out = true;
454 break;
455 case eConnectionStatusSuccess:
456 // printf ("status = success but error = %s\n",
457 // error.AsCString("<invalid>"));
458 break;
459
460 case eConnectionStatusEndOfFile:
461 case eConnectionStatusNoConnection:
462 case eConnectionStatusLostConnection:
463 case eConnectionStatusError:
464 disconnected = true;
465 Disconnect();
466 break;
467 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000469 }
470 packet.Clear();
471 if (disconnected)
472 return PacketResult::ErrorDisconnected;
473 if (timed_out)
474 return PacketResult::ErrorReplyTimeout;
475 else
476 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000477}
478
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479bool GDBRemoteCommunication::DecompressPacket() {
480 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000481
Kate Stoneb9c1b512016-09-06 20:57:50 +0000482 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000483 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000484
485 size_t pkt_size = m_bytes.size();
486
Adrian Prantl05097242018-04-30 16:49:04 +0000487 // Smallest possible compressed packet is $N#00 - an uncompressed empty
488 // reply, most commonly indicating an unsupported packet. Anything less than
489 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000490 if (pkt_size < 5)
491 return true;
492
493 if (m_bytes[0] != '$' && m_bytes[0] != '%')
494 return true;
495 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
496 return true;
497
498 size_t hash_mark_idx = m_bytes.find('#');
499 if (hash_mark_idx == std::string::npos)
500 return true;
501 if (hash_mark_idx + 2 >= m_bytes.size())
502 return true;
503
504 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
505 !::isxdigit(m_bytes[hash_mark_idx + 2]))
506 return true;
507
508 size_t content_length =
509 pkt_size -
510 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
511 size_t content_start = 2; // The first character of the
512 // compressed/not-compressed text of the packet
513 size_t checksum_idx =
514 hash_mark_idx +
515 1; // The first character of the two hex checksum characters
516
517 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000518 // multiple packets. size_of_first_packet is the size of the initial packet
519 // which we'll replace with the decompressed version of, leaving the rest of
520 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000521 size_t size_of_first_packet = hash_mark_idx + 3;
522
523 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000524 // the uncompressed payload, then a : and then the compressed data. e.g.
525 // $C1024:<binary>#00 Update content_start and content_length to only include
526 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000527
528 uint64_t decompressed_bufsize = ULONG_MAX;
529 if (m_bytes[1] == 'C') {
530 size_t i = content_start;
531 while (i < hash_mark_idx && isdigit(m_bytes[i]))
532 i++;
533 if (i < hash_mark_idx && m_bytes[i] == ':') {
534 i++;
535 content_start = i;
536 content_length = hash_mark_idx - content_start;
537 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
538 errno = 0;
539 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
540 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
541 m_bytes.erase(0, size_of_first_packet);
542 return false;
543 }
544 }
545 }
546
547 if (GetSendAcks()) {
548 char packet_checksum_cstr[3];
549 packet_checksum_cstr[0] = m_bytes[checksum_idx];
550 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
551 packet_checksum_cstr[2] = '\0';
552 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
553
554 long actual_checksum = CalculcateChecksum(
555 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
556 bool success = packet_checksum == actual_checksum;
557 if (!success) {
558 if (log)
559 log->Printf(
560 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
561 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
562 (uint8_t)actual_checksum);
563 }
564 // Send the ack or nack if needed
565 if (!success) {
566 SendNack();
567 m_bytes.erase(0, size_of_first_packet);
568 return false;
569 } else {
570 SendAck();
571 }
572 }
573
574 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000575 // This packet was not compressed -- delete the 'N' character at the start
576 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577 m_bytes.erase(1, 1);
578 return true;
579 }
580
Adrian Prantl05097242018-04-30 16:49:04 +0000581 // Reverse the gdb-remote binary escaping that was done to the compressed
582 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 std::vector<uint8_t> unescaped_content;
584 unescaped_content.reserve(content_length);
585 size_t i = content_start;
586 while (i < hash_mark_idx) {
587 if (m_bytes[i] == '}') {
588 i++;
589 unescaped_content.push_back(m_bytes[i] ^ 0x20);
590 } else {
591 unescaped_content.push_back(m_bytes[i]);
592 }
593 i++;
594 }
595
596 uint8_t *decompressed_buffer = nullptr;
597 size_t decompressed_bytes = 0;
598
599 if (decompressed_bufsize != ULONG_MAX) {
600 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1);
601 if (decompressed_buffer == nullptr) {
602 m_bytes.erase(0, size_of_first_packet);
603 return false;
604 }
605 }
606
607#if defined(HAVE_LIBCOMPRESSION)
608 // libcompression is weak linked so check that compression_decode_buffer() is
609 // available
Vedant Kumar606908a2017-12-06 19:21:10 +0000610 if (m_compression_type == CompressionType::ZlibDeflate ||
611 m_compression_type == CompressionType::LZFSE ||
612 m_compression_type == CompressionType::LZ4) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000613 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000614 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000616 else if (m_compression_type == CompressionType::ZlibDeflate)
617 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 else if (m_compression_type == CompressionType::LZ4)
619 compression_type = COMPRESSION_LZ4_RAW;
620 else if (m_compression_type == CompressionType::LZMA)
621 compression_type = COMPRESSION_LZMA;
622
Adrian Prantl05097242018-04-30 16:49:04 +0000623 // If we have the expected size of the decompressed payload, we can
624 // allocate the right-sized buffer and do it. If we don't have that
625 // information, we'll need to try decoding into a big buffer and if the
626 // buffer wasn't big enough, increase it and try again.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627
628 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
629 decompressed_bytes = compression_decode_buffer(
630 decompressed_buffer, decompressed_bufsize + 10,
631 (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL,
632 compression_type);
633 }
634 }
635#endif
636
637#if defined(HAVE_LIBZ)
638 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
639 decompressed_buffer != nullptr &&
640 m_compression_type == CompressionType::ZlibDeflate) {
641 z_stream stream;
642 memset(&stream, 0, sizeof(z_stream));
643 stream.next_in = (Bytef *)unescaped_content.data();
644 stream.avail_in = (uInt)unescaped_content.size();
645 stream.total_in = 0;
646 stream.next_out = (Bytef *)decompressed_buffer;
647 stream.avail_out = decompressed_bufsize;
648 stream.total_out = 0;
649 stream.zalloc = Z_NULL;
650 stream.zfree = Z_NULL;
651 stream.opaque = Z_NULL;
652
653 if (inflateInit2(&stream, -15) == Z_OK) {
654 int status = inflate(&stream, Z_NO_FLUSH);
655 inflateEnd(&stream);
656 if (status == Z_STREAM_END) {
657 decompressed_bytes = stream.total_out;
658 }
659 }
660 }
661#endif
662
663 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
664 if (decompressed_buffer)
665 free(decompressed_buffer);
666 m_bytes.erase(0, size_of_first_packet);
667 return false;
668 }
669
670 std::string new_packet;
671 new_packet.reserve(decompressed_bytes + 6);
672 new_packet.push_back(m_bytes[0]);
673 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
674 new_packet.push_back('#');
675 if (GetSendAcks()) {
676 uint8_t decompressed_checksum = CalculcateChecksum(
677 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
678 char decompressed_checksum_str[3];
679 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
680 new_packet.append(decompressed_checksum_str);
681 } else {
682 new_packet.push_back('0');
683 new_packet.push_back('0');
684 }
685
686 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
687 new_packet.size());
688
689 free(decompressed_buffer);
690 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000691}
692
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000693GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000694GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
695 StringExtractorGDBRemote &packet) {
696 // Put the packet data into the buffer in a thread safe fashion
697 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000698
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000700
Kate Stoneb9c1b512016-09-06 20:57:50 +0000701 if (src && src_len > 0) {
702 if (log && log->GetVerbose()) {
703 StreamString s;
704 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
705 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
706 }
707 m_bytes.append((const char *)src, src_len);
708 }
709
710 bool isNotifyPacket = false;
711
712 // Parse up the packets into gdb remote packets
713 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000714 // end_idx must be one past the last valid packet byte. Start it off with
715 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 size_t content_start = 0;
717 size_t content_length = 0;
718 size_t total_length = 0;
719 size_t checksum_idx = std::string::npos;
720
721 // Size of packet before it is decompressed, for logging purposes
722 size_t original_packet_size = m_bytes.size();
723 if (CompressionIsEnabled()) {
724 if (DecompressPacket() == false) {
725 packet.Clear();
726 return GDBRemoteCommunication::PacketType::Standard;
727 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000728 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000729
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 switch (m_bytes[0]) {
731 case '+': // Look for ack
732 case '-': // Look for cancel
733 case '\x03': // ^C to halt target
734 content_length = total_length = 1; // The command is one byte long...
735 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000736
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 case '%': // Async notify packet
738 isNotifyPacket = true;
739 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000740
Kate Stoneb9c1b512016-09-06 20:57:50 +0000741 case '$':
742 // Look for a standard gdb packet?
743 {
744 size_t hash_pos = m_bytes.find('#');
745 if (hash_pos != std::string::npos) {
746 if (hash_pos + 2 < m_bytes.size()) {
747 checksum_idx = hash_pos + 1;
748 // Skip the dollar sign
749 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000750 // Don't include the # in the content or the $ in the content
751 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000752 content_length = hash_pos - 1;
753
754 total_length =
755 hash_pos + 3; // Skip the # and the two hex checksum bytes
756 } else {
757 // Checksum bytes aren't all here yet
758 content_length = std::string::npos;
759 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000760 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 }
762 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000763
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000765 // We have an unexpected byte and we need to flush all bad data that is
766 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
767 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
768 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000769 const size_t bytes_len = m_bytes.size();
770 bool done = false;
771 uint32_t idx;
772 for (idx = 1; !done && idx < bytes_len; ++idx) {
773 switch (m_bytes[idx]) {
774 case '+':
775 case '-':
776 case '\x03':
777 case '%':
778 case '$':
779 done = true;
780 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000781
Kate Stoneb9c1b512016-09-06 20:57:50 +0000782 default:
783 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000785 }
786 if (log)
787 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
788 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
789 m_bytes.erase(0, idx - 1);
790 } break;
791 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793 if (content_length == std::string::npos) {
794 packet.Clear();
795 return GDBRemoteCommunication::PacketType::Invalid;
796 } else if (total_length > 0) {
797
798 // We have a valid packet...
799 assert(content_length <= m_bytes.size());
800 assert(total_length <= m_bytes.size());
801 assert(content_length <= total_length);
802 size_t content_end = content_start + content_length;
803
804 bool success = true;
805 std::string &packet_str = packet.GetStringRef();
806 if (log) {
807 // If logging was just enabled and we have history, then dump out what
808 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000809 // that logs all of the packet will set a boolean so that we don't dump
810 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 if (!m_history.DidDumpToLog())
812 m_history.Dump(log);
813
814 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000815 // Only detect binary for packets that start with a '$' and have a
816 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 if (m_bytes[0] == '$' && total_length > 4) {
818 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000819 unsigned char c = m_bytes[i];
820 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 binary = true;
822 }
823 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000824 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000825 if (binary) {
826 StreamString strm;
827 // Packet header...
828 if (CompressionIsEnabled())
829 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
830 (uint64_t)original_packet_size, (uint64_t)total_length,
831 m_bytes[0]);
832 else
833 strm.Printf("<%4" PRIu64 "> read packet: %c",
834 (uint64_t)total_length, m_bytes[0]);
835 for (size_t i = content_start; i < content_end; ++i) {
836 // Remove binary escaped bytes when displaying the packet...
837 const char ch = m_bytes[i];
838 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000839 // 0x7d is the escape character. The next character is to be
840 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000841 const char escapee = m_bytes[++i] ^ 0x20;
842 strm.Printf("%2.2x", escapee);
843 } else {
844 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000845 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000846 }
847 // Packet footer...
848 strm.Printf("%c%c%c", m_bytes[total_length - 3],
849 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000850 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000851 } else {
852 if (CompressionIsEnabled())
853 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
854 (uint64_t)original_packet_size, (uint64_t)total_length,
855 (int)(total_length), m_bytes.c_str());
856 else
857 log->Printf("<%4" PRIu64 "> read packet: %.*s",
858 (uint64_t)total_length, (int)(total_length),
859 m_bytes.c_str());
860 }
861 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000862
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000863 m_history.AddPacket(m_bytes, total_length, History::ePacketTypeRecv,
864 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000865
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 // Clear packet_str in case there is some existing data in it.
867 packet_str.clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000868 // Copy the packet from m_bytes to packet_str expanding the run-length
869 // encoding in the process. Reserve enough byte for the most common case
870 // (no RLE used)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000871 packet_str.reserve(m_bytes.length());
872 for (std::string::const_iterator c = m_bytes.begin() + content_start;
873 c != m_bytes.begin() + content_end; ++c) {
874 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000875 // '*' indicates RLE. Next character will give us the repeat count
876 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 char char_to_repeat = packet_str.back();
878 // Number of time the previous character is repeated
879 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000880 // We have the char_to_repeat and repeat_count. Now push it in the
881 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 for (int i = 0; i < repeat_count; ++i)
883 packet_str.push_back(char_to_repeat);
884 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000885 // 0x7d is the escape character. The next character is to be XOR'd
886 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000887 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);
Pavel Labath5a841232018-03-28 10:19:10 +0000901 char actual_checksum = CalculcateChecksum(
902 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 success = packet_checksum == actual_checksum;
904 if (!success) {
905 if (log)
906 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
907 "got 0x%2.2x",
908 (int)(total_length), m_bytes.c_str(),
909 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000910 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000911 // Send the ack or nack if needed
912 if (!success)
913 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000914 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915 SendAck();
916 }
917 } else {
918 success = false;
919 if (log)
920 log->Printf("error: invalid checksum in packet: '%s'\n",
921 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000922 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923 }
924
925 m_bytes.erase(0, total_length);
926 packet.SetFilePos(0);
927
928 if (isNotifyPacket)
929 return GDBRemoteCommunication::PacketType::Notify;
930 else
931 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000932 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 }
934 packet.Clear();
935 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000936}
937
Zachary Turner97206d52017-05-12 04:51:55 +0000938Status GDBRemoteCommunication::StartListenThread(const char *hostname,
939 uint16_t port) {
940 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 if (m_listen_thread.IsJoinable()) {
942 error.SetErrorString("listen thread already running");
943 } else {
944 char listen_url[512];
945 if (hostname && hostname[0])
946 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
947 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000948 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000949 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
950 m_listen_url = listen_url;
951 SetConnection(new ConnectionFileDescriptor());
952 m_listen_thread = ThreadLauncher::LaunchThread(
953 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
954 }
955 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000956}
957
Kate Stoneb9c1b512016-09-06 20:57:50 +0000958bool GDBRemoteCommunication::JoinListenThread() {
959 if (m_listen_thread.IsJoinable())
960 m_listen_thread.Join(nullptr);
961 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000962}
963
964lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000965GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
966 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000967 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 ConnectionFileDescriptor *connection =
969 (ConnectionFileDescriptor *)comm->GetConnection();
970
971 if (connection) {
972 // Do the listen on another thread so we can continue on...
973 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
974 eConnectionStatusSuccess)
975 comm->SetConnection(NULL);
976 }
977 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000978}
979
Zachary Turner97206d52017-05-12 04:51:55 +0000980Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
982 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
983 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
984 if (log)
985 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
986 __FUNCTION__, url ? url : "<empty>",
987 port ? *port : uint16_t(0));
988
Zachary Turner97206d52017-05-12 04:51:55 +0000989 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 // If we locate debugserver, keep that located version around
991 static FileSpec g_debugserver_file_spec;
992
993 char debugserver_path[PATH_MAX];
994 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
995
Adrian Prantl05097242018-04-30 16:49:04 +0000996 // Always check to see if we have an environment override for the path to the
997 // debugserver to use and use it if we do.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
999 if (env_debugserver_path) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00001000 debugserver_file_spec.SetFile(env_debugserver_path, false,
1001 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +00001002 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
1004 "from environment variable: %s",
1005 __FUNCTION__, env_debugserver_path);
1006 } else
1007 debugserver_file_spec = g_debugserver_file_spec;
1008 bool debugserver_exists = debugserver_file_spec.Exists();
1009 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +00001010 // The debugserver binary is in the LLDB.framework/Resources directory.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir,
1012 debugserver_file_spec)) {
1013 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
1014 debugserver_exists = debugserver_file_spec.Exists();
1015 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +00001016 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 log->Printf(
1018 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
1019 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +00001020
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 g_debugserver_file_spec = debugserver_file_spec;
1022 } else {
1023 debugserver_file_spec =
1024 platform->LocateExecutable(DEBUGSERVER_BASENAME);
1025 if (debugserver_file_spec) {
1026 // Platform::LocateExecutable() wouldn't return a path if it doesn't
1027 // exist
1028 debugserver_exists = true;
1029 } else {
1030 if (log)
1031 log->Printf("GDBRemoteCommunication::%s() could not find "
1032 "gdb-remote stub exe '%s'",
1033 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +00001034 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +00001036 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 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
Adrian Prantl05097242018-04-30 16:49:04 +00001084 // port is null when debug server should listen on domain socket - we're
1085 // not interested in port value but rather waiting for debug server to
1086 // 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) {
Adrian Prantl05097242018-04-30 16:49:04 +00001089// Create a temporary file to get the stdout/stderr and redirect the output of
1090// the command into this file. We will later read this file if all goes well
1091// 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
Adrian Prantl05097242018-04-30 16:49:04 +00001124 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 error = StartListenThread("127.0.0.1", 0);
1126 if (error.Fail()) {
1127 if (log)
1128 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1129 "thread: %s",
1130 __FUNCTION__, error.AsCString());
1131 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001132 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001133
1134 ConnectionFileDescriptor *connection =
1135 (ConnectionFileDescriptor *)GetConnection();
1136 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001137 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 if (port_ > 0) {
1139 char port_cstr[32];
1140 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1141 // Send the host and port down that debugserver and specify an option
1142 // so that it connects back to the port we are listening to in this
1143 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001144 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1145 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 if (port)
1147 *port = port_;
1148 } else {
1149 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1150 if (log)
1151 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1152 error.AsCString());
1153 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001154 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 }
1156 }
1157
1158 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1159 if (env_debugserver_log_file) {
1160 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1161 env_debugserver_log_file);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001162 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001163 }
1164
Vince Harron9753dd92015-05-10 15:22:09 +00001165#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001166 const char *env_debugserver_log_flags =
1167 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1168 if (env_debugserver_log_flags) {
1169 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1170 env_debugserver_log_flags);
Sean Callanan1355f472016-09-19 22:06:12 +00001171 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001172 }
Vince Harron9753dd92015-05-10 15:22:09 +00001173#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 const char *env_debugserver_log_channels =
1175 getenv("LLDB_SERVER_LOG_CHANNELS");
1176 if (env_debugserver_log_channels) {
1177 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1178 env_debugserver_log_channels);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001179 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001180 }
Vince Harron9753dd92015-05-10 15:22:09 +00001181#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001182
Kate Stoneb9c1b512016-09-06 20:57:50 +00001183 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1184 // env var doesn't come back.
1185 uint32_t env_var_index = 1;
1186 bool has_env_var;
1187 do {
1188 char env_var_name[64];
1189 snprintf(env_var_name, sizeof(env_var_name),
1190 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1191 const char *extra_arg = getenv(env_var_name);
1192 has_env_var = extra_arg != nullptr;
Todd Fiala34ba4262014-08-29 17:10:31 +00001193
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001195 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001196 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001197 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1198 "to stub command line (%s)",
1199 __FUNCTION__, env_var_name, extra_arg);
1200 }
1201 } while (has_env_var);
1202
1203 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001204 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001205 debugserver_args.AppendArguments(*inferior_args);
1206 }
1207
1208 // Copy the current environment to the gdbserver/debugserver instance
Pavel Labath62930e52018-01-10 11:57:31 +00001209 launch_info.GetEnvironment() = Host::GetEnvironment();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210
1211 // Close STDIN, STDOUT and STDERR.
1212 launch_info.AppendCloseFileAction(STDIN_FILENO);
1213 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1214 launch_info.AppendCloseFileAction(STDERR_FILENO);
1215
1216 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1217 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1218 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1219 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1220
1221 if (log) {
1222 StreamString string_stream;
1223 Platform *const platform = nullptr;
1224 launch_info.Dump(string_stream, platform);
1225 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001226 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 }
1228 error = Host::LaunchProcess(launch_info);
1229
1230 if (error.Success() &&
1231 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1232 pass_comm_fd == -1) {
1233 if (named_pipe_path.size() > 0) {
1234 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1235 if (error.Fail())
1236 if (log)
1237 log->Printf("GDBRemoteCommunication::%s() "
1238 "failed to open named pipe %s for reading: %s",
1239 __FUNCTION__, named_pipe_path.c_str(),
1240 error.AsCString());
1241 }
1242
1243 if (socket_pipe.CanWrite())
1244 socket_pipe.CloseWriteFileDescriptor();
1245 if (socket_pipe.CanRead()) {
1246 char port_cstr[PATH_MAX] = {0};
1247 port_cstr[0] = '\0';
1248 size_t num_bytes = sizeof(port_cstr);
1249 // Read port from pipe with 10 second timeout.
1250 error = socket_pipe.ReadWithTimeout(
1251 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1252 if (error.Success() && (port != nullptr)) {
1253 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001254 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1255 if (*port == 0 || *port == child_port) {
1256 *port = child_port;
1257 if (log)
1258 log->Printf("GDBRemoteCommunication::%s() "
1259 "debugserver listens %u port",
1260 __FUNCTION__, *port);
1261 } else {
1262 if (log)
1263 log->Printf("GDBRemoteCommunication::%s() "
1264 "debugserver listening on port "
1265 "%d but requested port was %d",
1266 __FUNCTION__, (uint32_t)child_port,
1267 (uint32_t)(*port));
1268 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001269 } else {
1270 if (log)
1271 log->Printf("GDBRemoteCommunication::%s() "
1272 "failed to read a port value from pipe %s: %s",
1273 __FUNCTION__, named_pipe_path.c_str(),
1274 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001275 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001276 socket_pipe.Close();
1277 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001278
Kate Stoneb9c1b512016-09-06 20:57:50 +00001279 if (named_pipe_path.size() > 0) {
1280 const auto err = socket_pipe.Delete(named_pipe_path);
1281 if (err.Fail()) {
1282 if (log)
1283 log->Printf(
1284 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1285 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001286 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001287 }
1288
1289 // Make sure we actually connect with the debugserver...
1290 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001291 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001292 } else {
1293 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1294 }
Vince Harron8b335672015-05-12 01:10:56 +00001295
Kate Stoneb9c1b512016-09-06 20:57:50 +00001296 if (error.Fail()) {
1297 if (log)
1298 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1299 error.AsCString());
1300 }
Vince Harron8b335672015-05-12 01:10:56 +00001301
Kate Stoneb9c1b512016-09-06 20:57:50 +00001302 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001303}
1304
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1306
1307GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001308 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Greg Clayton84577092017-04-17 16:20:22 +00001309 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1310 auto curr_timeout = gdb_comm.GetPacketTimeout();
1311 // Only update the timeout if the timeout is greater than the current
1312 // timeout. If the current timeout is larger, then just use that.
1313 if (curr_timeout < timeout) {
1314 m_timeout_modified = true;
1315 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1316 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001317}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001318
Kate Stoneb9c1b512016-09-06 20:57:50 +00001319GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001320 // Only restore the timeout if we set it in the constructor.
1321 if (m_timeout_modified)
1322 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001323}
1324
Kate Stoneb9c1b512016-09-06 20:57:50 +00001325// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001326// become available for this connection. This function will consume all
1327// incoming bytes and try to parse whole packets as they become available. Full
1328// packets are placed in a queue, so that all packet requests can simply pop
1329// from this queue. Async notification packets will be dispatched immediately
1330// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1332 size_t len, bool broadcast,
1333 lldb::ConnectionStatus status) {
1334 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001335
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 while (true) {
1337 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001338
Adrian Prantl05097242018-04-30 16:49:04 +00001339 // scrub the data so we do not pass it back to CheckForPacket on future
1340 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001341 bytes = nullptr;
1342 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001343
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344 // we may have received no packet so lets bail out
1345 if (type == PacketType::Invalid)
1346 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001347
Kate Stoneb9c1b512016-09-06 20:57:50 +00001348 if (type == PacketType::Standard) {
1349 // scope for the mutex
1350 {
1351 // lock down the packet queue
1352 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1353 // push a new packet into the queue
1354 m_packet_queue.push(packet);
1355 // Signal condition variable that we have a packet
1356 m_condition_queue_not_empty.notify_one();
1357 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001358 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001359
1360 if (type == PacketType::Notify) {
1361 // put this packet into an event
1362 const char *pdata = packet.GetStringRef().c_str();
1363
Adrian Prantl05097242018-04-30 16:49:04 +00001364 // as the communication class, we are a broadcaster and the async thread
1365 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001366 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1367 new EventDataBytes(pdata));
1368 }
1369 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001370}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001371
1372void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1373 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1374 StringRef Style) {
1375 using PacketResult = GDBRemoteCommunication::PacketResult;
1376
1377 switch (result) {
1378 case PacketResult::Success:
1379 Stream << "Success";
1380 break;
1381 case PacketResult::ErrorSendFailed:
1382 Stream << "ErrorSendFailed";
1383 break;
1384 case PacketResult::ErrorSendAck:
1385 Stream << "ErrorSendAck";
1386 break;
1387 case PacketResult::ErrorReplyFailed:
1388 Stream << "ErrorReplyFailed";
1389 break;
1390 case PacketResult::ErrorReplyTimeout:
1391 Stream << "ErrorReplyTimeout";
1392 break;
1393 case PacketResult::ErrorReplyInvalid:
1394 Stream << "ErrorReplyInvalid";
1395 break;
1396 case PacketResult::ErrorReplyAck:
1397 Stream << "ErrorReplyAck";
1398 break;
1399 case PacketResult::ErrorDisconnected:
1400 Stream << "ErrorDisconnected";
1401 break;
1402 case PacketResult::ErrorNoSequenceLock:
1403 Stream << "ErrorNoSequenceLock";
1404 break;
1405 }
1406}