blob: 38942ec2d1755cd463d1c24bea9cbc396c9ee01d [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 Claytonc1422c12012-04-09 22:46:21 +000021#include "lldb/Core/StreamFile.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/StreamString.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000023#include "lldb/Host/ConnectionFileDescriptor.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000024#include "lldb/Host/FileSpec.h"
25#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000026#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000027#include "lldb/Host/Pipe.h"
Zachary Turner98688922014-08-06 18:16:26 +000028#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000029#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000030#include "lldb/Host/ThreadLauncher.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031#include "lldb/Host/TimeValue.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000032#include "lldb/Target/Process.h"
Oleksiy Vyalov4536c452015-02-05 16:29:12 +000033#include "llvm/ADT/SmallString.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000034
35// Project includes
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036#include "ProcessGDBRemoteLog.h"
37
Todd Fiala015d8182014-07-22 23:41:36 +000038#if defined(__APPLE__)
39# define DEBUGSERVER_BASENAME "debugserver"
40#else
Tamas Berghammerc2c3d712015-02-18 15:39:41 +000041# define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000042#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000043
Chris Lattner30fdc8d2010-06-08 16:52:24 +000044using namespace lldb;
45using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000046using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047
Greg Claytonc1422c12012-04-09 22:46:21 +000048GDBRemoteCommunication::History::History (uint32_t size) :
49 m_packets(),
50 m_curr_idx (0),
51 m_total_packet_count (0),
52 m_dumped_to_log (false)
53{
54 m_packets.resize(size);
55}
56
57GDBRemoteCommunication::History::~History ()
58{
59}
60
61void
Greg Claytond451c1a2012-04-13 21:24:18 +000062GDBRemoteCommunication::History::AddPacket (char packet_char,
63 PacketType type,
64 uint32_t bytes_transmitted)
65{
66 const size_t size = m_packets.size();
67 if (size > 0)
68 {
69 const uint32_t idx = GetNextIndex();
70 m_packets[idx].packet.assign (1, packet_char);
71 m_packets[idx].type = type;
72 m_packets[idx].bytes_transmitted = bytes_transmitted;
73 m_packets[idx].packet_idx = m_total_packet_count;
74 m_packets[idx].tid = Host::GetCurrentThreadID();
75 }
76}
77
78void
79GDBRemoteCommunication::History::AddPacket (const std::string &src,
80 uint32_t src_len,
81 PacketType type,
82 uint32_t bytes_transmitted)
83{
84 const size_t size = m_packets.size();
85 if (size > 0)
86 {
87 const uint32_t idx = GetNextIndex();
88 m_packets[idx].packet.assign (src, 0, src_len);
89 m_packets[idx].type = type;
90 m_packets[idx].bytes_transmitted = bytes_transmitted;
91 m_packets[idx].packet_idx = m_total_packet_count;
92 m_packets[idx].tid = Host::GetCurrentThreadID();
93 }
94}
95
96void
Tamas Berghammerdb264a62015-03-31 09:52:22 +000097GDBRemoteCommunication::History::Dump (Stream &strm) const
Greg Claytonc1422c12012-04-09 22:46:21 +000098{
99 const uint32_t size = GetNumPacketsInHistory ();
100 const uint32_t first_idx = GetFirstSavedPacketIndex ();
101 const uint32_t stop_idx = m_curr_idx + size;
102 for (uint32_t i = first_idx; i < stop_idx; ++i)
103 {
104 const uint32_t idx = NormalizeIndex (i);
105 const Entry &entry = m_packets[idx];
106 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
107 break;
Daniel Malead01b2952012-11-29 21:49:15 +0000108 strm.Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s\n",
Greg Claytonc1422c12012-04-09 22:46:21 +0000109 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +0000110 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000111 entry.bytes_transmitted,
112 (entry.type == ePacketTypeSend) ? "send" : "read",
113 entry.packet.c_str());
114 }
115}
116
117void
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000118GDBRemoteCommunication::History::Dump (Log *log) const
Greg Claytonc1422c12012-04-09 22:46:21 +0000119{
120 if (log && !m_dumped_to_log)
121 {
122 m_dumped_to_log = true;
123 const uint32_t size = GetNumPacketsInHistory ();
124 const uint32_t first_idx = GetFirstSavedPacketIndex ();
125 const uint32_t stop_idx = m_curr_idx + size;
126 for (uint32_t i = first_idx; i < stop_idx; ++i)
127 {
128 const uint32_t idx = NormalizeIndex (i);
129 const Entry &entry = m_packets[idx];
130 if (entry.type == ePacketTypeInvalid || entry.packet.empty())
131 break;
Daniel Malead01b2952012-11-29 21:49:15 +0000132 log->Printf ("history[%u] tid=0x%4.4" PRIx64 " <%4u> %s packet: %s",
Greg Claytonc1422c12012-04-09 22:46:21 +0000133 entry.packet_idx,
Greg Claytond451c1a2012-04-13 21:24:18 +0000134 entry.tid,
Greg Claytonc1422c12012-04-09 22:46:21 +0000135 entry.bytes_transmitted,
136 (entry.type == ePacketTypeSend) ? "send" : "read",
137 entry.packet.c_str());
138 }
139 }
140}
141
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000142//----------------------------------------------------------------------
143// GDBRemoteCommunication constructor
144//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +0000145GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
Tamas Berghammere13c2732015-02-11 10:29:30 +0000146 const char *listener_name) :
Greg Clayton576d8832011-03-22 04:00:09 +0000147 Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000148#ifdef LLDB_CONFIGURATION_DEBUG
149 m_packet_timeout (1000),
150#else
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000151 m_packet_timeout (1),
Daniel Maleae0f8f572013-08-26 23:57:52 +0000152#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000153 m_sequence_mutex (Mutex::eMutexTypeRecursive),
Greg Clayton4dc72282011-01-20 07:53:45 +0000154 m_public_is_running (false),
Greg Clayton1cb64962011-03-24 04:28:38 +0000155 m_private_is_running (false),
Greg Claytonc1422c12012-04-09 22:46:21 +0000156 m_history (512),
Greg Clayton8b82f082011-04-12 05:54:46 +0000157 m_send_acks (true),
Greg Clayton00fe87b2013-12-05 22:58:22 +0000158 m_listen_url ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000159{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000160}
161
162//----------------------------------------------------------------------
163// Destructor
164//----------------------------------------------------------------------
165GDBRemoteCommunication::~GDBRemoteCommunication()
166{
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000167 if (IsConnected())
168 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000169 Disconnect();
170 }
171}
172
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000173char
174GDBRemoteCommunication::CalculcateChecksum (const char *payload, size_t payload_length)
175{
176 int checksum = 0;
177
Ed Mastea6b4c772013-08-20 14:12:58 +0000178 for (size_t i = 0; i < payload_length; ++i)
179 checksum += payload[i];
180
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000181 return checksum & 255;
182}
183
184size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000185GDBRemoteCommunication::SendAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000186{
Greg Clayton5160ce52013-03-27 23:08:40 +0000187 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000188 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000189 char ch = '+';
190 const size_t bytes_written = Write (&ch, 1, status, NULL);
191 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000192 log->Printf ("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000193 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
194 return bytes_written;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000195}
196
197size_t
Greg Clayton6ed95942011-01-22 07:12:45 +0000198GDBRemoteCommunication::SendNack ()
199{
Greg Clayton5160ce52013-03-27 23:08:40 +0000200 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton6ed95942011-01-22 07:12:45 +0000201 ConnectionStatus status = eConnectionStatusSuccess;
Greg Claytonc1422c12012-04-09 22:46:21 +0000202 char ch = '-';
203 const size_t bytes_written = Write (&ch, 1, status, NULL);
204 if (log)
Greg Clayton45989072013-10-23 18:24:30 +0000205 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000206 m_history.AddPacket (ch, History::ePacketTypeSend, bytes_written);
207 return bytes_written;
Greg Clayton32e0a752011-03-30 18:16:51 +0000208}
209
Greg Clayton3dedae12013-12-06 21:45:27 +0000210GDBRemoteCommunication::PacketResult
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000211GDBRemoteCommunication::SendPacket (const char *payload, size_t payload_length)
212{
213 Mutex::Locker locker(m_sequence_mutex);
214 return SendPacketNoLock (payload, payload_length);
215}
216
Greg Clayton3dedae12013-12-06 21:45:27 +0000217GDBRemoteCommunication::PacketResult
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000218GDBRemoteCommunication::SendPacketNoLock (const char *payload, size_t payload_length)
219{
220 if (IsConnected())
221 {
222 StreamString packet(0, 4, eByteOrderBig);
223
224 packet.PutChar('$');
225 packet.Write (payload, payload_length);
226 packet.PutChar('#');
227 packet.PutHex8(CalculcateChecksum (payload, payload_length));
228
Greg Clayton5160ce52013-03-27 23:08:40 +0000229 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000230 ConnectionStatus status = eConnectionStatusSuccess;
Greg Clayton7e244322014-09-18 00:17:36 +0000231 const char *packet_data = packet.GetData();
232 const size_t packet_length = packet.GetSize();
233 size_t bytes_written = Write (packet_data, packet_length, status, NULL);
Greg Claytonc1422c12012-04-09 22:46:21 +0000234 if (log)
235 {
Greg Clayton7e244322014-09-18 00:17:36 +0000236 size_t binary_start_offset = 0;
237 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) == 0)
238 {
239 const char *first_comma = strchr(packet_data, ',');
240 if (first_comma)
241 {
242 const char *second_comma = strchr(first_comma + 1, ',');
243 if (second_comma)
244 binary_start_offset = second_comma - packet_data + 1;
245 }
246 }
247
Greg Claytonc1422c12012-04-09 22:46:21 +0000248 // If logging was just enabled and we have history, then dump out what
249 // we have to the log so we get the historical context. The Dump() call that
250 // logs all of the packet will set a boolean so that we don't dump this more
251 // than once
252 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000253 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000254
Greg Clayton7e244322014-09-18 00:17:36 +0000255 if (binary_start_offset)
256 {
257 StreamString strm;
258 // Print non binary data header
259 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)binary_start_offset, packet_data);
260 const uint8_t *p;
261 // Print binary data exactly as sent
Vince Harron8b335672015-05-12 01:10:56 +0000262 for (p = (const uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p)
Greg Clayton7e244322014-09-18 00:17:36 +0000263 strm.Printf("\\x%2.2x", *p);
264 // Print the checksum
265 strm.Printf("%*s", (int)3, p);
266 log->PutCString(strm.GetString().c_str());
267 }
268 else
269 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written, (int)packet_length, packet_data);
Greg Claytonc1422c12012-04-09 22:46:21 +0000270 }
271
Greg Clayton7e244322014-09-18 00:17:36 +0000272 m_history.AddPacket (packet.GetString(), packet_length, History::ePacketTypeSend, bytes_written);
Greg Claytonc1422c12012-04-09 22:46:21 +0000273
274
Greg Clayton7e244322014-09-18 00:17:36 +0000275 if (bytes_written == packet_length)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000276 {
Greg Clayton71fc2a32011-02-12 06:28:37 +0000277 if (GetSendAcks ())
Greg Clayton3dedae12013-12-06 21:45:27 +0000278 return GetAck ();
279 else
280 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000281 }
Johnny Chend0c40dd2010-09-14 22:10:43 +0000282 else
283 {
Greg Clayton6d093452011-02-05 02:25:06 +0000284 if (log)
Greg Clayton7e244322014-09-18 00:17:36 +0000285 log->Printf ("error: failed to send packet: %.*s", (int)packet_length, packet_data);
Johnny Chend0c40dd2010-09-14 22:10:43 +0000286 }
Greg Claytonf5e56de2010-09-14 23:36:40 +0000287 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000288 return PacketResult::ErrorSendFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000289}
290
Greg Clayton3dedae12013-12-06 21:45:27 +0000291GDBRemoteCommunication::PacketResult
Greg Claytonc574ede2011-03-10 02:26:48 +0000292GDBRemoteCommunication::GetAck ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000293{
Greg Clayton576d8832011-03-22 04:00:09 +0000294 StringExtractorGDBRemote packet;
Greg Clayton3dedae12013-12-06 21:45:27 +0000295 PacketResult result = WaitForPacketWithTimeoutMicroSecondsNoLock (packet, GetPacketTimeoutInMicroSeconds ());
296 if (result == PacketResult::Success)
297 {
298 if (packet.GetResponseType() == StringExtractorGDBRemote::ResponseType::eAck)
299 return PacketResult::Success;
300 else
301 return PacketResult::ErrorSendAck;
302 }
303 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000304}
305
306bool
Jim Ingham4ceb9282012-06-08 22:50:40 +0000307GDBRemoteCommunication::GetSequenceMutex (Mutex::Locker& locker, const char *failure_message)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000308{
Greg Claytond9896732012-05-31 16:54:51 +0000309 if (IsRunning())
Jim Ingham4ceb9282012-06-08 22:50:40 +0000310 return locker.TryLock (m_sequence_mutex, failure_message);
Greg Claytond9896732012-05-31 16:54:51 +0000311
312 locker.Lock (m_sequence_mutex);
313 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000314}
315
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000316
Greg Clayton6779606a2011-01-22 23:43:18 +0000317bool
Greg Clayton6779606a2011-01-22 23:43:18 +0000318GDBRemoteCommunication::WaitForNotRunningPrivate (const TimeValue *timeout_ptr)
319{
320 return m_private_is_running.WaitForValueEqualTo (false, timeout_ptr, NULL);
321}
322
Greg Clayton3dedae12013-12-06 21:45:27 +0000323GDBRemoteCommunication::PacketResult
Greg Clayton73bf5db2011-06-17 01:22:15 +0000324GDBRemoteCommunication::WaitForPacketWithTimeoutMicroSecondsNoLock (StringExtractorGDBRemote &packet, uint32_t timeout_usec)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325{
Greg Clayton73bf5db2011-06-17 01:22:15 +0000326 uint8_t buffer[8192];
327 Error error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328
Greg Clayton5160ce52013-03-27 23:08:40 +0000329 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS | GDBR_LOG_VERBOSE));
Greg Clayton644247c2011-07-07 01:59:51 +0000330
Greg Clayton73bf5db2011-06-17 01:22:15 +0000331 // Check for a packet from our cache first without trying any reading...
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000332 if (CheckForPacket(NULL, 0, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000333 return PacketResult::Success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000334
Greg Clayton0c51ac32011-07-02 23:21:06 +0000335 bool timed_out = false;
Greg Clayton3dedae12013-12-06 21:45:27 +0000336 bool disconnected = false;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000337 while (IsConnected() && !timed_out)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000338 {
Johnny Chen74549c82011-07-19 01:13:00 +0000339 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000340 size_t bytes_read = Read (buffer, sizeof(buffer), timeout_usec, status, &error);
Greg Clayton644247c2011-07-07 01:59:51 +0000341
342 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000343 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 +0000344 __PRETTY_FUNCTION__,
345 timeout_usec,
346 Communication::ConnectionStatusAsCString (status),
347 error.AsCString(),
Greg Clayton43e0af02012-09-18 18:04:04 +0000348 (uint64_t)bytes_read);
Greg Clayton644247c2011-07-07 01:59:51 +0000349
Greg Clayton73bf5db2011-06-17 01:22:15 +0000350 if (bytes_read > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000351 {
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000352 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000353 return PacketResult::Success;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000354 }
355 else
356 {
357 switch (status)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000358 {
Greg Clayton197bacf2011-07-02 21:07:54 +0000359 case eConnectionStatusTimedOut:
Greg Claytonf0066ad2014-05-02 00:45:31 +0000360 case eConnectionStatusInterrupted:
Greg Clayton0c51ac32011-07-02 23:21:06 +0000361 timed_out = true;
362 break;
363 case eConnectionStatusSuccess:
364 //printf ("status = success but error = %s\n", error.AsCString("<invalid>"));
Greg Clayton73bf5db2011-06-17 01:22:15 +0000365 break;
366
367 case eConnectionStatusEndOfFile:
368 case eConnectionStatusNoConnection:
369 case eConnectionStatusLostConnection:
370 case eConnectionStatusError:
Greg Clayton3dedae12013-12-06 21:45:27 +0000371 disconnected = true;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000372 Disconnect();
373 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000374 }
375 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376 }
Greg Clayton3dedae12013-12-06 21:45:27 +0000377 packet.Clear ();
378 if (disconnected)
379 return PacketResult::ErrorDisconnected;
380 if (timed_out)
381 return PacketResult::ErrorReplyTimeout;
382 else
383 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384}
385
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000386GDBRemoteCommunication::PacketType
Greg Clayton73bf5db2011-06-17 01:22:15 +0000387GDBRemoteCommunication::CheckForPacket (const uint8_t *src, size_t src_len, StringExtractorGDBRemote &packet)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000388{
389 // Put the packet data into the buffer in a thread safe fashion
390 Mutex::Locker locker(m_bytes_mutex);
Greg Clayton197bacf2011-07-02 21:07:54 +0000391
Greg Clayton5160ce52013-03-27 23:08:40 +0000392 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000393
Greg Clayton73bf5db2011-06-17 01:22:15 +0000394 if (src && src_len > 0)
Greg Clayton197bacf2011-07-02 21:07:54 +0000395 {
Greg Clayton0c51ac32011-07-02 23:21:06 +0000396 if (log && log->GetVerbose())
Greg Clayton197bacf2011-07-02 21:07:54 +0000397 {
398 StreamString s;
Greg Clayton0c51ac32011-07-02 23:21:06 +0000399 log->Printf ("GDBRemoteCommunication::%s adding %u bytes: %.*s",
400 __FUNCTION__,
401 (uint32_t)src_len,
402 (uint32_t)src_len,
403 src);
Greg Clayton197bacf2011-07-02 21:07:54 +0000404 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000405 m_bytes.append ((const char *)src, src_len);
Greg Clayton197bacf2011-07-02 21:07:54 +0000406 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000407
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000408 bool isNotifyPacket = false;
409
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410 // Parse up the packets into gdb remote packets
Greg Clayton197bacf2011-07-02 21:07:54 +0000411 if (!m_bytes.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000412 {
413 // end_idx must be one past the last valid packet byte. Start
414 // it off with an invalid value that is the same as the current
415 // index.
Greg Clayton73bf5db2011-06-17 01:22:15 +0000416 size_t content_start = 0;
Greg Clayton118593a2014-11-03 21:02:54 +0000417 size_t content_length = 0;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000418 size_t total_length = 0;
419 size_t checksum_idx = std::string::npos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420
Greg Clayton118593a2014-11-03 21:02:54 +0000421 switch (m_bytes[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000422 {
Greg Clayton118593a2014-11-03 21:02:54 +0000423 case '+': // Look for ack
424 case '-': // Look for cancel
425 case '\x03': // ^C to halt target
426 content_length = total_length = 1; // The command is one byte long...
427 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000428
Ewan Crawford78baa192015-05-13 09:18:18 +0000429 case '%': // Async notify packet
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000430 isNotifyPacket = true;
431 // Intentional fall through
432
Greg Clayton118593a2014-11-03 21:02:54 +0000433 case '$':
434 // Look for a standard gdb packet?
435 {
436 size_t hash_pos = m_bytes.find('#');
437 if (hash_pos != std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000438 {
Greg Clayton118593a2014-11-03 21:02:54 +0000439 if (hash_pos + 2 < m_bytes.size())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000440 {
Greg Clayton118593a2014-11-03 21:02:54 +0000441 checksum_idx = hash_pos + 1;
442 // Skip the dollar sign
443 content_start = 1;
444 // Don't include the # in the content or the $ in the content length
445 content_length = hash_pos - 1;
446
447 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
448 }
449 else
450 {
451 // Checksum bytes aren't all here yet
452 content_length = std::string::npos;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000453 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000454 }
Greg Clayton118593a2014-11-03 21:02:54 +0000455 }
456 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000457
Greg Clayton118593a2014-11-03 21:02:54 +0000458 default:
459 {
460 // We have an unexpected byte and we need to flush all bad
461 // data that is in m_bytes, so we need to find the first
462 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
463 // or '$' character (start of packet header) or of course,
464 // the end of the data in m_bytes...
465 const size_t bytes_len = m_bytes.size();
466 bool done = false;
467 uint32_t idx;
468 for (idx = 1; !done && idx < bytes_len; ++idx)
Greg Clayton197bacf2011-07-02 21:07:54 +0000469 {
Greg Clayton118593a2014-11-03 21:02:54 +0000470 switch (m_bytes[idx])
Greg Clayton197bacf2011-07-02 21:07:54 +0000471 {
Greg Clayton118593a2014-11-03 21:02:54 +0000472 case '+':
473 case '-':
474 case '\x03':
Ewan Crawford78baa192015-05-13 09:18:18 +0000475 case '%':
Greg Clayton118593a2014-11-03 21:02:54 +0000476 case '$':
477 done = true;
478 break;
479
480 default:
481 break;
Greg Clayton197bacf2011-07-02 21:07:54 +0000482 }
483 }
Greg Clayton118593a2014-11-03 21:02:54 +0000484 if (log)
485 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
486 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
487 m_bytes.erase(0, idx - 1);
488 }
489 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000490 }
491
Greg Clayton73bf5db2011-06-17 01:22:15 +0000492 if (content_length == std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000494 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000495 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000496 }
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000497 else if (total_length > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000498 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000499
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000500 // We have a valid packet...
Greg Clayton73bf5db2011-06-17 01:22:15 +0000501 assert (content_length <= m_bytes.size());
502 assert (total_length <= m_bytes.size());
503 assert (content_length <= total_length);
Greg Clayton06f09b52014-06-20 20:41:07 +0000504 const size_t content_end = content_start + content_length;
505
Greg Clayton73bf5db2011-06-17 01:22:15 +0000506 bool success = true;
507 std::string &packet_str = packet.GetStringRef();
Greg Claytonc1422c12012-04-09 22:46:21 +0000508
509
510 if (log)
511 {
512 // If logging was just enabled and we have history, then dump out what
513 // we have to the log so we get the historical context. The Dump() call that
514 // logs all of the packet will set a boolean so that we don't dump this more
515 // than once
516 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000517 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000518
Greg Clayton06f09b52014-06-20 20:41:07 +0000519 bool binary = false;
520 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
521 if (m_bytes[0] == '$' && total_length > 4)
522 {
523 for (size_t i=0; !binary && i<total_length; ++i)
524 {
525 if (isprint(m_bytes[i]) == 0)
526 binary = true;
527 }
528 }
529 if (binary)
530 {
531 StreamString strm;
532 // Packet header...
533 strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
534 for (size_t i=content_start; i<content_end; ++i)
535 {
536 // Remove binary escaped bytes when displaying the packet...
537 const char ch = m_bytes[i];
538 if (ch == 0x7d)
539 {
540 // 0x7d is the escape character. The next character is to
541 // be XOR'd with 0x20.
542 const char escapee = m_bytes[++i] ^ 0x20;
543 strm.Printf("%2.2x", escapee);
544 }
545 else
546 {
547 strm.Printf("%2.2x", (uint8_t)ch);
548 }
549 }
550 // Packet footer...
551 strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
552 log->PutCString(strm.GetString().c_str());
553 }
554 else
555 {
556 log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
557 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000558 }
559
560 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
561
Hafiz Abid Qadeere5fd5e12013-08-28 15:10:37 +0000562 // Clear packet_str in case there is some existing data in it.
563 packet_str.clear();
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000564 // Copy the packet from m_bytes to packet_str expanding the
565 // run-length encoding in the process.
566 // Reserve enough byte for the most common case (no RLE used)
567 packet_str.reserve(m_bytes.length());
Greg Clayton06f09b52014-06-20 20:41:07 +0000568 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 +0000569 {
570 if (*c == '*')
571 {
572 // '*' indicates RLE. Next character will give us the
573 // repeat count and previous character is what is to be
574 // repeated.
575 char char_to_repeat = packet_str.back();
576 // Number of time the previous character is repeated
577 int repeat_count = *++c + 3 - ' ';
578 // We have the char_to_repeat and repeat_count. Now push
579 // it in the packet.
580 for (int i = 0; i < repeat_count; ++i)
581 packet_str.push_back(char_to_repeat);
582 }
Steve Pucci3c5d3332014-02-24 19:07:29 +0000583 else if (*c == 0x7d)
584 {
585 // 0x7d is the escape character. The next character is to
586 // be XOR'd with 0x20.
587 char escapee = *++c ^ 0x20;
588 packet_str.push_back(escapee);
589 }
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000590 else
591 {
592 packet_str.push_back(*c);
593 }
594 }
595
Ewan Crawford78baa192015-05-13 09:18:18 +0000596 if (m_bytes[0] == '$' || m_bytes[0] == '%')
Greg Clayton73bf5db2011-06-17 01:22:15 +0000597 {
598 assert (checksum_idx < m_bytes.size());
599 if (::isxdigit (m_bytes[checksum_idx+0]) ||
600 ::isxdigit (m_bytes[checksum_idx+1]))
601 {
602 if (GetSendAcks ())
603 {
604 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
605 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
606 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
607 success = packet_checksum == actual_checksum;
608 if (!success)
609 {
610 if (log)
611 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
612 (int)(total_length),
613 m_bytes.c_str(),
614 (uint8_t)packet_checksum,
615 (uint8_t)actual_checksum);
616 }
617 // Send the ack or nack if needed
618 if (!success)
619 SendNack();
620 else
621 SendAck();
622 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000623 }
624 else
625 {
626 success = false;
627 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000628 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
Greg Clayton73bf5db2011-06-17 01:22:15 +0000629 }
630 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000631
Greg Clayton73bf5db2011-06-17 01:22:15 +0000632 m_bytes.erase(0, total_length);
633 packet.SetFilePos(0);
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000634
635 if (isNotifyPacket)
636 return GDBRemoteCommunication::PacketType::Notify;
637 else
638 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000639 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000641 packet.Clear();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000642 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000643}
644
Greg Clayton8b82f082011-04-12 05:54:46 +0000645Error
Greg Claytond6299802013-12-06 17:46:35 +0000646GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
Greg Clayton00fe87b2013-12-05 22:58:22 +0000647{
648 Error error;
Zachary Turneracee96a2014-09-23 18:32:09 +0000649 if (m_listen_thread.IsJoinable())
Greg Clayton00fe87b2013-12-05 22:58:22 +0000650 {
651 error.SetErrorString("listen thread already running");
652 }
653 else
654 {
655 char listen_url[512];
656 if (hostname && hostname[0])
Jean-Daniel Dupas3c6774a2014-02-08 20:29:40 +0000657 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000658 else
659 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
660 m_listen_url = listen_url;
661 SetConnection(new ConnectionFileDescriptor());
Zachary Turner39de3112014-09-09 20:54:56 +0000662 m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000663 }
664 return error;
665}
666
667bool
668GDBRemoteCommunication::JoinListenThread ()
669{
Zachary Turneracee96a2014-09-23 18:32:09 +0000670 if (m_listen_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000671 m_listen_thread.Join(nullptr);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000672 return true;
673}
674
675lldb::thread_result_t
676GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
677{
678 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
679 Error error;
680 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
681
682 if (connection)
683 {
684 // Do the listen on another thread so we can continue on...
685 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
686 comm->SetConnection(NULL);
687 }
688 return NULL;
689}
690
691Error
Greg Claytonfda4fab2014-01-10 22:24:11 +0000692GDBRemoteCommunication::StartDebugserverProcess (const char *hostname,
693 uint16_t in_port,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000694 ProcessLaunchInfo &launch_info,
Greg Claytonfda4fab2014-01-10 22:24:11 +0000695 uint16_t &out_port)
Greg Clayton8b82f082011-04-12 05:54:46 +0000696{
Todd Fiala015d8182014-07-22 23:41:36 +0000697 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
698 if (log)
699 log->Printf ("GDBRemoteCommunication::%s(hostname=%s, in_port=%" PRIu16 ", out_port=%" PRIu16, __FUNCTION__, hostname ? hostname : "<empty>", in_port, out_port);
700
Greg Claytonfda4fab2014-01-10 22:24:11 +0000701 out_port = in_port;
Greg Clayton8b82f082011-04-12 05:54:46 +0000702 Error error;
703 // If we locate debugserver, keep that located version around
704 static FileSpec g_debugserver_file_spec;
705
Greg Clayton8b82f082011-04-12 05:54:46 +0000706 char debugserver_path[PATH_MAX];
707 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
708
709 // Always check to see if we have an environment override for the path
710 // to the debugserver to use and use it if we do.
711 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
712 if (env_debugserver_path)
Todd Fiala015d8182014-07-22 23:41:36 +0000713 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000714 debugserver_file_spec.SetFile (env_debugserver_path, false);
Todd Fiala015d8182014-07-22 23:41:36 +0000715 if (log)
716 log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path);
717 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000718 else
719 debugserver_file_spec = g_debugserver_file_spec;
720 bool debugserver_exists = debugserver_file_spec.Exists();
721 if (!debugserver_exists)
722 {
723 // The debugserver binary is in the LLDB.framework/Resources
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000724 // directory.
725 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec))
Greg Clayton8b82f082011-04-12 05:54:46 +0000726 {
Jason Molenda6fd86772014-08-21 23:22:33 +0000727 debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME);
Greg Clayton8b82f082011-04-12 05:54:46 +0000728 debugserver_exists = debugserver_file_spec.Exists();
729 if (debugserver_exists)
730 {
Todd Fiala015d8182014-07-22 23:41:36 +0000731 if (log)
732 log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
733
Greg Clayton8b82f082011-04-12 05:54:46 +0000734 g_debugserver_file_spec = debugserver_file_spec;
735 }
736 else
737 {
Todd Fiala015d8182014-07-22 23:41:36 +0000738 if (log)
739 log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
740
Greg Clayton8b82f082011-04-12 05:54:46 +0000741 g_debugserver_file_spec.Clear();
742 debugserver_file_spec.Clear();
743 }
744 }
745 }
746
747 if (debugserver_exists)
748 {
749 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
750
751 Args &debugserver_args = launch_info.GetArguments();
752 debugserver_args.Clear();
753 char arg_cstr[PATH_MAX];
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000754
Greg Clayton8b82f082011-04-12 05:54:46 +0000755 // Start args with "debugserver /file/path -r --"
756 debugserver_args.AppendArgument(debugserver_path);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000757
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000758#if !defined(__APPLE__)
759 // First argument to lldb-server must be mode in which to run.
760 debugserver_args.AppendArgument("gdbserver");
761#endif
762
Greg Clayton00fe87b2013-12-05 22:58:22 +0000763 // If a host and port is supplied then use it
Greg Claytonfda4fab2014-01-10 22:24:11 +0000764 char host_and_port[128];
765 if (hostname)
766 {
767 snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000768 debugserver_args.AppendArgument(host_and_port);
Greg Claytonfda4fab2014-01-10 22:24:11 +0000769 }
770 else
771 {
772 host_and_port[0] = '\0';
773 }
774
Greg Clayton8b82f082011-04-12 05:54:46 +0000775 // use native registers, not the GDB registers
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +0000776 debugserver_args.AppendArgument("--native-regs");
777
778 if (launch_info.GetLaunchInSeparateProcessGroup())
779 {
780 debugserver_args.AppendArgument("--setsid");
781 }
Greg Clayton91a9b2472013-12-04 19:19:12 +0000782
Oleksiy Vyalov4536c452015-02-05 16:29:12 +0000783 llvm::SmallString<PATH_MAX> named_pipe_path;
Chaoren Lin368c9f62015-04-27 23:20:30 +0000784 Pipe port_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000785
Vince Harrond7e6a4f2015-05-13 00:25:54 +0000786 if (host_and_port[0] && in_port == 0)
Greg Clayton91a9b2472013-12-04 19:19:12 +0000787 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000788 // Create a temporary file to get the stdout/stderr and redirect the
789 // output of the command into this file. We will later read this file
790 // if all goes well and fill the data into "command_output_ptr"
Greg Clayton00fe87b2013-12-05 22:58:22 +0000791
Vince Harrond7e6a4f2015-05-13 00:25:54 +0000792 // Binding to port zero, we need to figure out what port it ends up
793 // using using a named pipe...
794 error = port_pipe.CreateWithUniqueName("debugserver-named-pipe", false, named_pipe_path);
795 if (error.Success())
Greg Clayton00fe87b2013-12-05 22:58:22 +0000796 {
Vince Harrond7e6a4f2015-05-13 00:25:54 +0000797 debugserver_args.AppendArgument("--named-pipe");
798 debugserver_args.AppendArgument(named_pipe_path.c_str());
Greg Clayton91a9b2472013-12-04 19:19:12 +0000799 }
800 else
Greg Claytonfda4fab2014-01-10 22:24:11 +0000801 {
Vince Harrond7e6a4f2015-05-13 00:25:54 +0000802 if (log)
803 log->Printf("GDBRemoteCommunication::%s() "
804 "named pipe creation failed: %s",
805 __FUNCTION__, error.AsCString());
806 // let's try an unnamed pipe
807 error = port_pipe.CreateNew(true);
808 if (error.Fail())
809 {
810 if (log)
811 log->Printf("GDBRemoteCommunication::%s() "
812 "unnamed pipe creation failed: %s",
813 __FUNCTION__, error.AsCString());
814 return error;
815 }
816 int write_fd = port_pipe.GetWriteFileDescriptor();
817 debugserver_args.AppendArgument("--pipe");
818 debugserver_args.AppendArgument(std::to_string(write_fd).c_str());
819 launch_info.AppendCloseFileAction(port_pipe.GetReadFileDescriptor());
Greg Claytonfda4fab2014-01-10 22:24:11 +0000820 }
Greg Clayton91a9b2472013-12-04 19:19:12 +0000821 }
822 else
Greg Clayton00fe87b2013-12-05 22:58:22 +0000823 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000824 // No host and port given, so lets listen on our end and make the debugserver
825 // connect to us..
Greg Clayton16810922014-02-27 19:38:18 +0000826 error = StartListenThread ("127.0.0.1", 0);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000827 if (error.Fail())
Vince Harron8b335672015-05-12 01:10:56 +0000828 {
829 if (log)
830 log->Printf ("GDBRemoteCommunication::%s() unable to start listen thread: %s", __FUNCTION__, error.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +0000831 return error;
Vince Harron8b335672015-05-12 01:10:56 +0000832 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000833
Greg Clayton00fe87b2013-12-05 22:58:22 +0000834 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
Greg Clayton16810922014-02-27 19:38:18 +0000835 // Wait for 10 seconds to resolve the bound port
Zachary Turner98688922014-08-06 18:16:26 +0000836 out_port = connection->GetListeningPort(10);
Greg Clayton16810922014-02-27 19:38:18 +0000837 if (out_port > 0)
838 {
839 char port_cstr[32];
840 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", out_port);
841 // Send the host and port down that debugserver and specify an option
842 // so that it connects back to the port we are listening to in this process
843 debugserver_args.AppendArgument("--reverse-connect");
844 debugserver_args.AppendArgument(port_cstr);
845 }
846 else
847 {
848 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
Vince Harron8b335672015-05-12 01:10:56 +0000849 if (log)
850 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
Greg Clayton16810922014-02-27 19:38:18 +0000851 return error;
852 }
Greg Clayton00fe87b2013-12-05 22:58:22 +0000853 }
Greg Clayton00fe87b2013-12-05 22:58:22 +0000854
Greg Clayton8b82f082011-04-12 05:54:46 +0000855 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
856 if (env_debugserver_log_file)
857 {
858 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
859 debugserver_args.AppendArgument(arg_cstr);
860 }
861
Vince Harron9753dd92015-05-10 15:22:09 +0000862#if defined(__APPLE__)
Greg Clayton8b82f082011-04-12 05:54:46 +0000863 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
864 if (env_debugserver_log_flags)
865 {
866 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
867 debugserver_args.AppendArgument(arg_cstr);
868 }
Vince Harron9753dd92015-05-10 15:22:09 +0000869#else
870 const char *env_debugserver_log_channels = getenv("LLDB_SERVER_LOG_CHANNELS");
871 if (env_debugserver_log_channels)
872 {
873 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-channels=%s", env_debugserver_log_channels);
874 debugserver_args.AppendArgument(arg_cstr);
875 }
876#endif
Todd Fiala34ba4262014-08-29 17:10:31 +0000877
878 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back.
879 uint32_t env_var_index = 1;
880 bool has_env_var;
881 do
882 {
883 char env_var_name[64];
884 snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
885 const char *extra_arg = getenv(env_var_name);
886 has_env_var = extra_arg != nullptr;
887
888 if (has_env_var)
889 {
890 debugserver_args.AppendArgument (extra_arg);
891 if (log)
892 log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg);
893 }
894 } while (has_env_var);
895
Shawn Best629680e2014-11-05 00:58:55 +0000896 // Close STDIN, STDOUT and STDERR.
Greg Clayton91a9b2472013-12-04 19:19:12 +0000897 launch_info.AppendCloseFileAction (STDIN_FILENO);
898 launch_info.AppendCloseFileAction (STDOUT_FILENO);
899 launch_info.AppendCloseFileAction (STDERR_FILENO);
Shawn Best629680e2014-11-05 00:58:55 +0000900
901 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
902 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
903 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
904 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
Zachary Turner9b693272014-12-04 22:06:42 +0000905
Greg Clayton8b82f082011-04-12 05:54:46 +0000906 error = Host::LaunchProcess(launch_info);
Zachary Turner9b693272014-12-04 22:06:42 +0000907
Greg Clayton3121fde2014-02-28 20:47:08 +0000908 if (error.Success() && launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
Greg Clayton91a9b2472013-12-04 19:19:12 +0000909 {
Oleksiy Vyalov4536c452015-02-05 16:29:12 +0000910 if (named_pipe_path.size() > 0)
Greg Clayton91a9b2472013-12-04 19:19:12 +0000911 {
Chaoren Lin368c9f62015-04-27 23:20:30 +0000912 error = port_pipe.OpenAsReader(named_pipe_path, false);
913 if (error.Fail())
914 if (log)
915 log->Printf("GDBRemoteCommunication::%s() "
916 "failed to open named pipe %s for reading: %s",
917 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
918 }
919
920 if (port_pipe.CanWrite())
921 port_pipe.CloseWriteFileDescriptor();
922 if (port_pipe.CanRead())
923 {
924 char port_cstr[256];
925 port_cstr[0] = '\0';
926 size_t num_bytes = sizeof(port_cstr);
927 // Read port from pipe with 10 second timeout.
928 error = port_pipe.ReadWithTimeout(port_cstr, num_bytes,
929 std::chrono::seconds{10}, num_bytes);
Greg Clayton3121fde2014-02-28 20:47:08 +0000930 if (error.Success())
931 {
Chaoren Lin368c9f62015-04-27 23:20:30 +0000932 assert(num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
933 out_port = StringConvert::ToUInt32(port_cstr, 0);
934 if (log)
935 log->Printf("GDBRemoteCommunication::%s() "
936 "debugserver listens %u port",
937 __FUNCTION__, out_port);
Greg Clayton3121fde2014-02-28 20:47:08 +0000938 }
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000939 else
940 {
941 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +0000942 log->Printf("GDBRemoteCommunication::%s() "
943 "failed to read a port value from pipe %s: %s",
944 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
945
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000946 }
Chaoren Lin368c9f62015-04-27 23:20:30 +0000947 port_pipe.Close();
948 }
949
950 if (named_pipe_path.size() > 0)
951 {
952 const auto err = port_pipe.Delete(named_pipe_path);
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000953 if (err.Fail())
954 {
955 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +0000956 log->Printf ("GDBRemoteCommunication::%s failed to delete pipe %s: %s",
957 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000958 }
Greg Clayton91a9b2472013-12-04 19:19:12 +0000959 }
Chaoren Lin368c9f62015-04-27 23:20:30 +0000960
961 // Make sure we actually connect with the debugserver...
962 JoinListenThread();
Greg Clayton00fe87b2013-12-05 22:58:22 +0000963 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000964 }
965 else
966 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000967 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
Greg Clayton8b82f082011-04-12 05:54:46 +0000968 }
Vince Harron8b335672015-05-12 01:10:56 +0000969
970 if (error.Fail())
971 {
972 if (log)
973 log->Printf ("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__, error.AsCString());
974 }
975
Greg Clayton8b82f082011-04-12 05:54:46 +0000976 return error;
977}
978
Greg Claytonc1422c12012-04-09 22:46:21 +0000979void
Greg Claytond451c1a2012-04-13 21:24:18 +0000980GDBRemoteCommunication::DumpHistory(Stream &strm)
Greg Claytonc1422c12012-04-09 22:46:21 +0000981{
Greg Claytond451c1a2012-04-13 21:24:18 +0000982 m_history.Dump (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000983}
Tamas Berghammer912800c2015-02-24 10:23:39 +0000984
985GDBRemoteCommunication::ScopedTimeout::ScopedTimeout (GDBRemoteCommunication& gdb_comm,
986 uint32_t timeout) :
987 m_gdb_comm (gdb_comm)
988{
989 m_saved_timeout = m_gdb_comm.SetPacketTimeout (timeout);
990}
991
992GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout ()
993{
994 m_gdb_comm.SetPacketTimeout (m_saved_timeout);
995}