blob: 9c263c8c40879c34b8f197bb055947dd53ae5b8f [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 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"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035
36// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "ProcessGDBRemoteLog.h"
38
Todd Fiala015d8182014-07-22 23:41:36 +000039#if defined(__APPLE__)
40# define DEBUGSERVER_BASENAME "debugserver"
41#else
Tamas Berghammerc2c3d712015-02-18 15:39:41 +000042# define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000043#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000044
Jason Molenda91ffe0a2015-06-18 21:46:06 +000045#if defined (HAVE_LIBCOMPRESSION)
46#include <compression.h>
47#endif
48
49#if defined (HAVE_LIBZ)
50#include <zlib.h>
51#endif
52
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053using namespace lldb;
54using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000055using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056
Greg Claytonc1422c12012-04-09 22:46:21 +000057GDBRemoteCommunication::History::History (uint32_t size) :
58 m_packets(),
59 m_curr_idx (0),
60 m_total_packet_count (0),
61 m_dumped_to_log (false)
62{
63 m_packets.resize(size);
64}
65
66GDBRemoteCommunication::History::~History ()
67{
68}
69
70void
Greg Claytond451c1a2012-04-13 21:24:18 +000071GDBRemoteCommunication::History::AddPacket (char packet_char,
72 PacketType type,
73 uint32_t bytes_transmitted)
74{
75 const size_t size = m_packets.size();
76 if (size > 0)
77 {
78 const uint32_t idx = GetNextIndex();
79 m_packets[idx].packet.assign (1, packet_char);
80 m_packets[idx].type = type;
81 m_packets[idx].bytes_transmitted = bytes_transmitted;
82 m_packets[idx].packet_idx = m_total_packet_count;
83 m_packets[idx].tid = Host::GetCurrentThreadID();
84 }
85}
86
87void
88GDBRemoteCommunication::History::AddPacket (const std::string &src,
89 uint32_t src_len,
90 PacketType type,
91 uint32_t bytes_transmitted)
92{
93 const size_t size = m_packets.size();
94 if (size > 0)
95 {
96 const uint32_t idx = GetNextIndex();
97 m_packets[idx].packet.assign (src, 0, src_len);
98 m_packets[idx].type = type;
99 m_packets[idx].bytes_transmitted = bytes_transmitted;
100 m_packets[idx].packet_idx = m_total_packet_count;
101 m_packets[idx].tid = Host::GetCurrentThreadID();
102 }
103}
104
105void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000106GDBRemoteCommunication::History::Dump (Stream &strm) const
Greg Claytonc1422c12012-04-09 22:46:21 +0000107{
108 const uint32_t size = GetNumPacketsInHistory ();
109 const uint32_t first_idx = GetFirstSavedPacketIndex ();
110 const uint32_t stop_idx = m_curr_idx + size;
111 for (uint32_t i = first_idx; i < stop_idx; ++i)
112 {
113 const uint32_t idx = NormalizeIndex (i);
114 const Entry &entry = m_packets[idx];
115 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
116 break;
Daniel Malead01b2952012-11-29 21:49:15 +0000117 strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
Greg Claytonc1422c12012-04-09 22:46:21 +0000118 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +0000119 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000120 entry.bytes_transmitted,
121 (entry.type == ePacketTypeSend) ? "send" : "read",
122 entry.packet.c_str());
123 }
124}
125
126void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000127GDBRemoteCommunication::History::Dump (Log *log) const
Greg Claytonc1422c12012-04-09 22:46:21 +0000128{
129 if (log && !m_dumped_to_log)
130 {
131 m_dumped_to_log = true;
132 const uint32_t size = GetNumPacketsInHistory ();
133 const uint32_t first_idx = GetFirstSavedPacketIndex ();
134 const uint32_t stop_idx = m_curr_idx + size;
135 for (uint32_t i = first_idx; i < stop_idx; ++i)
136 {
137 const uint32_t idx = NormalizeIndex (i);
138 const Entry &entry = m_packets[idx];
139 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
140 break;
Daniel Malead01b2952012-11-29 21:49:15 +0000141 log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
Greg Claytonc1422c12012-04-09 22:46:21 +0000142 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +0000143 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000144 entry.bytes_transmitted,
145 (entry.type == ePacketTypeSend) ? "send" : "read",
146 entry.packet.c_str());
147 }
148 }
149}
150
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000151//----------------------------------------------------------------------
152// GDBRemoteCommunication constructor
153//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +0000154GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
Tamas Berghammere13c2732015-02-11 10:29:30 +0000155 const char *listener_name) :
Greg Clayton576d8832011-03-22 04:00:09 +0000156 Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000157#ifdef LLDB_CONFIGURATION_DEBUG
158 m_packet_timeout (1000),
159#else
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000160 m_packet_timeout (1),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000161#endif
Greg Claytonb30c50c2015-05-29 00:01:55 +0000162 m_echo_number(0),
163 m_supports_qEcho (eLazyBoolCalculate),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000164 m_sequence_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton4dc72282011-01-20 07:53:45 +0000165 m_public_is_running (false),
Greg Clayton1cb64962011-03-24 04:28:38 +0000166 m_private_is_running (false),
Greg Claytonc1422c12012-04-09 22:46:21 +0000167 m_history (512),
Greg Clayton8b82f082011-04-12 05:54:46 +0000168 m_send_acks (true),
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000169 m_compression_type (CompressionType::None),
Greg Clayton00fe87b2013-12-05 22:58:22 +0000170 m_listen_url ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000171{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000172}
173
174//----------------------------------------------------------------------
175// Destructor
176//----------------------------------------------------------------------
177GDBRemoteCommunication::~GDBRemoteCommunication()
178{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000179 if (IsConnected())
180 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000181 Disconnect();
182 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000183
184 // Stop the communications read thread which is used to parse all
185 // incoming packets. This function will block until the read
186 // thread returns.
187 if (m_read_thread_enabled)
188 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000189}
190
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000191char
192GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
193{
194 int checksum = 0;
195
Ed Mastea6b4c772013-08-20 14:12:58 +0000196 for (size_t i = 0; i < payload_length; ++i)
197 checksum += payload[i];
198
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199 return checksum & 255;
200}
201
202size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000203GDBRemoteCommunication::SendAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000204{
Greg Clayton5160ce52013-03-27 23:08:40 +0000205 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000206 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000207 char ch = '+';
208 const size_t bytes_written = Write (&ch, 1, status, NULL);
209 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000210 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000211 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
212 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000213}
214
215size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000216GDBRemoteCommunication::SendNack ()
217{
Greg Clayton5160ce52013-03-27 23:08:40 +0000218 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton6ed95942011-01-22 07:12:45 +0000219 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000220 char ch = '-';
221 const size_t bytes_written = Write (&ch, 1, status, NULL);
222 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000223 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000224 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
225 return bytes_written;
Greg Clayton32e0a752011-03-30 18:16:51 +0000226}
227
Greg Clayton3dedae12013-12-06 21:45:27 +0000228GDBRemoteCommunication::PacketResult
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000229GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
230{
231 Mutex::Locker locker(m_sequence_mutex);
232 return SendPacketNoLock (payload, payload_length);
233}
234
Greg Clayton3dedae12013-12-06 21:45:27 +0000235GDBRemoteCommunication::PacketResult
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000236GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
237{
238 if (IsConnected())
239 {
240 StreamString packet(0, 4, eByteOrderBig);
241
242 packet.PutChar('$');
243 packet.Write (payload, payload_length);
244 packet.PutChar('#');
245 packet.PutHex8(CalculcateChecksum (payload, payload_length));
246
Greg Clayton5160ce52013-03-27 23:08:40 +0000247 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000248 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton7e244322014-09-18 00:17:36 +0000249 const char *packet_data = packet.GetData();
250 const size_t packet_length = packet.GetSize();
251 size_t bytes_written = Write (packet_data, packet_length, status, NULL);
Greg Claytonc1422c12012-04-09 22:46:21 +0000252 if (log)
253 {
Greg Clayton7e244322014-09-18 00:17:36 +0000254 size_t binary_start_offset = 0;
255 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == 0)
256 {
257 const char *first_comma = strchr(packet_data, ',');
258 if (first_comma)
259 {
260 const char *second_comma = strchr(first_comma + 1, ',');
261 if (second_comma)
262 binary_start_offset = second_comma - packet_data + 1;
263 }
264 }
265
Greg Claytonc1422c12012-04-09 22:46:21 +0000266 // If logging was just enabled and we have history, then dump out what
267 // we have to the log so we get the historical context. The Dump() call that
268 // logs all of the packet will set a boolean so that we don't dump this more
269 // than once
270 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000271 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000272
Greg Clayton7e244322014-09-18 00:17:36 +0000273 if (binary_start_offset)
274 {
275 StreamString strm;
276 // Print non binary data header
277 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)binary_start_offset, packet_data);
278 const uint8_t *p;
279 // Print binary data exactly as sent
Vince Harron8b335672015-05-12 01:10:56 +0000280 for (p = (const uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p)
Greg Clayton7e244322014-09-18 00:17:36 +0000281 strm.Printf("\\x%2.2x", *p);
282 // Print the checksum
283 strm.Printf("%*s", (int)3, p);
284 log->PutCString(strm.GetString().c_str());
285 }
286 else
287 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet_length, packet_data);
Greg Claytonc1422c12012-04-09 22:46:21 +0000288 }
289
Greg Clayton7e244322014-09-18 00:17:36 +0000290 m_history.AddPacket (packet.GetString(), packet_length, History::ePacketTypeSend, bytes_written);
Greg Claytonc1422c12012-04-09 22:46:21 +0000291
292
Greg Clayton7e244322014-09-18 00:17:36 +0000293 if (bytes_written == packet_length)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000294 {
Greg Clayton71fc2a32011-02-12 06:28:37 +0000295 if (GetSendAcks ())
Greg Clayton3dedae12013-12-06 21:45:27 +0000296 return GetAck ();
297 else
298 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000299 }
Johnny Chend0c40dd2010-09-14 22:10:43 +0000300 else
301 {
Greg Clayton6d093452011-02-05 02:25:06 +0000302 if (log)
Greg Clayton7e244322014-09-18 00:17:36 +0000303 log->Printf ("error: failed to send packet: %.*s", (int)packet_length, packet_data);
Johnny Chend0c40dd2010-09-14 22:10:43 +0000304 }
Greg Claytonf5e56de2010-09-14 23:36:40 +0000305 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000306 return PacketResult::ErrorSendFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000307}
308
Greg Clayton3dedae12013-12-06 21:45:27 +0000309GDBRemoteCommunication::PacketResult
Greg Claytonc574ede2011-03-10 02:26:48 +0000310GDBRemoteCommunication::GetAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000311{
Greg Clayton576d8832011-03-22 04:00:09 +0000312 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000313 PacketResult result = ReadPacket (packet, GetPacketTimeoutInMicroSeconds (), false);
Greg Clayton3dedae12013-12-06 21:45:27 +0000314 if (result == PacketResult::Success)
315 {
316 if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
317 return PacketResult::Success;
318 else
319 return PacketResult::ErrorSendAck;
320 }
321 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000322}
323
324bool
Jim Ingham4ceb9282012-06-08 22:50:40 +0000325GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326{
Greg Claytond9896732012-05-31 16:54:51 +0000327 if (IsRunning())
Jim Ingham4ceb9282012-06-08 22:50:40 +0000328 return locker.TryLock (m_sequence_mutex, failure_message);
Greg Claytond9896732012-05-31 16:54:51 +0000329
330 locker.Lock (m_sequence_mutex);
331 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000332}
333
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000334
Greg Clayton6779606a2011-01-22 23:43:18 +0000335bool
Greg Clayton6779606a2011-01-22 23:43:18 +0000336GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
337{
338 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
339}
340
Greg Clayton3dedae12013-12-06 21:45:27 +0000341GDBRemoteCommunication::PacketResult
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000342GDBRemoteCommunication::ReadPacket (StringExtractorGDBRemote &response, uint32_t timeout_usec, bool sync_on_timeout)
343{
344 if (m_read_thread_enabled)
345 return PopPacketFromQueue (response, timeout_usec);
346 else
347 return WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec, sync_on_timeout);
348}
349
350
351// This function is called when a packet is requested.
352// A whole packet is popped from the packet queue and returned to the caller.
353// Packets are placed into this queue from the communication read thread.
354// See GDBRemoteCommunication::AppendBytesToCache.
355GDBRemoteCommunication::PacketResult
356GDBRemoteCommunication::PopPacketFromQueue (StringExtractorGDBRemote &response, uint32_t timeout_usec)
357{
358 // Calculate absolute timeout value
359 TimeValue timeout = TimeValue::Now();
360 timeout.OffsetWithMicroSeconds(timeout_usec);
361
362 do
363 {
364 // scope for the mutex
365 {
366 // lock down the packet queue
367 Mutex::Locker locker(m_packet_queue_mutex);
368
369 // Wait on condition variable.
370 if (m_packet_queue.size() == 0)
371 m_condition_queue_not_empty.Wait(m_packet_queue_mutex, &timeout);
372
373 if (m_packet_queue.size() > 0)
374 {
375 // get the front element of the queue
376 response = m_packet_queue.front();
377
378 // remove the front element
379 m_packet_queue.pop();
380
381 // we got a packet
382 return PacketResult::Success;
383 }
384 }
385
386 // Disconnected
387 if (!IsConnected())
388 return PacketResult::ErrorDisconnected;
389
390 // Loop while not timed out
391 } while (TimeValue::Now() < timeout);
392
393 return PacketResult::ErrorReplyTimeout;
394}
395
396
397GDBRemoteCommunication::PacketResult
Greg Claytonb30c50c2015-05-29 00:01:55 +0000398GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec, bool sync_on_timeout)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000399{
Greg Clayton73bf5db2011-06-17 01:22:15 +0000400 uint8_t buffer[8192];
401 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000402
Greg Clayton5160ce52013-03-27 23:08:40 +0000403 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
Greg Clayton644247c2011-07-07 01:59:51 +0000404
Greg Clayton73bf5db2011-06-17 01:22:15 +0000405 // Check for a packet from our cache first without trying any reading...
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000406 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000407 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000408
Greg Clayton0c51ac32011-07-02 23:21:06 +0000409 bool timed_out = false;
Greg Clayton3dedae12013-12-06 21:45:27 +0000410 bool disconnected = false;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000411 while (IsConnected() && !timed_out)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412 {
Johnny Chen74549c82011-07-19 01:13:00 +0000413 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000414 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
Greg Clayton644247c2011-07-07 01:59:51 +0000415
416 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000417 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 +0000418 __PRETTY_FUNCTION__,
419 timeout_usec,
420 Communication::ConnectionStatusAsCString (status),
421 error.AsCString(),
Greg Clayton43e0af02012-09-18 18:04:04 +0000422 (uint64_t)bytes_read);
Greg Clayton644247c2011-07-07 01:59:51 +0000423
Greg Clayton73bf5db2011-06-17 01:22:15 +0000424 if (bytes_read > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000425 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000426 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000427 return PacketResult::Success;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000428 }
429 else
430 {
431 switch (status)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000432 {
Greg Clayton197bacf2011-07-02 21:07:54 +0000433 case eConnectionStatusTimedOut:
Greg Claytonf0066ad2014-05-02 00:45:31 +0000434 case eConnectionStatusInterrupted:
Greg Claytonb30c50c2015-05-29 00:01:55 +0000435 if (sync_on_timeout)
436 {
437 //------------------------------------------------------------------
438 /// Sync the remote GDB server and make sure we get a response that
439 /// corresponds to what we send.
440 ///
441 /// Sends a "qEcho" packet and makes sure it gets the exact packet
442 /// echoed back. If the qEcho packet isn't supported, we send a qC
443 /// packet and make sure we get a valid thread ID back. We use the
444 /// "qC" packet since its response if very unique: is responds with
445 /// "QC%x" where %x is the thread ID of the current thread. This
446 /// makes the response unique enough from other packet responses to
447 /// ensure we are back on track.
448 ///
449 /// This packet is needed after we time out sending a packet so we
450 /// can ensure that we are getting the response for the packet we
451 /// are sending. There are no sequence IDs in the GDB remote
452 /// protocol (there used to be, but they are not supported anymore)
453 /// so if you timeout sending packet "abc", you might then send
454 /// packet "cde" and get the response for the previous "abc" packet.
455 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
456 /// many responses for packets can look like responses for other
457 /// packets. So if we timeout, we need to ensure that we can get
458 /// back on track. If we can't get back on track, we must
459 /// disconnect.
460 //------------------------------------------------------------------
461 bool sync_success = false;
462 bool got_actual_response = false;
463 // We timed out, we need to sync back up with the
464 char echo_packet[32];
465 int echo_packet_len = 0;
466 RegularExpression response_regex;
467
468 if (m_supports_qEcho == eLazyBoolYes)
469 {
470 echo_packet_len = ::snprintf (echo_packet, sizeof(echo_packet), "qEcho:%u", ++m_echo_number);
471 std::string regex_str = "^";
472 regex_str += echo_packet;
473 regex_str += "$";
474 response_regex.Compile(regex_str.c_str());
475 }
476 else
477 {
478 echo_packet_len = ::snprintf (echo_packet, sizeof(echo_packet), "qC");
479 response_regex.Compile("^QC[0-9A-Fa-f]+$");
480 }
481
482 PacketResult echo_packet_result = SendPacketNoLock (echo_packet, echo_packet_len);
483 if (echo_packet_result == PacketResult::Success)
484 {
485 const uint32_t max_retries = 3;
486 uint32_t successful_responses = 0;
487 for (uint32_t i=0; i<max_retries; ++i)
488 {
489 StringExtractorGDBRemote echo_response;
490 echo_packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (echo_response, timeout_usec, false);
491 if (echo_packet_result == PacketResult::Success)
492 {
493 ++successful_responses;
494 if (response_regex.Execute(echo_response.GetStringRef().c_str()))
495 {
496 sync_success = true;
497 break;
498 }
499 else if (successful_responses == 1)
500 {
501 // We got something else back as the first successful response, it probably is
502 // the response to the packet we actually wanted, so copy it over if this
503 // is the first success and continue to try to get the qEcho response
504 packet = echo_response;
505 got_actual_response = true;
506 }
507 }
508 else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
509 continue; // Packet timed out, continue waiting for a response
510 else
511 break; // Something else went wrong getting the packet back, we failed and are done trying
512 }
513 }
514
515 // We weren't able to sync back up with the server, we must abort otherwise
516 // all responses might not be from the right packets...
517 if (sync_success)
518 {
519 // We timed out, but were able to recover
520 if (got_actual_response)
521 {
522 // We initially timed out, but we did get a response that came in before the successful
523 // reply to our qEcho packet, so lets say everything is fine...
524 return PacketResult::Success;
525 }
526 }
527 else
528 {
529 disconnected = true;
530 Disconnect();
531 }
532 }
Greg Clayton0c51ac32011-07-02 23:21:06 +0000533 timed_out = true;
534 break;
535 case eConnectionStatusSuccess:
536 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
Greg Clayton73bf5db2011-06-17 01:22:15 +0000537 break;
538
539 case eConnectionStatusEndOfFile:
540 case eConnectionStatusNoConnection:
541 case eConnectionStatusLostConnection:
542 case eConnectionStatusError:
Greg Clayton3dedae12013-12-06 21:45:27 +0000543 disconnected = true;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000544 Disconnect();
545 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000546 }
547 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000548 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000549 packet.Clear ();
550 if (disconnected)
551 return PacketResult::ErrorDisconnected;
552 if (timed_out)
553 return PacketResult::ErrorReplyTimeout;
554 else
555 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000556}
557
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000558bool
559GDBRemoteCommunication::DecompressPacket ()
560{
561 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
562
563 if (!CompressionIsEnabled())
564 return true;
565
566 size_t pkt_size = m_bytes.size();
Jason Molendafea77652015-07-14 19:19:07 +0000567
568 // Smallest possible compressed packet is $N#00 - an uncompressed empty reply, most commonly indicating
569 // an unsupported packet. Anything less than 5 characters, it's definitely not a compressed packet.
Jason Molenda21c34ac2015-07-14 04:51:05 +0000570 if (pkt_size < 5)
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000571 return true;
Jason Molendafea77652015-07-14 19:19:07 +0000572
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000573 if (m_bytes[0] != '$' && m_bytes[0] != '%')
574 return true;
575 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
576 return true;
577 if (m_bytes[pkt_size - 3] != '#')
578 return true;
579 if (!::isxdigit (m_bytes[pkt_size - 2]) || !::isxdigit (m_bytes[pkt_size - 1]))
580 return true;
581
582 size_t content_length = pkt_size - 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
583 size_t content_start = 2; // The first character of the compressed/not-compressed text of the packet
584 size_t hash_mark_idx = pkt_size - 3; // The '#' character marking the end of the packet
585 size_t checksum_idx = pkt_size - 2; // The first character of the two hex checksum characters
586
587 // Compressed packets ("$C") start with a base10 number which is the size of the uncompressed payload,
588 // then a : and then the compressed data. e.g. $C1024:<binary>#00
589 // Update content_start and content_length to only include the <binary> part of the packet.
590
591 uint64_t decompressed_bufsize = ULONG_MAX;
592 if (m_bytes[1] == 'C')
593 {
594 size_t i = content_start;
595 while (i < hash_mark_idx && isdigit(m_bytes[i]))
596 i++;
597 if (i < hash_mark_idx && m_bytes[i] == ':')
598 {
599 i++;
600 content_start = i;
601 content_length = hash_mark_idx - content_start;
602 std::string bufsize_str (m_bytes.data() + 2, i - 2 - 1);
603 errno = 0;
604 decompressed_bufsize = ::strtoul (bufsize_str.c_str(), NULL, 10);
605 if (errno != 0 || decompressed_bufsize == ULONG_MAX)
606 {
607 m_bytes.erase (0, pkt_size);
608 return false;
609 }
610 }
611 }
612
613 if (GetSendAcks ())
614 {
615 char packet_checksum_cstr[3];
616 packet_checksum_cstr[0] = m_bytes[checksum_idx];
617 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
618 packet_checksum_cstr[2] = '\0';
619 long packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
620
621 long actual_checksum = CalculcateChecksum (m_bytes.data() + 1, hash_mark_idx - 1);
622 bool success = packet_checksum == actual_checksum;
623 if (!success)
624 {
625 if (log)
626 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
627 (int)(pkt_size),
628 m_bytes.c_str(),
629 (uint8_t)packet_checksum,
630 (uint8_t)actual_checksum);
631 }
632 // Send the ack or nack if needed
633 if (!success)
634 {
635 SendNack();
636 m_bytes.erase (0, pkt_size);
637 return false;
638 }
639 else
640 {
641 SendAck();
642 }
643 }
644
645 if (m_bytes[1] == 'N')
646 {
647 // This packet was not compressed -- delete the 'N' character at the
648 // start and the packet may be processed as-is.
649 m_bytes.erase(1, 1);
650 return true;
651 }
652
653 // Reverse the gdb-remote binary escaping that was done to the compressed text to
654 // guard characters like '$', '#', '}', etc.
655 std::vector<uint8_t> unescaped_content;
656 unescaped_content.reserve (content_length);
657 size_t i = content_start;
658 while (i < hash_mark_idx)
659 {
660 if (m_bytes[i] == '}')
661 {
662 i++;
663 unescaped_content.push_back (m_bytes[i] ^ 0x20);
664 }
665 else
666 {
667 unescaped_content.push_back (m_bytes[i]);
668 }
669 i++;
670 }
671
672 uint8_t *decompressed_buffer = nullptr;
673 size_t decompressed_bytes = 0;
674
675 if (decompressed_bufsize != ULONG_MAX)
676 {
677 decompressed_buffer = (uint8_t *) malloc (decompressed_bufsize + 1);
678 if (decompressed_buffer == nullptr)
679 {
680 m_bytes.erase (0, pkt_size);
681 return false;
682 }
683
684 }
685
686#if defined (HAVE_LIBCOMPRESSION)
687 // libcompression is weak linked so check that compression_decode_buffer() is available
688 if (compression_decode_buffer != NULL &&
689 (m_compression_type == CompressionType::ZlibDeflate
690 || m_compression_type == CompressionType::LZFSE
691 || m_compression_type == CompressionType::LZ4))
692 {
693 compression_algorithm compression_type;
694 if (m_compression_type == CompressionType::ZlibDeflate)
695 compression_type = COMPRESSION_ZLIB;
696 else if (m_compression_type == CompressionType::LZFSE)
697 compression_type = COMPRESSION_LZFSE;
698 else if (m_compression_type == CompressionType::LZ4)
699 compression_type = COMPRESSION_LZ4_RAW;
700 else if (m_compression_type == CompressionType::LZMA)
701 compression_type = COMPRESSION_LZMA;
702
703
704 // If we have the expected size of the decompressed payload, we can allocate
705 // the right-sized buffer and do it. If we don't have that information, we'll
706 // need to try decoding into a big buffer and if the buffer wasn't big enough,
707 // increase it and try again.
708
709 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr)
710 {
711 decompressed_bytes = compression_decode_buffer (decompressed_buffer, decompressed_bufsize + 10 ,
712 (uint8_t*) unescaped_content.data(),
713 unescaped_content.size(),
714 NULL,
715 compression_type);
716 }
717 }
718#endif
719
720#if defined (HAVE_LIBZ)
721 if (decompressed_bytes == 0
722 && decompressed_bufsize != ULONG_MAX
723 && decompressed_buffer != nullptr
724 && m_compression_type == CompressionType::ZlibDeflate)
725 {
726 z_stream stream;
727 memset (&stream, 0, sizeof (z_stream));
728 stream.next_in = (Bytef *) unescaped_content.data();
729 stream.avail_in = (uInt) unescaped_content.size();
730 stream.total_in = 0;
731 stream.next_out = (Bytef *) decompressed_buffer;
732 stream.avail_out = decompressed_bufsize;
733 stream.total_out = 0;
734 stream.zalloc = Z_NULL;
735 stream.zfree = Z_NULL;
736 stream.opaque = Z_NULL;
737
738 if (inflateInit2 (&stream, -15) == Z_OK)
739 {
740 int status = inflate (&stream, Z_NO_FLUSH);
741 inflateEnd (&stream);
742 if (status == Z_STREAM_END)
743 {
744 decompressed_bytes = stream.total_out;
745 }
746 }
747 }
748#endif
749
750 if (decompressed_bytes == 0 || decompressed_buffer == nullptr)
751 {
752 if (decompressed_buffer)
753 free (decompressed_buffer);
754 m_bytes.erase (0, pkt_size);
755 return false;
756 }
757
758 std::string new_packet;
759 new_packet.reserve (decompressed_bytes + 6);
760 new_packet.push_back (m_bytes[0]);
761 new_packet.append ((const char *) decompressed_buffer, decompressed_bytes);
762 new_packet.push_back ('#');
763 if (GetSendAcks ())
764 {
765 uint8_t decompressed_checksum = CalculcateChecksum ((const char *) decompressed_buffer, decompressed_bytes);
766 char decompressed_checksum_str[3];
767 snprintf (decompressed_checksum_str, 3, "%02x", decompressed_checksum);
768 new_packet.append (decompressed_checksum_str);
769 }
770 else
771 {
772 new_packet.push_back ('0');
773 new_packet.push_back ('0');
774 }
775
776 m_bytes = new_packet;
777
778 free (decompressed_buffer);
779 return true;
780}
781
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000782GDBRemoteCommunication::PacketType
Greg Clayton73bf5db2011-06-17 01:22:15 +0000783GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784{
785 // Put the packet data into the buffer in a thread safe fashion
786 Mutex::Locker locker(m_bytes_mutex);
Greg Clayton197bacf2011-07-02 21:07:54 +0000787
Greg Clayton5160ce52013-03-27 23:08:40 +0000788 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000789
Greg Clayton73bf5db2011-06-17 01:22:15 +0000790 if (src && src_len > 0)
Greg Clayton197bacf2011-07-02 21:07:54 +0000791 {
Greg Clayton0c51ac32011-07-02 23:21:06 +0000792 if (log && log->GetVerbose())
Greg Clayton197bacf2011-07-02 21:07:54 +0000793 {
794 StreamString s;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000795 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
796 __FUNCTION__,
797 (uint32_t)src_len,
798 (uint32_t)src_len,
799 src);
Greg Clayton197bacf2011-07-02 21:07:54 +0000800 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000801 m_bytes.append ((const char *)src, src_len);
Greg Clayton197bacf2011-07-02 21:07:54 +0000802 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000803
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000804 bool isNotifyPacket = false;
805
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000806 // Parse up the packets into gdb remote packets
Greg Clayton197bacf2011-07-02 21:07:54 +0000807 if (!m_bytes.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000808 {
809 // end_idx must be one past the last valid packet byte. Start
810 // it off with an invalid value that is the same as the current
811 // index.
Greg Clayton73bf5db2011-06-17 01:22:15 +0000812 size_t content_start = 0;
Greg Clayton118593a2014-11-03 21:02:54 +0000813 size_t content_length = 0;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000814 size_t total_length = 0;
815 size_t checksum_idx = std::string::npos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000817 // Size of packet before it is decompressed, for logging purposes
818 size_t original_packet_size = m_bytes.size();
819 if (CompressionIsEnabled())
820 {
821 if (DecompressPacket() == false)
822 {
823 packet.Clear();
824 return GDBRemoteCommunication::PacketType::Standard;
825 }
826 }
827
Greg Clayton118593a2014-11-03 21:02:54 +0000828 switch (m_bytes[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000829 {
Greg Clayton118593a2014-11-03 21:02:54 +0000830 case '+': // Look for ack
831 case '-': // Look for cancel
832 case '\x03': // ^C to halt target
833 content_length = total_length = 1; // The command is one byte long...
834 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000835
Ewan Crawford78baa192015-05-13 09:18:18 +0000836 case '%': // Async notify packet
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000837 isNotifyPacket = true;
838 // Intentional fall through
839
Greg Clayton118593a2014-11-03 21:02:54 +0000840 case '$':
841 // Look for a standard gdb packet?
842 {
843 size_t hash_pos = m_bytes.find('#');
844 if (hash_pos != std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845 {
Greg Clayton118593a2014-11-03 21:02:54 +0000846 if (hash_pos + 2 < m_bytes.size())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000847 {
Greg Clayton118593a2014-11-03 21:02:54 +0000848 checksum_idx = hash_pos + 1;
849 // Skip the dollar sign
850 content_start = 1;
851 // Don't include the # in the content or the $ in the content length
852 content_length = hash_pos - 1;
853
854 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
855 }
856 else
857 {
858 // Checksum bytes aren't all here yet
859 content_length = std::string::npos;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000860 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000861 }
Greg Clayton118593a2014-11-03 21:02:54 +0000862 }
863 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000864
Greg Clayton118593a2014-11-03 21:02:54 +0000865 default:
866 {
867 // We have an unexpected byte and we need to flush all bad
868 // data that is in m_bytes, so we need to find the first
869 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
870 // or '$' character (start of packet header) or of course,
871 // the end of the data in m_bytes...
872 const size_t bytes_len = m_bytes.size();
873 bool done = false;
874 uint32_t idx;
875 for (idx = 1; !done && idx < bytes_len; ++idx)
Greg Clayton197bacf2011-07-02 21:07:54 +0000876 {
Greg Clayton118593a2014-11-03 21:02:54 +0000877 switch (m_bytes[idx])
Greg Clayton197bacf2011-07-02 21:07:54 +0000878 {
Greg Clayton118593a2014-11-03 21:02:54 +0000879 case '+':
880 case '-':
881 case '\x03':
Ewan Crawford78baa192015-05-13 09:18:18 +0000882 case '%':
Greg Clayton118593a2014-11-03 21:02:54 +0000883 case '$':
884 done = true;
885 break;
886
887 default:
888 break;
Greg Clayton197bacf2011-07-02 21:07:54 +0000889 }
890 }
Greg Clayton118593a2014-11-03 21:02:54 +0000891 if (log)
892 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
893 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
894 m_bytes.erase(0, idx - 1);
895 }
896 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897 }
898
Greg Clayton73bf5db2011-06-17 01:22:15 +0000899 if (content_length == std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000901 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000902 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 }
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000904 else if (total_length > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000906
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907 // We have a valid packet...
Greg Clayton73bf5db2011-06-17 01:22:15 +0000908 assert (content_length <= m_bytes.size());
909 assert (total_length <= m_bytes.size());
910 assert (content_length <= total_length);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000911 size_t content_end = content_start + content_length;
Greg Clayton06f09b52014-06-20 20:41:07 +0000912
Greg Clayton73bf5db2011-06-17 01:22:15 +0000913 bool success = true;
914 std::string &packet_str = packet.GetStringRef();
Greg Claytonc1422c12012-04-09 22:46:21 +0000915 if (log)
916 {
917 // If logging was just enabled and we have history, then dump out what
918 // we have to the log so we get the historical context. The Dump() call that
919 // logs all of the packet will set a boolean so that we don't dump this more
920 // than once
921 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000922 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000923
Greg Clayton06f09b52014-06-20 20:41:07 +0000924 bool binary = false;
925 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
926 if (m_bytes[0] == '$' && total_length > 4)
927 {
928 for (size_t i=0; !binary && i<total_length; ++i)
929 {
930 if (isprint(m_bytes[i]) == 0)
931 binary = true;
932 }
933 }
934 if (binary)
935 {
936 StreamString strm;
937 // Packet header...
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000938 if (CompressionIsEnabled())
939 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c", (uint64_t) original_packet_size, (uint64_t)total_length, m_bytes[0]);
940 else
941 strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
Greg Clayton06f09b52014-06-20 20:41:07 +0000942 for (size_t i=content_start; i<content_end; ++i)
943 {
944 // Remove binary escaped bytes when displaying the packet...
945 const char ch = m_bytes[i];
946 if (ch == 0x7d)
947 {
948 // 0x7d is the escape character. The next character is to
949 // be XOR'd with 0x20.
950 const char escapee = m_bytes[++i] ^ 0x20;
951 strm.Printf("%2.2x", escapee);
952 }
953 else
954 {
955 strm.Printf("%2.2x", (uint8_t)ch);
956 }
957 }
958 // Packet footer...
959 strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
960 log->PutCString(strm.GetString().c_str());
961 }
962 else
963 {
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000964 if (CompressionIsEnabled())
965 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s", (uint64_t) original_packet_size, (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
966 else
967 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 +0000968 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000969 }
970
971 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
972
Hafiz Abid Qadeere5fd5e12013-08-28 15:10:37 +0000973 // Clear packet_str in case there is some existing data in it.
974 packet_str.clear();
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000975 // Copy the packet from m_bytes to packet_str expanding the
976 // run-length encoding in the process.
977 // Reserve enough byte for the most common case (no RLE used)
978 packet_str.reserve(m_bytes.length());
Greg Clayton06f09b52014-06-20 20:41:07 +0000979 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 +0000980 {
981 if (*c == '*')
982 {
983 // '*' indicates RLE. Next character will give us the
984 // repeat count and previous character is what is to be
985 // repeated.
986 char char_to_repeat = packet_str.back();
987 // Number of time the previous character is repeated
988 int repeat_count = *++c + 3 - ' ';
989 // We have the char_to_repeat and repeat_count. Now push
990 // it in the packet.
991 for (int i = 0; i < repeat_count; ++i)
992 packet_str.push_back(char_to_repeat);
993 }
Steve Pucci3c5d3332014-02-24 19:07:29 +0000994 else if (*c == 0x7d)
995 {
996 // 0x7d is the escape character. The next character is to
997 // be XOR'd with 0x20.
998 char escapee = *++c ^ 0x20;
999 packet_str.push_back(escapee);
1000 }
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +00001001 else
1002 {
1003 packet_str.push_back(*c);
1004 }
1005 }
1006
Ewan Crawford78baa192015-05-13 09:18:18 +00001007 if (m_bytes[0] == '$' || m_bytes[0] == '%')
Greg Clayton73bf5db2011-06-17 01:22:15 +00001008 {
1009 assert (checksum_idx < m_bytes.size());
1010 if (::isxdigit (m_bytes[checksum_idx+0]) ||
1011 ::isxdigit (m_bytes[checksum_idx+1]))
1012 {
1013 if (GetSendAcks ())
1014 {
1015 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
1016 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
1017 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
1018 success = packet_checksum == actual_checksum;
1019 if (!success)
1020 {
1021 if (log)
1022 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
1023 (int)(total_length),
1024 m_bytes.c_str(),
1025 (uint8_t)packet_checksum,
1026 (uint8_t)actual_checksum);
1027 }
1028 // Send the ack or nack if needed
1029 if (!success)
1030 SendNack();
1031 else
1032 SendAck();
1033 }
Greg Clayton73bf5db2011-06-17 01:22:15 +00001034 }
1035 else
1036 {
1037 success = false;
1038 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001039 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
Greg Clayton73bf5db2011-06-17 01:22:15 +00001040 }
1041 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001042
Greg Clayton73bf5db2011-06-17 01:22:15 +00001043 m_bytes.erase(0, total_length);
1044 packet.SetFilePos(0);
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001045
1046 if (isNotifyPacket)
1047 return GDBRemoteCommunication::PacketType::Notify;
1048 else
1049 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001051 }
Greg Clayton73bf5db2011-06-17 01:22:15 +00001052 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001053 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001054}
1055
Greg Clayton8b82f082011-04-12 05:54:46 +00001056Error
Greg Claytond6299802013-12-06 17:46:35 +00001057GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
Greg Clayton00fe87b2013-12-05 22:58:22 +00001058{
1059 Error error;
Zachary Turneracee96a2014-09-23 18:32:09 +00001060 if (m_listen_thread.IsJoinable())
Greg Clayton00fe87b2013-12-05 22:58:22 +00001061 {
1062 error.SetErrorString("listen thread already running");
1063 }
1064 else
1065 {
1066 char listen_url[512];
1067 if (hostname && hostname[0])
Jean-Daniel Dupas3c6774a2014-02-08 20:29:40 +00001068 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001069 else
1070 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
1071 m_listen_url = listen_url;
1072 SetConnection(new ConnectionFileDescriptor());
Zachary Turner39de3112014-09-09 20:54:56 +00001073 m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001074 }
1075 return error;
1076}
1077
1078bool
1079GDBRemoteCommunication::JoinListenThread ()
1080{
Zachary Turneracee96a2014-09-23 18:32:09 +00001081 if (m_listen_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +00001082 m_listen_thread.Join(nullptr);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001083 return true;
1084}
1085
1086lldb::thread_result_t
1087GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
1088{
1089 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
1090 Error error;
1091 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
1092
1093 if (connection)
1094 {
1095 // Do the listen on another thread so we can continue on...
1096 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
1097 comm->SetConnection(NULL);
1098 }
1099 return NULL;
1100}
1101
1102Error
Greg Claytonfda4fab2014-01-10 22:24:11 +00001103GDBRemoteCommunication::StartDebugserverProcess (const char *hostname,
1104 uint16_t in_port,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001105 ProcessLaunchInfo &launch_info,
Greg Claytonfda4fab2014-01-10 22:24:11 +00001106 uint16_t &out_port)
Greg Clayton8b82f082011-04-12 05:54:46 +00001107{
Todd Fiala015d8182014-07-22 23:41:36 +00001108 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1109 if (log)
1110 log->Printf ("GDBRemoteCommunication::%s(hostname=%s, in_port=%" PRIu16 ", out_port=%" PRIu16, __FUNCTION__, hostname ? hostname : "<empty>", in_port, out_port);
1111
Greg Claytonfda4fab2014-01-10 22:24:11 +00001112 out_port = in_port;
Greg Clayton8b82f082011-04-12 05:54:46 +00001113 Error error;
1114 // If we locate debugserver, keep that located version around
1115 static FileSpec g_debugserver_file_spec;
1116
Greg Clayton8b82f082011-04-12 05:54:46 +00001117 char debugserver_path[PATH_MAX];
1118 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
1119
1120 // Always check to see if we have an environment override for the path
1121 // to the debugserver to use and use it if we do.
1122 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1123 if (env_debugserver_path)
Todd Fiala015d8182014-07-22 23:41:36 +00001124 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001125 debugserver_file_spec.SetFile (env_debugserver_path, false);
Todd Fiala015d8182014-07-22 23:41:36 +00001126 if (log)
1127 log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path);
1128 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001129 else
1130 debugserver_file_spec = g_debugserver_file_spec;
1131 bool debugserver_exists = debugserver_file_spec.Exists();
1132 if (!debugserver_exists)
1133 {
1134 // The debugserver binary is in the LLDB.framework/Resources
Zachary Turner42ff0ad2014-08-21 17:29:12 +00001135 // directory.
1136 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec))
Greg Clayton8b82f082011-04-12 05:54:46 +00001137 {
Jason Molenda6fd86772014-08-21 23:22:33 +00001138 debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME);
Greg Clayton8b82f082011-04-12 05:54:46 +00001139 debugserver_exists = debugserver_file_spec.Exists();
1140 if (debugserver_exists)
1141 {
Todd Fiala015d8182014-07-22 23:41:36 +00001142 if (log)
1143 log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
1144
Greg Clayton8b82f082011-04-12 05:54:46 +00001145 g_debugserver_file_spec = debugserver_file_spec;
1146 }
1147 else
1148 {
Todd Fiala015d8182014-07-22 23:41:36 +00001149 if (log)
1150 log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
1151
Greg Clayton8b82f082011-04-12 05:54:46 +00001152 g_debugserver_file_spec.Clear();
1153 debugserver_file_spec.Clear();
1154 }
1155 }
1156 }
1157
1158 if (debugserver_exists)
1159 {
1160 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1161
1162 Args &debugserver_args = launch_info.GetArguments();
1163 debugserver_args.Clear();
1164 char arg_cstr[PATH_MAX];
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001165
Greg Clayton8b82f082011-04-12 05:54:46 +00001166 // Start args with "debugserver /file/path -r --"
1167 debugserver_args.AppendArgument(debugserver_path);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001168
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001169#if !defined(__APPLE__)
1170 // First argument to lldb-server must be mode in which to run.
1171 debugserver_args.AppendArgument("gdbserver");
1172#endif
1173
Greg Clayton00fe87b2013-12-05 22:58:22 +00001174 // If a host and port is supplied then use it
Greg Claytonfda4fab2014-01-10 22:24:11 +00001175 char host_and_port[128];
1176 if (hostname)
1177 {
1178 snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001179 debugserver_args.AppendArgument(host_and_port);
Greg Claytonfda4fab2014-01-10 22:24:11 +00001180 }
1181 else
1182 {
1183 host_and_port[0] = '\0';
1184 }
1185
Greg Clayton8b82f082011-04-12 05:54:46 +00001186 // use native registers, not the GDB registers
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001187 debugserver_args.AppendArgument("--native-regs");
1188
1189 if (launch_info.GetLaunchInSeparateProcessGroup())
1190 {
1191 debugserver_args.AppendArgument("--setsid");
1192 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001193
Oleksiy Vyalov4536c452015-02-05 16:29:12 +00001194 llvm::SmallString<PATH_MAX> named_pipe_path;
Chaoren Lin368c9f62015-04-27 23:20:30 +00001195 Pipe port_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001196
Vince Harrond7e6a4f2015-05-13 00:25:54 +00001197 if (host_and_port[0] && in_port == 0)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001198 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001199 // Create a temporary file to get the stdout/stderr and redirect the
1200 // output of the command into this file. We will later read this file
1201 // if all goes well and fill the data into "command_output_ptr"
Greg Clayton00fe87b2013-12-05 22:58:22 +00001202
Vince Harrond7e6a4f2015-05-13 00:25:54 +00001203 // Binding to port zero, we need to figure out what port it ends up
1204 // using using a named pipe...
1205 error = port_pipe.CreateWithUniqueName("debugserver-named-pipe", false, named_pipe_path);
1206 if (error.Success())
Greg Clayton00fe87b2013-12-05 22:58:22 +00001207 {
Vince Harrond7e6a4f2015-05-13 00:25:54 +00001208 debugserver_args.AppendArgument("--named-pipe");
1209 debugserver_args.AppendArgument(named_pipe_path.c_str());
Greg Clayton91a9b2472013-12-04 19:19:12 +00001210 }
1211 else
Greg Claytonfda4fab2014-01-10 22:24:11 +00001212 {
Vince Harrond7e6a4f2015-05-13 00:25:54 +00001213 if (log)
1214 log->Printf("GDBRemoteCommunication::%s() "
1215 "named pipe creation failed: %s",
1216 __FUNCTION__, error.AsCString());
1217 // let's try an unnamed pipe
1218 error = port_pipe.CreateNew(true);
1219 if (error.Fail())
1220 {
1221 if (log)
1222 log->Printf("GDBRemoteCommunication::%s() "
1223 "unnamed pipe creation failed: %s",
1224 __FUNCTION__, error.AsCString());
1225 return error;
1226 }
1227 int write_fd = port_pipe.GetWriteFileDescriptor();
1228 debugserver_args.AppendArgument("--pipe");
1229 debugserver_args.AppendArgument(std::to_string(write_fd).c_str());
1230 launch_info.AppendCloseFileAction(port_pipe.GetReadFileDescriptor());
Greg Claytonfda4fab2014-01-10 22:24:11 +00001231 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001232 }
1233 else
Greg Clayton00fe87b2013-12-05 22:58:22 +00001234 {
Greg Clayton00fe87b2013-12-05 22:58:22 +00001235 // No host and port given, so lets listen on our end and make the debugserver
1236 // connect to us..
Greg Clayton16810922014-02-27 19:38:18 +00001237 error = StartListenThread ("127.0.0.1", 0);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001238 if (error.Fail())
Vince Harron8b335672015-05-12 01:10:56 +00001239 {
1240 if (log)
1241 log->Printf ("GDBRemoteCommunication::%s() unable to start listen thread: %s", __FUNCTION__, error.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001242 return error;
Vince Harron8b335672015-05-12 01:10:56 +00001243 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001244
Greg Clayton00fe87b2013-12-05 22:58:22 +00001245 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
Greg Clayton16810922014-02-27 19:38:18 +00001246 // Wait for 10 seconds to resolve the bound port
Zachary Turner98688922014-08-06 18:16:26 +00001247 out_port = connection->GetListeningPort(10);
Greg Clayton16810922014-02-27 19:38:18 +00001248 if (out_port > 0)
1249 {
1250 char port_cstr[32];
1251 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", out_port);
1252 // Send the host and port down that debugserver and specify an option
1253 // so that it connects back to the port we are listening to in this process
1254 debugserver_args.AppendArgument("--reverse-connect");
1255 debugserver_args.AppendArgument(port_cstr);
1256 }
1257 else
1258 {
1259 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
Vince Harron8b335672015-05-12 01:10:56 +00001260 if (log)
1261 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
Greg Clayton16810922014-02-27 19:38:18 +00001262 return error;
1263 }
Greg Clayton00fe87b2013-12-05 22:58:22 +00001264 }
Greg Clayton00fe87b2013-12-05 22:58:22 +00001265
Greg Clayton8b82f082011-04-12 05:54:46 +00001266 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1267 if (env_debugserver_log_file)
1268 {
1269 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1270 debugserver_args.AppendArgument(arg_cstr);
1271 }
1272
Vince Harron9753dd92015-05-10 15:22:09 +00001273#if defined(__APPLE__)
Greg Clayton8b82f082011-04-12 05:54:46 +00001274 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1275 if (env_debugserver_log_flags)
1276 {
1277 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1278 debugserver_args.AppendArgument(arg_cstr);
1279 }
Vince Harron9753dd92015-05-10 15:22:09 +00001280#else
1281 const char *env_debugserver_log_channels = getenv("LLDB_SERVER_LOG_CHANNELS");
1282 if (env_debugserver_log_channels)
1283 {
1284 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-channels=%s", env_debugserver_log_channels);
1285 debugserver_args.AppendArgument(arg_cstr);
1286 }
1287#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001288
1289 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back.
1290 uint32_t env_var_index = 1;
1291 bool has_env_var;
1292 do
1293 {
1294 char env_var_name[64];
1295 snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1296 const char *extra_arg = getenv(env_var_name);
1297 has_env_var = extra_arg != nullptr;
1298
1299 if (has_env_var)
1300 {
1301 debugserver_args.AppendArgument (extra_arg);
1302 if (log)
1303 log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg);
1304 }
1305 } while (has_env_var);
1306
Shawn Best629680e2014-11-05 00:58:55 +00001307 // Close STDIN, STDOUT and STDERR.
Greg Clayton91a9b2472013-12-04 19:19:12 +00001308 launch_info.AppendCloseFileAction (STDIN_FILENO);
1309 launch_info.AppendCloseFileAction (STDOUT_FILENO);
1310 launch_info.AppendCloseFileAction (STDERR_FILENO);
Shawn Best629680e2014-11-05 00:58:55 +00001311
1312 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1313 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1314 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1315 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
Zachary Turner9b693272014-12-04 22:06:42 +00001316
Greg Clayton8b82f082011-04-12 05:54:46 +00001317 error = Host::LaunchProcess(launch_info);
Zachary Turner9b693272014-12-04 22:06:42 +00001318
Greg Clayton3121fde2014-02-28 20:47:08 +00001319 if (error.Success() && launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001320 {
Oleksiy Vyalov4536c452015-02-05 16:29:12 +00001321 if (named_pipe_path.size() > 0)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001322 {
Chaoren Lin368c9f62015-04-27 23:20:30 +00001323 error = port_pipe.OpenAsReader(named_pipe_path, false);
1324 if (error.Fail())
1325 if (log)
1326 log->Printf("GDBRemoteCommunication::%s() "
1327 "failed to open named pipe %s for reading: %s",
1328 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1329 }
1330
1331 if (port_pipe.CanWrite())
1332 port_pipe.CloseWriteFileDescriptor();
1333 if (port_pipe.CanRead())
1334 {
1335 char port_cstr[256];
1336 port_cstr[0] = '\0';
1337 size_t num_bytes = sizeof(port_cstr);
1338 // Read port from pipe with 10 second timeout.
1339 error = port_pipe.ReadWithTimeout(port_cstr, num_bytes,
1340 std::chrono::seconds{10}, num_bytes);
Greg Clayton3121fde2014-02-28 20:47:08 +00001341 if (error.Success())
1342 {
Chaoren Lin368c9f62015-04-27 23:20:30 +00001343 assert(num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
1344 out_port = StringConvert::ToUInt32(port_cstr, 0);
1345 if (log)
1346 log->Printf("GDBRemoteCommunication::%s() "
1347 "debugserver listens %u port",
1348 __FUNCTION__, out_port);
Greg Clayton3121fde2014-02-28 20:47:08 +00001349 }
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001350 else
1351 {
1352 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +00001353 log->Printf("GDBRemoteCommunication::%s() "
1354 "failed to read a port value from pipe %s: %s",
1355 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1356
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001357 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001358 port_pipe.Close();
1359 }
1360
1361 if (named_pipe_path.size() > 0)
1362 {
1363 const auto err = port_pipe.Delete(named_pipe_path);
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001364 if (err.Fail())
1365 {
1366 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +00001367 log->Printf ("GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1368 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001369 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001370 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001371
1372 // Make sure we actually connect with the debugserver...
1373 JoinListenThread();
Greg Clayton00fe87b2013-12-05 22:58:22 +00001374 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001375 }
1376 else
1377 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001378 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
Greg Clayton8b82f082011-04-12 05:54:46 +00001379 }
Vince Harron8b335672015-05-12 01:10:56 +00001380
1381 if (error.Fail())
1382 {
1383 if (log)
1384 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
1385 }
1386
Greg Clayton8b82f082011-04-12 05:54:46 +00001387 return error;
1388}
1389
Greg Claytonc1422c12012-04-09 22:46:21 +00001390void
Greg Claytond451c1a2012-04-13 21:24:18 +00001391GDBRemoteCommunication::DumpHistory(Stream &strm)
Greg Claytonc1422c12012-04-09 22:46:21 +00001392{
Greg Claytond451c1a2012-04-13 21:24:18 +00001393 m_history.Dump (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +00001394}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001395
1396GDBRemoteCommunication::ScopedTimeout::ScopedTimeout (GDBRemoteCommunication& gdb_comm,
1397 uint32_t timeout) :
1398 m_gdb_comm (gdb_comm)
1399{
1400 m_saved_timeout = m_gdb_comm.SetPacketTimeout (timeout);
1401}
1402
1403GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout ()
1404{
1405 m_gdb_comm.SetPacketTimeout (m_saved_timeout);
1406}
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001407
1408// This function is called via the Communications class read thread when bytes become available
1409// for this connection. This function will consume all incoming bytes and try to parse whole
1410// packets as they become available. Full packets are placed in a queue, so that all packet
1411// requests can simply pop from this queue. Async notification packets will be dispatched
1412// immediately to the ProcessGDBRemote Async thread via an event.
1413void GDBRemoteCommunication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, lldb::ConnectionStatus status)
1414{
1415 StringExtractorGDBRemote packet;
1416
1417 while (true)
1418 {
1419 PacketType type = CheckForPacket(bytes, len, packet);
1420
1421 // scrub the data so we do not pass it back to CheckForPacket
1422 // on future passes of the loop
1423 bytes = nullptr;
1424 len = 0;
1425
1426 // we may have received no packet so lets bail out
1427 if (type == PacketType::Invalid)
1428 break;
1429
1430 if (type == PacketType::Standard)
1431 {
1432 // scope for the mutex
1433 {
1434 // lock down the packet queue
1435 Mutex::Locker locker(m_packet_queue_mutex);
1436 // push a new packet into the queue
1437 m_packet_queue.push(packet);
1438 // Signal condition variable that we have a packet
1439 m_condition_queue_not_empty.Signal();
1440
1441 }
1442 }
1443
1444 if (type == PacketType::Notify)
1445 {
1446 // put this packet into an event
1447 const char *pdata = packet.GetStringRef().c_str();
1448
1449 // as the communication class, we are a broadcaster and the
1450 // async thread is tuned to listen to us
1451 BroadcastEvent(
1452 eBroadcastBitGdbReadThreadGotNotify,
1453 new EventDataBytes(pdata));
1454 }
1455 }
1456}