blob: 2c0a5e06c78cb0a3efedde34231567ca26bea002 [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
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Core/Log.h"
Greg Claytonb30c50c2015-05-29 00:01:55 +000020#include "lldb/Core/RegularExpression.h"
Greg Claytonc1422c12012-04-09 22:46:21 +000021#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000023#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000024#include "lldb/Host/FileSpec.h"
25#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000026#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000027#include "lldb/Host/Pipe.h"
Zachary Turner98688922014-08-06 18:16:26 +000028#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000029#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000030#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Host/TimeValue.h"
Greg Clayton6988abc2015-10-19 20:44:01 +000032#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000033#include "lldb/Target/Process.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;
76 m_packets[idx].tid = Host::GetCurrentThreadID();
77 }
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;
91 m_packets[idx].tid = Host::GetCurrentThreadID();
92 }
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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 // Stop the communications read thread which is used to parse all
155 // incoming packets. This function will block until the read
156 // thread returns.
157 if (m_read_thread_enabled)
158 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000159}
160
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
162 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000163
Kate Stoneb9c1b512016-09-06 20:57:50 +0000164 for (char c : payload)
165 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +0000166
Kate Stoneb9c1b512016-09-06 20:57:50 +0000167 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000168}
169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170size_t GDBRemoteCommunication::SendAck() {
171 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
172 ConnectionStatus status = eConnectionStatusSuccess;
173 char ch = '+';
174 const size_t bytes_written = Write(&ch, 1, status, NULL);
175 if (log)
176 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
177 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
178 return bytes_written;
179}
180
181size_t GDBRemoteCommunication::SendNack() {
182 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
183 ConnectionStatus status = eConnectionStatusSuccess;
184 char ch = '-';
185 const size_t bytes_written = Write(&ch, 1, status, NULL);
186 if (log)
187 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
188 m_history.AddPacket(ch, History::ePacketTypeSend, bytes_written);
189 return bytes_written;
190}
191
192GDBRemoteCommunication::PacketResult
193GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
194 if (IsConnected()) {
195 StreamString packet(0, 4, eByteOrderBig);
196
197 packet.PutChar('$');
198 packet.Write(payload.data(), payload.size());
199 packet.PutChar('#');
200 packet.PutHex8(CalculcateChecksum(payload));
201
202 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203 ConnectionStatus status = eConnectionStatusSuccess;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000204 const char *packet_data = packet.GetData();
205 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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219 // If logging was just enabled and we have history, then dump out what
220 // we have to the log so we get the historical context. The Dump() call
221 // that
222 // logs all of the packet will set a boolean so that we don't dump this
223 // more
224 // than once
225 if (!m_history.DidDumpToLog())
226 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000227
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228 if (binary_start_offset) {
229 StreamString strm;
230 // Print non binary data header
231 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
232 (int)binary_start_offset, packet_data);
233 const uint8_t *p;
234 // Print binary data exactly as sent
235 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
236 ++p)
237 strm.Printf("\\x%2.2x", *p);
238 // Print the checksum
239 strm.Printf("%*s", (int)3, p);
240 log->PutCString(strm.GetString().c_str());
241 } else
242 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
243 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000244 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000245
Kate Stoneb9c1b512016-09-06 20:57:50 +0000246 m_history.AddPacket(packet.GetString(), packet_length,
247 History::ePacketTypeSend, bytes_written);
248
249 if (bytes_written == packet_length) {
250 if (GetSendAcks())
251 return GetAck();
252 else
253 return PacketResult::Success;
254 } else {
255 if (log)
256 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
257 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000258 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 }
260 return PacketResult::ErrorSendFailed;
261}
262
263GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
264 StringExtractorGDBRemote packet;
265 PacketResult result =
266 ReadPacket(packet, GetPacketTimeoutInMicroSeconds(), false);
267 if (result == PacketResult::Success) {
268 if (packet.GetResponseType() ==
269 StringExtractorGDBRemote::ResponseType::eAck)
270 return PacketResult::Success;
271 else
272 return PacketResult::ErrorSendAck;
273 }
274 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000275}
276
Greg Clayton3dedae12013-12-06 21:45:27 +0000277GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
279 uint32_t timeout_usec,
280 bool sync_on_timeout) {
281 if (m_read_thread_enabled)
282 return PopPacketFromQueue(response, timeout_usec);
283 else
284 return WaitForPacketWithTimeoutMicroSecondsNoLock(response, timeout_usec,
285 sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000286}
287
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000288// This function is called when a packet is requested.
289// A whole packet is popped from the packet queue and returned to the caller.
290// Packets are placed into this queue from the communication read thread.
291// See GDBRemoteCommunication::AppendBytesToCache.
292GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000293GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
294 uint32_t timeout_usec) {
295 auto until = std::chrono::system_clock::now() +
296 std::chrono::microseconds(timeout_usec);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000297
Kate Stoneb9c1b512016-09-06 20:57:50 +0000298 while (true) {
299 // scope for the mutex
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000300 {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 // lock down the packet queue
302 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000303
Kate Stoneb9c1b512016-09-06 20:57:50 +0000304 // Wait on condition variable.
305 if (m_packet_queue.size() == 0) {
306 std::cv_status result =
307 m_condition_queue_not_empty.wait_until(lock, until);
308 if (result == std::cv_status::timeout)
309 break;
310 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000311
Kate Stoneb9c1b512016-09-06 20:57:50 +0000312 if (m_packet_queue.size() > 0) {
313 // get the front element of the queue
314 response = m_packet_queue.front();
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000315
Kate Stoneb9c1b512016-09-06 20:57:50 +0000316 // remove the front element
317 m_packet_queue.pop();
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000318
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 // we got a packet
320 return PacketResult::Success;
321 }
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000322 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000323
Kate Stoneb9c1b512016-09-06 20:57:50 +0000324 // Disconnected
325 if (!IsConnected())
326 return PacketResult::ErrorDisconnected;
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000327
Kate Stoneb9c1b512016-09-06 20:57:50 +0000328 // Loop while not timed out
329 }
330
331 return PacketResult::ErrorReplyTimeout;
332}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000333
334GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000335GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock(
336 StringExtractorGDBRemote &packet, uint32_t timeout_usec,
337 bool sync_on_timeout) {
338 uint8_t buffer[8192];
339 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000340
Kate Stoneb9c1b512016-09-06 20:57:50 +0000341 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS |
342 GDBR_LOG_VERBOSE));
Greg Clayton644247c2011-07-07 01:59:51 +0000343
Kate Stoneb9c1b512016-09-06 20:57:50 +0000344 // Check for a packet from our cache first without trying any reading...
345 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
346 return PacketResult::Success;
347
348 bool timed_out = false;
349 bool disconnected = false;
350 while (IsConnected() && !timed_out) {
351 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
352 size_t bytes_read =
353 Read(buffer, sizeof(buffer), timeout_usec, status, &error);
354
355 if (log)
356 log->Printf("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, "
357 "status = %s, error = %s) => bytes_read = %" PRIu64,
358 LLVM_PRETTY_FUNCTION, timeout_usec,
359 Communication::ConnectionStatusAsCString(status),
360 error.AsCString(), (uint64_t)bytes_read);
361
362 if (bytes_read > 0) {
363 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000364 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000365 } else {
366 switch (status) {
367 case eConnectionStatusTimedOut:
368 case eConnectionStatusInterrupted:
369 if (sync_on_timeout) {
370 //------------------------------------------------------------------
371 /// Sync the remote GDB server and make sure we get a response that
372 /// corresponds to what we send.
373 ///
374 /// Sends a "qEcho" packet and makes sure it gets the exact packet
375 /// echoed back. If the qEcho packet isn't supported, we send a qC
376 /// packet and make sure we get a valid thread ID back. We use the
377 /// "qC" packet since its response if very unique: is responds with
378 /// "QC%x" where %x is the thread ID of the current thread. This
379 /// makes the response unique enough from other packet responses to
380 /// ensure we are back on track.
381 ///
382 /// This packet is needed after we time out sending a packet so we
383 /// can ensure that we are getting the response for the packet we
384 /// are sending. There are no sequence IDs in the GDB remote
385 /// protocol (there used to be, but they are not supported anymore)
386 /// so if you timeout sending packet "abc", you might then send
387 /// packet "cde" and get the response for the previous "abc" packet.
388 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
389 /// many responses for packets can look like responses for other
390 /// packets. So if we timeout, we need to ensure that we can get
391 /// back on track. If we can't get back on track, we must
392 /// disconnect.
393 //------------------------------------------------------------------
394 bool sync_success = false;
395 bool got_actual_response = false;
396 // We timed out, we need to sync back up with the
397 char echo_packet[32];
398 int echo_packet_len = 0;
399 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 if (m_supports_qEcho == eLazyBoolYes) {
402 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
403 "qEcho:%u", ++m_echo_number);
404 std::string regex_str = "^";
405 regex_str += echo_packet;
406 regex_str += "$";
407 response_regex.Compile(regex_str.c_str());
408 } else {
409 echo_packet_len =
410 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
411 response_regex.Compile("^QC[0-9A-Fa-f]+$");
412 }
Greg Clayton644247c2011-07-07 01:59:51 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 PacketResult echo_packet_result =
415 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
416 if (echo_packet_result == PacketResult::Success) {
417 const uint32_t max_retries = 3;
418 uint32_t successful_responses = 0;
419 for (uint32_t i = 0; i < max_retries; ++i) {
420 StringExtractorGDBRemote echo_response;
421 echo_packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock(
422 echo_response, timeout_usec, false);
423 if (echo_packet_result == PacketResult::Success) {
424 ++successful_responses;
425 if (response_regex.Execute(
426 echo_response.GetStringRef().c_str())) {
427 sync_success = true;
428 break;
429 } else if (successful_responses == 1) {
430 // We got something else back as the first successful
431 // response, it probably is
432 // the response to the packet we actually wanted, so copy it
433 // over if this
434 // is the first success and continue to try to get the qEcho
435 // response
436 packet = echo_response;
437 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000438 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000439 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
440 continue; // Packet timed out, continue waiting for a response
441 else
442 break; // Something else went wrong getting the packet back, we
443 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000444 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445 }
446
447 // We weren't able to sync back up with the server, we must abort
448 // otherwise
449 // all responses might not be from the right packets...
450 if (sync_success) {
451 // We timed out, but were able to recover
452 if (got_actual_response) {
453 // We initially timed out, but we did get a response that came in
454 // before the successful
455 // reply to our qEcho packet, so lets say everything is fine...
456 return PacketResult::Success;
457 }
458 } else {
459 disconnected = true;
460 Disconnect();
461 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000462 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000463 timed_out = true;
464 break;
465 case eConnectionStatusSuccess:
466 // printf ("status = success but error = %s\n",
467 // error.AsCString("<invalid>"));
468 break;
469
470 case eConnectionStatusEndOfFile:
471 case eConnectionStatusNoConnection:
472 case eConnectionStatusLostConnection:
473 case eConnectionStatusError:
474 disconnected = true;
475 Disconnect();
476 break;
477 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000478 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000479 }
480 packet.Clear();
481 if (disconnected)
482 return PacketResult::ErrorDisconnected;
483 if (timed_out)
484 return PacketResult::ErrorReplyTimeout;
485 else
486 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000487}
488
Kate Stoneb9c1b512016-09-06 20:57:50 +0000489bool GDBRemoteCommunication::DecompressPacket() {
490 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000491
Kate Stoneb9c1b512016-09-06 20:57:50 +0000492 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000493 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494
495 size_t pkt_size = m_bytes.size();
496
497 // Smallest possible compressed packet is $N#00 - an uncompressed empty reply,
498 // most commonly indicating
499 // an unsupported packet. Anything less than 5 characters, it's definitely
500 // not a compressed packet.
501 if (pkt_size < 5)
502 return true;
503
504 if (m_bytes[0] != '$' && m_bytes[0] != '%')
505 return true;
506 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
507 return true;
508
509 size_t hash_mark_idx = m_bytes.find('#');
510 if (hash_mark_idx == std::string::npos)
511 return true;
512 if (hash_mark_idx + 2 >= m_bytes.size())
513 return true;
514
515 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
516 !::isxdigit(m_bytes[hash_mark_idx + 2]))
517 return true;
518
519 size_t content_length =
520 pkt_size -
521 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
522 size_t content_start = 2; // The first character of the
523 // compressed/not-compressed text of the packet
524 size_t checksum_idx =
525 hash_mark_idx +
526 1; // The first character of the two hex checksum characters
527
528 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
529 // multiple packets.
530 // size_of_first_packet is the size of the initial packet which we'll replace
531 // with the decompressed
532 // version of, leaving the rest of m_bytes unmodified.
533 size_t size_of_first_packet = hash_mark_idx + 3;
534
535 // Compressed packets ("$C") start with a base10 number which is the size of
536 // the uncompressed payload,
537 // then a : and then the compressed data. e.g. $C1024:<binary>#00
538 // Update content_start and content_length to only include the <binary> part
539 // of the packet.
540
541 uint64_t decompressed_bufsize = ULONG_MAX;
542 if (m_bytes[1] == 'C') {
543 size_t i = content_start;
544 while (i < hash_mark_idx && isdigit(m_bytes[i]))
545 i++;
546 if (i < hash_mark_idx && m_bytes[i] == ':') {
547 i++;
548 content_start = i;
549 content_length = hash_mark_idx - content_start;
550 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
551 errno = 0;
552 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), NULL, 10);
553 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
554 m_bytes.erase(0, size_of_first_packet);
555 return false;
556 }
557 }
558 }
559
560 if (GetSendAcks()) {
561 char packet_checksum_cstr[3];
562 packet_checksum_cstr[0] = m_bytes[checksum_idx];
563 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
564 packet_checksum_cstr[2] = '\0';
565 long packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
566
567 long actual_checksum = CalculcateChecksum(
568 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
569 bool success = packet_checksum == actual_checksum;
570 if (!success) {
571 if (log)
572 log->Printf(
573 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
574 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
575 (uint8_t)actual_checksum);
576 }
577 // Send the ack or nack if needed
578 if (!success) {
579 SendNack();
580 m_bytes.erase(0, size_of_first_packet);
581 return false;
582 } else {
583 SendAck();
584 }
585 }
586
587 if (m_bytes[1] == 'N') {
588 // This packet was not compressed -- delete the 'N' character at the
589 // start and the packet may be processed as-is.
590 m_bytes.erase(1, 1);
591 return true;
592 }
593
594 // Reverse the gdb-remote binary escaping that was done to the compressed text
595 // to
596 // guard characters like '$', '#', '}', etc.
597 std::vector<uint8_t> unescaped_content;
598 unescaped_content.reserve(content_length);
599 size_t i = content_start;
600 while (i < hash_mark_idx) {
601 if (m_bytes[i] == '}') {
602 i++;
603 unescaped_content.push_back(m_bytes[i] ^ 0x20);
604 } else {
605 unescaped_content.push_back(m_bytes[i]);
606 }
607 i++;
608 }
609
610 uint8_t *decompressed_buffer = nullptr;
611 size_t decompressed_bytes = 0;
612
613 if (decompressed_bufsize != ULONG_MAX) {
614 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize + 1);
615 if (decompressed_buffer == nullptr) {
616 m_bytes.erase(0, size_of_first_packet);
617 return false;
618 }
619 }
620
621#if defined(HAVE_LIBCOMPRESSION)
622 // libcompression is weak linked so check that compression_decode_buffer() is
623 // available
624 if (compression_decode_buffer != NULL &&
625 (m_compression_type == CompressionType::ZlibDeflate ||
626 m_compression_type == CompressionType::LZFSE ||
627 m_compression_type == CompressionType::LZ4)) {
628 compression_algorithm compression_type;
629 if (m_compression_type == CompressionType::ZlibDeflate)
630 compression_type = COMPRESSION_ZLIB;
631 else if (m_compression_type == CompressionType::LZFSE)
632 compression_type = COMPRESSION_LZFSE;
633 else if (m_compression_type == CompressionType::LZ4)
634 compression_type = COMPRESSION_LZ4_RAW;
635 else if (m_compression_type == CompressionType::LZMA)
636 compression_type = COMPRESSION_LZMA;
637
638 // If we have the expected size of the decompressed payload, we can allocate
639 // the right-sized buffer and do it. If we don't have that information,
640 // we'll
641 // need to try decoding into a big buffer and if the buffer wasn't big
642 // enough,
643 // increase it and try again.
644
645 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
646 decompressed_bytes = compression_decode_buffer(
647 decompressed_buffer, decompressed_bufsize + 10,
648 (uint8_t *)unescaped_content.data(), unescaped_content.size(), NULL,
649 compression_type);
650 }
651 }
652#endif
653
654#if defined(HAVE_LIBZ)
655 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
656 decompressed_buffer != nullptr &&
657 m_compression_type == CompressionType::ZlibDeflate) {
658 z_stream stream;
659 memset(&stream, 0, sizeof(z_stream));
660 stream.next_in = (Bytef *)unescaped_content.data();
661 stream.avail_in = (uInt)unescaped_content.size();
662 stream.total_in = 0;
663 stream.next_out = (Bytef *)decompressed_buffer;
664 stream.avail_out = decompressed_bufsize;
665 stream.total_out = 0;
666 stream.zalloc = Z_NULL;
667 stream.zfree = Z_NULL;
668 stream.opaque = Z_NULL;
669
670 if (inflateInit2(&stream, -15) == Z_OK) {
671 int status = inflate(&stream, Z_NO_FLUSH);
672 inflateEnd(&stream);
673 if (status == Z_STREAM_END) {
674 decompressed_bytes = stream.total_out;
675 }
676 }
677 }
678#endif
679
680 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
681 if (decompressed_buffer)
682 free(decompressed_buffer);
683 m_bytes.erase(0, size_of_first_packet);
684 return false;
685 }
686
687 std::string new_packet;
688 new_packet.reserve(decompressed_bytes + 6);
689 new_packet.push_back(m_bytes[0]);
690 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
691 new_packet.push_back('#');
692 if (GetSendAcks()) {
693 uint8_t decompressed_checksum = CalculcateChecksum(
694 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
695 char decompressed_checksum_str[3];
696 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
697 new_packet.append(decompressed_checksum_str);
698 } else {
699 new_packet.push_back('0');
700 new_packet.push_back('0');
701 }
702
703 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
704 new_packet.size());
705
706 free(decompressed_buffer);
707 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000708}
709
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000710GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
712 StringExtractorGDBRemote &packet) {
713 // Put the packet data into the buffer in a thread safe fashion
714 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000715
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000717
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 if (src && src_len > 0) {
719 if (log && log->GetVerbose()) {
720 StreamString s;
721 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
722 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
723 }
724 m_bytes.append((const char *)src, src_len);
725 }
726
727 bool isNotifyPacket = false;
728
729 // Parse up the packets into gdb remote packets
730 if (!m_bytes.empty()) {
731 // end_idx must be one past the last valid packet byte. Start
732 // it off with an invalid value that is the same as the current
733 // index.
734 size_t content_start = 0;
735 size_t content_length = 0;
736 size_t total_length = 0;
737 size_t checksum_idx = std::string::npos;
738
739 // Size of packet before it is decompressed, for logging purposes
740 size_t original_packet_size = m_bytes.size();
741 if (CompressionIsEnabled()) {
742 if (DecompressPacket() == false) {
743 packet.Clear();
744 return GDBRemoteCommunication::PacketType::Standard;
745 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000746 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000747
Kate Stoneb9c1b512016-09-06 20:57:50 +0000748 switch (m_bytes[0]) {
749 case '+': // Look for ack
750 case '-': // Look for cancel
751 case '\x03': // ^C to halt target
752 content_length = total_length = 1; // The command is one byte long...
753 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000754
Kate Stoneb9c1b512016-09-06 20:57:50 +0000755 case '%': // Async notify packet
756 isNotifyPacket = true;
757 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000758
Kate Stoneb9c1b512016-09-06 20:57:50 +0000759 case '$':
760 // Look for a standard gdb packet?
761 {
762 size_t hash_pos = m_bytes.find('#');
763 if (hash_pos != std::string::npos) {
764 if (hash_pos + 2 < m_bytes.size()) {
765 checksum_idx = hash_pos + 1;
766 // Skip the dollar sign
767 content_start = 1;
768 // Don't include the # in the content or the $ in the content length
769 content_length = hash_pos - 1;
770
771 total_length =
772 hash_pos + 3; // Skip the # and the two hex checksum bytes
773 } else {
774 // Checksum bytes aren't all here yet
775 content_length = std::string::npos;
776 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000777 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000778 }
779 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000780
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 default: {
782 // We have an unexpected byte and we need to flush all bad
783 // data that is in m_bytes, so we need to find the first
784 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
785 // or '$' character (start of packet header) or of course,
786 // the end of the data in m_bytes...
787 const size_t bytes_len = m_bytes.size();
788 bool done = false;
789 uint32_t idx;
790 for (idx = 1; !done && idx < bytes_len; ++idx) {
791 switch (m_bytes[idx]) {
792 case '+':
793 case '-':
794 case '\x03':
795 case '%':
796 case '$':
797 done = true;
798 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000799
Kate Stoneb9c1b512016-09-06 20:57:50 +0000800 default:
801 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000802 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803 }
804 if (log)
805 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
806 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
807 m_bytes.erase(0, idx - 1);
808 } break;
809 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000810
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 if (content_length == std::string::npos) {
812 packet.Clear();
813 return GDBRemoteCommunication::PacketType::Invalid;
814 } else if (total_length > 0) {
815
816 // We have a valid packet...
817 assert(content_length <= m_bytes.size());
818 assert(total_length <= m_bytes.size());
819 assert(content_length <= total_length);
820 size_t content_end = content_start + content_length;
821
822 bool success = true;
823 std::string &packet_str = packet.GetStringRef();
824 if (log) {
825 // If logging was just enabled and we have history, then dump out what
826 // we have to the log so we get the historical context. The Dump() call
827 // that
828 // logs all of the packet will set a boolean so that we don't dump this
829 // more
830 // than once
831 if (!m_history.DidDumpToLog())
832 m_history.Dump(log);
833
834 bool binary = false;
835 // Only detect binary for packets that start with a '$' and have a '#CC'
836 // checksum
837 if (m_bytes[0] == '$' && total_length > 4) {
838 for (size_t i = 0; !binary && i < total_length; ++i) {
839 if (isprint(m_bytes[i]) == 0 && isspace(m_bytes[i]) == 0) {
840 binary = true;
841 }
842 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000843 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000844 if (binary) {
845 StreamString strm;
846 // Packet header...
847 if (CompressionIsEnabled())
848 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
849 (uint64_t)original_packet_size, (uint64_t)total_length,
850 m_bytes[0]);
851 else
852 strm.Printf("<%4" PRIu64 "> read packet: %c",
853 (uint64_t)total_length, m_bytes[0]);
854 for (size_t i = content_start; i < content_end; ++i) {
855 // Remove binary escaped bytes when displaying the packet...
856 const char ch = m_bytes[i];
857 if (ch == 0x7d) {
858 // 0x7d is the escape character. The next character is to
859 // be XOR'd with 0x20.
860 const char escapee = m_bytes[++i] ^ 0x20;
861 strm.Printf("%2.2x", escapee);
862 } else {
863 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000864 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865 }
866 // Packet footer...
867 strm.Printf("%c%c%c", m_bytes[total_length - 3],
868 m_bytes[total_length - 2], m_bytes[total_length - 1]);
869 log->PutCString(strm.GetString().c_str());
870 } else {
871 if (CompressionIsEnabled())
872 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
873 (uint64_t)original_packet_size, (uint64_t)total_length,
874 (int)(total_length), m_bytes.c_str());
875 else
876 log->Printf("<%4" PRIu64 "> read packet: %.*s",
877 (uint64_t)total_length, (int)(total_length),
878 m_bytes.c_str());
879 }
880 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000881
Kate Stoneb9c1b512016-09-06 20:57:50 +0000882 m_history.AddPacket(m_bytes.c_str(), total_length,
883 History::ePacketTypeRecv, total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000884
Kate Stoneb9c1b512016-09-06 20:57:50 +0000885 // Clear packet_str in case there is some existing data in it.
886 packet_str.clear();
887 // Copy the packet from m_bytes to packet_str expanding the
888 // run-length encoding in the process.
889 // Reserve enough byte for the most common case (no RLE used)
890 packet_str.reserve(m_bytes.length());
891 for (std::string::const_iterator c = m_bytes.begin() + content_start;
892 c != m_bytes.begin() + content_end; ++c) {
893 if (*c == '*') {
894 // '*' indicates RLE. Next character will give us the
895 // repeat count and previous character is what is to be
896 // repeated.
897 char char_to_repeat = packet_str.back();
898 // Number of time the previous character is repeated
899 int repeat_count = *++c + 3 - ' ';
900 // We have the char_to_repeat and repeat_count. Now push
901 // it in the packet.
902 for (int i = 0; i < repeat_count; ++i)
903 packet_str.push_back(char_to_repeat);
904 } else if (*c == 0x7d) {
905 // 0x7d is the escape character. The next character is to
906 // be XOR'd with 0x20.
907 char escapee = *++c ^ 0x20;
908 packet_str.push_back(escapee);
909 } else {
910 packet_str.push_back(*c);
911 }
912 }
913
914 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
915 assert(checksum_idx < m_bytes.size());
916 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
917 ::isxdigit(m_bytes[checksum_idx + 1])) {
918 if (GetSendAcks()) {
919 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
920 char packet_checksum = strtol(packet_checksum_cstr, NULL, 16);
921 char actual_checksum = CalculcateChecksum(packet_str);
922 success = packet_checksum == actual_checksum;
923 if (!success) {
924 if (log)
925 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
926 "got 0x%2.2x",
927 (int)(total_length), m_bytes.c_str(),
928 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000929 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000930 // Send the ack or nack if needed
931 if (!success)
932 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000933 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000934 SendAck();
935 }
936 } else {
937 success = false;
938 if (log)
939 log->Printf("error: invalid checksum in packet: '%s'\n",
940 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000941 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 }
943
944 m_bytes.erase(0, total_length);
945 packet.SetFilePos(0);
946
947 if (isNotifyPacket)
948 return GDBRemoteCommunication::PacketType::Notify;
949 else
950 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000951 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 }
953 packet.Clear();
954 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000955}
956
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957Error GDBRemoteCommunication::StartListenThread(const char *hostname,
958 uint16_t port) {
959 Error error;
960 if (m_listen_thread.IsJoinable()) {
961 error.SetErrorString("listen thread already running");
962 } else {
963 char listen_url[512];
964 if (hostname && hostname[0])
965 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
966 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000967 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
969 m_listen_url = listen_url;
970 SetConnection(new ConnectionFileDescriptor());
971 m_listen_thread = ThreadLauncher::LaunchThread(
972 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
973 }
974 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000975}
976
Kate Stoneb9c1b512016-09-06 20:57:50 +0000977bool GDBRemoteCommunication::JoinListenThread() {
978 if (m_listen_thread.IsJoinable())
979 m_listen_thread.Join(nullptr);
980 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000981}
982
983lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000984GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
985 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
986 Error error;
987 ConnectionFileDescriptor *connection =
988 (ConnectionFileDescriptor *)comm->GetConnection();
989
990 if (connection) {
991 // Do the listen on another thread so we can continue on...
992 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
993 eConnectionStatusSuccess)
994 comm->SetConnection(NULL);
995 }
996 return NULL;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000997}
998
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999Error GDBRemoteCommunication::StartDebugserverProcess(
1000 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
1001 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
1002 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1003 if (log)
1004 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
1005 __FUNCTION__, url ? url : "<empty>",
1006 port ? *port : uint16_t(0));
1007
1008 Error error;
1009 // If we locate debugserver, keep that located version around
1010 static FileSpec g_debugserver_file_spec;
1011
1012 char debugserver_path[PATH_MAX];
1013 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
1014
1015 // Always check to see if we have an environment override for the path
1016 // to the debugserver to use and use it if we do.
1017 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1018 if (env_debugserver_path) {
1019 debugserver_file_spec.SetFile(env_debugserver_path, false);
Todd Fiala015d8182014-07-22 23:41:36 +00001020 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
1022 "from environment variable: %s",
1023 __FUNCTION__, env_debugserver_path);
1024 } else
1025 debugserver_file_spec = g_debugserver_file_spec;
1026 bool debugserver_exists = debugserver_file_spec.Exists();
1027 if (!debugserver_exists) {
1028 // The debugserver binary is in the LLDB.framework/Resources
1029 // directory.
1030 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir,
1031 debugserver_file_spec)) {
1032 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
1033 debugserver_exists = debugserver_file_spec.Exists();
1034 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +00001035 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036 log->Printf(
1037 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
1038 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +00001039
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 g_debugserver_file_spec = debugserver_file_spec;
1041 } else {
1042 debugserver_file_spec =
1043 platform->LocateExecutable(DEBUGSERVER_BASENAME);
1044 if (debugserver_file_spec) {
1045 // Platform::LocateExecutable() wouldn't return a path if it doesn't
1046 // exist
1047 debugserver_exists = true;
1048 } else {
1049 if (log)
1050 log->Printf("GDBRemoteCommunication::%s() could not find "
1051 "gdb-remote stub exe '%s'",
1052 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +00001053 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 // Don't cache the platform specific GDB server binary as it could
1055 // change
1056 // from platform to platform
1057 g_debugserver_file_spec.Clear();
1058 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001059 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001061
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 if (debugserver_exists) {
1063 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001064
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065 Args &debugserver_args = launch_info.GetArguments();
1066 debugserver_args.Clear();
1067 char arg_cstr[PATH_MAX];
1068
1069 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001070 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001071
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001072#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001073 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001074 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001075#endif
1076
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 // If a url is supplied then use it
1078 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001079 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001080
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 if (pass_comm_fd >= 0) {
1082 StreamString fd_arg;
1083 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001084 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 // Send "pass_comm_fd" down to the inferior so it can use it to
1086 // communicate back with this process
1087 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1088 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001089
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001091 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001092
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001094 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001096
Kate Stoneb9c1b512016-09-06 20:57:50 +00001097 llvm::SmallString<PATH_MAX> named_pipe_path;
1098 // socket_pipe is used by debug server to communicate back either
1099 // TCP port or domain socket name which it listens on.
1100 // The second purpose of the pipe to serve as a synchronization point -
1101 // once data is written to the pipe, debug server is up and running.
1102 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001103
Kate Stoneb9c1b512016-09-06 20:57:50 +00001104 // port is null when debug server should listen on domain socket -
1105 // we're not interested in port value but rather waiting for debug server
1106 // to become available.
1107 if (pass_comm_fd == -1 &&
1108 ((port != nullptr && *port == 0) || port == nullptr)) {
1109 if (url) {
1110// Create a temporary file to get the stdout/stderr and redirect the
1111// output of the command into this file. We will later read this file
1112// if all goes well and fill the data into "command_output_ptr"
1113
Chaoren Lin46951b52015-07-30 17:48:44 +00001114#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001115 // Binding to port zero, we need to figure out what port it ends up
1116 // using using a named pipe...
1117 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1118 false, named_pipe_path);
1119 if (error.Fail()) {
1120 if (log)
1121 log->Printf("GDBRemoteCommunication::%s() "
1122 "named pipe creation failed: %s",
1123 __FUNCTION__, error.AsCString());
1124 return error;
1125 }
Sean Callanan1355f472016-09-19 22:06:12 +00001126 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1127 debugserver_args.AppendArgument(
1128 llvm::StringRef(named_pipe_path.c_str()));
Chaoren Lin46951b52015-07-30 17:48:44 +00001129#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 // Binding to port zero, we need to figure out what port it ends up
1131 // using using an unnamed pipe...
1132 error = socket_pipe.CreateNew(true);
1133 if (error.Fail()) {
1134 if (log)
1135 log->Printf("GDBRemoteCommunication::%s() "
1136 "unnamed pipe creation failed: %s",
1137 __FUNCTION__, error.AsCString());
1138 return error;
1139 }
1140 int write_fd = socket_pipe.GetWriteFileDescriptor();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001141 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1142 debugserver_args.AppendArgument(llvm::to_string(write_fd));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001143 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001144#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001145 } else {
1146 // No host and port given, so lets listen on our end and make the
1147 // debugserver
1148 // connect to us..
1149 error = StartListenThread("127.0.0.1", 0);
1150 if (error.Fail()) {
1151 if (log)
1152 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1153 "thread: %s",
1154 __FUNCTION__, error.AsCString());
1155 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001156 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001157
1158 ConnectionFileDescriptor *connection =
1159 (ConnectionFileDescriptor *)GetConnection();
1160 // Wait for 10 seconds to resolve the bound port
1161 uint16_t port_ = connection->GetListeningPort(10);
1162 if (port_ > 0) {
1163 char port_cstr[32];
1164 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1165 // Send the host and port down that debugserver and specify an option
1166 // so that it connects back to the port we are listening to in this
1167 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001168 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1169 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001170 if (port)
1171 *port = port_;
1172 } else {
1173 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1174 if (log)
1175 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1176 error.AsCString());
1177 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001178 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001179 }
1180 }
1181
1182 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1183 if (env_debugserver_log_file) {
1184 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-file=%s",
1185 env_debugserver_log_file);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001186 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001187 }
1188
Vince Harron9753dd92015-05-10 15:22:09 +00001189#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001190 const char *env_debugserver_log_flags =
1191 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1192 if (env_debugserver_log_flags) {
1193 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-flags=%s",
1194 env_debugserver_log_flags);
Sean Callanan1355f472016-09-19 22:06:12 +00001195 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001196 }
Vince Harron9753dd92015-05-10 15:22:09 +00001197#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001198 const char *env_debugserver_log_channels =
1199 getenv("LLDB_SERVER_LOG_CHANNELS");
1200 if (env_debugserver_log_channels) {
1201 ::snprintf(arg_cstr, sizeof(arg_cstr), "--log-channels=%s",
1202 env_debugserver_log_channels);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001203 debugserver_args.AppendArgument(llvm::StringRef(arg_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001204 }
Vince Harron9753dd92015-05-10 15:22:09 +00001205#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001206
Kate Stoneb9c1b512016-09-06 20:57:50 +00001207 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1208 // env var doesn't come back.
1209 uint32_t env_var_index = 1;
1210 bool has_env_var;
1211 do {
1212 char env_var_name[64];
1213 snprintf(env_var_name, sizeof(env_var_name),
1214 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1215 const char *extra_arg = getenv(env_var_name);
1216 has_env_var = extra_arg != nullptr;
Todd Fiala34ba4262014-08-29 17:10:31 +00001217
Kate Stoneb9c1b512016-09-06 20:57:50 +00001218 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001219 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001220 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001221 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1222 "to stub command line (%s)",
1223 __FUNCTION__, env_var_name, extra_arg);
1224 }
1225 } while (has_env_var);
1226
1227 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001228 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001229 debugserver_args.AppendArguments(*inferior_args);
1230 }
1231
1232 // Copy the current environment to the gdbserver/debugserver instance
1233 StringList env;
1234 if (Host::GetEnvironment(env)) {
1235 for (size_t i = 0; i < env.GetSize(); ++i)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001236 launch_info.GetEnvironmentEntries().AppendArgument(env[i]);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001237 }
1238
1239 // Close STDIN, STDOUT and STDERR.
1240 launch_info.AppendCloseFileAction(STDIN_FILENO);
1241 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1242 launch_info.AppendCloseFileAction(STDERR_FILENO);
1243
1244 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1245 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1246 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1247 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1248
1249 if (log) {
1250 StreamString string_stream;
1251 Platform *const platform = nullptr;
1252 launch_info.Dump(string_stream, platform);
1253 log->Printf("launch info for gdb-remote stub:\n%s",
1254 string_stream.GetString().c_str());
1255 }
1256 error = Host::LaunchProcess(launch_info);
1257
1258 if (error.Success() &&
1259 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1260 pass_comm_fd == -1) {
1261 if (named_pipe_path.size() > 0) {
1262 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1263 if (error.Fail())
1264 if (log)
1265 log->Printf("GDBRemoteCommunication::%s() "
1266 "failed to open named pipe %s for reading: %s",
1267 __FUNCTION__, named_pipe_path.c_str(),
1268 error.AsCString());
1269 }
1270
1271 if (socket_pipe.CanWrite())
1272 socket_pipe.CloseWriteFileDescriptor();
1273 if (socket_pipe.CanRead()) {
1274 char port_cstr[PATH_MAX] = {0};
1275 port_cstr[0] = '\0';
1276 size_t num_bytes = sizeof(port_cstr);
1277 // Read port from pipe with 10 second timeout.
1278 error = socket_pipe.ReadWithTimeout(
1279 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1280 if (error.Success() && (port != nullptr)) {
1281 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
1282 *port = StringConvert::ToUInt32(port_cstr, 0);
1283 if (log)
1284 log->Printf("GDBRemoteCommunication::%s() "
1285 "debugserver listens %u port",
1286 __FUNCTION__, *port);
1287 } else {
1288 if (log)
1289 log->Printf("GDBRemoteCommunication::%s() "
1290 "failed to read a port value from pipe %s: %s",
1291 __FUNCTION__, named_pipe_path.c_str(),
1292 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001293 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001294 socket_pipe.Close();
1295 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001296
Kate Stoneb9c1b512016-09-06 20:57:50 +00001297 if (named_pipe_path.size() > 0) {
1298 const auto err = socket_pipe.Delete(named_pipe_path);
1299 if (err.Fail()) {
1300 if (log)
1301 log->Printf(
1302 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1303 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001304 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001305 }
1306
1307 // Make sure we actually connect with the debugserver...
1308 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001309 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310 } else {
1311 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1312 }
Vince Harron8b335672015-05-12 01:10:56 +00001313
Kate Stoneb9c1b512016-09-06 20:57:50 +00001314 if (error.Fail()) {
1315 if (log)
1316 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1317 error.AsCString());
1318 }
Vince Harron8b335672015-05-12 01:10:56 +00001319
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001321}
1322
Kate Stoneb9c1b512016-09-06 20:57:50 +00001323void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1324
1325GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1326 GDBRemoteCommunication &gdb_comm, uint32_t timeout)
1327 : m_gdb_comm(gdb_comm) {
1328 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
Greg Claytonc1422c12012-04-09 22:46:21 +00001329}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001330
Kate Stoneb9c1b512016-09-06 20:57:50 +00001331GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1332 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001333}
1334
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335// This function is called via the Communications class read thread when bytes
1336// become available
1337// for this connection. This function will consume all incoming bytes and try to
1338// parse whole
1339// packets as they become available. Full packets are placed in a queue, so that
1340// all packet
1341// requests can simply pop from this queue. Async notification packets will be
1342// dispatched
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001343// immediately to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001344void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1345 size_t len, bool broadcast,
1346 lldb::ConnectionStatus status) {
1347 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001348
Kate Stoneb9c1b512016-09-06 20:57:50 +00001349 while (true) {
1350 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001351
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352 // scrub the data so we do not pass it back to CheckForPacket
1353 // on future passes of the loop
1354 bytes = nullptr;
1355 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001356
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357 // we may have received no packet so lets bail out
1358 if (type == PacketType::Invalid)
1359 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001360
Kate Stoneb9c1b512016-09-06 20:57:50 +00001361 if (type == PacketType::Standard) {
1362 // scope for the mutex
1363 {
1364 // lock down the packet queue
1365 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1366 // push a new packet into the queue
1367 m_packet_queue.push(packet);
1368 // Signal condition variable that we have a packet
1369 m_condition_queue_not_empty.notify_one();
1370 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001371 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372
1373 if (type == PacketType::Notify) {
1374 // put this packet into an event
1375 const char *pdata = packet.GetStringRef().c_str();
1376
1377 // as the communication class, we are a broadcaster and the
1378 // async thread is tuned to listen to us
1379 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1380 new EventDataBytes(pdata));
1381 }
1382 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001383}