blob: c4f0a673b3af65e8679107e32afc58c5b0f6b4a5 [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"
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +000021#include "lldb/Host/FileSystem.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000022#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000023#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000024#include "lldb/Host/Pipe.h"
Zachary Turner98688922014-08-06 18:16:26 +000025#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000026#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000027#include "lldb/Host/ThreadLauncher.h"
Greg Clayton6988abc2015-10-19 20:44:01 +000028#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000029#include "lldb/Target/Process.h"
Zachary Turner5713a052017-03-22 18:40:07 +000030#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000031#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000032#include "lldb/Utility/RegularExpression.h"
33#include "lldb/Utility/StreamString.h"
Oleksiy Vyalov4536c452015-02-05 16:29:12 +000034#include "llvm/ADT/SmallString.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000035#include "llvm/Support/ScopedPrinter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036
37// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "ProcessGDBRemoteLog.h"
39
Todd Fiala015d8182014-07-22 23:41:36 +000040#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +000041#define DEBUGSERVER_BASENAME "debugserver"
Todd Fiala015d8182014-07-22 23:41:36 +000042#else
Kate Stoneb9c1b512016-09-06 20:57:50 +000043#define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000044#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000045
Kate Stoneb9c1b512016-09-06 20:57:50 +000046#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000047#include <compression.h>
48#endif
49
Kate Stoneb9c1b512016-09-06 20:57:50 +000050#if defined(HAVE_LIBZ)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000051#include <zlib.h>
52#endif
53
Chris Lattner30fdc8d2010-06-08 16:52:24 +000054using namespace lldb;
55using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000056using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057
Kate Stoneb9c1b512016-09-06 20:57:50 +000058GDBRemoteCommunication::History::History(uint32_t size)
59 : m_packets(), m_curr_idx(0), m_total_packet_count(0),
60 m_dumped_to_log(false) {
61 m_packets.resize(size);
Greg Claytonc1422c12012-04-09 22:46:21 +000062}
63
Kate Stoneb9c1b512016-09-06 20:57:50 +000064GDBRemoteCommunication::History::~History() {}
65
66void GDBRemoteCommunication::History::AddPacket(char packet_char,
67 PacketType type,
68 uint32_t bytes_transmitted) {
69 const size_t size = m_packets.size();
70 if (size > 0) {
71 const uint32_t idx = GetNextIndex();
72 m_packets[idx].packet.assign(1, packet_char);
73 m_packets[idx].type = type;
74 m_packets[idx].bytes_transmitted = bytes_transmitted;
75 m_packets[idx].packet_idx = m_total_packet_count;
Zachary Turnered96be92017-03-04 01:31:06 +000076 m_packets[idx].tid = llvm::get_threadid();
Kate Stoneb9c1b512016-09-06 20:57:50 +000077 }
Greg Claytonc1422c12012-04-09 22:46:21 +000078}
79
Kate Stoneb9c1b512016-09-06 20:57:50 +000080void GDBRemoteCommunication::History::AddPacket(const std::string &src,
81 uint32_t src_len,
82 PacketType type,
83 uint32_t bytes_transmitted) {
84 const size_t size = m_packets.size();
85 if (size > 0) {
86 const uint32_t idx = GetNextIndex();
87 m_packets[idx].packet.assign(src, 0, src_len);
88 m_packets[idx].type = type;
89 m_packets[idx].bytes_transmitted = bytes_transmitted;
90 m_packets[idx].packet_idx = m_total_packet_count;
Zachary Turnered96be92017-03-04 01:31:06 +000091 m_packets[idx].tid = llvm::get_threadid();
Kate Stoneb9c1b512016-09-06 20:57:50 +000092 }
Greg Claytond451c1a2012-04-13 21:24:18 +000093}
94
Kate Stoneb9c1b512016-09-06 20:57:50 +000095void GDBRemoteCommunication::History::Dump(Stream &strm) const {
96 const uint32_t size = GetNumPacketsInHistory();
97 const uint32_t first_idx = GetFirstSavedPacketIndex();
98 const uint32_t stop_idx = m_curr_idx + size;
99 for (uint32_t i = first_idx; i < stop_idx; ++i) {
100 const uint32_t idx = NormalizeIndex(i);
101 const Entry &entry = m_packets[idx];
102 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
103 break;
104 strm.Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
105 entry.packet_idx, entry.tid, entry.bytes_transmitted,
106 (entry.type == ePacketTypeSend) ? "send" : "read",
107 entry.packet.c_str());
108 }
Greg Claytond451c1a2012-04-13 21:24:18 +0000109}
110
Kate Stoneb9c1b512016-09-06 20:57:50 +0000111void GDBRemoteCommunication::History::Dump(Log *log) const {
112 if (log && !m_dumped_to_log) {
113 m_dumped_to_log = true;
114 const uint32_t size = GetNumPacketsInHistory();
115 const uint32_t first_idx = GetFirstSavedPacketIndex();
Greg Claytonc1422c12012-04-09 22:46:21 +0000116 const uint32_t stop_idx = m_curr_idx + size;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 for (uint32_t i = first_idx; i < stop_idx; ++i) {
118 const uint32_t idx = NormalizeIndex(i);
119 const Entry &entry = m_packets[idx];
120 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
121 break;
122 log->Printf("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
123 entry.packet_idx, entry.tid, entry.bytes_transmitted,
124 (entry.type == ePacketTypeSend) ? "send" : "read",
125 entry.packet.c_str());
Greg Claytonc1422c12012-04-09 22:46:21 +0000126 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000128}
129
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000130//----------------------------------------------------------------------
131// GDBRemoteCommunication constructor
132//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
134 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000135 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000136#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000137 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000138#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000139 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000140#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
142 m_send_acks(true), m_compression_type(CompressionType::None),
143 m_listen_url() {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000144}
145
146//----------------------------------------------------------------------
147// Destructor
148//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149GDBRemoteCommunication::~GDBRemoteCommunication() {
150 if (IsConnected()) {
151 Disconnect();
152 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000153
Adrian Prantl05097242018-04-30 16:49:04 +0000154 // Stop the communications read thread which is used to parse all incoming
155 // packets. This function will block until the read thread returns.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 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
Adrian Prantl05097242018-04-30 16:49:04 +0000220 // If logging was just enabled and we have history, then dump out what we
221 // have to the log so we get the historical context. The Dump() call that
Kate Stoneb9c1b512016-09-06 20:57:50 +0000222 // logs all of the packet will set a boolean so that we don't dump this
Adrian Prantl05097242018-04-30 16:49:04 +0000223 // more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000224 if (!m_history.DidDumpToLog())
225 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 if (binary_start_offset) {
228 StreamString strm;
229 // Print non binary data header
230 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
231 (int)binary_start_offset, packet_data);
232 const uint8_t *p;
233 // Print binary data exactly as sent
234 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
235 ++p)
236 strm.Printf("\\x%2.2x", *p);
237 // Print the checksum
238 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000239 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 } else
241 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
242 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000243 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245 m_history.AddPacket(packet.GetString(), packet_length,
246 History::ePacketTypeSend, bytes_written);
247
248 if (bytes_written == packet_length) {
249 if (GetSendAcks())
250 return GetAck();
251 else
252 return PacketResult::Success;
253 } else {
254 if (log)
255 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
256 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000257 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000258 }
259 return PacketResult::ErrorSendFailed;
260}
261
262GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
263 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000264 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 if (result == PacketResult::Success) {
266 if (packet.GetResponseType() ==
267 StringExtractorGDBRemote::ResponseType::eAck)
268 return PacketResult::Success;
269 else
270 return PacketResult::ErrorSendAck;
271 }
272 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273}
274
Greg Clayton3dedae12013-12-06 21:45:27 +0000275GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000276GDBRemoteCommunication::ReadPacketWithOutputSupport(
277 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
278 bool sync_on_timeout,
279 llvm::function_ref<void(llvm::StringRef)> output_callback) {
280 auto result = ReadPacket(response, timeout, sync_on_timeout);
281 while (result == PacketResult::Success && response.IsNormalResponse() &&
282 response.PeekChar() == 'O') {
283 response.GetChar();
284 std::string output;
285 if (response.GetHexByteString(output))
286 output_callback(output);
287 result = ReadPacket(response, timeout, sync_on_timeout);
288 }
289 return result;
290}
291
292GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000294 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 bool sync_on_timeout) {
296 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000297 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000299 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000300}
301
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000302// This function is called when a packet is requested.
303// A whole packet is popped from the packet queue and returned to the caller.
Adrian Prantl05097242018-04-30 16:49:04 +0000304// Packets are placed into this queue from the communication read thread. See
305// GDBRemoteCommunication::AppendBytesToCache.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000306GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000307GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000308 Timeout<std::micro> timeout) {
309 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
310 // lock down the packet queue
311 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000312
Pavel Labath1eff73c2016-11-24 10:54:49 +0000313 if (!timeout)
314 m_condition_queue_not_empty.wait(lock, pred);
315 else {
316 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
317 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000318 if (!IsConnected())
319 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 }
321
Pavel Labath1eff73c2016-11-24 10:54:49 +0000322 // get the front element of the queue
323 response = m_packet_queue.front();
324
325 // remove the front element
326 m_packet_queue.pop();
327
328 // we got a packet
329 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000330}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000331
332GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000333GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
334 Timeout<std::micro> timeout,
335 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000337 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000338
Pavel Labathe8a7b982017-02-06 19:31:09 +0000339 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000340
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 // Check for a packet from our cache first without trying any reading...
342 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
343 return PacketResult::Success;
344
345 bool timed_out = false;
346 bool disconnected = false;
347 while (IsConnected() && !timed_out) {
348 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000349 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000350
Pavel Labathe8a7b982017-02-06 19:31:09 +0000351 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000352 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000353 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000354 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000355 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000356
357 if (bytes_read > 0) {
358 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000359 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000360 } else {
361 switch (status) {
362 case eConnectionStatusTimedOut:
363 case eConnectionStatusInterrupted:
364 if (sync_on_timeout) {
365 //------------------------------------------------------------------
366 /// Sync the remote GDB server and make sure we get a response that
367 /// corresponds to what we send.
368 ///
369 /// Sends a "qEcho" packet and makes sure it gets the exact packet
370 /// echoed back. If the qEcho packet isn't supported, we send a qC
371 /// packet and make sure we get a valid thread ID back. We use the
372 /// "qC" packet since its response if very unique: is responds with
373 /// "QC%x" where %x is the thread ID of the current thread. This
374 /// makes the response unique enough from other packet responses to
375 /// ensure we are back on track.
376 ///
377 /// This packet is needed after we time out sending a packet so we
378 /// can ensure that we are getting the response for the packet we
379 /// are sending. There are no sequence IDs in the GDB remote
380 /// protocol (there used to be, but they are not supported anymore)
381 /// so if you timeout sending packet "abc", you might then send
382 /// packet "cde" and get the response for the previous "abc" packet.
383 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
384 /// many responses for packets can look like responses for other
385 /// packets. So if we timeout, we need to ensure that we can get
386 /// back on track. If we can't get back on track, we must
387 /// disconnect.
388 //------------------------------------------------------------------
389 bool sync_success = false;
390 bool got_actual_response = false;
391 // We timed out, we need to sync back up with the
392 char echo_packet[32];
393 int echo_packet_len = 0;
394 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000395
Kate Stoneb9c1b512016-09-06 20:57:50 +0000396 if (m_supports_qEcho == eLazyBoolYes) {
397 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
398 "qEcho:%u", ++m_echo_number);
399 std::string regex_str = "^";
400 regex_str += echo_packet;
401 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000402 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 } else {
404 echo_packet_len =
405 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000406 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000407 }
Greg Clayton644247c2011-07-07 01:59:51 +0000408
Kate Stoneb9c1b512016-09-06 20:57:50 +0000409 PacketResult echo_packet_result =
410 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
411 if (echo_packet_result == PacketResult::Success) {
412 const uint32_t max_retries = 3;
413 uint32_t successful_responses = 0;
414 for (uint32_t i = 0; i < max_retries; ++i) {
415 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000416 echo_packet_result =
417 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 if (echo_packet_result == PacketResult::Success) {
419 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000420 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000421 sync_success = true;
422 break;
423 } else if (successful_responses == 1) {
424 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000425 // response, it probably is the response to the packet we
426 // actually wanted, so copy it over if this is the first
427 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000428 packet = echo_response;
429 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000430 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
432 continue; // Packet timed out, continue waiting for a response
433 else
434 break; // Something else went wrong getting the packet back, we
435 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000436 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 }
438
439 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000440 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000441 if (sync_success) {
442 // We timed out, but were able to recover
443 if (got_actual_response) {
444 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000445 // before the successful reply to our qEcho packet, so lets say
446 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000447 return PacketResult::Success;
448 }
449 } else {
450 disconnected = true;
451 Disconnect();
452 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000453 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 timed_out = true;
455 break;
456 case eConnectionStatusSuccess:
457 // printf ("status = success but error = %s\n",
458 // error.AsCString("<invalid>"));
459 break;
460
461 case eConnectionStatusEndOfFile:
462 case eConnectionStatusNoConnection:
463 case eConnectionStatusLostConnection:
464 case eConnectionStatusError:
465 disconnected = true;
466 Disconnect();
467 break;
468 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000469 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470 }
471 packet.Clear();
472 if (disconnected)
473 return PacketResult::ErrorDisconnected;
474 if (timed_out)
475 return PacketResult::ErrorReplyTimeout;
476 else
477 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000478}
479
Kate Stoneb9c1b512016-09-06 20:57:50 +0000480bool GDBRemoteCommunication::DecompressPacket() {
481 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000482
Kate Stoneb9c1b512016-09-06 20:57:50 +0000483 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000484 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485
486 size_t pkt_size = m_bytes.size();
487
Adrian Prantl05097242018-04-30 16:49:04 +0000488 // Smallest possible compressed packet is $N#00 - an uncompressed empty
489 // reply, most commonly indicating an unsupported packet. Anything less than
490 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000491 if (pkt_size < 5)
492 return true;
493
494 if (m_bytes[0] != '$' && m_bytes[0] != '%')
495 return true;
496 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
497 return true;
498
499 size_t hash_mark_idx = m_bytes.find('#');
500 if (hash_mark_idx == std::string::npos)
501 return true;
502 if (hash_mark_idx + 2 >= m_bytes.size())
503 return true;
504
505 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
506 !::isxdigit(m_bytes[hash_mark_idx + 2]))
507 return true;
508
509 size_t content_length =
510 pkt_size -
511 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
512 size_t content_start = 2; // The first character of the
513 // compressed/not-compressed text of the packet
514 size_t checksum_idx =
515 hash_mark_idx +
516 1; // The first character of the two hex checksum characters
517
518 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000519 // multiple packets. size_of_first_packet is the size of the initial packet
520 // which we'll replace with the decompressed version of, leaving the rest of
521 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 size_t size_of_first_packet = hash_mark_idx + 3;
523
524 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000525 // the uncompressed payload, then a : and then the compressed data. e.g.
526 // $C1024:<binary>#00 Update content_start and content_length to only include
527 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528
529 uint64_t decompressed_bufsize = ULONG_MAX;
530 if (m_bytes[1] == 'C') {
531 size_t i = content_start;
532 while (i < hash_mark_idx && isdigit(m_bytes[i]))
533 i++;
534 if (i < hash_mark_idx && m_bytes[i] == ':') {
535 i++;
536 content_start = i;
537 content_length = hash_mark_idx - content_start;
538 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
539 errno = 0;
540 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
541 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
542 m_bytes.erase(0, size_of_first_packet);
543 return false;
544 }
545 }
546 }
547
548 if (GetSendAcks()) {
549 char packet_checksum_cstr[3];
550 packet_checksum_cstr[0] = m_bytes[checksum_idx];
551 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
552 packet_checksum_cstr[2] = '\0';
553 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
554
555 long actual_checksum = CalculcateChecksum(
556 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
557 bool success = packet_checksum == actual_checksum;
558 if (!success) {
559 if (log)
560 log->Printf(
561 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
562 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
563 (uint8_t)actual_checksum);
564 }
565 // Send the ack or nack if needed
566 if (!success) {
567 SendNack();
568 m_bytes.erase(0, size_of_first_packet);
569 return false;
570 } else {
571 SendAck();
572 }
573 }
574
575 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000576 // This packet was not compressed -- delete the 'N' character at the start
577 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000578 m_bytes.erase(1, 1);
579 return true;
580 }
581
Adrian Prantl05097242018-04-30 16:49:04 +0000582 // Reverse the gdb-remote binary escaping that was done to the compressed
583 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000584 std::vector<uint8_t> unescaped_content;
585 unescaped_content.reserve(content_length);
586 size_t i = content_start;
587 while (i < hash_mark_idx) {
588 if (m_bytes[i] == '}') {
589 i++;
590 unescaped_content.push_back(m_bytes[i] ^ 0x20);
591 } else {
592 unescaped_content.push_back(m_bytes[i]);
593 }
594 i++;
595 }
596
597 uint8_t *decompressed_buffer = nullptr;
598 size_t decompressed_bytes = 0;
599
600 if (decompressed_bufsize != ULONG_MAX) {
601 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1);
602 if (decompressed_buffer == nullptr) {
603 m_bytes.erase(0, size_of_first_packet);
604 return false;
605 }
606 }
607
608#if defined(HAVE_LIBCOMPRESSION)
609 // libcompression is weak linked so check that compression_decode_buffer() is
610 // available
Vedant Kumar606908a2017-12-06 19:21:10 +0000611 if (m_compression_type == CompressionType::ZlibDeflate ||
612 m_compression_type == CompressionType::LZFSE ||
613 m_compression_type == CompressionType::LZ4) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000614 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000615 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000616 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000617 else if (m_compression_type == CompressionType::ZlibDeflate)
618 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000619 else if (m_compression_type == CompressionType::LZ4)
620 compression_type = COMPRESSION_LZ4_RAW;
621 else if (m_compression_type == CompressionType::LZMA)
622 compression_type = COMPRESSION_LZMA;
623
Adrian Prantl05097242018-04-30 16:49:04 +0000624 // If we have the expected size of the decompressed payload, we can
625 // allocate the right-sized buffer and do it. If we don't have that
626 // information, we'll need to try decoding into a big buffer and if the
627 // buffer wasn't big enough, increase it and try again.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628
629 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
630 decompressed_bytes = compression_decode_buffer(
631 decompressed_buffer, decompressed_bufsize + 10,
632 (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL,
633 compression_type);
634 }
635 }
636#endif
637
638#if defined(HAVE_LIBZ)
639 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
640 decompressed_buffer != nullptr &&
641 m_compression_type == CompressionType::ZlibDeflate) {
642 z_stream stream;
643 memset(&stream, 0, sizeof(z_stream));
644 stream.next_in = (Bytef *)unescaped_content.data();
645 stream.avail_in = (uInt)unescaped_content.size();
646 stream.total_in = 0;
647 stream.next_out = (Bytef *)decompressed_buffer;
648 stream.avail_out = decompressed_bufsize;
649 stream.total_out = 0;
650 stream.zalloc = Z_NULL;
651 stream.zfree = Z_NULL;
652 stream.opaque = Z_NULL;
653
654 if (inflateInit2(&stream, -15) == Z_OK) {
655 int status = inflate(&stream, Z_NO_FLUSH);
656 inflateEnd(&stream);
657 if (status == Z_STREAM_END) {
658 decompressed_bytes = stream.total_out;
659 }
660 }
661 }
662#endif
663
664 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
665 if (decompressed_buffer)
666 free(decompressed_buffer);
667 m_bytes.erase(0, size_of_first_packet);
668 return false;
669 }
670
671 std::string new_packet;
672 new_packet.reserve(decompressed_bytes + 6);
673 new_packet.push_back(m_bytes[0]);
674 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
675 new_packet.push_back('#');
676 if (GetSendAcks()) {
677 uint8_t decompressed_checksum = CalculcateChecksum(
678 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
679 char decompressed_checksum_str[3];
680 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
681 new_packet.append(decompressed_checksum_str);
682 } else {
683 new_packet.push_back('0');
684 new_packet.push_back('0');
685 }
686
687 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
688 new_packet.size());
689
690 free(decompressed_buffer);
691 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000692}
693
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000694GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
696 StringExtractorGDBRemote &packet) {
697 // Put the packet data into the buffer in a thread safe fashion
698 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000699
Kate Stoneb9c1b512016-09-06 20:57:50 +0000700 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000701
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 if (src && src_len > 0) {
703 if (log && log->GetVerbose()) {
704 StreamString s;
705 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
706 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
707 }
708 m_bytes.append((const char *)src, src_len);
709 }
710
711 bool isNotifyPacket = false;
712
713 // Parse up the packets into gdb remote packets
714 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000715 // end_idx must be one past the last valid packet byte. Start it off with
716 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 size_t content_start = 0;
718 size_t content_length = 0;
719 size_t total_length = 0;
720 size_t checksum_idx = std::string::npos;
721
722 // Size of packet before it is decompressed, for logging purposes
723 size_t original_packet_size = m_bytes.size();
724 if (CompressionIsEnabled()) {
725 if (DecompressPacket() == false) {
726 packet.Clear();
727 return GDBRemoteCommunication::PacketType::Standard;
728 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000729 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000730
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 switch (m_bytes[0]) {
732 case '+': // Look for ack
733 case '-': // Look for cancel
734 case '\x03': // ^C to halt target
735 content_length = total_length = 1; // The command is one byte long...
736 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000737
Kate Stoneb9c1b512016-09-06 20:57:50 +0000738 case '%': // Async notify packet
739 isNotifyPacket = true;
740 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000741
Kate Stoneb9c1b512016-09-06 20:57:50 +0000742 case '$':
743 // Look for a standard gdb packet?
744 {
745 size_t hash_pos = m_bytes.find('#');
746 if (hash_pos != std::string::npos) {
747 if (hash_pos + 2 < m_bytes.size()) {
748 checksum_idx = hash_pos + 1;
749 // Skip the dollar sign
750 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000751 // Don't include the # in the content or the $ in the content
752 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000753 content_length = hash_pos - 1;
754
755 total_length =
756 hash_pos + 3; // Skip the # and the two hex checksum bytes
757 } else {
758 // Checksum bytes aren't all here yet
759 content_length = std::string::npos;
760 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000761 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 }
763 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000764
Kate Stoneb9c1b512016-09-06 20:57:50 +0000765 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000766 // We have an unexpected byte and we need to flush all bad data that is
767 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
768 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
769 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 const size_t bytes_len = m_bytes.size();
771 bool done = false;
772 uint32_t idx;
773 for (idx = 1; !done && idx < bytes_len; ++idx) {
774 switch (m_bytes[idx]) {
775 case '+':
776 case '-':
777 case '\x03':
778 case '%':
779 case '$':
780 done = true;
781 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000782
Kate Stoneb9c1b512016-09-06 20:57:50 +0000783 default:
784 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000785 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 }
787 if (log)
788 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
789 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
790 m_bytes.erase(0, idx - 1);
791 } break;
792 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000793
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 if (content_length == std::string::npos) {
795 packet.Clear();
796 return GDBRemoteCommunication::PacketType::Invalid;
797 } else if (total_length > 0) {
798
799 // We have a valid packet...
800 assert(content_length <= m_bytes.size());
801 assert(total_length <= m_bytes.size());
802 assert(content_length <= total_length);
803 size_t content_end = content_start + content_length;
804
805 bool success = true;
806 std::string &packet_str = packet.GetStringRef();
807 if (log) {
808 // If logging was just enabled and we have history, then dump out what
809 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000810 // that logs all of the packet will set a boolean so that we don't dump
811 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000812 if (!m_history.DidDumpToLog())
813 m_history.Dump(log);
814
815 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000816 // Only detect binary for packets that start with a '$' and have a
817 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000818 if (m_bytes[0] == '$' && total_length > 4) {
819 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000820 unsigned char c = m_bytes[i];
821 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 binary = true;
823 }
824 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000825 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 if (binary) {
827 StreamString strm;
828 // Packet header...
829 if (CompressionIsEnabled())
830 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
831 (uint64_t)original_packet_size, (uint64_t)total_length,
832 m_bytes[0]);
833 else
834 strm.Printf("<%4" PRIu64 "> read packet: %c",
835 (uint64_t)total_length, m_bytes[0]);
836 for (size_t i = content_start; i < content_end; ++i) {
837 // Remove binary escaped bytes when displaying the packet...
838 const char ch = m_bytes[i];
839 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000840 // 0x7d is the escape character. The next character is to be
841 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000842 const char escapee = m_bytes[++i] ^ 0x20;
843 strm.Printf("%2.2x", escapee);
844 } else {
845 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000846 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 }
848 // Packet footer...
849 strm.Printf("%c%c%c", m_bytes[total_length - 3],
850 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000851 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000852 } else {
853 if (CompressionIsEnabled())
854 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
855 (uint64_t)original_packet_size, (uint64_t)total_length,
856 (int)(total_length), m_bytes.c_str());
857 else
858 log->Printf("<%4" PRIu64 "> read packet: %.*s",
859 (uint64_t)total_length, (int)(total_length),
860 m_bytes.c_str());
861 }
862 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000863
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000864 m_history.AddPacket(m_bytes, total_length, History::ePacketTypeRecv,
865 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000866
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 // Clear packet_str in case there is some existing data in it.
868 packet_str.clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000869 // Copy the packet from m_bytes to packet_str expanding the run-length
870 // encoding in the process. Reserve enough byte for the most common case
871 // (no RLE used)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000872 packet_str.reserve(m_bytes.length());
873 for (std::string::const_iterator c = m_bytes.begin() + content_start;
874 c != m_bytes.begin() + content_end; ++c) {
875 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000876 // '*' indicates RLE. Next character will give us the repeat count
877 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000878 char char_to_repeat = packet_str.back();
879 // Number of time the previous character is repeated
880 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000881 // We have the char_to_repeat and repeat_count. Now push it in the
882 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000883 for (int i = 0; i < repeat_count; ++i)
884 packet_str.push_back(char_to_repeat);
885 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000886 // 0x7d is the escape character. The next character is to be XOR'd
887 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000888 char escapee = *++c ^ 0x20;
889 packet_str.push_back(escapee);
890 } else {
891 packet_str.push_back(*c);
892 }
893 }
894
895 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
896 assert(checksum_idx < m_bytes.size());
897 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
898 ::isxdigit(m_bytes[checksum_idx + 1])) {
899 if (GetSendAcks()) {
900 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
901 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
Pavel Labath5a841232018-03-28 10:19:10 +0000902 char actual_checksum = CalculcateChecksum(
903 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000904 success = packet_checksum == actual_checksum;
905 if (!success) {
906 if (log)
907 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
908 "got 0x%2.2x",
909 (int)(total_length), m_bytes.c_str(),
910 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000911 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912 // Send the ack or nack if needed
913 if (!success)
914 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000915 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916 SendAck();
917 }
918 } else {
919 success = false;
920 if (log)
921 log->Printf("error: invalid checksum in packet: '%s'\n",
922 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 }
925
926 m_bytes.erase(0, total_length);
927 packet.SetFilePos(0);
928
929 if (isNotifyPacket)
930 return GDBRemoteCommunication::PacketType::Notify;
931 else
932 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000933 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934 }
935 packet.Clear();
936 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000937}
938
Zachary Turner97206d52017-05-12 04:51:55 +0000939Status GDBRemoteCommunication::StartListenThread(const char *hostname,
940 uint16_t port) {
941 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 if (m_listen_thread.IsJoinable()) {
943 error.SetErrorString("listen thread already running");
944 } else {
945 char listen_url[512];
946 if (hostname && hostname[0])
947 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
948 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000949 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
951 m_listen_url = listen_url;
952 SetConnection(new ConnectionFileDescriptor());
953 m_listen_thread = ThreadLauncher::LaunchThread(
954 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
955 }
956 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000957}
958
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959bool GDBRemoteCommunication::JoinListenThread() {
960 if (m_listen_thread.IsJoinable())
961 m_listen_thread.Join(nullptr);
962 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000963}
964
965lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
967 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000968 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 ConnectionFileDescriptor *connection =
970 (ConnectionFileDescriptor *)comm->GetConnection();
971
972 if (connection) {
973 // Do the listen on another thread so we can continue on...
974 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
975 eConnectionStatusSuccess)
976 comm->SetConnection(NULL);
977 }
978 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000979}
980
Zachary Turner97206d52017-05-12 04:51:55 +0000981Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
983 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
984 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
985 if (log)
986 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
987 __FUNCTION__, url ? url : "<empty>",
988 port ? *port : uint16_t(0));
989
Zachary Turner97206d52017-05-12 04:51:55 +0000990 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000991 // If we locate debugserver, keep that located version around
992 static FileSpec g_debugserver_file_spec;
993
994 char debugserver_path[PATH_MAX];
995 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
996
Adrian Prantl05097242018-04-30 16:49:04 +0000997 // Always check to see if we have an environment override for the path to the
998 // debugserver to use and use it if we do.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1000 if (env_debugserver_path) {
Jonas Devlieghere937348c2018-06-13 22:08:14 +00001001 debugserver_file_spec.SetFile(env_debugserver_path, false,
1002 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +00001003 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
1005 "from environment variable: %s",
1006 __FUNCTION__, env_debugserver_path);
1007 } else
1008 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00001009 bool debugserver_exists =
1010 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001011 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +00001012 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +00001013 debugserver_file_spec = HostInfo::GetSupportExeDir();
1014 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001015 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +00001016 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +00001018 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001019 log->Printf(
1020 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
1021 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +00001022
Kate Stoneb9c1b512016-09-06 20:57:50 +00001023 g_debugserver_file_spec = debugserver_file_spec;
1024 } else {
1025 debugserver_file_spec =
1026 platform->LocateExecutable(DEBUGSERVER_BASENAME);
1027 if (debugserver_file_spec) {
1028 // Platform::LocateExecutable() wouldn't return a path if it doesn't
1029 // exist
1030 debugserver_exists = true;
1031 } else {
1032 if (log)
1033 log->Printf("GDBRemoteCommunication::%s() could not find "
1034 "gdb-remote stub exe '%s'",
1035 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +00001036 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001037 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +00001038 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039 g_debugserver_file_spec.Clear();
1040 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001041 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001042 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001043
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 if (debugserver_exists) {
1045 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001046
Kate Stoneb9c1b512016-09-06 20:57:50 +00001047 Args &debugserver_args = launch_info.GetArguments();
1048 debugserver_args.Clear();
1049 char arg_cstr[PATH_MAX];
1050
1051 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001052 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001053
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001054#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001055 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001056 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001057#endif
1058
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059 // If a url is supplied then use it
1060 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001061 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001062
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 if (pass_comm_fd >= 0) {
1064 StreamString fd_arg;
1065 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001066 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 // Send "pass_comm_fd" down to the inferior so it can use it to
1068 // communicate back with this process
1069 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1070 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001071
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001073 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001074
Kate Stoneb9c1b512016-09-06 20:57:50 +00001075 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001076 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001078
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 llvm::SmallString<PATH_MAX> named_pipe_path;
1080 // socket_pipe is used by debug server to communicate back either
1081 // TCP port or domain socket name which it listens on.
1082 // The second purpose of the pipe to serve as a synchronization point -
1083 // once data is written to the pipe, debug server is up and running.
1084 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001085
Adrian Prantl05097242018-04-30 16:49:04 +00001086 // port is null when debug server should listen on domain socket - we're
1087 // not interested in port value but rather waiting for debug server to
1088 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001089 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001091// Create a temporary file to get the stdout/stderr and redirect the output of
1092// the command into this file. We will later read this file if all goes well
1093// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001094#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 // Binding to port zero, we need to figure out what port it ends up
1096 // using using a named pipe...
1097 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1098 false, named_pipe_path);
1099 if (error.Fail()) {
1100 if (log)
1101 log->Printf("GDBRemoteCommunication::%s() "
1102 "named pipe creation failed: %s",
1103 __FUNCTION__, error.AsCString());
1104 return error;
1105 }
Sean Callanan1355f472016-09-19 22:06:12 +00001106 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001107 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001108#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001109 // Binding to port zero, we need to figure out what port it ends up
1110 // using using an unnamed pipe...
1111 error = socket_pipe.CreateNew(true);
1112 if (error.Fail()) {
1113 if (log)
1114 log->Printf("GDBRemoteCommunication::%s() "
1115 "unnamed pipe creation failed: %s",
1116 __FUNCTION__, error.AsCString());
1117 return error;
1118 }
1119 int write_fd = socket_pipe.GetWriteFileDescriptor();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001120 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1121 debugserver_args.AppendArgument(llvm::to_string(write_fd));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001123#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 } else {
1125 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001126 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 error = StartListenThread("127.0.0.1", 0);
1128 if (error.Fail()) {
1129 if (log)
1130 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1131 "thread: %s",
1132 __FUNCTION__, error.AsCString());
1133 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001134 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135
1136 ConnectionFileDescriptor *connection =
1137 (ConnectionFileDescriptor *)GetConnection();
1138 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001139 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001140 if (port_ > 0) {
1141 char port_cstr[32];
1142 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1143 // Send the host and port down that debugserver and specify an option
1144 // so that it connects back to the port we are listening to in this
1145 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001146 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1147 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 if (port)
1149 *port = port_;
1150 } else {
1151 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1152 if (log)
1153 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1154 error.AsCString());
1155 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001156 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157 }
1158 }
1159
1160 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1161 if (env_debugserver_log_file) {
1162 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1163 env_debugserver_log_file);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001164 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 }
1166
Vince Harron9753dd92015-05-10 15:22:09 +00001167#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001168 const char *env_debugserver_log_flags =
1169 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1170 if (env_debugserver_log_flags) {
1171 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1172 env_debugserver_log_flags);
Sean Callanan1355f472016-09-19 22:06:12 +00001173 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001174 }
Vince Harron9753dd92015-05-10 15:22:09 +00001175#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176 const char *env_debugserver_log_channels =
1177 getenv("LLDB_SERVER_LOG_CHANNELS");
1178 if (env_debugserver_log_channels) {
1179 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1180 env_debugserver_log_channels);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001181 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 }
Vince Harron9753dd92015-05-10 15:22:09 +00001183#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001184
Kate Stoneb9c1b512016-09-06 20:57:50 +00001185 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1186 // env var doesn't come back.
1187 uint32_t env_var_index = 1;
1188 bool has_env_var;
1189 do {
1190 char env_var_name[64];
1191 snprintf(env_var_name, sizeof(env_var_name),
1192 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1193 const char *extra_arg = getenv(env_var_name);
1194 has_env_var = extra_arg != nullptr;
Todd Fiala34ba4262014-08-29 17:10:31 +00001195
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001197 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001198 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001199 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1200 "to stub command line (%s)",
1201 __FUNCTION__, env_var_name, extra_arg);
1202 }
1203 } while (has_env_var);
1204
1205 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001206 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 debugserver_args.AppendArguments(*inferior_args);
1208 }
1209
1210 // Copy the current environment to the gdbserver/debugserver instance
Pavel Labath62930e52018-01-10 11:57:31 +00001211 launch_info.GetEnvironment() = Host::GetEnvironment();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001212
1213 // Close STDIN, STDOUT and STDERR.
1214 launch_info.AppendCloseFileAction(STDIN_FILENO);
1215 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1216 launch_info.AppendCloseFileAction(STDERR_FILENO);
1217
1218 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1219 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1220 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1221 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1222
1223 if (log) {
1224 StreamString string_stream;
1225 Platform *const platform = nullptr;
1226 launch_info.Dump(string_stream, platform);
1227 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001228 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 }
1230 error = Host::LaunchProcess(launch_info);
1231
1232 if (error.Success() &&
1233 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1234 pass_comm_fd == -1) {
1235 if (named_pipe_path.size() > 0) {
1236 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1237 if (error.Fail())
1238 if (log)
1239 log->Printf("GDBRemoteCommunication::%s() "
1240 "failed to open named pipe %s for reading: %s",
1241 __FUNCTION__, named_pipe_path.c_str(),
1242 error.AsCString());
1243 }
1244
1245 if (socket_pipe.CanWrite())
1246 socket_pipe.CloseWriteFileDescriptor();
1247 if (socket_pipe.CanRead()) {
1248 char port_cstr[PATH_MAX] = {0};
1249 port_cstr[0] = '\0';
1250 size_t num_bytes = sizeof(port_cstr);
1251 // Read port from pipe with 10 second timeout.
1252 error = socket_pipe.ReadWithTimeout(
1253 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1254 if (error.Success() && (port != nullptr)) {
1255 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001256 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1257 if (*port == 0 || *port == child_port) {
1258 *port = child_port;
1259 if (log)
1260 log->Printf("GDBRemoteCommunication::%s() "
1261 "debugserver listens %u port",
1262 __FUNCTION__, *port);
1263 } else {
1264 if (log)
1265 log->Printf("GDBRemoteCommunication::%s() "
1266 "debugserver listening on port "
1267 "%d but requested port was %d",
1268 __FUNCTION__, (uint32_t)child_port,
1269 (uint32_t)(*port));
1270 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001271 } else {
1272 if (log)
1273 log->Printf("GDBRemoteCommunication::%s() "
1274 "failed to read a port value from pipe %s: %s",
1275 __FUNCTION__, named_pipe_path.c_str(),
1276 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001277 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001278 socket_pipe.Close();
1279 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001280
Kate Stoneb9c1b512016-09-06 20:57:50 +00001281 if (named_pipe_path.size() > 0) {
1282 const auto err = socket_pipe.Delete(named_pipe_path);
1283 if (err.Fail()) {
1284 if (log)
1285 log->Printf(
1286 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1287 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001288 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001289 }
1290
1291 // Make sure we actually connect with the debugserver...
1292 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001293 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 } else {
1295 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1296 }
Vince Harron8b335672015-05-12 01:10:56 +00001297
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298 if (error.Fail()) {
1299 if (log)
1300 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1301 error.AsCString());
1302 }
Vince Harron8b335672015-05-12 01:10:56 +00001303
Kate Stoneb9c1b512016-09-06 20:57:50 +00001304 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001305}
1306
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1308
1309GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001310 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Greg Clayton84577092017-04-17 16:20:22 +00001311 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1312 auto curr_timeout = gdb_comm.GetPacketTimeout();
1313 // Only update the timeout if the timeout is greater than the current
1314 // timeout. If the current timeout is larger, then just use that.
1315 if (curr_timeout < timeout) {
1316 m_timeout_modified = true;
1317 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1318 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001319}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001320
Kate Stoneb9c1b512016-09-06 20:57:50 +00001321GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001322 // Only restore the timeout if we set it in the constructor.
1323 if (m_timeout_modified)
1324 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001325}
1326
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001328// become available for this connection. This function will consume all
1329// incoming bytes and try to parse whole packets as they become available. Full
1330// packets are placed in a queue, so that all packet requests can simply pop
1331// from this queue. Async notification packets will be dispatched immediately
1332// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1334 size_t len, bool broadcast,
1335 lldb::ConnectionStatus status) {
1336 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001337
Kate Stoneb9c1b512016-09-06 20:57:50 +00001338 while (true) {
1339 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001340
Adrian Prantl05097242018-04-30 16:49:04 +00001341 // scrub the data so we do not pass it back to CheckForPacket on future
1342 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001343 bytes = nullptr;
1344 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001345
Kate Stoneb9c1b512016-09-06 20:57:50 +00001346 // we may have received no packet so lets bail out
1347 if (type == PacketType::Invalid)
1348 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001349
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350 if (type == PacketType::Standard) {
1351 // scope for the mutex
1352 {
1353 // lock down the packet queue
1354 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1355 // push a new packet into the queue
1356 m_packet_queue.push(packet);
1357 // Signal condition variable that we have a packet
1358 m_condition_queue_not_empty.notify_one();
1359 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001360 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361
1362 if (type == PacketType::Notify) {
1363 // put this packet into an event
1364 const char *pdata = packet.GetStringRef().c_str();
1365
Adrian Prantl05097242018-04-30 16:49:04 +00001366 // as the communication class, we are a broadcaster and the async thread
1367 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001368 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1369 new EventDataBytes(pdata));
1370 }
1371 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001372}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001373
1374void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1375 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1376 StringRef Style) {
1377 using PacketResult = GDBRemoteCommunication::PacketResult;
1378
1379 switch (result) {
1380 case PacketResult::Success:
1381 Stream << "Success";
1382 break;
1383 case PacketResult::ErrorSendFailed:
1384 Stream << "ErrorSendFailed";
1385 break;
1386 case PacketResult::ErrorSendAck:
1387 Stream << "ErrorSendAck";
1388 break;
1389 case PacketResult::ErrorReplyFailed:
1390 Stream << "ErrorReplyFailed";
1391 break;
1392 case PacketResult::ErrorReplyTimeout:
1393 Stream << "ErrorReplyTimeout";
1394 break;
1395 case PacketResult::ErrorReplyInvalid:
1396 Stream << "ErrorReplyInvalid";
1397 break;
1398 case PacketResult::ErrorReplyAck:
1399 Stream << "ErrorReplyAck";
1400 break;
1401 case PacketResult::ErrorDisconnected:
1402 Stream << "ErrorDisconnected";
1403 break;
1404 case PacketResult::ErrorNoSequenceLock:
1405 Stream << "ErrorNoSequenceLock";
1406 break;
1407 }
1408}