blob: ac3a6df75df41255ce298cffaa4d1c9572b46c9f [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
10
11#include "GDBRemoteCommunication.h"
12
13// C Includes
Johnny Chena5663552011-05-13 20:07:25 +000014#include <limits.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015#include <string.h>
Greg Clayton91a9b2472013-12-04 19:19:12 +000016#include <sys/stat.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000017
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018// C++ Includes
19// Other libraries and framework includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Log.h"
Greg Claytonb30c50c2015-05-29 00:01:55 +000021#include "lldb/Core/RegularExpression.h"
Greg Claytonc1422c12012-04-09 22:46:21 +000022#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000024#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000025#include "lldb/Host/FileSpec.h"
26#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000027#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000028#include "lldb/Host/Pipe.h"
Zachary Turner98688922014-08-06 18:16:26 +000029#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000030#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000031#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032#include "lldb/Host/TimeValue.h"
Greg Clayton6988abc2015-10-19 20:44:01 +000033#include "lldb/Target/Platform.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000034#include "lldb/Target/Process.h"
Oleksiy Vyalov4536c452015-02-05 16:29:12 +000035#include "llvm/ADT/SmallString.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__)
41# define DEBUGSERVER_BASENAME "debugserver"
42#else
Tamas Berghammerc2c3d712015-02-18 15:39:41 +000043# define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000044#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000045
Jason Molenda91ffe0a2015-06-18 21:46:06 +000046#if defined (HAVE_LIBCOMPRESSION)
47#include <compression.h>
48#endif
49
50#if defined (HAVE_LIBZ)
51#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
Greg Claytonc1422c12012-04-09 22:46:21 +000058GDBRemoteCommunication::History::History (uint32_t size) :
59 m_packets(),
60 m_curr_idx (0),
61 m_total_packet_count (0),
62 m_dumped_to_log (false)
63{
64 m_packets.resize(size);
65}
66
67GDBRemoteCommunication::History::~History ()
68{
69}
70
71void
Greg Claytond451c1a2012-04-13 21:24:18 +000072GDBRemoteCommunication::History::AddPacket (char packet_char,
73 PacketType type,
74 uint32_t bytes_transmitted)
75{
76 const size_t size = m_packets.size();
77 if (size > 0)
78 {
79 const uint32_t idx = GetNextIndex();
80 m_packets[idx].packet.assign (1, packet_char);
81 m_packets[idx].type = type;
82 m_packets[idx].bytes_transmitted = bytes_transmitted;
83 m_packets[idx].packet_idx = m_total_packet_count;
84 m_packets[idx].tid = Host::GetCurrentThreadID();
85 }
86}
87
88void
89GDBRemoteCommunication::History::AddPacket (const std::string &src,
90 uint32_t src_len,
91 PacketType type,
92 uint32_t bytes_transmitted)
93{
94 const size_t size = m_packets.size();
95 if (size > 0)
96 {
97 const uint32_t idx = GetNextIndex();
98 m_packets[idx].packet.assign (src, 0, src_len);
99 m_packets[idx].type = type;
100 m_packets[idx].bytes_transmitted = bytes_transmitted;
101 m_packets[idx].packet_idx = m_total_packet_count;
102 m_packets[idx].tid = Host::GetCurrentThreadID();
103 }
104}
105
106void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000107GDBRemoteCommunication::History::Dump (Stream &strm) const
Greg Claytonc1422c12012-04-09 22:46:21 +0000108{
109 const uint32_t size = GetNumPacketsInHistory ();
110 const uint32_t first_idx = GetFirstSavedPacketIndex ();
111 const uint32_t stop_idx = m_curr_idx + size;
112 for (uint32_t i = first_idx; i < stop_idx; ++i)
113 {
114 const uint32_t idx = NormalizeIndex (i);
115 const Entry &entry = m_packets[idx];
116 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
117 break;
Daniel Malead01b2952012-11-29 21:49:15 +0000118 strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
Greg Claytonc1422c12012-04-09 22:46:21 +0000119 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +0000120 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000121 entry.bytes_transmitted,
122 (entry.type == ePacketTypeSend) ? "send" : "read",
123 entry.packet.c_str());
124 }
125}
126
127void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000128GDBRemoteCommunication::History::Dump (Log *log) const
Greg Claytonc1422c12012-04-09 22:46:21 +0000129{
130 if (log && !m_dumped_to_log)
131 {
132 m_dumped_to_log = true;
133 const uint32_t size = GetNumPacketsInHistory ();
134 const uint32_t first_idx = GetFirstSavedPacketIndex ();
135 const uint32_t stop_idx = m_curr_idx + size;
136 for (uint32_t i = first_idx; i < stop_idx; ++i)
137 {
138 const uint32_t idx = NormalizeIndex (i);
139 const Entry &entry = m_packets[idx];
140 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
141 break;
Daniel Malead01b2952012-11-29 21:49:15 +0000142 log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
Greg Claytonc1422c12012-04-09 22:46:21 +0000143 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +0000144 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000145 entry.bytes_transmitted,
146 (entry.type == ePacketTypeSend) ? "send" : "read",
147 entry.packet.c_str());
148 }
149 }
150}
151
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000152//----------------------------------------------------------------------
153// GDBRemoteCommunication constructor
154//----------------------------------------------------------------------
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000155GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name, const char *listener_name)
156 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000157#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000158 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000159#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000160 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000161#endif
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000162 m_echo_number(0),
163 m_supports_qEcho(eLazyBoolCalculate),
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000164 m_history(512),
165 m_send_acks(true),
166 m_compression_type(CompressionType::None),
167 m_listen_url()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000168{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000169}
170
171//----------------------------------------------------------------------
172// Destructor
173//----------------------------------------------------------------------
174GDBRemoteCommunication::~GDBRemoteCommunication()
175{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000176 if (IsConnected())
177 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000178 Disconnect();
179 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000180
181 // Stop the communications read thread which is used to parse all
182 // incoming packets. This function will block until the read
183 // thread returns.
184 if (m_read_thread_enabled)
185 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000186}
187
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000188char
189GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
190{
191 int checksum = 0;
192
Ed Mastea6b4c772013-08-20 14:12:58 +0000193 for (size_t i = 0; i < payload_length; ++i)
194 checksum += payload[i];
195
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000196 return checksum & 255;
197}
198
199size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000200GDBRemoteCommunication::SendAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000201{
Greg Clayton5160ce52013-03-27 23:08:40 +0000202 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000204 char ch = '+';
205 const size_t bytes_written = Write (&ch, 1, status, NULL);
206 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000207 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000208 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
209 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000210}
211
212size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000213GDBRemoteCommunication::SendNack ()
214{
Greg Clayton5160ce52013-03-27 23:08:40 +0000215 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton6ed95942011-01-22 07:12:45 +0000216 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000217 char ch = '-';
218 const size_t bytes_written = Write (&ch, 1, status, NULL);
219 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000220 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000221 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
222 return bytes_written;
Greg Clayton32e0a752011-03-30 18:16:51 +0000223}
224
Greg Clayton3dedae12013-12-06 21:45:27 +0000225GDBRemoteCommunication::PacketResult
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000226GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
227{
228 if (IsConnected())
229 {
230 StreamString packet(0, 4, eByteOrderBig);
231
232 packet.PutChar('$');
233 packet.Write (payload, payload_length);
234 packet.PutChar('#');
235 packet.PutHex8(CalculcateChecksum (payload, payload_length));
236
Greg Clayton5160ce52013-03-27 23:08:40 +0000237 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000238 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton7e244322014-09-18 00:17:36 +0000239 const char *packet_data = packet.GetData();
240 const size_t packet_length = packet.GetSize();
241 size_t bytes_written = Write (packet_data, packet_length, status, NULL);
Greg Claytonc1422c12012-04-09 22:46:21 +0000242 if (log)
243 {
Greg Clayton7e244322014-09-18 00:17:36 +0000244 size_t binary_start_offset = 0;
245 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == 0)
246 {
247 const char *first_comma = strchr(packet_data, ',');
248 if (first_comma)
249 {
250 const char *second_comma = strchr(first_comma + 1, ',');
251 if (second_comma)
252 binary_start_offset = second_comma - packet_data + 1;
253 }
254 }
255
Greg Claytonc1422c12012-04-09 22:46:21 +0000256 // If logging was just enabled and we have history, then dump out what
257 // we have to the log so we get the historical context. The Dump() call that
258 // logs all of the packet will set a boolean so that we don't dump this more
259 // than once
260 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000261 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000262
Greg Clayton7e244322014-09-18 00:17:36 +0000263 if (binary_start_offset)
264 {
265 StreamString strm;
266 // Print non binary data header
267 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)binary_start_offset, packet_data);
268 const uint8_t *p;
269 // Print binary data exactly as sent
Vince Harron8b335672015-05-12 01:10:56 +0000270 for (p = (const uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p)
Greg Clayton7e244322014-09-18 00:17:36 +0000271 strm.Printf("\\x%2.2x", *p);
272 // Print the checksum
273 strm.Printf("%*s", (int)3, p);
274 log->PutCString(strm.GetString().c_str());
275 }
276 else
277 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet_length, packet_data);
Greg Claytonc1422c12012-04-09 22:46:21 +0000278 }
279
Greg Clayton7e244322014-09-18 00:17:36 +0000280 m_history.AddPacket (packet.GetString(), packet_length, History::ePacketTypeSend, bytes_written);
Greg Claytonc1422c12012-04-09 22:46:21 +0000281
282
Greg Clayton7e244322014-09-18 00:17:36 +0000283 if (bytes_written == packet_length)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000284 {
Greg Clayton71fc2a32011-02-12 06:28:37 +0000285 if (GetSendAcks ())
Greg Clayton3dedae12013-12-06 21:45:27 +0000286 return GetAck ();
287 else
288 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289 }
Johnny Chend0c40dd2010-09-14 22:10:43 +0000290 else
291 {
Greg Clayton6d093452011-02-05 02:25:06 +0000292 if (log)
Greg Clayton7e244322014-09-18 00:17:36 +0000293 log->Printf ("error: failed to send packet: %.*s", (int)packet_length, packet_data);
Johnny Chend0c40dd2010-09-14 22:10:43 +0000294 }
Greg Claytonf5e56de2010-09-14 23:36:40 +0000295 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000296 return PacketResult::ErrorSendFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000297}
298
Greg Clayton3dedae12013-12-06 21:45:27 +0000299GDBRemoteCommunication::PacketResult
Greg Claytonc574ede2011-03-10 02:26:48 +0000300GDBRemoteCommunication::GetAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000301{
Greg Clayton576d8832011-03-22 04:00:09 +0000302 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000303 PacketResult result = ReadPacket (packet, GetPacketTimeoutInMicroSeconds (), false);
Greg Clayton3dedae12013-12-06 21:45:27 +0000304 if (result == PacketResult::Success)
305 {
306 if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
307 return PacketResult::Success;
308 else
309 return PacketResult::ErrorSendAck;
310 }
311 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312}
313
Greg Clayton3dedae12013-12-06 21:45:27 +0000314GDBRemoteCommunication::PacketResult
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000315GDBRemoteCommunication::ReadPacket (StringExtractorGDBRemote &response, uint32_t timeout_usec, bool sync_on_timeout)
316{
317 if (m_read_thread_enabled)
318 return PopPacketFromQueue (response, timeout_usec);
319 else
320 return WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec, sync_on_timeout);
321}
322
323
324// This function is called when a packet is requested.
325// A whole packet is popped from the packet queue and returned to the caller.
326// Packets are placed into this queue from the communication read thread.
327// See GDBRemoteCommunication::AppendBytesToCache.
328GDBRemoteCommunication::PacketResult
329GDBRemoteCommunication::PopPacketFromQueue (StringExtractorGDBRemote &response, uint32_t timeout_usec)
330{
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000331 auto until = std::chrono::system_clock::now() + std::chrono::microseconds(timeout_usec);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000332
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000333 while (true)
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000334 {
335 // scope for the mutex
336 {
337 // lock down the packet queue
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000338 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000339
340 // Wait on condition variable.
341 if (m_packet_queue.size() == 0)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000342 {
343 std::cv_status result = m_condition_queue_not_empty.wait_until(lock, until);
344 if (result == std::cv_status::timeout)
345 break;
346 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000347
348 if (m_packet_queue.size() > 0)
349 {
350 // get the front element of the queue
351 response = m_packet_queue.front();
352
353 // remove the front element
354 m_packet_queue.pop();
355
356 // we got a packet
357 return PacketResult::Success;
358 }
359 }
360
361 // Disconnected
362 if (!IsConnected())
363 return PacketResult::ErrorDisconnected;
364
365 // Loop while not timed out
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +0000366 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000367
368 return PacketResult::ErrorReplyTimeout;
369}
370
371
372GDBRemoteCommunication::PacketResult
Greg Claytonb30c50c2015-05-29 00:01:55 +0000373GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec, bool sync_on_timeout)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374{
Greg Clayton73bf5db2011-06-17 01:22:15 +0000375 uint8_t buffer[8192];
376 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000377
Greg Clayton5160ce52013-03-27 23:08:40 +0000378 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
Greg Clayton644247c2011-07-07 01:59:51 +0000379
Greg Clayton73bf5db2011-06-17 01:22:15 +0000380 // Check for a packet from our cache first without trying any reading...
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000381 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000382 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000383
Greg Clayton0c51ac32011-07-02 23:21:06 +0000384 bool timed_out = false;
Greg Clayton3dedae12013-12-06 21:45:27 +0000385 bool disconnected = false;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000386 while (IsConnected() && !timed_out)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387 {
Johnny Chen74549c82011-07-19 01:13:00 +0000388 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000389 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
Greg Clayton644247c2011-07-07 01:59:51 +0000390
391 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000392 log->Printf ("%s: Read (buffer, (sizeof(buffer), timeout_usec = 0x%x, status = %s, error = %s) => bytes_read = %" PRIu64,
Greg Clayton644247c2011-07-07 01:59:51 +0000393 __PRETTY_FUNCTION__,
394 timeout_usec,
395 Communication::ConnectionStatusAsCString (status),
396 error.AsCString(),
Greg Clayton43e0af02012-09-18 18:04:04 +0000397 (uint64_t)bytes_read);
Greg Clayton644247c2011-07-07 01:59:51 +0000398
Greg Clayton73bf5db2011-06-17 01:22:15 +0000399 if (bytes_read > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000401 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000402 return PacketResult::Success;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000403 }
404 else
405 {
406 switch (status)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407 {
Greg Clayton197bacf2011-07-02 21:07:54 +0000408 case eConnectionStatusTimedOut:
Greg Claytonf0066ad2014-05-02 00:45:31 +0000409 case eConnectionStatusInterrupted:
Greg Claytonb30c50c2015-05-29 00:01:55 +0000410 if (sync_on_timeout)
411 {
412 //------------------------------------------------------------------
413 /// Sync the remote GDB server and make sure we get a response that
414 /// corresponds to what we send.
415 ///
416 /// Sends a "qEcho" packet and makes sure it gets the exact packet
417 /// echoed back. If the qEcho packet isn't supported, we send a qC
418 /// packet and make sure we get a valid thread ID back. We use the
419 /// "qC" packet since its response if very unique: is responds with
420 /// "QC%x" where %x is the thread ID of the current thread. This
421 /// makes the response unique enough from other packet responses to
422 /// ensure we are back on track.
423 ///
424 /// This packet is needed after we time out sending a packet so we
425 /// can ensure that we are getting the response for the packet we
426 /// are sending. There are no sequence IDs in the GDB remote
427 /// protocol (there used to be, but they are not supported anymore)
428 /// so if you timeout sending packet "abc", you might then send
429 /// packet "cde" and get the response for the previous "abc" packet.
430 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
431 /// many responses for packets can look like responses for other
432 /// packets. So if we timeout, we need to ensure that we can get
433 /// back on track. If we can't get back on track, we must
434 /// disconnect.
435 //------------------------------------------------------------------
436 bool sync_success = false;
437 bool got_actual_response = false;
438 // We timed out, we need to sync back up with the
439 char echo_packet[32];
440 int echo_packet_len = 0;
441 RegularExpression response_regex;
442
443 if (m_supports_qEcho == eLazyBoolYes)
444 {
445 echo_packet_len = ::snprintf (echo_packet, sizeof(echo_packet), "qEcho:%u", ++m_echo_number);
446 std::string regex_str = "^";
447 regex_str += echo_packet;
448 regex_str += "$";
449 response_regex.Compile(regex_str.c_str());
450 }
451 else
452 {
453 echo_packet_len = ::snprintf (echo_packet, sizeof(echo_packet), "qC");
454 response_regex.Compile("^QC[0-9A-Fa-f]+$");
455 }
456
457 PacketResult echo_packet_result = SendPacketNoLock (echo_packet, echo_packet_len);
458 if (echo_packet_result == PacketResult::Success)
459 {
460 const uint32_t max_retries = 3;
461 uint32_t successful_responses = 0;
462 for (uint32_t i=0; i<max_retries; ++i)
463 {
464 StringExtractorGDBRemote echo_response;
465 echo_packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (echo_response, timeout_usec, false);
466 if (echo_packet_result == PacketResult::Success)
467 {
468 ++successful_responses;
469 if (response_regex.Execute(echo_response.GetStringRef().c_str()))
470 {
471 sync_success = true;
472 break;
473 }
474 else if (successful_responses == 1)
475 {
476 // We got something else back as the first successful response, it probably is
477 // the response to the packet we actually wanted, so copy it over if this
478 // is the first success and continue to try to get the qEcho response
479 packet = echo_response;
480 got_actual_response = true;
481 }
482 }
483 else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
484 continue; // Packet timed out, continue waiting for a response
485 else
486 break; // Something else went wrong getting the packet back, we failed and are done trying
487 }
488 }
489
490 // We weren't able to sync back up with the server, we must abort otherwise
491 // all responses might not be from the right packets...
492 if (sync_success)
493 {
494 // We timed out, but were able to recover
495 if (got_actual_response)
496 {
497 // We initially timed out, but we did get a response that came in before the successful
498 // reply to our qEcho packet, so lets say everything is fine...
499 return PacketResult::Success;
500 }
501 }
502 else
503 {
504 disconnected = true;
505 Disconnect();
506 }
507 }
Greg Clayton0c51ac32011-07-02 23:21:06 +0000508 timed_out = true;
509 break;
510 case eConnectionStatusSuccess:
511 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
Greg Clayton73bf5db2011-06-17 01:22:15 +0000512 break;
513
514 case eConnectionStatusEndOfFile:
515 case eConnectionStatusNoConnection:
516 case eConnectionStatusLostConnection:
517 case eConnectionStatusError:
Greg Clayton3dedae12013-12-06 21:45:27 +0000518 disconnected = true;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000519 Disconnect();
520 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000521 }
522 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000523 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000524 packet.Clear ();
525 if (disconnected)
526 return PacketResult::ErrorDisconnected;
527 if (timed_out)
528 return PacketResult::ErrorReplyTimeout;
529 else
530 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000531}
532
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000533bool
534GDBRemoteCommunication::DecompressPacket ()
535{
536 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
537
538 if (!CompressionIsEnabled())
539 return true;
540
541 size_t pkt_size = m_bytes.size();
Jason Molendafea77652015-07-14 19:19:07 +0000542
543 // Smallest possible compressed packet is $N#00 - an uncompressed empty reply, most commonly indicating
544 // an unsupported packet. Anything less than 5 characters, it's definitely not a compressed packet.
Jason Molenda21c34ac2015-07-14 04:51:05 +0000545 if (pkt_size < 5)
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000546 return true;
Jason Molendafea77652015-07-14 19:19:07 +0000547
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000548 if (m_bytes[0] != '$' && m_bytes[0] != '%')
549 return true;
550 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
551 return true;
Jason Molendaa21fdb02015-08-02 01:36:09 +0000552
553 size_t hash_mark_idx = m_bytes.find ('#');
554 if (hash_mark_idx == std::string::npos)
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000555 return true;
Jason Molendaa21fdb02015-08-02 01:36:09 +0000556 if (hash_mark_idx + 2 >= m_bytes.size())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000557 return true;
558
Jason Molendaa21fdb02015-08-02 01:36:09 +0000559 if (!::isxdigit (m_bytes[hash_mark_idx + 1]) || !::isxdigit (m_bytes[hash_mark_idx + 2]))
560 return true;
561
562 size_t content_length = pkt_size - 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
563 size_t content_start = 2; // The first character of the compressed/not-compressed text of the packet
564 size_t checksum_idx = hash_mark_idx + 1; // The first character of the two hex checksum characters
565
566 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain multiple packets.
567 // size_of_first_packet is the size of the initial packet which we'll replace with the decompressed
568 // version of, leaving the rest of m_bytes unmodified.
569 size_t size_of_first_packet = hash_mark_idx + 3;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000570
571 // Compressed packets ("$C") start with a base10 number which is the size of the uncompressed payload,
572 // then a : and then the compressed data. e.g. $C1024:<binary>#00
573 // Update content_start and content_length to only include the <binary> part of the packet.
574
575 uint64_t decompressed_bufsize = ULONG_MAX;
576 if (m_bytes[1] == 'C')
577 {
578 size_t i = content_start;
579 while (i < hash_mark_idx && isdigit(m_bytes[i]))
580 i++;
581 if (i < hash_mark_idx && m_bytes[i] == ':')
582 {
583 i++;
584 content_start = i;
585 content_length = hash_mark_idx - content_start;
586 std::string bufsize_str (m_bytes.data() + 2, i - 2 - 1);
587 errno = 0;
588 decompressed_bufsize = ::strtoul (bufsize_str.c_str(), NULL, 10);
589 if (errno != 0 || decompressed_bufsize == ULONG_MAX)
590 {
Jason Molendaa21fdb02015-08-02 01:36:09 +0000591 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000592 return false;
593 }
594 }
595 }
596
597 if (GetSendAcks ())
598 {
599 char packet_checksum_cstr[3];
600 packet_checksum_cstr[0] = m_bytes[checksum_idx];
601 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
602 packet_checksum_cstr[2] = '\0';
603 long packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
604
605 long actual_checksum = CalculcateChecksum (m_bytes.data() + 1, hash_mark_idx - 1);
606 bool success = packet_checksum == actual_checksum;
607 if (!success)
608 {
609 if (log)
610 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
611 (int)(pkt_size),
612 m_bytes.c_str(),
613 (uint8_t)packet_checksum,
614 (uint8_t)actual_checksum);
615 }
616 // Send the ack or nack if needed
617 if (!success)
618 {
619 SendNack();
Jason Molendaa21fdb02015-08-02 01:36:09 +0000620 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000621 return false;
622 }
623 else
624 {
625 SendAck();
626 }
627 }
628
629 if (m_bytes[1] == 'N')
630 {
631 // This packet was not compressed -- delete the 'N' character at the
632 // start and the packet may be processed as-is.
633 m_bytes.erase(1, 1);
634 return true;
635 }
636
637 // Reverse the gdb-remote binary escaping that was done to the compressed text to
638 // guard characters like '$', '#', '}', etc.
639 std::vector<uint8_t> unescaped_content;
640 unescaped_content.reserve (content_length);
641 size_t i = content_start;
642 while (i < hash_mark_idx)
643 {
644 if (m_bytes[i] == '}')
645 {
646 i++;
647 unescaped_content.push_back (m_bytes[i] ^ 0x20);
648 }
649 else
650 {
651 unescaped_content.push_back (m_bytes[i]);
652 }
653 i++;
654 }
655
656 uint8_t *decompressed_buffer = nullptr;
657 size_t decompressed_bytes = 0;
658
659 if (decompressed_bufsize != ULONG_MAX)
660 {
661 decompressed_buffer = (uint8_t *) malloc (decompressed_bufsize + 1);
662 if (decompressed_buffer == nullptr)
663 {
Jason Molendaa21fdb02015-08-02 01:36:09 +0000664 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000665 return false;
666 }
667
668 }
669
670#if defined (HAVE_LIBCOMPRESSION)
671 // libcompression is weak linked so check that compression_decode_buffer() is available
672 if (compression_decode_buffer != NULL &&
673 (m_compression_type == CompressionType::ZlibDeflate
674 || m_compression_type == CompressionType::LZFSE
675 || m_compression_type == CompressionType::LZ4))
676 {
677 compression_algorithm compression_type;
678 if (m_compression_type == CompressionType::ZlibDeflate)
679 compression_type = COMPRESSION_ZLIB;
680 else if (m_compression_type == CompressionType::LZFSE)
681 compression_type = COMPRESSION_LZFSE;
682 else if (m_compression_type == CompressionType::LZ4)
683 compression_type = COMPRESSION_LZ4_RAW;
684 else if (m_compression_type == CompressionType::LZMA)
685 compression_type = COMPRESSION_LZMA;
686
687
688 // If we have the expected size of the decompressed payload, we can allocate
689 // the right-sized buffer and do it. If we don't have that information, we'll
690 // need to try decoding into a big buffer and if the buffer wasn't big enough,
691 // increase it and try again.
692
693 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr)
694 {
695 decompressed_bytes = compression_decode_buffer (decompressed_buffer, decompressed_bufsize + 10 ,
696 (uint8_t*) unescaped_content.data(),
697 unescaped_content.size(),
698 NULL,
699 compression_type);
700 }
701 }
702#endif
703
704#if defined (HAVE_LIBZ)
705 if (decompressed_bytes == 0
706 && decompressed_bufsize != ULONG_MAX
707 && decompressed_buffer != nullptr
708 && m_compression_type == CompressionType::ZlibDeflate)
709 {
710 z_stream stream;
711 memset (&stream, 0, sizeof (z_stream));
712 stream.next_in = (Bytef *) unescaped_content.data();
713 stream.avail_in = (uInt) unescaped_content.size();
714 stream.total_in = 0;
715 stream.next_out = (Bytef *) decompressed_buffer;
716 stream.avail_out = decompressed_bufsize;
717 stream.total_out = 0;
718 stream.zalloc = Z_NULL;
719 stream.zfree = Z_NULL;
720 stream.opaque = Z_NULL;
721
722 if (inflateInit2 (&stream, -15) == Z_OK)
723 {
724 int status = inflate (&stream, Z_NO_FLUSH);
725 inflateEnd (&stream);
726 if (status == Z_STREAM_END)
727 {
728 decompressed_bytes = stream.total_out;
729 }
730 }
731 }
732#endif
733
734 if (decompressed_bytes == 0 || decompressed_buffer == nullptr)
735 {
736 if (decompressed_buffer)
737 free (decompressed_buffer);
Jason Molendaa21fdb02015-08-02 01:36:09 +0000738 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000739 return false;
740 }
741
742 std::string new_packet;
743 new_packet.reserve (decompressed_bytes + 6);
744 new_packet.push_back (m_bytes[0]);
745 new_packet.append ((const char *) decompressed_buffer, decompressed_bytes);
746 new_packet.push_back ('#');
747 if (GetSendAcks ())
748 {
749 uint8_t decompressed_checksum = CalculcateChecksum ((const char *) decompressed_buffer, decompressed_bytes);
750 char decompressed_checksum_str[3];
751 snprintf (decompressed_checksum_str, 3, "%02x", decompressed_checksum);
752 new_packet.append (decompressed_checksum_str);
753 }
754 else
755 {
756 new_packet.push_back ('0');
757 new_packet.push_back ('0');
758 }
759
Jason Molendaa21fdb02015-08-02 01:36:09 +0000760 m_bytes.replace (0, size_of_first_packet, new_packet.data(), new_packet.size());
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000761
762 free (decompressed_buffer);
763 return true;
764}
765
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000766GDBRemoteCommunication::PacketType
Greg Clayton73bf5db2011-06-17 01:22:15 +0000767GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000768{
769 // Put the packet data into the buffer in a thread safe fashion
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000770 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
771
Greg Clayton5160ce52013-03-27 23:08:40 +0000772 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000773
Greg Clayton73bf5db2011-06-17 01:22:15 +0000774 if (src && src_len > 0)
Greg Clayton197bacf2011-07-02 21:07:54 +0000775 {
Greg Clayton0c51ac32011-07-02 23:21:06 +0000776 if (log && log->GetVerbose())
Greg Clayton197bacf2011-07-02 21:07:54 +0000777 {
778 StreamString s;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000779 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
780 __FUNCTION__,
781 (uint32_t)src_len,
782 (uint32_t)src_len,
783 src);
Greg Clayton197bacf2011-07-02 21:07:54 +0000784 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000785 m_bytes.append ((const char *)src, src_len);
Greg Clayton197bacf2011-07-02 21:07:54 +0000786 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000787
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000788 bool isNotifyPacket = false;
789
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790 // Parse up the packets into gdb remote packets
Greg Clayton197bacf2011-07-02 21:07:54 +0000791 if (!m_bytes.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000792 {
793 // end_idx must be one past the last valid packet byte. Start
794 // it off with an invalid value that is the same as the current
795 // index.
Greg Clayton73bf5db2011-06-17 01:22:15 +0000796 size_t content_start = 0;
Greg Clayton118593a2014-11-03 21:02:54 +0000797 size_t content_length = 0;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000798 size_t total_length = 0;
799 size_t checksum_idx = std::string::npos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000800
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000801 // Size of packet before it is decompressed, for logging purposes
802 size_t original_packet_size = m_bytes.size();
803 if (CompressionIsEnabled())
804 {
805 if (DecompressPacket() == false)
806 {
807 packet.Clear();
808 return GDBRemoteCommunication::PacketType::Standard;
809 }
810 }
811
Greg Clayton118593a2014-11-03 21:02:54 +0000812 switch (m_bytes[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813 {
Greg Clayton118593a2014-11-03 21:02:54 +0000814 case '+': // Look for ack
815 case '-': // Look for cancel
816 case '\x03': // ^C to halt target
817 content_length = total_length = 1; // The command is one byte long...
818 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819
Ewan Crawford78baa192015-05-13 09:18:18 +0000820 case '%': // Async notify packet
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000821 isNotifyPacket = true;
Jason Molenda62e06812016-02-16 04:14:33 +0000822 LLVM_FALLTHROUGH;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000823
Greg Clayton118593a2014-11-03 21:02:54 +0000824 case '$':
825 // Look for a standard gdb packet?
826 {
827 size_t hash_pos = m_bytes.find('#');
828 if (hash_pos != std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829 {
Greg Clayton118593a2014-11-03 21:02:54 +0000830 if (hash_pos + 2 < m_bytes.size())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000831 {
Greg Clayton118593a2014-11-03 21:02:54 +0000832 checksum_idx = hash_pos + 1;
833 // Skip the dollar sign
834 content_start = 1;
835 // Don't include the # in the content or the $ in the content length
836 content_length = hash_pos - 1;
837
838 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
839 }
840 else
841 {
842 // Checksum bytes aren't all here yet
843 content_length = std::string::npos;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000844 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845 }
Greg Clayton118593a2014-11-03 21:02:54 +0000846 }
847 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000848
Greg Clayton118593a2014-11-03 21:02:54 +0000849 default:
850 {
851 // We have an unexpected byte and we need to flush all bad
852 // data that is in m_bytes, so we need to find the first
853 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
854 // or '$' character (start of packet header) or of course,
855 // the end of the data in m_bytes...
856 const size_t bytes_len = m_bytes.size();
857 bool done = false;
858 uint32_t idx;
859 for (idx = 1; !done && idx < bytes_len; ++idx)
Greg Clayton197bacf2011-07-02 21:07:54 +0000860 {
Greg Clayton118593a2014-11-03 21:02:54 +0000861 switch (m_bytes[idx])
Greg Clayton197bacf2011-07-02 21:07:54 +0000862 {
Greg Clayton118593a2014-11-03 21:02:54 +0000863 case '+':
864 case '-':
865 case '\x03':
Ewan Crawford78baa192015-05-13 09:18:18 +0000866 case '%':
Greg Clayton118593a2014-11-03 21:02:54 +0000867 case '$':
868 done = true;
869 break;
870
871 default:
872 break;
Greg Clayton197bacf2011-07-02 21:07:54 +0000873 }
874 }
Greg Clayton118593a2014-11-03 21:02:54 +0000875 if (log)
876 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
877 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
878 m_bytes.erase(0, idx - 1);
879 }
880 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000881 }
882
Greg Clayton73bf5db2011-06-17 01:22:15 +0000883 if (content_length == std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000884 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000885 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000886 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887 }
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000888 else if (total_length > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000889 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000890
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000891 // We have a valid packet...
Greg Clayton73bf5db2011-06-17 01:22:15 +0000892 assert (content_length <= m_bytes.size());
893 assert (total_length <= m_bytes.size());
894 assert (content_length <= total_length);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000895 size_t content_end = content_start + content_length;
Greg Clayton06f09b52014-06-20 20:41:07 +0000896
Greg Clayton73bf5db2011-06-17 01:22:15 +0000897 bool success = true;
898 std::string &packet_str = packet.GetStringRef();
Greg Claytonc1422c12012-04-09 22:46:21 +0000899 if (log)
900 {
901 // If logging was just enabled and we have history, then dump out what
902 // we have to the log so we get the historical context. The Dump() call that
903 // logs all of the packet will set a boolean so that we don't dump this more
904 // than once
905 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000906 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000907
Greg Clayton06f09b52014-06-20 20:41:07 +0000908 bool binary = false;
909 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
910 if (m_bytes[0] == '$' && total_length > 4)
911 {
912 for (size_t i=0; !binary && i<total_length; ++i)
913 {
Jason Molenda0ace3f52015-09-09 03:24:52 +0000914 if (isprint (m_bytes[i]) == 0 && isspace (m_bytes[i]) == 0)
915 {
Greg Clayton06f09b52014-06-20 20:41:07 +0000916 binary = true;
Jason Molenda0ace3f52015-09-09 03:24:52 +0000917 }
Greg Clayton06f09b52014-06-20 20:41:07 +0000918 }
919 }
920 if (binary)
921 {
922 StreamString strm;
923 // Packet header...
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000924 if (CompressionIsEnabled())
925 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c", (uint64_t) original_packet_size, (uint64_t)total_length, m_bytes[0]);
926 else
927 strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
Greg Clayton06f09b52014-06-20 20:41:07 +0000928 for (size_t i=content_start; i<content_end; ++i)
929 {
930 // Remove binary escaped bytes when displaying the packet...
931 const char ch = m_bytes[i];
932 if (ch == 0x7d)
933 {
934 // 0x7d is the escape character. The next character is to
935 // be XOR'd with 0x20.
936 const char escapee = m_bytes[++i] ^ 0x20;
937 strm.Printf("%2.2x", escapee);
938 }
939 else
940 {
941 strm.Printf("%2.2x", (uint8_t)ch);
942 }
943 }
944 // Packet footer...
945 strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
946 log->PutCString(strm.GetString().c_str());
947 }
948 else
949 {
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000950 if (CompressionIsEnabled())
951 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s", (uint64_t) original_packet_size, (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
952 else
953 log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
Greg Clayton06f09b52014-06-20 20:41:07 +0000954 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000955 }
956
957 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
958
Hafiz Abid Qadeere5fd5e12013-08-28 15:10:37 +0000959 // Clear packet_str in case there is some existing data in it.
960 packet_str.clear();
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000961 // Copy the packet from m_bytes to packet_str expanding the
962 // run-length encoding in the process.
963 // Reserve enough byte for the most common case (no RLE used)
964 packet_str.reserve(m_bytes.length());
Greg Clayton06f09b52014-06-20 20:41:07 +0000965 for (std::string::const_iterator c = m_bytes.begin() + content_start; c != m_bytes.begin() + content_end; ++c)
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000966 {
967 if (*c == '*')
968 {
969 // '*' indicates RLE. Next character will give us the
970 // repeat count and previous character is what is to be
971 // repeated.
972 char char_to_repeat = packet_str.back();
973 // Number of time the previous character is repeated
974 int repeat_count = *++c + 3 - ' ';
975 // We have the char_to_repeat and repeat_count. Now push
976 // it in the packet.
977 for (int i = 0; i < repeat_count; ++i)
978 packet_str.push_back(char_to_repeat);
979 }
Steve Pucci3c5d3332014-02-24 19:07:29 +0000980 else if (*c == 0x7d)
981 {
982 // 0x7d is the escape character. The next character is to
983 // be XOR'd with 0x20.
984 char escapee = *++c ^ 0x20;
985 packet_str.push_back(escapee);
986 }
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000987 else
988 {
989 packet_str.push_back(*c);
990 }
991 }
992
Ewan Crawford78baa192015-05-13 09:18:18 +0000993 if (m_bytes[0] == '$' || m_bytes[0] == '%')
Greg Clayton73bf5db2011-06-17 01:22:15 +0000994 {
995 assert (checksum_idx < m_bytes.size());
996 if (::isxdigit (m_bytes[checksum_idx+0]) ||
997 ::isxdigit (m_bytes[checksum_idx+1]))
998 {
999 if (GetSendAcks ())
1000 {
1001 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
1002 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
1003 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
1004 success = packet_checksum == actual_checksum;
1005 if (!success)
1006 {
1007 if (log)
1008 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
1009 (int)(total_length),
1010 m_bytes.c_str(),
1011 (uint8_t)packet_checksum,
1012 (uint8_t)actual_checksum);
1013 }
1014 // Send the ack or nack if needed
1015 if (!success)
1016 SendNack();
1017 else
1018 SendAck();
1019 }
Greg Clayton73bf5db2011-06-17 01:22:15 +00001020 }
1021 else
1022 {
1023 success = false;
1024 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001025 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
Greg Clayton73bf5db2011-06-17 01:22:15 +00001026 }
1027 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001028
Greg Clayton73bf5db2011-06-17 01:22:15 +00001029 m_bytes.erase(0, total_length);
1030 packet.SetFilePos(0);
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001031
1032 if (isNotifyPacket)
1033 return GDBRemoteCommunication::PacketType::Notify;
1034 else
1035 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001036 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001037 }
Greg Clayton73bf5db2011-06-17 01:22:15 +00001038 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001039 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001040}
1041
Greg Clayton8b82f082011-04-12 05:54:46 +00001042Error
Greg Claytond6299802013-12-06 17:46:35 +00001043GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
Greg Clayton00fe87b2013-12-05 22:58:22 +00001044{
1045 Error error;
Zachary Turneracee96a2014-09-23 18:32:09 +00001046 if (m_listen_thread.IsJoinable())
Greg Clayton00fe87b2013-12-05 22:58:22 +00001047 {
1048 error.SetErrorString("listen thread already running");
1049 }
1050 else
1051 {
1052 char listen_url[512];
1053 if (hostname && hostname[0])
Jean-Daniel Dupas3c6774a2014-02-08 20:29:40 +00001054 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001055 else
1056 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
1057 m_listen_url = listen_url;
1058 SetConnection(new ConnectionFileDescriptor());
Zachary Turner39de3112014-09-09 20:54:56 +00001059 m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001060 }
1061 return error;
1062}
1063
1064bool
1065GDBRemoteCommunication::JoinListenThread ()
1066{
Zachary Turneracee96a2014-09-23 18:32:09 +00001067 if (m_listen_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +00001068 m_listen_thread.Join(nullptr);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001069 return true;
1070}
1071
1072lldb::thread_result_t
1073GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
1074{
1075 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
1076 Error error;
1077 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
1078
1079 if (connection)
1080 {
1081 // Do the listen on another thread so we can continue on...
1082 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
1083 comm->SetConnection(NULL);
1084 }
1085 return NULL;
1086}
1087
1088Error
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001089GDBRemoteCommunication::StartDebugserverProcess (const char *url,
Greg Clayton6988abc2015-10-19 20:44:01 +00001090 Platform *platform,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001091 ProcessLaunchInfo &launch_info,
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001092 uint16_t *port,
1093 const Args& inferior_args)
Greg Clayton8b82f082011-04-12 05:54:46 +00001094{
Todd Fiala015d8182014-07-22 23:41:36 +00001095 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1096 if (log)
Todd Fiala7aa4d972016-05-31 18:32:20 +00001097 log->Printf ("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")", __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
Todd Fiala015d8182014-07-22 23:41:36 +00001098
Greg Clayton8b82f082011-04-12 05:54:46 +00001099 Error error;
1100 // If we locate debugserver, keep that located version around
1101 static FileSpec g_debugserver_file_spec;
1102
Greg Clayton8b82f082011-04-12 05:54:46 +00001103 char debugserver_path[PATH_MAX];
1104 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
1105
1106 // Always check to see if we have an environment override for the path
1107 // to the debugserver to use and use it if we do.
1108 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1109 if (env_debugserver_path)
Todd Fiala015d8182014-07-22 23:41:36 +00001110 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001111 debugserver_file_spec.SetFile (env_debugserver_path, false);
Todd Fiala015d8182014-07-22 23:41:36 +00001112 if (log)
1113 log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path);
1114 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001115 else
1116 debugserver_file_spec = g_debugserver_file_spec;
1117 bool debugserver_exists = debugserver_file_spec.Exists();
1118 if (!debugserver_exists)
1119 {
1120 // The debugserver binary is in the LLDB.framework/Resources
Zachary Turner42ff0ad2014-08-21 17:29:12 +00001121 // directory.
1122 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec))
Greg Clayton8b82f082011-04-12 05:54:46 +00001123 {
Jason Molenda6fd86772014-08-21 23:22:33 +00001124 debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME);
Greg Clayton8b82f082011-04-12 05:54:46 +00001125 debugserver_exists = debugserver_file_spec.Exists();
1126 if (debugserver_exists)
1127 {
Todd Fiala015d8182014-07-22 23:41:36 +00001128 if (log)
1129 log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
1130
Greg Clayton8b82f082011-04-12 05:54:46 +00001131 g_debugserver_file_spec = debugserver_file_spec;
1132 }
1133 else
1134 {
Greg Clayton6988abc2015-10-19 20:44:01 +00001135 debugserver_file_spec = platform->LocateExecutable(DEBUGSERVER_BASENAME);
1136 if (debugserver_file_spec)
1137 {
1138 // Platform::LocateExecutable() wouldn't return a path if it doesn't exist
1139 debugserver_exists = true;
1140 }
1141 else
1142 {
1143 if (log)
1144 log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
1145 }
1146 // Don't cache the platform specific GDB server binary as it could change
1147 // from platform to platform
Greg Clayton8b82f082011-04-12 05:54:46 +00001148 g_debugserver_file_spec.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00001149 }
1150 }
1151 }
1152
1153 if (debugserver_exists)
1154 {
1155 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1156
1157 Args &debugserver_args = launch_info.GetArguments();
1158 debugserver_args.Clear();
1159 char arg_cstr[PATH_MAX];
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001160
Greg Clayton8b82f082011-04-12 05:54:46 +00001161 // Start args with "debugserver /file/path -r --"
1162 debugserver_args.AppendArgument(debugserver_path);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001163
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001164#if !defined(__APPLE__)
1165 // First argument to lldb-server must be mode in which to run.
1166 debugserver_args.AppendArgument("gdbserver");
1167#endif
1168
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001169 // If a url is supplied then use it
1170 if (url)
1171 debugserver_args.AppendArgument(url);
Greg Claytonfda4fab2014-01-10 22:24:11 +00001172
Greg Clayton8b82f082011-04-12 05:54:46 +00001173 // use native registers, not the GDB registers
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001174 debugserver_args.AppendArgument("--native-regs");
1175
1176 if (launch_info.GetLaunchInSeparateProcessGroup())
1177 {
1178 debugserver_args.AppendArgument("--setsid");
1179 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001180
Oleksiy Vyalov4536c452015-02-05 16:29:12 +00001181 llvm::SmallString<PATH_MAX> named_pipe_path;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001182 // socket_pipe is used by debug server to communicate back either
1183 // TCP port or domain socket name which it listens on.
1184 // The second purpose of the pipe to serve as a synchronization point -
1185 // once data is written to the pipe, debug server is up and running.
1186 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001187
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001188 // port is null when debug server should listen on domain socket -
1189 // we're not interested in port value but rather waiting for debug server
1190 // to become available.
1191 if ((port != nullptr && *port == 0) || port == nullptr)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001192 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001193 if (url)
Jason Molenda04097542015-09-22 23:25:44 +00001194 {
1195 // Create a temporary file to get the stdout/stderr and redirect the
1196 // output of the command into this file. We will later read this file
1197 // if all goes well and fill the data into "command_output_ptr"
1198
Chaoren Lin46951b52015-07-30 17:48:44 +00001199#if defined(__APPLE__)
Jason Molenda04097542015-09-22 23:25:44 +00001200 // Binding to port zero, we need to figure out what port it ends up
1201 // using using a named pipe...
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001202 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe", false, named_pipe_path);
Jason Molenda04097542015-09-22 23:25:44 +00001203 if (error.Fail())
1204 {
1205 if (log)
1206 log->Printf("GDBRemoteCommunication::%s() "
1207 "named pipe creation failed: %s",
1208 __FUNCTION__, error.AsCString());
1209 return error;
1210 }
1211 debugserver_args.AppendArgument("--named-pipe");
1212 debugserver_args.AppendArgument(named_pipe_path.c_str());
Chaoren Lin46951b52015-07-30 17:48:44 +00001213#else
Jason Molenda04097542015-09-22 23:25:44 +00001214 // Binding to port zero, we need to figure out what port it ends up
1215 // using using an unnamed pipe...
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001216 error = socket_pipe.CreateNew(true);
Jason Molenda04097542015-09-22 23:25:44 +00001217 if (error.Fail())
1218 {
1219 if (log)
1220 log->Printf("GDBRemoteCommunication::%s() "
1221 "unnamed pipe creation failed: %s",
1222 __FUNCTION__, error.AsCString());
1223 return error;
1224 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001225 int write_fd = socket_pipe.GetWriteFileDescriptor();
Jason Molenda04097542015-09-22 23:25:44 +00001226 debugserver_args.AppendArgument("--pipe");
1227 debugserver_args.AppendArgument(std::to_string(write_fd).c_str());
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001228 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001229#endif
Greg Clayton16810922014-02-27 19:38:18 +00001230 }
1231 else
1232 {
Jason Molenda04097542015-09-22 23:25:44 +00001233 // No host and port given, so lets listen on our end and make the debugserver
1234 // connect to us..
1235 error = StartListenThread ("127.0.0.1", 0);
1236 if (error.Fail())
1237 {
1238 if (log)
1239 log->Printf ("GDBRemoteCommunication::%s() unable to start listen thread: %s", __FUNCTION__, error.AsCString());
1240 return error;
1241 }
1242
1243 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
1244 // Wait for 10 seconds to resolve the bound port
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001245 *port = connection->GetListeningPort(10);
1246 if (*port > 0)
Jason Molenda04097542015-09-22 23:25:44 +00001247 {
1248 char port_cstr[32];
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001249 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", *port);
Jason Molenda04097542015-09-22 23:25:44 +00001250 // Send the host and port down that debugserver and specify an option
1251 // so that it connects back to the port we are listening to in this process
1252 debugserver_args.AppendArgument("--reverse-connect");
1253 debugserver_args.AppendArgument(port_cstr);
1254 }
1255 else
1256 {
1257 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
1258 if (log)
1259 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
1260 return error;
1261 }
Greg Clayton16810922014-02-27 19:38:18 +00001262 }
Greg Clayton00fe87b2013-12-05 22:58:22 +00001263 }
Greg Clayton00fe87b2013-12-05 22:58:22 +00001264
Greg Clayton8b82f082011-04-12 05:54:46 +00001265 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1266 if (env_debugserver_log_file)
1267 {
1268 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1269 debugserver_args.AppendArgument(arg_cstr);
1270 }
1271
Vince Harron9753dd92015-05-10 15:22:09 +00001272#if defined(__APPLE__)
Greg Clayton8b82f082011-04-12 05:54:46 +00001273 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1274 if (env_debugserver_log_flags)
1275 {
1276 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1277 debugserver_args.AppendArgument(arg_cstr);
1278 }
Vince Harron9753dd92015-05-10 15:22:09 +00001279#else
1280 const char *env_debugserver_log_channels = getenv("LLDB_SERVER_LOG_CHANNELS");
1281 if (env_debugserver_log_channels)
1282 {
1283 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-channels=%s", env_debugserver_log_channels);
1284 debugserver_args.AppendArgument(arg_cstr);
1285 }
1286#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001287
1288 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back.
1289 uint32_t env_var_index = 1;
1290 bool has_env_var;
1291 do
1292 {
1293 char env_var_name[64];
1294 snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1295 const char *extra_arg = getenv(env_var_name);
1296 has_env_var = extra_arg != nullptr;
1297
1298 if (has_env_var)
1299 {
1300 debugserver_args.AppendArgument (extra_arg);
1301 if (log)
1302 log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg);
1303 }
1304 } while (has_env_var);
1305
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001306 if (inferior_args.GetArgumentCount() > 0)
1307 {
1308 debugserver_args.AppendArgument ("--");
1309 debugserver_args.AppendArguments (inferior_args);
1310 }
1311
1312 // Copy the current environment to the gdbserver/debugserver instance
1313 StringList env;
1314 if (Host::GetEnvironment(env))
1315 {
1316 for (size_t i = 0; i < env.GetSize(); ++i)
1317 launch_info.GetEnvironmentEntries().AppendArgument(env[i].c_str());
1318 }
1319
Shawn Best629680e2014-11-05 00:58:55 +00001320 // Close STDIN, STDOUT and STDERR.
Greg Clayton91a9b2472013-12-04 19:19:12 +00001321 launch_info.AppendCloseFileAction (STDIN_FILENO);
1322 launch_info.AppendCloseFileAction (STDOUT_FILENO);
1323 launch_info.AppendCloseFileAction (STDERR_FILENO);
Shawn Best629680e2014-11-05 00:58:55 +00001324
1325 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1326 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1327 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1328 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
Todd Fiala7aa4d972016-05-31 18:32:20 +00001329
1330 if (log)
1331 {
1332 StreamString string_stream;
1333 Platform *const platform = nullptr;
1334 launch_info.Dump(string_stream, platform);
1335 log->Printf("launch info for gdb-remote stub:\n%s", string_stream.GetString().c_str());
1336 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001337 error = Host::LaunchProcess(launch_info);
Zachary Turner9b693272014-12-04 22:06:42 +00001338
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001339 if (error.Success() &&
1340 launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001341 {
Oleksiy Vyalov4536c452015-02-05 16:29:12 +00001342 if (named_pipe_path.size() > 0)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001343 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001344 error = socket_pipe.OpenAsReader(named_pipe_path, false);
Chaoren Lin368c9f62015-04-27 23:20:30 +00001345 if (error.Fail())
1346 if (log)
1347 log->Printf("GDBRemoteCommunication::%s() "
1348 "failed to open named pipe %s for reading: %s",
1349 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1350 }
1351
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001352 if (socket_pipe.CanWrite())
1353 socket_pipe.CloseWriteFileDescriptor();
1354 if (socket_pipe.CanRead())
Chaoren Lin368c9f62015-04-27 23:20:30 +00001355 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001356 char port_cstr[PATH_MAX] = {0};
Chaoren Lin368c9f62015-04-27 23:20:30 +00001357 port_cstr[0] = '\0';
1358 size_t num_bytes = sizeof(port_cstr);
1359 // Read port from pipe with 10 second timeout.
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001360 error = socket_pipe.ReadWithTimeout(port_cstr, num_bytes,
Chaoren Lin368c9f62015-04-27 23:20:30 +00001361 std::chrono::seconds{10}, num_bytes);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001362 if (error.Success() && (port != nullptr))
Greg Clayton3121fde2014-02-28 20:47:08 +00001363 {
Chaoren Lin368c9f62015-04-27 23:20:30 +00001364 assert(num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001365 *port = StringConvert::ToUInt32(port_cstr, 0);
Chaoren Lin368c9f62015-04-27 23:20:30 +00001366 if (log)
1367 log->Printf("GDBRemoteCommunication::%s() "
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001368 "debugserver listens %u port",
1369 __FUNCTION__, *port);
Greg Clayton3121fde2014-02-28 20:47:08 +00001370 }
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001371 else
1372 {
1373 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +00001374 log->Printf("GDBRemoteCommunication::%s() "
1375 "failed to read a port value from pipe %s: %s",
1376 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1377
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001378 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001379 socket_pipe.Close();
Chaoren Lin368c9f62015-04-27 23:20:30 +00001380 }
1381
1382 if (named_pipe_path.size() > 0)
1383 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001384 const auto err = socket_pipe.Delete(named_pipe_path);
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001385 if (err.Fail())
1386 {
1387 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +00001388 log->Printf ("GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1389 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001390 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001391 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001392
1393 // Make sure we actually connect with the debugserver...
1394 JoinListenThread();
Greg Clayton00fe87b2013-12-05 22:58:22 +00001395 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001396 }
1397 else
1398 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001399 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
Greg Clayton8b82f082011-04-12 05:54:46 +00001400 }
Vince Harron8b335672015-05-12 01:10:56 +00001401
1402 if (error.Fail())
1403 {
1404 if (log)
1405 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
1406 }
1407
Greg Clayton8b82f082011-04-12 05:54:46 +00001408 return error;
1409}
1410
Greg Claytonc1422c12012-04-09 22:46:21 +00001411void
Greg Claytond451c1a2012-04-13 21:24:18 +00001412GDBRemoteCommunication::DumpHistory(Stream &strm)
Greg Claytonc1422c12012-04-09 22:46:21 +00001413{
Greg Claytond451c1a2012-04-13 21:24:18 +00001414 m_history.Dump (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +00001415}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001416
1417GDBRemoteCommunication::ScopedTimeout::ScopedTimeout (GDBRemoteCommunication& gdb_comm,
1418 uint32_t timeout) :
1419 m_gdb_comm (gdb_comm)
1420{
1421 m_saved_timeout = m_gdb_comm.SetPacketTimeout (timeout);
1422}
1423
1424GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout ()
1425{
1426 m_gdb_comm.SetPacketTimeout (m_saved_timeout);
1427}
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001428
1429// This function is called via the Communications class read thread when bytes become available
1430// for this connection. This function will consume all incoming bytes and try to parse whole
1431// packets as they become available. Full packets are placed in a queue, so that all packet
1432// requests can simply pop from this queue. Async notification packets will be dispatched
1433// immediately to the ProcessGDBRemote Async thread via an event.
1434void GDBRemoteCommunication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, lldb::ConnectionStatus status)
1435{
1436 StringExtractorGDBRemote packet;
1437
1438 while (true)
1439 {
1440 PacketType type = CheckForPacket(bytes, len, packet);
1441
1442 // scrub the data so we do not pass it back to CheckForPacket
1443 // on future passes of the loop
1444 bytes = nullptr;
1445 len = 0;
1446
1447 // we may have received no packet so lets bail out
1448 if (type == PacketType::Invalid)
1449 break;
1450
1451 if (type == PacketType::Standard)
1452 {
1453 // scope for the mutex
1454 {
1455 // lock down the packet queue
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001456 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001457 // push a new packet into the queue
1458 m_packet_queue.push(packet);
1459 // Signal condition variable that we have a packet
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +00001460 m_condition_queue_not_empty.notify_one();
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001461 }
1462 }
1463
1464 if (type == PacketType::Notify)
1465 {
1466 // put this packet into an event
1467 const char *pdata = packet.GetStringRef().c_str();
1468
1469 // as the communication class, we are a broadcaster and the
1470 // async thread is tuned to listen to us
1471 BroadcastEvent(
1472 eBroadcastBitGdbReadThreadGotNotify,
1473 new EventDataBytes(pdata));
1474 }
1475 }
1476}