blob: 5966ccadffcc88fe8f4c47785db751794b85fcd0 [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
Greg Clayton00fe87b2013-12-05 22:58:22 +000020#include "lldb/Core/ConnectionFileDescriptor.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000021#include "lldb/Core/Log.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"
Greg Clayton8b82f082011-04-12 05:54:46 +000024#include "lldb/Host/FileSpec.h"
25#include "lldb/Host/Host.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include "lldb/Host/TimeValue.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000027#include "lldb/Target/Process.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000028
29// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000030#include "ProcessGDBRemoteLog.h"
31
Greg Clayton8b82f082011-04-12 05:54:46 +000032#define DEBUGSERVER_BASENAME "debugserver"
33
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034using namespace lldb;
35using namespace lldb_private;
36
Greg Claytonc1422c12012-04-09 22:46:21 +000037GDBRemoteCommunication::History::History (uint32_t size) :
38 m_packets(),
39 m_curr_idx (0),
40 m_total_packet_count (0),
41 m_dumped_to_log (false)
42{
43 m_packets.resize(size);
44}
45
46GDBRemoteCommunication::History::~History ()
47{
48}
49
50void
Greg Claytond451c1a2012-04-13 21:24:18 +000051GDBRemoteCommunication::History::AddPacket (char packet_char,
52 PacketType type,
53 uint32_t bytes_transmitted)
54{
55 const size_t size = m_packets.size();
56 if (size > 0)
57 {
58 const uint32_t idx = GetNextIndex();
59 m_packets[idx].packet.assign (1, packet_char);
60 m_packets[idx].type = type;
61 m_packets[idx].bytes_transmitted = bytes_transmitted;
62 m_packets[idx].packet_idx = m_total_packet_count;
63 m_packets[idx].tid = Host::GetCurrentThreadID();
64 }
65}
66
67void
68GDBRemoteCommunication::History::AddPacket (const std::string &src,
69 uint32_t src_len,
70 PacketType type,
71 uint32_t bytes_transmitted)
72{
73 const size_t size = m_packets.size();
74 if (size > 0)
75 {
76 const uint32_t idx = GetNextIndex();
77 m_packets[idx].packet.assign (src, 0, src_len);
78 m_packets[idx].type = type;
79 m_packets[idx].bytes_transmitted = bytes_transmitted;
80 m_packets[idx].packet_idx = m_total_packet_count;
81 m_packets[idx].tid = Host::GetCurrentThreadID();
82 }
83}
84
85void
Greg Claytonc1422c12012-04-09 22:46:21 +000086GDBRemoteCommunication::History::Dump (lldb_private::Stream &strm) const
87{
88 const uint32_t size = GetNumPacketsInHistory ();
89 const uint32_t first_idx = GetFirstSavedPacketIndex ();
90 const uint32_t stop_idx = m_curr_idx + size;
91 for (uint32_t i = first_idx; i < stop_idx; ++i)
92 {
93 const uint32_t idx = NormalizeIndex (i);
94 const Entry &entry = m_packets[idx];
95 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
96 break;
Daniel Malead01b2952012-11-29 21:49:15 +000097 strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
Greg Claytonc1422c12012-04-09 22:46:21 +000098 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +000099 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000100 entry.bytes_transmitted,
101 (entry.type == ePacketTypeSend) ? "send" : "read",
102 entry.packet.c_str());
103 }
104}
105
106void
107GDBRemoteCommunication::History::Dump (lldb_private::Log *log) const
108{
109 if (log && !m_dumped_to_log)
110 {
111 m_dumped_to_log = true;
112 const uint32_t size = GetNumPacketsInHistory ();
113 const uint32_t first_idx = GetFirstSavedPacketIndex ();
114 const uint32_t stop_idx = m_curr_idx + size;
115 for (uint32_t i = first_idx; i < stop_idx; ++i)
116 {
117 const uint32_t idx = NormalizeIndex (i);
118 const Entry &entry = m_packets[idx];
119 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
120 break;
Daniel Malead01b2952012-11-29 21:49:15 +0000121 log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
Greg Claytonc1422c12012-04-09 22:46:21 +0000122 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +0000123 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000124 entry.bytes_transmitted,
125 (entry.type == ePacketTypeSend) ? "send" : "read",
126 entry.packet.c_str());
127 }
128 }
129}
130
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000131//----------------------------------------------------------------------
132// GDBRemoteCommunication constructor
133//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +0000134GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
135 const char *listener_name,
136 bool is_platform) :
Greg Clayton576d8832011-03-22 04:00:09 +0000137 Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000138#ifdef LLDB_CONFIGURATION_DEBUG
139 m_packet_timeout (1000),
140#else
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000141 m_packet_timeout (1),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000142#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000143 m_sequence_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton4dc72282011-01-20 07:53:45 +0000144 m_public_is_running (false),
Greg Clayton1cb64962011-03-24 04:28:38 +0000145 m_private_is_running (false),
Greg Claytonc1422c12012-04-09 22:46:21 +0000146 m_history (512),
Greg Clayton8b82f082011-04-12 05:54:46 +0000147 m_send_acks (true),
Greg Clayton00fe87b2013-12-05 22:58:22 +0000148 m_is_platform (is_platform),
149 m_listen_thread (LLDB_INVALID_HOST_THREAD),
150 m_listen_url ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000151{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000152}
153
154//----------------------------------------------------------------------
155// Destructor
156//----------------------------------------------------------------------
157GDBRemoteCommunication::~GDBRemoteCommunication()
158{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000159 if (IsConnected())
160 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000161 Disconnect();
162 }
163}
164
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000165char
166GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
167{
168 int checksum = 0;
169
Ed Mastea6b4c772013-08-20 14:12:58 +0000170 for (size_t i = 0; i < payload_length; ++i)
171 checksum += payload[i];
172
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000173 return checksum & 255;
174}
175
176size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000177GDBRemoteCommunication::SendAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000178{
Greg Clayton5160ce52013-03-27 23:08:40 +0000179 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000180 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000181 char ch = '+';
182 const size_t bytes_written = Write (&ch, 1, status, NULL);
183 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000184 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000185 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
186 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000187}
188
189size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000190GDBRemoteCommunication::SendNack ()
191{
Greg Clayton5160ce52013-03-27 23:08:40 +0000192 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton6ed95942011-01-22 07:12:45 +0000193 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000194 char ch = '-';
195 const size_t bytes_written = Write (&ch, 1, status, NULL);
196 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000197 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000198 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
199 return bytes_written;
Greg Clayton32e0a752011-03-30 18:16:51 +0000200}
201
202size_t
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
204{
205 Mutex::Locker locker(m_sequence_mutex);
206 return SendPacketNoLock (payload, payload_length);
207}
208
209size_t
210GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
211{
212 if (IsConnected())
213 {
214 StreamString packet(0, 4, eByteOrderBig);
215
216 packet.PutChar('$');
217 packet.Write (payload, payload_length);
218 packet.PutChar('#');
219 packet.PutHex8(CalculcateChecksum (payload, payload_length));
220
Greg Clayton5160ce52013-03-27 23:08:40 +0000221 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000222 ConnectionStatus status = eConnectionStatusSuccess;
223 size_t bytes_written = Write (packet.GetData(), packet.GetSize(), status, NULL);
Greg Claytonc1422c12012-04-09 22:46:21 +0000224 if (log)
225 {
226 // If logging was just enabled and we have history, then dump out what
227 // we have to the log so we get the historical context. The Dump() call that
228 // logs all of the packet will set a boolean so that we don't dump this more
229 // than once
230 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000231 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000232
Greg Clayton45989072013-10-23 18:24:30 +0000233 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet.GetSize(), packet.GetData());
Greg Claytonc1422c12012-04-09 22:46:21 +0000234 }
235
236 m_history.AddPacket (packet.GetString(), packet.GetSize(), History::ePacketTypeSend, bytes_written);
237
238
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000239 if (bytes_written == packet.GetSize())
240 {
Greg Clayton71fc2a32011-02-12 06:28:37 +0000241 if (GetSendAcks ())
Greg Claytonc982c762010-07-09 20:39:50 +0000242 {
Greg Claytonc574ede2011-03-10 02:26:48 +0000243 if (GetAck () != '+')
Greg Clayton1cb64962011-03-24 04:28:38 +0000244 {
Johnny Chen561e1902012-06-02 00:22:07 +0000245 if (log)
246 log->Printf("get ack failed...");
Greg Claytonc982c762010-07-09 20:39:50 +0000247 return 0;
Greg Clayton1cb64962011-03-24 04:28:38 +0000248 }
Greg Claytonc982c762010-07-09 20:39:50 +0000249 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000250 }
Johnny Chend0c40dd2010-09-14 22:10:43 +0000251 else
252 {
Greg Clayton6d093452011-02-05 02:25:06 +0000253 if (log)
Greg Clayton5fe15d22011-05-20 03:15:54 +0000254 log->Printf ("error: failed to send packet: %.*s", (int)packet.GetSize(), packet.GetData());
Johnny Chend0c40dd2010-09-14 22:10:43 +0000255 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000256 return bytes_written;
Greg Claytonf5e56de2010-09-14 23:36:40 +0000257 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000258 return 0;
259}
260
261char
Greg Claytonc574ede2011-03-10 02:26:48 +0000262GDBRemoteCommunication::GetAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000263{
Greg Clayton576d8832011-03-22 04:00:09 +0000264 StringExtractorGDBRemote packet;
Greg Clayton37a0a242012-04-11 00:24:49 +0000265 if (WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ()) == 1)
Greg Clayton576d8832011-03-22 04:00:09 +0000266 return packet.GetChar();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000267 return 0;
268}
269
270bool
Jim Ingham4ceb9282012-06-08 22:50:40 +0000271GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000272{
Greg Claytond9896732012-05-31 16:54:51 +0000273 if (IsRunning())
Jim Ingham4ceb9282012-06-08 22:50:40 +0000274 return locker.TryLock (m_sequence_mutex, failure_message);
Greg Claytond9896732012-05-31 16:54:51 +0000275
276 locker.Lock (m_sequence_mutex);
277 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000278}
279
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000280
Greg Clayton6779606a2011-01-22 23:43:18 +0000281bool
Greg Clayton6779606a2011-01-22 23:43:18 +0000282GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
283{
284 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
285}
286
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000287size_t
Greg Clayton73bf5db2011-06-17 01:22:15 +0000288GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289{
Greg Clayton73bf5db2011-06-17 01:22:15 +0000290 uint8_t buffer[8192];
291 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000292
Greg Clayton5160ce52013-03-27 23:08:40 +0000293 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
Greg Clayton644247c2011-07-07 01:59:51 +0000294
Greg Clayton73bf5db2011-06-17 01:22:15 +0000295 // Check for a packet from our cache first without trying any reading...
296 if (CheckForPacket (NULL, 0, packet))
297 return packet.GetStringRef().size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000298
Greg Clayton0c51ac32011-07-02 23:21:06 +0000299 bool timed_out = false;
300 while (IsConnected() && !timed_out)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000301 {
Johnny Chen74549c82011-07-19 01:13:00 +0000302 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000303 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
Greg Clayton644247c2011-07-07 01:59:51 +0000304
305 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000306 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 +0000307 __PRETTY_FUNCTION__,
308 timeout_usec,
309 Communication::ConnectionStatusAsCString (status),
310 error.AsCString(),
Greg Clayton43e0af02012-09-18 18:04:04 +0000311 (uint64_t)bytes_read);
Greg Clayton644247c2011-07-07 01:59:51 +0000312
Greg Clayton73bf5db2011-06-17 01:22:15 +0000313 if (bytes_read > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000315 if (CheckForPacket (buffer, bytes_read, packet))
316 return packet.GetStringRef().size();
317 }
318 else
319 {
320 switch (status)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000321 {
Greg Clayton197bacf2011-07-02 21:07:54 +0000322 case eConnectionStatusTimedOut:
Greg Clayton0c51ac32011-07-02 23:21:06 +0000323 timed_out = true;
324 break;
325 case eConnectionStatusSuccess:
326 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
Greg Clayton73bf5db2011-06-17 01:22:15 +0000327 break;
328
329 case eConnectionStatusEndOfFile:
330 case eConnectionStatusNoConnection:
331 case eConnectionStatusLostConnection:
332 case eConnectionStatusError:
333 Disconnect();
334 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000335 }
336 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000338 packet.Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000339 return 0;
340}
341
Greg Clayton73bf5db2011-06-17 01:22:15 +0000342bool
343GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000344{
345 // Put the packet data into the buffer in a thread safe fashion
346 Mutex::Locker locker(m_bytes_mutex);
Greg Clayton197bacf2011-07-02 21:07:54 +0000347
Greg Clayton5160ce52013-03-27 23:08:40 +0000348 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000349
Greg Clayton73bf5db2011-06-17 01:22:15 +0000350 if (src && src_len > 0)
Greg Clayton197bacf2011-07-02 21:07:54 +0000351 {
Greg Clayton0c51ac32011-07-02 23:21:06 +0000352 if (log && log->GetVerbose())
Greg Clayton197bacf2011-07-02 21:07:54 +0000353 {
354 StreamString s;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000355 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
356 __FUNCTION__,
357 (uint32_t)src_len,
358 (uint32_t)src_len,
359 src);
Greg Clayton197bacf2011-07-02 21:07:54 +0000360 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000361 m_bytes.append ((const char *)src, src_len);
Greg Clayton197bacf2011-07-02 21:07:54 +0000362 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000363
364 // Parse up the packets into gdb remote packets
Greg Clayton197bacf2011-07-02 21:07:54 +0000365 if (!m_bytes.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000366 {
367 // end_idx must be one past the last valid packet byte. Start
368 // it off with an invalid value that is the same as the current
369 // index.
Greg Clayton73bf5db2011-06-17 01:22:15 +0000370 size_t content_start = 0;
371 size_t content_length = 0;
372 size_t total_length = 0;
373 size_t checksum_idx = std::string::npos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374
375 switch (m_bytes[0])
376 {
377 case '+': // Look for ack
378 case '-': // Look for cancel
379 case '\x03': // ^C to halt target
Greg Clayton73bf5db2011-06-17 01:22:15 +0000380 content_length = total_length = 1; // The command is one byte long...
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000381 break;
382
383 case '$':
384 // Look for a standard gdb packet?
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000385 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000386 size_t hash_pos = m_bytes.find('#');
387 if (hash_pos != std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000389 if (hash_pos + 2 < m_bytes.size())
390 {
391 checksum_idx = hash_pos + 1;
392 // Skip the dollar sign
393 content_start = 1;
394 // Don't include the # in the content or the $ in the content length
395 content_length = hash_pos - 1;
396
397 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
398 }
399 else
400 {
401 // Checksum bytes aren't all here yet
402 content_length = std::string::npos;
403 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000404 }
405 }
406 break;
407
408 default:
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000409 {
Greg Clayton197bacf2011-07-02 21:07:54 +0000410 // We have an unexpected byte and we need to flush all bad
411 // data that is in m_bytes, so we need to find the first
412 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
413 // or '$' character (start of packet header) or of course,
414 // the end of the data in m_bytes...
415 const size_t bytes_len = m_bytes.size();
416 bool done = false;
417 uint32_t idx;
418 for (idx = 1; !done && idx < bytes_len; ++idx)
419 {
420 switch (m_bytes[idx])
421 {
422 case '+':
423 case '-':
424 case '\x03':
425 case '$':
426 done = true;
427 break;
428
429 default:
430 break;
431 }
432 }
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000433 if (log)
Greg Clayton197bacf2011-07-02 21:07:54 +0000434 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
435 __FUNCTION__, idx, idx, m_bytes.c_str());
436 m_bytes.erase(0, idx);
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000437 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438 break;
439 }
440
Greg Clayton73bf5db2011-06-17 01:22:15 +0000441 if (content_length == std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000442 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000443 packet.Clear();
444 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000445 }
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000446 else if (total_length > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000447 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000448
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000449 // We have a valid packet...
Greg Clayton73bf5db2011-06-17 01:22:15 +0000450 assert (content_length <= m_bytes.size());
451 assert (total_length <= m_bytes.size());
452 assert (content_length <= total_length);
453
454 bool success = true;
455 std::string &packet_str = packet.GetStringRef();
Greg Claytonc1422c12012-04-09 22:46:21 +0000456
457
458 if (log)
459 {
460 // If logging was just enabled and we have history, then dump out what
461 // we have to the log so we get the historical context. The Dump() call that
462 // logs all of the packet will set a boolean so that we don't dump this more
463 // than once
464 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000465 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000466
Greg Clayton45989072013-10-23 18:24:30 +0000467 log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
Greg Claytonc1422c12012-04-09 22:46:21 +0000468 }
469
470 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
471
Hafiz Abid Qadeere5fd5e12013-08-28 15:10:37 +0000472 // Clear packet_str in case there is some existing data in it.
473 packet_str.clear();
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000474 // Copy the packet from m_bytes to packet_str expanding the
475 // run-length encoding in the process.
476 // Reserve enough byte for the most common case (no RLE used)
477 packet_str.reserve(m_bytes.length());
478 for (std::string::const_iterator c = m_bytes.begin() + content_start; c != m_bytes.begin() + content_start + content_length; ++c)
479 {
480 if (*c == '*')
481 {
482 // '*' indicates RLE. Next character will give us the
483 // repeat count and previous character is what is to be
484 // repeated.
485 char char_to_repeat = packet_str.back();
486 // Number of time the previous character is repeated
487 int repeat_count = *++c + 3 - ' ';
488 // We have the char_to_repeat and repeat_count. Now push
489 // it in the packet.
490 for (int i = 0; i < repeat_count; ++i)
491 packet_str.push_back(char_to_repeat);
492 }
493 else
494 {
495 packet_str.push_back(*c);
496 }
497 }
498
Greg Clayton73bf5db2011-06-17 01:22:15 +0000499 if (m_bytes[0] == '$')
500 {
501 assert (checksum_idx < m_bytes.size());
502 if (::isxdigit (m_bytes[checksum_idx+0]) ||
503 ::isxdigit (m_bytes[checksum_idx+1]))
504 {
505 if (GetSendAcks ())
506 {
507 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
508 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
509 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
510 success = packet_checksum == actual_checksum;
511 if (!success)
512 {
513 if (log)
514 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
515 (int)(total_length),
516 m_bytes.c_str(),
517 (uint8_t)packet_checksum,
518 (uint8_t)actual_checksum);
519 }
520 // Send the ack or nack if needed
521 if (!success)
522 SendNack();
523 else
524 SendAck();
525 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000526 }
527 else
528 {
529 success = false;
530 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000531 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
Greg Clayton73bf5db2011-06-17 01:22:15 +0000532 }
533 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000534
Greg Clayton73bf5db2011-06-17 01:22:15 +0000535 m_bytes.erase(0, total_length);
536 packet.SetFilePos(0);
537 return success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000538 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000539 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000540 packet.Clear();
541 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000542}
543
Greg Clayton8b82f082011-04-12 05:54:46 +0000544Error
Greg Claytond6299802013-12-06 17:46:35 +0000545GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
Greg Clayton00fe87b2013-12-05 22:58:22 +0000546{
547 Error error;
548 if (IS_VALID_LLDB_HOST_THREAD(m_listen_thread))
549 {
550 error.SetErrorString("listen thread already running");
551 }
552 else
553 {
554 char listen_url[512];
555 if (hostname && hostname[0])
556 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname ? hostname : "localhost", port);
557 else
558 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
559 m_listen_url = listen_url;
560 SetConnection(new ConnectionFileDescriptor());
561 m_listen_thread = Host::ThreadCreate (listen_url, GDBRemoteCommunication::ListenThread, this, &error);
562 }
563 return error;
564}
565
566bool
567GDBRemoteCommunication::JoinListenThread ()
568{
569 if (IS_VALID_LLDB_HOST_THREAD(m_listen_thread))
570 {
571 Host::ThreadJoin(m_listen_thread, NULL, NULL);
572 m_listen_thread = LLDB_INVALID_HOST_THREAD;
573 }
574 return true;
575}
576
577lldb::thread_result_t
578GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
579{
580 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
581 Error error;
582 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
583
584 if (connection)
585 {
586 // Do the listen on another thread so we can continue on...
587 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
588 comm->SetConnection(NULL);
589 }
590 return NULL;
591}
592
593Error
594GDBRemoteCommunication::StartDebugserverProcess (const char *host_and_port,
Greg Clayton91a9b2472013-12-04 19:19:12 +0000595 lldb_private::ProcessLaunchInfo &launch_info,
596 uint16_t &port)
Greg Clayton8b82f082011-04-12 05:54:46 +0000597{
Greg Clayton91a9b2472013-12-04 19:19:12 +0000598 port = 0;
599
Greg Clayton8b82f082011-04-12 05:54:46 +0000600 Error error;
601 // If we locate debugserver, keep that located version around
602 static FileSpec g_debugserver_file_spec;
603
604 // This function will fill in the launch information for the debugserver
605 // instance that gets launched.
606 launch_info.Clear();
607
608 char debugserver_path[PATH_MAX];
609 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
610
611 // Always check to see if we have an environment override for the path
612 // to the debugserver to use and use it if we do.
613 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
614 if (env_debugserver_path)
615 debugserver_file_spec.SetFile (env_debugserver_path, false);
616 else
617 debugserver_file_spec = g_debugserver_file_spec;
618 bool debugserver_exists = debugserver_file_spec.Exists();
619 if (!debugserver_exists)
620 {
621 // The debugserver binary is in the LLDB.framework/Resources
622 // directory.
623 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec))
624 {
625 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME);
626 debugserver_exists = debugserver_file_spec.Exists();
627 if (debugserver_exists)
628 {
629 g_debugserver_file_spec = debugserver_file_spec;
630 }
631 else
632 {
633 g_debugserver_file_spec.Clear();
634 debugserver_file_spec.Clear();
635 }
636 }
637 }
638
639 if (debugserver_exists)
640 {
641 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
642
643 Args &debugserver_args = launch_info.GetArguments();
644 debugserver_args.Clear();
645 char arg_cstr[PATH_MAX];
646
647 // Start args with "debugserver /file/path -r --"
648 debugserver_args.AppendArgument(debugserver_path);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000649
650 // If a host and port is supplied then use it
651 if (host_and_port)
652 debugserver_args.AppendArgument(host_and_port);
Greg Clayton8b82f082011-04-12 05:54:46 +0000653 // use native registers, not the GDB registers
654 debugserver_args.AppendArgument("--native-regs");
655 // make debugserver run in its own session so signals generated by
656 // special terminal key sequences (^C) don't affect debugserver
657 debugserver_args.AppendArgument("--setsid");
Greg Clayton91a9b2472013-12-04 19:19:12 +0000658
Greg Clayton00fe87b2013-12-05 22:58:22 +0000659 char named_pipe_path[PATH_MAX];
660
661 if (host_and_port)
Greg Clayton91a9b2472013-12-04 19:19:12 +0000662 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000663 // Create a temporary file to get the stdout/stderr and redirect the
664 // output of the command into this file. We will later read this file
665 // if all goes well and fill the data into "command_output_ptr"
666 FileSpec tmpdir_file_spec;
667 if (Host::GetLLDBPath (ePathTypeLLDBTempSystemDir, tmpdir_file_spec))
Greg Clayton91a9b2472013-12-04 19:19:12 +0000668 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000669 tmpdir_file_spec.GetFilename().SetCString("debugserver-named-pipe.XXXXXX");
670 strncpy(named_pipe_path, tmpdir_file_spec.GetPath().c_str(), sizeof(named_pipe_path));
671 }
672 else
673 {
674 strncpy(named_pipe_path, "/tmp/debugserver-named-pipe.XXXXXX", sizeof(named_pipe_path));
675 }
676
677 if (::mktemp (named_pipe_path))
678 {
679 if (::mkfifo(named_pipe_path, 0600) == 0)
680 {
681 debugserver_args.AppendArgument("--named-pipe");
682 debugserver_args.AppendArgument(named_pipe_path);
683 }
684 else
685 named_pipe_path[0] = '\0';
Greg Clayton91a9b2472013-12-04 19:19:12 +0000686 }
687 else
688 named_pipe_path[0] = '\0';
689 }
690 else
Greg Clayton00fe87b2013-12-05 22:58:22 +0000691 {
Greg Clayton91a9b2472013-12-04 19:19:12 +0000692 named_pipe_path[0] = '\0';
Greg Clayton00fe87b2013-12-05 22:58:22 +0000693
694 // No host and port given, so lets listen on our end and make the debugserver
695 // connect to us..
696 error = StartListenThread ("localhost", 0);
697 if (error.Fail())
698 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +0000699
Greg Clayton00fe87b2013-12-05 22:58:22 +0000700 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
701 port = connection->GetBoundPort(3);
702 assert (port != 0);
703 char port_cstr[32];
704 snprintf(port_cstr, sizeof(port_cstr), "localhost:%i", port);
705 // Send the host and port down that debugserver and specify an option
706 // so that it connects back to the port we are listening to in this process
707 debugserver_args.AppendArgument("--reverse-connect");
708 debugserver_args.AppendArgument(port_cstr);
709 }
710
711
Greg Clayton8b82f082011-04-12 05:54:46 +0000712 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
713 if (env_debugserver_log_file)
714 {
715 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
716 debugserver_args.AppendArgument(arg_cstr);
717 }
718
719 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
720 if (env_debugserver_log_flags)
721 {
722 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
723 debugserver_args.AppendArgument(arg_cstr);
724 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000725
726 // Close STDIN, STDOUT and STDERR. We might need to redirect them
727 // to "/dev/null" if we run into any problems.
Greg Clayton91a9b2472013-12-04 19:19:12 +0000728 launch_info.AppendCloseFileAction (STDIN_FILENO);
729 launch_info.AppendCloseFileAction (STDOUT_FILENO);
730 launch_info.AppendCloseFileAction (STDERR_FILENO);
Greg Clayton8b82f082011-04-12 05:54:46 +0000731
732 error = Host::LaunchProcess(launch_info);
Greg Clayton91a9b2472013-12-04 19:19:12 +0000733
734 if (named_pipe_path[0])
735 {
736 File name_pipe_file;
737 error = name_pipe_file.Open(named_pipe_path, File::eOpenOptionRead);
738 if (error.Success())
739 {
740 char port_cstr[256];
741 port_cstr[0] = '\0';
742 size_t num_bytes = sizeof(port_cstr);
743 error = name_pipe_file.Read(port_cstr, num_bytes);
744 assert (error.Success());
745 assert (num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
746 port = Args::StringToUInt32(port_cstr, 0);
747 name_pipe_file.Close();
748 }
749 Host::Unlink(named_pipe_path);
750 }
Greg Clayton00fe87b2013-12-05 22:58:22 +0000751 else
752 {
753 // Make sure we actually connect with the debugserver...
754 JoinListenThread();
755 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000756 }
757 else
758 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000759 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
Greg Clayton8b82f082011-04-12 05:54:46 +0000760 }
761 return error;
762}
763
Greg Claytonc1422c12012-04-09 22:46:21 +0000764void
Greg Claytond451c1a2012-04-13 21:24:18 +0000765GDBRemoteCommunication::DumpHistory(Stream &strm)
Greg Claytonc1422c12012-04-09 22:46:21 +0000766{
Greg Claytond451c1a2012-04-13 21:24:18 +0000767 m_history.Dump (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000768}