blob: 891cc22fec72cd4ed55891653e89096d01db9763 [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//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +0000155GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
Tamas Berghammere13c2732015-02-11 10:29:30 +0000156 const char *listener_name) :
Greg Clayton576d8832011-03-22 04:00:09 +0000157 Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000158#ifdef LLDB_CONFIGURATION_DEBUG
159 m_packet_timeout (1000),
160#else
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000161 m_packet_timeout (1),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000162#endif
Greg Claytonb30c50c2015-05-29 00:01:55 +0000163 m_echo_number(0),
164 m_supports_qEcho (eLazyBoolCalculate),
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000165 m_sequence_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton4dc72282011-01-20 07:53:45 +0000166 m_public_is_running (false),
Greg Clayton1cb64962011-03-24 04:28:38 +0000167 m_private_is_running (false),
Greg Claytonc1422c12012-04-09 22:46:21 +0000168 m_history (512),
Greg Clayton8b82f082011-04-12 05:54:46 +0000169 m_send_acks (true),
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000170 m_compression_type (CompressionType::None),
Greg Clayton00fe87b2013-12-05 22:58:22 +0000171 m_listen_url ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000172{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000173}
174
175//----------------------------------------------------------------------
176// Destructor
177//----------------------------------------------------------------------
178GDBRemoteCommunication::~GDBRemoteCommunication()
179{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000180 if (IsConnected())
181 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000182 Disconnect();
183 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000184
185 // Stop the communications read thread which is used to parse all
186 // incoming packets. This function will block until the read
187 // thread returns.
188 if (m_read_thread_enabled)
189 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000190}
191
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000192char
193GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
194{
195 int checksum = 0;
196
Ed Mastea6b4c772013-08-20 14:12:58 +0000197 for (size_t i = 0; i < payload_length; ++i)
198 checksum += payload[i];
199
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000200 return checksum & 255;
201}
202
203size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000204GDBRemoteCommunication::SendAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000205{
Greg Clayton5160ce52013-03-27 23:08:40 +0000206 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000208 char ch = '+';
209 const size_t bytes_written = Write (&ch, 1, status, NULL);
210 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000211 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000212 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
213 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000214}
215
216size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000217GDBRemoteCommunication::SendNack ()
218{
Greg Clayton5160ce52013-03-27 23:08:40 +0000219 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton6ed95942011-01-22 07:12:45 +0000220 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000221 char ch = '-';
222 const size_t bytes_written = Write (&ch, 1, status, NULL);
223 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000224 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000225 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
226 return bytes_written;
Greg Clayton32e0a752011-03-30 18:16:51 +0000227}
228
Greg Clayton3dedae12013-12-06 21:45:27 +0000229GDBRemoteCommunication::PacketResult
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000230GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
231{
232 Mutex::Locker locker(m_sequence_mutex);
233 return SendPacketNoLock (payload, payload_length);
234}
235
Greg Clayton3dedae12013-12-06 21:45:27 +0000236GDBRemoteCommunication::PacketResult
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000237GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
238{
239 if (IsConnected())
240 {
241 StreamString packet(0, 4, eByteOrderBig);
242
243 packet.PutChar('$');
244 packet.Write (payload, payload_length);
245 packet.PutChar('#');
246 packet.PutHex8(CalculcateChecksum (payload, payload_length));
247
Greg Clayton5160ce52013-03-27 23:08:40 +0000248 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000249 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton7e244322014-09-18 00:17:36 +0000250 const char *packet_data = packet.GetData();
251 const size_t packet_length = packet.GetSize();
252 size_t bytes_written = Write (packet_data, packet_length, status, NULL);
Greg Claytonc1422c12012-04-09 22:46:21 +0000253 if (log)
254 {
Greg Clayton7e244322014-09-18 00:17:36 +0000255 size_t binary_start_offset = 0;
256 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == 0)
257 {
258 const char *first_comma = strchr(packet_data, ',');
259 if (first_comma)
260 {
261 const char *second_comma = strchr(first_comma + 1, ',');
262 if (second_comma)
263 binary_start_offset = second_comma - packet_data + 1;
264 }
265 }
266
Greg Claytonc1422c12012-04-09 22:46:21 +0000267 // If logging was just enabled and we have history, then dump out what
268 // we have to the log so we get the historical context. The Dump() call that
269 // logs all of the packet will set a boolean so that we don't dump this more
270 // than once
271 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000272 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000273
Greg Clayton7e244322014-09-18 00:17:36 +0000274 if (binary_start_offset)
275 {
276 StreamString strm;
277 // Print non binary data header
278 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)binary_start_offset, packet_data);
279 const uint8_t *p;
280 // Print binary data exactly as sent
Vince Harron8b335672015-05-12 01:10:56 +0000281 for (p = (const uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p)
Greg Clayton7e244322014-09-18 00:17:36 +0000282 strm.Printf("\\x%2.2x", *p);
283 // Print the checksum
284 strm.Printf("%*s", (int)3, p);
285 log->PutCString(strm.GetString().c_str());
286 }
287 else
288 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet_length, packet_data);
Greg Claytonc1422c12012-04-09 22:46:21 +0000289 }
290
Greg Clayton7e244322014-09-18 00:17:36 +0000291 m_history.AddPacket (packet.GetString(), packet_length, History::ePacketTypeSend, bytes_written);
Greg Claytonc1422c12012-04-09 22:46:21 +0000292
293
Greg Clayton7e244322014-09-18 00:17:36 +0000294 if (bytes_written == packet_length)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000295 {
Greg Clayton71fc2a32011-02-12 06:28:37 +0000296 if (GetSendAcks ())
Greg Clayton3dedae12013-12-06 21:45:27 +0000297 return GetAck ();
298 else
299 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000300 }
Johnny Chend0c40dd2010-09-14 22:10:43 +0000301 else
302 {
Greg Clayton6d093452011-02-05 02:25:06 +0000303 if (log)
Greg Clayton7e244322014-09-18 00:17:36 +0000304 log->Printf ("error: failed to send packet: %.*s", (int)packet_length, packet_data);
Johnny Chend0c40dd2010-09-14 22:10:43 +0000305 }
Greg Claytonf5e56de2010-09-14 23:36:40 +0000306 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000307 return PacketResult::ErrorSendFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308}
309
Greg Clayton3dedae12013-12-06 21:45:27 +0000310GDBRemoteCommunication::PacketResult
Greg Claytonc574ede2011-03-10 02:26:48 +0000311GDBRemoteCommunication::GetAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000312{
Greg Clayton576d8832011-03-22 04:00:09 +0000313 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000314 PacketResult result = ReadPacket (packet, GetPacketTimeoutInMicroSeconds (), false);
Greg Clayton3dedae12013-12-06 21:45:27 +0000315 if (result == PacketResult::Success)
316 {
317 if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
318 return PacketResult::Success;
319 else
320 return PacketResult::ErrorSendAck;
321 }
322 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000323}
324
325bool
Jim Ingham4ceb9282012-06-08 22:50:40 +0000326GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000327{
Greg Claytond9896732012-05-31 16:54:51 +0000328 if (IsRunning())
Jim Ingham4ceb9282012-06-08 22:50:40 +0000329 return locker.TryLock (m_sequence_mutex, failure_message);
Greg Claytond9896732012-05-31 16:54:51 +0000330
331 locker.Lock (m_sequence_mutex);
332 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000333}
334
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000335
Greg Clayton6779606a2011-01-22 23:43:18 +0000336bool
Greg Clayton6779606a2011-01-22 23:43:18 +0000337GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
338{
339 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
340}
341
Greg Clayton3dedae12013-12-06 21:45:27 +0000342GDBRemoteCommunication::PacketResult
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000343GDBRemoteCommunication::ReadPacket (StringExtractorGDBRemote &response, uint32_t timeout_usec, bool sync_on_timeout)
344{
345 if (m_read_thread_enabled)
346 return PopPacketFromQueue (response, timeout_usec);
347 else
348 return WaitForPacketWithTimeoutMicroSecondsNoLock (response, timeout_usec, sync_on_timeout);
349}
350
351
352// This function is called when a packet is requested.
353// A whole packet is popped from the packet queue and returned to the caller.
354// Packets are placed into this queue from the communication read thread.
355// See GDBRemoteCommunication::AppendBytesToCache.
356GDBRemoteCommunication::PacketResult
357GDBRemoteCommunication::PopPacketFromQueue (StringExtractorGDBRemote &response, uint32_t timeout_usec)
358{
359 // Calculate absolute timeout value
360 TimeValue timeout = TimeValue::Now();
361 timeout.OffsetWithMicroSeconds(timeout_usec);
362
363 do
364 {
365 // scope for the mutex
366 {
367 // lock down the packet queue
368 Mutex::Locker locker(m_packet_queue_mutex);
369
370 // Wait on condition variable.
371 if (m_packet_queue.size() == 0)
372 m_condition_queue_not_empty.Wait(m_packet_queue_mutex, &timeout);
373
374 if (m_packet_queue.size() > 0)
375 {
376 // get the front element of the queue
377 response = m_packet_queue.front();
378
379 // remove the front element
380 m_packet_queue.pop();
381
382 // we got a packet
383 return PacketResult::Success;
384 }
385 }
386
387 // Disconnected
388 if (!IsConnected())
389 return PacketResult::ErrorDisconnected;
390
391 // Loop while not timed out
392 } while (TimeValue::Now() < timeout);
393
394 return PacketResult::ErrorReplyTimeout;
395}
396
397
398GDBRemoteCommunication::PacketResult
Greg Claytonb30c50c2015-05-29 00:01:55 +0000399GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec, bool sync_on_timeout)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400{
Greg Clayton73bf5db2011-06-17 01:22:15 +0000401 uint8_t buffer[8192];
402 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000403
Greg Clayton5160ce52013-03-27 23:08:40 +0000404 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
Greg Clayton644247c2011-07-07 01:59:51 +0000405
Greg Clayton73bf5db2011-06-17 01:22:15 +0000406 // Check for a packet from our cache first without trying any reading...
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000407 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000408 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409
Greg Clayton0c51ac32011-07-02 23:21:06 +0000410 bool timed_out = false;
Greg Clayton3dedae12013-12-06 21:45:27 +0000411 bool disconnected = false;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000412 while (IsConnected() && !timed_out)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000413 {
Johnny Chen74549c82011-07-19 01:13:00 +0000414 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000415 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
Greg Clayton644247c2011-07-07 01:59:51 +0000416
417 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000418 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 +0000419 __PRETTY_FUNCTION__,
420 timeout_usec,
421 Communication::ConnectionStatusAsCString (status),
422 error.AsCString(),
Greg Clayton43e0af02012-09-18 18:04:04 +0000423 (uint64_t)bytes_read);
Greg Clayton644247c2011-07-07 01:59:51 +0000424
Greg Clayton73bf5db2011-06-17 01:22:15 +0000425 if (bytes_read > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000426 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000427 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000428 return PacketResult::Success;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000429 }
430 else
431 {
432 switch (status)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000433 {
Greg Clayton197bacf2011-07-02 21:07:54 +0000434 case eConnectionStatusTimedOut:
Greg Claytonf0066ad2014-05-02 00:45:31 +0000435 case eConnectionStatusInterrupted:
Greg Claytonb30c50c2015-05-29 00:01:55 +0000436 if (sync_on_timeout)
437 {
438 //------------------------------------------------------------------
439 /// Sync the remote GDB server and make sure we get a response that
440 /// corresponds to what we send.
441 ///
442 /// Sends a "qEcho" packet and makes sure it gets the exact packet
443 /// echoed back. If the qEcho packet isn't supported, we send a qC
444 /// packet and make sure we get a valid thread ID back. We use the
445 /// "qC" packet since its response if very unique: is responds with
446 /// "QC%x" where %x is the thread ID of the current thread. This
447 /// makes the response unique enough from other packet responses to
448 /// ensure we are back on track.
449 ///
450 /// This packet is needed after we time out sending a packet so we
451 /// can ensure that we are getting the response for the packet we
452 /// are sending. There are no sequence IDs in the GDB remote
453 /// protocol (there used to be, but they are not supported anymore)
454 /// so if you timeout sending packet "abc", you might then send
455 /// packet "cde" and get the response for the previous "abc" packet.
456 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
457 /// many responses for packets can look like responses for other
458 /// packets. So if we timeout, we need to ensure that we can get
459 /// back on track. If we can't get back on track, we must
460 /// disconnect.
461 //------------------------------------------------------------------
462 bool sync_success = false;
463 bool got_actual_response = false;
464 // We timed out, we need to sync back up with the
465 char echo_packet[32];
466 int echo_packet_len = 0;
467 RegularExpression response_regex;
468
469 if (m_supports_qEcho == eLazyBoolYes)
470 {
471 echo_packet_len = ::snprintf (echo_packet, sizeof(echo_packet), "qEcho:%u", ++m_echo_number);
472 std::string regex_str = "^";
473 regex_str += echo_packet;
474 regex_str += "$";
475 response_regex.Compile(regex_str.c_str());
476 }
477 else
478 {
479 echo_packet_len = ::snprintf (echo_packet, sizeof(echo_packet), "qC");
480 response_regex.Compile("^QC[0-9A-Fa-f]+$");
481 }
482
483 PacketResult echo_packet_result = SendPacketNoLock (echo_packet, echo_packet_len);
484 if (echo_packet_result == PacketResult::Success)
485 {
486 const uint32_t max_retries = 3;
487 uint32_t successful_responses = 0;
488 for (uint32_t i=0; i<max_retries; ++i)
489 {
490 StringExtractorGDBRemote echo_response;
491 echo_packet_result = WaitForPacketWithTimeoutMicroSecondsNoLock (echo_response, timeout_usec, false);
492 if (echo_packet_result == PacketResult::Success)
493 {
494 ++successful_responses;
495 if (response_regex.Execute(echo_response.GetStringRef().c_str()))
496 {
497 sync_success = true;
498 break;
499 }
500 else if (successful_responses == 1)
501 {
502 // We got something else back as the first successful response, it probably is
503 // the response to the packet we actually wanted, so copy it over if this
504 // is the first success and continue to try to get the qEcho response
505 packet = echo_response;
506 got_actual_response = true;
507 }
508 }
509 else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
510 continue; // Packet timed out, continue waiting for a response
511 else
512 break; // Something else went wrong getting the packet back, we failed and are done trying
513 }
514 }
515
516 // We weren't able to sync back up with the server, we must abort otherwise
517 // all responses might not be from the right packets...
518 if (sync_success)
519 {
520 // We timed out, but were able to recover
521 if (got_actual_response)
522 {
523 // We initially timed out, but we did get a response that came in before the successful
524 // reply to our qEcho packet, so lets say everything is fine...
525 return PacketResult::Success;
526 }
527 }
528 else
529 {
530 disconnected = true;
531 Disconnect();
532 }
533 }
Greg Clayton0c51ac32011-07-02 23:21:06 +0000534 timed_out = true;
535 break;
536 case eConnectionStatusSuccess:
537 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
Greg Clayton73bf5db2011-06-17 01:22:15 +0000538 break;
539
540 case eConnectionStatusEndOfFile:
541 case eConnectionStatusNoConnection:
542 case eConnectionStatusLostConnection:
543 case eConnectionStatusError:
Greg Clayton3dedae12013-12-06 21:45:27 +0000544 disconnected = true;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000545 Disconnect();
546 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000547 }
548 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000549 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000550 packet.Clear ();
551 if (disconnected)
552 return PacketResult::ErrorDisconnected;
553 if (timed_out)
554 return PacketResult::ErrorReplyTimeout;
555 else
556 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000557}
558
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000559bool
560GDBRemoteCommunication::DecompressPacket ()
561{
562 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
563
564 if (!CompressionIsEnabled())
565 return true;
566
567 size_t pkt_size = m_bytes.size();
Jason Molendafea77652015-07-14 19:19:07 +0000568
569 // Smallest possible compressed packet is $N#00 - an uncompressed empty reply, most commonly indicating
570 // an unsupported packet. Anything less than 5 characters, it's definitely not a compressed packet.
Jason Molenda21c34ac2015-07-14 04:51:05 +0000571 if (pkt_size < 5)
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000572 return true;
Jason Molendafea77652015-07-14 19:19:07 +0000573
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000574 if (m_bytes[0] != '$' && m_bytes[0] != '%')
575 return true;
576 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
577 return true;
Jason Molendaa21fdb02015-08-02 01:36:09 +0000578
579 size_t hash_mark_idx = m_bytes.find ('#');
580 if (hash_mark_idx == std::string::npos)
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000581 return true;
Jason Molendaa21fdb02015-08-02 01:36:09 +0000582 if (hash_mark_idx + 2 >= m_bytes.size())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000583 return true;
584
Jason Molendaa21fdb02015-08-02 01:36:09 +0000585 if (!::isxdigit (m_bytes[hash_mark_idx + 1]) || !::isxdigit (m_bytes[hash_mark_idx + 2]))
586 return true;
587
588 size_t content_length = pkt_size - 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
589 size_t content_start = 2; // The first character of the compressed/not-compressed text of the packet
590 size_t checksum_idx = hash_mark_idx + 1; // The first character of the two hex checksum characters
591
592 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain multiple packets.
593 // size_of_first_packet is the size of the initial packet which we'll replace with the decompressed
594 // version of, leaving the rest of m_bytes unmodified.
595 size_t size_of_first_packet = hash_mark_idx + 3;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000596
597 // Compressed packets ("$C") start with a base10 number which is the size of the uncompressed payload,
598 // then a : and then the compressed data. e.g. $C1024:<binary>#00
599 // Update content_start and content_length to only include the <binary> part of the packet.
600
601 uint64_t decompressed_bufsize = ULONG_MAX;
602 if (m_bytes[1] == 'C')
603 {
604 size_t i = content_start;
605 while (i < hash_mark_idx && isdigit(m_bytes[i]))
606 i++;
607 if (i < hash_mark_idx && m_bytes[i] == ':')
608 {
609 i++;
610 content_start = i;
611 content_length = hash_mark_idx - content_start;
612 std::string bufsize_str (m_bytes.data() + 2, i - 2 - 1);
613 errno = 0;
614 decompressed_bufsize = ::strtoul (bufsize_str.c_str(), NULL, 10);
615 if (errno != 0 || decompressed_bufsize == ULONG_MAX)
616 {
Jason Molendaa21fdb02015-08-02 01:36:09 +0000617 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000618 return false;
619 }
620 }
621 }
622
623 if (GetSendAcks ())
624 {
625 char packet_checksum_cstr[3];
626 packet_checksum_cstr[0] = m_bytes[checksum_idx];
627 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
628 packet_checksum_cstr[2] = '\0';
629 long packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
630
631 long actual_checksum = CalculcateChecksum (m_bytes.data() + 1, hash_mark_idx - 1);
632 bool success = packet_checksum == actual_checksum;
633 if (!success)
634 {
635 if (log)
636 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
637 (int)(pkt_size),
638 m_bytes.c_str(),
639 (uint8_t)packet_checksum,
640 (uint8_t)actual_checksum);
641 }
642 // Send the ack or nack if needed
643 if (!success)
644 {
645 SendNack();
Jason Molendaa21fdb02015-08-02 01:36:09 +0000646 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000647 return false;
648 }
649 else
650 {
651 SendAck();
652 }
653 }
654
655 if (m_bytes[1] == 'N')
656 {
657 // This packet was not compressed -- delete the 'N' character at the
658 // start and the packet may be processed as-is.
659 m_bytes.erase(1, 1);
660 return true;
661 }
662
663 // Reverse the gdb-remote binary escaping that was done to the compressed text to
664 // guard characters like '$', '#', '}', etc.
665 std::vector<uint8_t> unescaped_content;
666 unescaped_content.reserve (content_length);
667 size_t i = content_start;
668 while (i < hash_mark_idx)
669 {
670 if (m_bytes[i] == '}')
671 {
672 i++;
673 unescaped_content.push_back (m_bytes[i] ^ 0x20);
674 }
675 else
676 {
677 unescaped_content.push_back (m_bytes[i]);
678 }
679 i++;
680 }
681
682 uint8_t *decompressed_buffer = nullptr;
683 size_t decompressed_bytes = 0;
684
685 if (decompressed_bufsize != ULONG_MAX)
686 {
687 decompressed_buffer = (uint8_t *) malloc (decompressed_bufsize + 1);
688 if (decompressed_buffer == nullptr)
689 {
Jason Molendaa21fdb02015-08-02 01:36:09 +0000690 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000691 return false;
692 }
693
694 }
695
696#if defined (HAVE_LIBCOMPRESSION)
697 // libcompression is weak linked so check that compression_decode_buffer() is available
698 if (compression_decode_buffer != NULL &&
699 (m_compression_type == CompressionType::ZlibDeflate
700 || m_compression_type == CompressionType::LZFSE
701 || m_compression_type == CompressionType::LZ4))
702 {
703 compression_algorithm compression_type;
704 if (m_compression_type == CompressionType::ZlibDeflate)
705 compression_type = COMPRESSION_ZLIB;
706 else if (m_compression_type == CompressionType::LZFSE)
707 compression_type = COMPRESSION_LZFSE;
708 else if (m_compression_type == CompressionType::LZ4)
709 compression_type = COMPRESSION_LZ4_RAW;
710 else if (m_compression_type == CompressionType::LZMA)
711 compression_type = COMPRESSION_LZMA;
712
713
714 // If we have the expected size of the decompressed payload, we can allocate
715 // the right-sized buffer and do it. If we don't have that information, we'll
716 // need to try decoding into a big buffer and if the buffer wasn't big enough,
717 // increase it and try again.
718
719 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr)
720 {
721 decompressed_bytes = compression_decode_buffer (decompressed_buffer, decompressed_bufsize + 10 ,
722 (uint8_t*) unescaped_content.data(),
723 unescaped_content.size(),
724 NULL,
725 compression_type);
726 }
727 }
728#endif
729
730#if defined (HAVE_LIBZ)
731 if (decompressed_bytes == 0
732 && decompressed_bufsize != ULONG_MAX
733 && decompressed_buffer != nullptr
734 && m_compression_type == CompressionType::ZlibDeflate)
735 {
736 z_stream stream;
737 memset (&stream, 0, sizeof (z_stream));
738 stream.next_in = (Bytef *) unescaped_content.data();
739 stream.avail_in = (uInt) unescaped_content.size();
740 stream.total_in = 0;
741 stream.next_out = (Bytef *) decompressed_buffer;
742 stream.avail_out = decompressed_bufsize;
743 stream.total_out = 0;
744 stream.zalloc = Z_NULL;
745 stream.zfree = Z_NULL;
746 stream.opaque = Z_NULL;
747
748 if (inflateInit2 (&stream, -15) == Z_OK)
749 {
750 int status = inflate (&stream, Z_NO_FLUSH);
751 inflateEnd (&stream);
752 if (status == Z_STREAM_END)
753 {
754 decompressed_bytes = stream.total_out;
755 }
756 }
757 }
758#endif
759
760 if (decompressed_bytes == 0 || decompressed_buffer == nullptr)
761 {
762 if (decompressed_buffer)
763 free (decompressed_buffer);
Jason Molendaa21fdb02015-08-02 01:36:09 +0000764 m_bytes.erase (0, size_of_first_packet);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000765 return false;
766 }
767
768 std::string new_packet;
769 new_packet.reserve (decompressed_bytes + 6);
770 new_packet.push_back (m_bytes[0]);
771 new_packet.append ((const char *) decompressed_buffer, decompressed_bytes);
772 new_packet.push_back ('#');
773 if (GetSendAcks ())
774 {
775 uint8_t decompressed_checksum = CalculcateChecksum ((const char *) decompressed_buffer, decompressed_bytes);
776 char decompressed_checksum_str[3];
777 snprintf (decompressed_checksum_str, 3, "%02x", decompressed_checksum);
778 new_packet.append (decompressed_checksum_str);
779 }
780 else
781 {
782 new_packet.push_back ('0');
783 new_packet.push_back ('0');
784 }
785
Jason Molendaa21fdb02015-08-02 01:36:09 +0000786 m_bytes.replace (0, size_of_first_packet, new_packet.data(), new_packet.size());
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000787
788 free (decompressed_buffer);
789 return true;
790}
791
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000792GDBRemoteCommunication::PacketType
Greg Clayton73bf5db2011-06-17 01:22:15 +0000793GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000794{
795 // Put the packet data into the buffer in a thread safe fashion
796 Mutex::Locker locker(m_bytes_mutex);
Greg Clayton197bacf2011-07-02 21:07:54 +0000797
Greg Clayton5160ce52013-03-27 23:08:40 +0000798 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000799
Greg Clayton73bf5db2011-06-17 01:22:15 +0000800 if (src && src_len > 0)
Greg Clayton197bacf2011-07-02 21:07:54 +0000801 {
Greg Clayton0c51ac32011-07-02 23:21:06 +0000802 if (log && log->GetVerbose())
Greg Clayton197bacf2011-07-02 21:07:54 +0000803 {
804 StreamString s;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000805 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
806 __FUNCTION__,
807 (uint32_t)src_len,
808 (uint32_t)src_len,
809 src);
Greg Clayton197bacf2011-07-02 21:07:54 +0000810 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000811 m_bytes.append ((const char *)src, src_len);
Greg Clayton197bacf2011-07-02 21:07:54 +0000812 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000813
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000814 bool isNotifyPacket = false;
815
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000816 // Parse up the packets into gdb remote packets
Greg Clayton197bacf2011-07-02 21:07:54 +0000817 if (!m_bytes.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000818 {
819 // end_idx must be one past the last valid packet byte. Start
820 // it off with an invalid value that is the same as the current
821 // index.
Greg Clayton73bf5db2011-06-17 01:22:15 +0000822 size_t content_start = 0;
Greg Clayton118593a2014-11-03 21:02:54 +0000823 size_t content_length = 0;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000824 size_t total_length = 0;
825 size_t checksum_idx = std::string::npos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000826
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000827 // Size of packet before it is decompressed, for logging purposes
828 size_t original_packet_size = m_bytes.size();
829 if (CompressionIsEnabled())
830 {
831 if (DecompressPacket() == false)
832 {
833 packet.Clear();
834 return GDBRemoteCommunication::PacketType::Standard;
835 }
836 }
837
Greg Clayton118593a2014-11-03 21:02:54 +0000838 switch (m_bytes[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000839 {
Greg Clayton118593a2014-11-03 21:02:54 +0000840 case '+': // Look for ack
841 case '-': // Look for cancel
842 case '\x03': // ^C to halt target
843 content_length = total_length = 1; // The command is one byte long...
844 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845
Ewan Crawford78baa192015-05-13 09:18:18 +0000846 case '%': // Async notify packet
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000847 isNotifyPacket = true;
Jason Molenda62e06812016-02-16 04:14:33 +0000848 LLVM_FALLTHROUGH;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000849
Greg Clayton118593a2014-11-03 21:02:54 +0000850 case '$':
851 // Look for a standard gdb packet?
852 {
853 size_t hash_pos = m_bytes.find('#');
854 if (hash_pos != std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000855 {
Greg Clayton118593a2014-11-03 21:02:54 +0000856 if (hash_pos + 2 < m_bytes.size())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000857 {
Greg Clayton118593a2014-11-03 21:02:54 +0000858 checksum_idx = hash_pos + 1;
859 // Skip the dollar sign
860 content_start = 1;
861 // Don't include the # in the content or the $ in the content length
862 content_length = hash_pos - 1;
863
864 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
865 }
866 else
867 {
868 // Checksum bytes aren't all here yet
869 content_length = std::string::npos;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000870 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000871 }
Greg Clayton118593a2014-11-03 21:02:54 +0000872 }
873 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000874
Greg Clayton118593a2014-11-03 21:02:54 +0000875 default:
876 {
877 // We have an unexpected byte and we need to flush all bad
878 // data that is in m_bytes, so we need to find the first
879 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
880 // or '$' character (start of packet header) or of course,
881 // the end of the data in m_bytes...
882 const size_t bytes_len = m_bytes.size();
883 bool done = false;
884 uint32_t idx;
885 for (idx = 1; !done && idx < bytes_len; ++idx)
Greg Clayton197bacf2011-07-02 21:07:54 +0000886 {
Greg Clayton118593a2014-11-03 21:02:54 +0000887 switch (m_bytes[idx])
Greg Clayton197bacf2011-07-02 21:07:54 +0000888 {
Greg Clayton118593a2014-11-03 21:02:54 +0000889 case '+':
890 case '-':
891 case '\x03':
Ewan Crawford78baa192015-05-13 09:18:18 +0000892 case '%':
Greg Clayton118593a2014-11-03 21:02:54 +0000893 case '$':
894 done = true;
895 break;
896
897 default:
898 break;
Greg Clayton197bacf2011-07-02 21:07:54 +0000899 }
900 }
Greg Clayton118593a2014-11-03 21:02:54 +0000901 if (log)
902 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
903 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
904 m_bytes.erase(0, idx - 1);
905 }
906 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000907 }
908
Greg Clayton73bf5db2011-06-17 01:22:15 +0000909 if (content_length == std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000910 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000911 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000912 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000913 }
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000914 else if (total_length > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000915 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000916
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000917 // We have a valid packet...
Greg Clayton73bf5db2011-06-17 01:22:15 +0000918 assert (content_length <= m_bytes.size());
919 assert (total_length <= m_bytes.size());
920 assert (content_length <= total_length);
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000921 size_t content_end = content_start + content_length;
Greg Clayton06f09b52014-06-20 20:41:07 +0000922
Greg Clayton73bf5db2011-06-17 01:22:15 +0000923 bool success = true;
924 std::string &packet_str = packet.GetStringRef();
Greg Claytonc1422c12012-04-09 22:46:21 +0000925 if (log)
926 {
927 // If logging was just enabled and we have history, then dump out what
928 // we have to the log so we get the historical context. The Dump() call that
929 // logs all of the packet will set a boolean so that we don't dump this more
930 // than once
931 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000932 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000933
Greg Clayton06f09b52014-06-20 20:41:07 +0000934 bool binary = false;
935 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
936 if (m_bytes[0] == '$' && total_length > 4)
937 {
938 for (size_t i=0; !binary && i<total_length; ++i)
939 {
Jason Molenda0ace3f52015-09-09 03:24:52 +0000940 if (isprint (m_bytes[i]) == 0 && isspace (m_bytes[i]) == 0)
941 {
Greg Clayton06f09b52014-06-20 20:41:07 +0000942 binary = true;
Jason Molenda0ace3f52015-09-09 03:24:52 +0000943 }
Greg Clayton06f09b52014-06-20 20:41:07 +0000944 }
945 }
946 if (binary)
947 {
948 StreamString strm;
949 // Packet header...
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000950 if (CompressionIsEnabled())
951 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c", (uint64_t) original_packet_size, (uint64_t)total_length, m_bytes[0]);
952 else
953 strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
Greg Clayton06f09b52014-06-20 20:41:07 +0000954 for (size_t i=content_start; i<content_end; ++i)
955 {
956 // Remove binary escaped bytes when displaying the packet...
957 const char ch = m_bytes[i];
958 if (ch == 0x7d)
959 {
960 // 0x7d is the escape character. The next character is to
961 // be XOR'd with 0x20.
962 const char escapee = m_bytes[++i] ^ 0x20;
963 strm.Printf("%2.2x", escapee);
964 }
965 else
966 {
967 strm.Printf("%2.2x", (uint8_t)ch);
968 }
969 }
970 // Packet footer...
971 strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
972 log->PutCString(strm.GetString().c_str());
973 }
974 else
975 {
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000976 if (CompressionIsEnabled())
977 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s", (uint64_t) original_packet_size, (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
978 else
979 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 +0000980 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000981 }
982
983 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
984
Hafiz Abid Qadeere5fd5e12013-08-28 15:10:37 +0000985 // Clear packet_str in case there is some existing data in it.
986 packet_str.clear();
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000987 // Copy the packet from m_bytes to packet_str expanding the
988 // run-length encoding in the process.
989 // Reserve enough byte for the most common case (no RLE used)
990 packet_str.reserve(m_bytes.length());
Greg Clayton06f09b52014-06-20 20:41:07 +0000991 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 +0000992 {
993 if (*c == '*')
994 {
995 // '*' indicates RLE. Next character will give us the
996 // repeat count and previous character is what is to be
997 // repeated.
998 char char_to_repeat = packet_str.back();
999 // Number of time the previous character is repeated
1000 int repeat_count = *++c + 3 - ' ';
1001 // We have the char_to_repeat and repeat_count. Now push
1002 // it in the packet.
1003 for (int i = 0; i < repeat_count; ++i)
1004 packet_str.push_back(char_to_repeat);
1005 }
Steve Pucci3c5d3332014-02-24 19:07:29 +00001006 else if (*c == 0x7d)
1007 {
1008 // 0x7d is the escape character. The next character is to
1009 // be XOR'd with 0x20.
1010 char escapee = *++c ^ 0x20;
1011 packet_str.push_back(escapee);
1012 }
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +00001013 else
1014 {
1015 packet_str.push_back(*c);
1016 }
1017 }
1018
Ewan Crawford78baa192015-05-13 09:18:18 +00001019 if (m_bytes[0] == '$' || m_bytes[0] == '%')
Greg Clayton73bf5db2011-06-17 01:22:15 +00001020 {
1021 assert (checksum_idx < m_bytes.size());
1022 if (::isxdigit (m_bytes[checksum_idx+0]) ||
1023 ::isxdigit (m_bytes[checksum_idx+1]))
1024 {
1025 if (GetSendAcks ())
1026 {
1027 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
1028 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
1029 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
1030 success = packet_checksum == actual_checksum;
1031 if (!success)
1032 {
1033 if (log)
1034 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
1035 (int)(total_length),
1036 m_bytes.c_str(),
1037 (uint8_t)packet_checksum,
1038 (uint8_t)actual_checksum);
1039 }
1040 // Send the ack or nack if needed
1041 if (!success)
1042 SendNack();
1043 else
1044 SendAck();
1045 }
Greg Clayton73bf5db2011-06-17 01:22:15 +00001046 }
1047 else
1048 {
1049 success = false;
1050 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +00001051 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
Greg Clayton73bf5db2011-06-17 01:22:15 +00001052 }
1053 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001054
Greg Clayton73bf5db2011-06-17 01:22:15 +00001055 m_bytes.erase(0, total_length);
1056 packet.SetFilePos(0);
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001057
1058 if (isNotifyPacket)
1059 return GDBRemoteCommunication::PacketType::Notify;
1060 else
1061 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001062 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063 }
Greg Clayton73bf5db2011-06-17 01:22:15 +00001064 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +00001065 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001066}
1067
Greg Clayton8b82f082011-04-12 05:54:46 +00001068Error
Greg Claytond6299802013-12-06 17:46:35 +00001069GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
Greg Clayton00fe87b2013-12-05 22:58:22 +00001070{
1071 Error error;
Zachary Turneracee96a2014-09-23 18:32:09 +00001072 if (m_listen_thread.IsJoinable())
Greg Clayton00fe87b2013-12-05 22:58:22 +00001073 {
1074 error.SetErrorString("listen thread already running");
1075 }
1076 else
1077 {
1078 char listen_url[512];
1079 if (hostname && hostname[0])
Jean-Daniel Dupas3c6774a2014-02-08 20:29:40 +00001080 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001081 else
1082 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
1083 m_listen_url = listen_url;
1084 SetConnection(new ConnectionFileDescriptor());
Zachary Turner39de3112014-09-09 20:54:56 +00001085 m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001086 }
1087 return error;
1088}
1089
1090bool
1091GDBRemoteCommunication::JoinListenThread ()
1092{
Zachary Turneracee96a2014-09-23 18:32:09 +00001093 if (m_listen_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +00001094 m_listen_thread.Join(nullptr);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001095 return true;
1096}
1097
1098lldb::thread_result_t
1099GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
1100{
1101 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
1102 Error error;
1103 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
1104
1105 if (connection)
1106 {
1107 // Do the listen on another thread so we can continue on...
1108 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
1109 comm->SetConnection(NULL);
1110 }
1111 return NULL;
1112}
1113
1114Error
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001115GDBRemoteCommunication::StartDebugserverProcess (const char *url,
Greg Clayton6988abc2015-10-19 20:44:01 +00001116 Platform *platform,
Tamas Berghammerdb264a62015-03-31 09:52:22 +00001117 ProcessLaunchInfo &launch_info,
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001118 uint16_t *port,
1119 const Args& inferior_args)
Greg Clayton8b82f082011-04-12 05:54:46 +00001120{
Todd Fiala015d8182014-07-22 23:41:36 +00001121 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1122 if (log)
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001123 log->Printf ("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16, __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
Todd Fiala015d8182014-07-22 23:41:36 +00001124
Greg Clayton8b82f082011-04-12 05:54:46 +00001125 Error error;
1126 // If we locate debugserver, keep that located version around
1127 static FileSpec g_debugserver_file_spec;
1128
Greg Clayton8b82f082011-04-12 05:54:46 +00001129 char debugserver_path[PATH_MAX];
1130 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
1131
1132 // Always check to see if we have an environment override for the path
1133 // to the debugserver to use and use it if we do.
1134 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
1135 if (env_debugserver_path)
Todd Fiala015d8182014-07-22 23:41:36 +00001136 {
Greg Clayton8b82f082011-04-12 05:54:46 +00001137 debugserver_file_spec.SetFile (env_debugserver_path, false);
Todd Fiala015d8182014-07-22 23:41:36 +00001138 if (log)
1139 log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path);
1140 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001141 else
1142 debugserver_file_spec = g_debugserver_file_spec;
1143 bool debugserver_exists = debugserver_file_spec.Exists();
1144 if (!debugserver_exists)
1145 {
1146 // The debugserver binary is in the LLDB.framework/Resources
Zachary Turner42ff0ad2014-08-21 17:29:12 +00001147 // directory.
1148 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec))
Greg Clayton8b82f082011-04-12 05:54:46 +00001149 {
Jason Molenda6fd86772014-08-21 23:22:33 +00001150 debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME);
Greg Clayton8b82f082011-04-12 05:54:46 +00001151 debugserver_exists = debugserver_file_spec.Exists();
1152 if (debugserver_exists)
1153 {
Todd Fiala015d8182014-07-22 23:41:36 +00001154 if (log)
1155 log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
1156
Greg Clayton8b82f082011-04-12 05:54:46 +00001157 g_debugserver_file_spec = debugserver_file_spec;
1158 }
1159 else
1160 {
Greg Clayton6988abc2015-10-19 20:44:01 +00001161 debugserver_file_spec = platform->LocateExecutable(DEBUGSERVER_BASENAME);
1162 if (debugserver_file_spec)
1163 {
1164 // Platform::LocateExecutable() wouldn't return a path if it doesn't exist
1165 debugserver_exists = true;
1166 }
1167 else
1168 {
1169 if (log)
1170 log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
1171 }
1172 // Don't cache the platform specific GDB server binary as it could change
1173 // from platform to platform
Greg Clayton8b82f082011-04-12 05:54:46 +00001174 g_debugserver_file_spec.Clear();
Greg Clayton8b82f082011-04-12 05:54:46 +00001175 }
1176 }
1177 }
1178
1179 if (debugserver_exists)
1180 {
1181 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
1182
1183 Args &debugserver_args = launch_info.GetArguments();
1184 debugserver_args.Clear();
1185 char arg_cstr[PATH_MAX];
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001186
Greg Clayton8b82f082011-04-12 05:54:46 +00001187 // Start args with "debugserver /file/path -r --"
1188 debugserver_args.AppendArgument(debugserver_path);
Greg Clayton00fe87b2013-12-05 22:58:22 +00001189
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001190#if !defined(__APPLE__)
1191 // First argument to lldb-server must be mode in which to run.
1192 debugserver_args.AppendArgument("gdbserver");
1193#endif
1194
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001195 // If a url is supplied then use it
1196 if (url)
1197 debugserver_args.AppendArgument(url);
Greg Claytonfda4fab2014-01-10 22:24:11 +00001198
Greg Clayton8b82f082011-04-12 05:54:46 +00001199 // use native registers, not the GDB registers
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001200 debugserver_args.AppendArgument("--native-regs");
1201
1202 if (launch_info.GetLaunchInSeparateProcessGroup())
1203 {
1204 debugserver_args.AppendArgument("--setsid");
1205 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001206
Oleksiy Vyalov4536c452015-02-05 16:29:12 +00001207 llvm::SmallString<PATH_MAX> named_pipe_path;
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001208 // socket_pipe is used by debug server to communicate back either
1209 // TCP port or domain socket name which it listens on.
1210 // The second purpose of the pipe to serve as a synchronization point -
1211 // once data is written to the pipe, debug server is up and running.
1212 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001213
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001214 // port is null when debug server should listen on domain socket -
1215 // we're not interested in port value but rather waiting for debug server
1216 // to become available.
1217 if ((port != nullptr && *port == 0) || port == nullptr)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001218 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001219 if (url)
Jason Molenda04097542015-09-22 23:25:44 +00001220 {
1221 // Create a temporary file to get the stdout/stderr and redirect the
1222 // output of the command into this file. We will later read this file
1223 // if all goes well and fill the data into "command_output_ptr"
1224
Chaoren Lin46951b52015-07-30 17:48:44 +00001225#if defined(__APPLE__)
Jason Molenda04097542015-09-22 23:25:44 +00001226 // Binding to port zero, we need to figure out what port it ends up
1227 // using using a named pipe...
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001228 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe", false, named_pipe_path);
Jason Molenda04097542015-09-22 23:25:44 +00001229 if (error.Fail())
1230 {
1231 if (log)
1232 log->Printf("GDBRemoteCommunication::%s() "
1233 "named pipe creation failed: %s",
1234 __FUNCTION__, error.AsCString());
1235 return error;
1236 }
1237 debugserver_args.AppendArgument("--named-pipe");
1238 debugserver_args.AppendArgument(named_pipe_path.c_str());
Chaoren Lin46951b52015-07-30 17:48:44 +00001239#else
Jason Molenda04097542015-09-22 23:25:44 +00001240 // Binding to port zero, we need to figure out what port it ends up
1241 // using using an unnamed pipe...
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001242 error = socket_pipe.CreateNew(true);
Jason Molenda04097542015-09-22 23:25:44 +00001243 if (error.Fail())
1244 {
1245 if (log)
1246 log->Printf("GDBRemoteCommunication::%s() "
1247 "unnamed pipe creation failed: %s",
1248 __FUNCTION__, error.AsCString());
1249 return error;
1250 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001251 int write_fd = socket_pipe.GetWriteFileDescriptor();
Jason Molenda04097542015-09-22 23:25:44 +00001252 debugserver_args.AppendArgument("--pipe");
1253 debugserver_args.AppendArgument(std::to_string(write_fd).c_str());
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001254 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001255#endif
Greg Clayton16810922014-02-27 19:38:18 +00001256 }
1257 else
1258 {
Jason Molenda04097542015-09-22 23:25:44 +00001259 // No host and port given, so lets listen on our end and make the debugserver
1260 // connect to us..
1261 error = StartListenThread ("127.0.0.1", 0);
1262 if (error.Fail())
1263 {
1264 if (log)
1265 log->Printf ("GDBRemoteCommunication::%s() unable to start listen thread: %s", __FUNCTION__, error.AsCString());
1266 return error;
1267 }
1268
1269 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
1270 // Wait for 10 seconds to resolve the bound port
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001271 *port = connection->GetListeningPort(10);
1272 if (*port > 0)
Jason Molenda04097542015-09-22 23:25:44 +00001273 {
1274 char port_cstr[32];
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001275 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", *port);
Jason Molenda04097542015-09-22 23:25:44 +00001276 // Send the host and port down that debugserver and specify an option
1277 // so that it connects back to the port we are listening to in this process
1278 debugserver_args.AppendArgument("--reverse-connect");
1279 debugserver_args.AppendArgument(port_cstr);
1280 }
1281 else
1282 {
1283 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
1284 if (log)
1285 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
1286 return error;
1287 }
Greg Clayton16810922014-02-27 19:38:18 +00001288 }
Greg Clayton00fe87b2013-12-05 22:58:22 +00001289 }
Greg Clayton00fe87b2013-12-05 22:58:22 +00001290
Greg Clayton8b82f082011-04-12 05:54:46 +00001291 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
1292 if (env_debugserver_log_file)
1293 {
1294 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
1295 debugserver_args.AppendArgument(arg_cstr);
1296 }
1297
Vince Harron9753dd92015-05-10 15:22:09 +00001298#if defined(__APPLE__)
Greg Clayton8b82f082011-04-12 05:54:46 +00001299 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1300 if (env_debugserver_log_flags)
1301 {
1302 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
1303 debugserver_args.AppendArgument(arg_cstr);
1304 }
Vince Harron9753dd92015-05-10 15:22:09 +00001305#else
1306 const char *env_debugserver_log_channels = getenv("LLDB_SERVER_LOG_CHANNELS");
1307 if (env_debugserver_log_channels)
1308 {
1309 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-channels=%s", env_debugserver_log_channels);
1310 debugserver_args.AppendArgument(arg_cstr);
1311 }
1312#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001313
1314 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back.
1315 uint32_t env_var_index = 1;
1316 bool has_env_var;
1317 do
1318 {
1319 char env_var_name[64];
1320 snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
1321 const char *extra_arg = getenv(env_var_name);
1322 has_env_var = extra_arg != nullptr;
1323
1324 if (has_env_var)
1325 {
1326 debugserver_args.AppendArgument (extra_arg);
1327 if (log)
1328 log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg);
1329 }
1330 } while (has_env_var);
1331
Tamas Berghammerccd6cff2015-12-08 14:08:19 +00001332 if (inferior_args.GetArgumentCount() > 0)
1333 {
1334 debugserver_args.AppendArgument ("--");
1335 debugserver_args.AppendArguments (inferior_args);
1336 }
1337
1338 // Copy the current environment to the gdbserver/debugserver instance
1339 StringList env;
1340 if (Host::GetEnvironment(env))
1341 {
1342 for (size_t i = 0; i < env.GetSize(); ++i)
1343 launch_info.GetEnvironmentEntries().AppendArgument(env[i].c_str());
1344 }
1345
Shawn Best629680e2014-11-05 00:58:55 +00001346 // Close STDIN, STDOUT and STDERR.
Greg Clayton91a9b2472013-12-04 19:19:12 +00001347 launch_info.AppendCloseFileAction (STDIN_FILENO);
1348 launch_info.AppendCloseFileAction (STDOUT_FILENO);
1349 launch_info.AppendCloseFileAction (STDERR_FILENO);
Shawn Best629680e2014-11-05 00:58:55 +00001350
1351 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1352 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
1353 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
1354 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
Zachary Turner9b693272014-12-04 22:06:42 +00001355
Greg Clayton8b82f082011-04-12 05:54:46 +00001356 error = Host::LaunchProcess(launch_info);
Zachary Turner9b693272014-12-04 22:06:42 +00001357
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001358 if (error.Success() &&
1359 launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001360 {
Oleksiy Vyalov4536c452015-02-05 16:29:12 +00001361 if (named_pipe_path.size() > 0)
Greg Clayton91a9b2472013-12-04 19:19:12 +00001362 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001363 error = socket_pipe.OpenAsReader(named_pipe_path, false);
Chaoren Lin368c9f62015-04-27 23:20:30 +00001364 if (error.Fail())
1365 if (log)
1366 log->Printf("GDBRemoteCommunication::%s() "
1367 "failed to open named pipe %s for reading: %s",
1368 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1369 }
1370
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001371 if (socket_pipe.CanWrite())
1372 socket_pipe.CloseWriteFileDescriptor();
1373 if (socket_pipe.CanRead())
Chaoren Lin368c9f62015-04-27 23:20:30 +00001374 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001375 char port_cstr[PATH_MAX] = {0};
Chaoren Lin368c9f62015-04-27 23:20:30 +00001376 port_cstr[0] = '\0';
1377 size_t num_bytes = sizeof(port_cstr);
1378 // Read port from pipe with 10 second timeout.
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001379 error = socket_pipe.ReadWithTimeout(port_cstr, num_bytes,
Chaoren Lin368c9f62015-04-27 23:20:30 +00001380 std::chrono::seconds{10}, num_bytes);
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001381 if (error.Success() && (port != nullptr))
Greg Clayton3121fde2014-02-28 20:47:08 +00001382 {
Chaoren Lin368c9f62015-04-27 23:20:30 +00001383 assert(num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001384 *port = StringConvert::ToUInt32(port_cstr, 0);
Chaoren Lin368c9f62015-04-27 23:20:30 +00001385 if (log)
1386 log->Printf("GDBRemoteCommunication::%s() "
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001387 "debugserver listens %u port",
1388 __FUNCTION__, *port);
Greg Clayton3121fde2014-02-28 20:47:08 +00001389 }
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001390 else
1391 {
1392 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +00001393 log->Printf("GDBRemoteCommunication::%s() "
1394 "failed to read a port value from pipe %s: %s",
1395 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
1396
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001397 }
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001398 socket_pipe.Close();
Chaoren Lin368c9f62015-04-27 23:20:30 +00001399 }
1400
1401 if (named_pipe_path.size() > 0)
1402 {
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +00001403 const auto err = socket_pipe.Delete(named_pipe_path);
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001404 if (err.Fail())
1405 {
1406 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +00001407 log->Printf ("GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1408 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +00001409 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001410 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001411
1412 // Make sure we actually connect with the debugserver...
1413 JoinListenThread();
Greg Clayton00fe87b2013-12-05 22:58:22 +00001414 }
Greg Clayton8b82f082011-04-12 05:54:46 +00001415 }
1416 else
1417 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001418 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
Greg Clayton8b82f082011-04-12 05:54:46 +00001419 }
Vince Harron8b335672015-05-12 01:10:56 +00001420
1421 if (error.Fail())
1422 {
1423 if (log)
1424 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
1425 }
1426
Greg Clayton8b82f082011-04-12 05:54:46 +00001427 return error;
1428}
1429
Greg Claytonc1422c12012-04-09 22:46:21 +00001430void
Greg Claytond451c1a2012-04-13 21:24:18 +00001431GDBRemoteCommunication::DumpHistory(Stream &strm)
Greg Claytonc1422c12012-04-09 22:46:21 +00001432{
Greg Claytond451c1a2012-04-13 21:24:18 +00001433 m_history.Dump (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +00001434}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001435
1436GDBRemoteCommunication::ScopedTimeout::ScopedTimeout (GDBRemoteCommunication& gdb_comm,
1437 uint32_t timeout) :
1438 m_gdb_comm (gdb_comm)
1439{
1440 m_saved_timeout = m_gdb_comm.SetPacketTimeout (timeout);
1441}
1442
1443GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout ()
1444{
1445 m_gdb_comm.SetPacketTimeout (m_saved_timeout);
1446}
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001447
1448// This function is called via the Communications class read thread when bytes become available
1449// for this connection. This function will consume all incoming bytes and try to parse whole
1450// packets as they become available. Full packets are placed in a queue, so that all packet
1451// requests can simply pop from this queue. Async notification packets will be dispatched
1452// immediately to the ProcessGDBRemote Async thread via an event.
1453void GDBRemoteCommunication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, lldb::ConnectionStatus status)
1454{
1455 StringExtractorGDBRemote packet;
1456
1457 while (true)
1458 {
1459 PacketType type = CheckForPacket(bytes, len, packet);
1460
1461 // scrub the data so we do not pass it back to CheckForPacket
1462 // on future passes of the loop
1463 bytes = nullptr;
1464 len = 0;
1465
1466 // we may have received no packet so lets bail out
1467 if (type == PacketType::Invalid)
1468 break;
1469
1470 if (type == PacketType::Standard)
1471 {
1472 // scope for the mutex
1473 {
1474 // lock down the packet queue
1475 Mutex::Locker locker(m_packet_queue_mutex);
1476 // push a new packet into the queue
1477 m_packet_queue.push(packet);
1478 // Signal condition variable that we have a packet
1479 m_condition_queue_not_empty.Signal();
1480
1481 }
1482 }
1483
1484 if (type == PacketType::Notify)
1485 {
1486 // put this packet into an event
1487 const char *pdata = packet.GetStringRef().c_str();
1488
1489 // as the communication class, we are a broadcaster and the
1490 // async thread is tuned to listen to us
1491 BroadcastEvent(
1492 eBroadcastBitGdbReadThreadGotNotify,
1493 new EventDataBytes(pdata));
1494 }
1495 }
1496}