blob: 064b60a238aa414dedba4e1c81db17b2cc96ec4c [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
262 for (p = (uint8_t*)packet_data + binary_start_offset; *p != '#'; ++p)
263 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...
332 if (CheckForPacket (NULL, 0, packet))
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 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000352 if (CheckForPacket (buffer, bytes_read, packet))
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
Greg Clayton73bf5db2011-06-17 01:22:15 +0000386bool
387GDBRemoteCommunication::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
408 // Parse up the packets into gdb remote packets
Greg Clayton197bacf2011-07-02 21:07:54 +0000409 if (!m_bytes.empty())
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410 {
411 // end_idx must be one past the last valid packet byte. Start
412 // it off with an invalid value that is the same as the current
413 // index.
Greg Clayton73bf5db2011-06-17 01:22:15 +0000414 size_t content_start = 0;
Greg Clayton118593a2014-11-03 21:02:54 +0000415 size_t content_length = 0;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000416 size_t total_length = 0;
417 size_t checksum_idx = std::string::npos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000418
Greg Clayton118593a2014-11-03 21:02:54 +0000419 switch (m_bytes[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000420 {
Greg Clayton118593a2014-11-03 21:02:54 +0000421 case '+': // Look for ack
422 case '-': // Look for cancel
423 case '\x03': // ^C to halt target
424 content_length = total_length = 1; // The command is one byte long...
425 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000426
Greg Clayton118593a2014-11-03 21:02:54 +0000427 case '$':
428 // Look for a standard gdb packet?
429 {
430 size_t hash_pos = m_bytes.find('#');
431 if (hash_pos != std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000432 {
Greg Clayton118593a2014-11-03 21:02:54 +0000433 if (hash_pos + 2 < m_bytes.size())
Greg Clayton73bf5db2011-06-17 01:22:15 +0000434 {
Greg Clayton118593a2014-11-03 21:02:54 +0000435 checksum_idx = hash_pos + 1;
436 // Skip the dollar sign
437 content_start = 1;
438 // Don't include the # in the content or the $ in the content length
439 content_length = hash_pos - 1;
440
441 total_length = hash_pos + 3; // Skip the # and the two hex checksum bytes
442 }
443 else
444 {
445 // Checksum bytes aren't all here yet
446 content_length = std::string::npos;
Greg Clayton73bf5db2011-06-17 01:22:15 +0000447 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000448 }
Greg Clayton118593a2014-11-03 21:02:54 +0000449 }
450 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000451
Greg Clayton118593a2014-11-03 21:02:54 +0000452 default:
453 {
454 // We have an unexpected byte and we need to flush all bad
455 // data that is in m_bytes, so we need to find the first
456 // byte that is a '+' (ACK), '-' (NACK), \x03 (CTRL+C interrupt),
457 // or '$' character (start of packet header) or of course,
458 // the end of the data in m_bytes...
459 const size_t bytes_len = m_bytes.size();
460 bool done = false;
461 uint32_t idx;
462 for (idx = 1; !done && idx < bytes_len; ++idx)
Greg Clayton197bacf2011-07-02 21:07:54 +0000463 {
Greg Clayton118593a2014-11-03 21:02:54 +0000464 switch (m_bytes[idx])
Greg Clayton197bacf2011-07-02 21:07:54 +0000465 {
Greg Clayton118593a2014-11-03 21:02:54 +0000466 case '+':
467 case '-':
468 case '\x03':
469 case '$':
470 done = true;
471 break;
472
473 default:
474 break;
Greg Clayton197bacf2011-07-02 21:07:54 +0000475 }
476 }
Greg Clayton118593a2014-11-03 21:02:54 +0000477 if (log)
478 log->Printf ("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
479 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
480 m_bytes.erase(0, idx - 1);
481 }
482 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000483 }
484
Greg Clayton73bf5db2011-06-17 01:22:15 +0000485 if (content_length == std::string::npos)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000486 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000487 packet.Clear();
488 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000489 }
Greg Claytonf3dd93c2011-06-17 03:31:01 +0000490 else if (total_length > 0)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000491 {
Greg Clayton73bf5db2011-06-17 01:22:15 +0000492
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000493 // We have a valid packet...
Greg Clayton73bf5db2011-06-17 01:22:15 +0000494 assert (content_length <= m_bytes.size());
495 assert (total_length <= m_bytes.size());
496 assert (content_length <= total_length);
Greg Clayton06f09b52014-06-20 20:41:07 +0000497 const size_t content_end = content_start + content_length;
498
Greg Clayton73bf5db2011-06-17 01:22:15 +0000499 bool success = true;
500 std::string &packet_str = packet.GetStringRef();
Greg Claytonc1422c12012-04-09 22:46:21 +0000501
502
503 if (log)
504 {
505 // If logging was just enabled and we have history, then dump out what
506 // we have to the log so we get the historical context. The Dump() call that
507 // logs all of the packet will set a boolean so that we don't dump this more
508 // than once
509 if (!m_history.DidDumpToLog ())
Greg Clayton5160ce52013-03-27 23:08:40 +0000510 m_history.Dump (log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000511
Greg Clayton06f09b52014-06-20 20:41:07 +0000512 bool binary = false;
513 // Only detect binary for packets that start with a '$' and have a '#CC' checksum
514 if (m_bytes[0] == '$' && total_length > 4)
515 {
516 for (size_t i=0; !binary && i<total_length; ++i)
517 {
518 if (isprint(m_bytes[i]) == 0)
519 binary = true;
520 }
521 }
522 if (binary)
523 {
524 StreamString strm;
525 // Packet header...
526 strm.Printf("<%4" PRIu64 "> read packet: %c", (uint64_t)total_length, m_bytes[0]);
527 for (size_t i=content_start; i<content_end; ++i)
528 {
529 // Remove binary escaped bytes when displaying the packet...
530 const char ch = m_bytes[i];
531 if (ch == 0x7d)
532 {
533 // 0x7d is the escape character. The next character is to
534 // be XOR'd with 0x20.
535 const char escapee = m_bytes[++i] ^ 0x20;
536 strm.Printf("%2.2x", escapee);
537 }
538 else
539 {
540 strm.Printf("%2.2x", (uint8_t)ch);
541 }
542 }
543 // Packet footer...
544 strm.Printf("%c%c%c", m_bytes[total_length-3], m_bytes[total_length-2], m_bytes[total_length-1]);
545 log->PutCString(strm.GetString().c_str());
546 }
547 else
548 {
549 log->Printf("<%4" PRIu64 "> read packet: %.*s", (uint64_t)total_length, (int)(total_length), m_bytes.c_str());
550 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000551 }
552
553 m_history.AddPacket (m_bytes.c_str(), total_length, History::ePacketTypeRecv, total_length);
554
Hafiz Abid Qadeere5fd5e12013-08-28 15:10:37 +0000555 // Clear packet_str in case there is some existing data in it.
556 packet_str.clear();
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000557 // Copy the packet from m_bytes to packet_str expanding the
558 // run-length encoding in the process.
559 // Reserve enough byte for the most common case (no RLE used)
560 packet_str.reserve(m_bytes.length());
Greg Clayton06f09b52014-06-20 20:41:07 +0000561 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 +0000562 {
563 if (*c == '*')
564 {
565 // '*' indicates RLE. Next character will give us the
566 // repeat count and previous character is what is to be
567 // repeated.
568 char char_to_repeat = packet_str.back();
569 // Number of time the previous character is repeated
570 int repeat_count = *++c + 3 - ' ';
571 // We have the char_to_repeat and repeat_count. Now push
572 // it in the packet.
573 for (int i = 0; i < repeat_count; ++i)
574 packet_str.push_back(char_to_repeat);
575 }
Steve Pucci3c5d3332014-02-24 19:07:29 +0000576 else if (*c == 0x7d)
577 {
578 // 0x7d is the escape character. The next character is to
579 // be XOR'd with 0x20.
580 char escapee = *++c ^ 0x20;
581 packet_str.push_back(escapee);
582 }
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000583 else
584 {
585 packet_str.push_back(*c);
586 }
587 }
588
Greg Clayton73bf5db2011-06-17 01:22:15 +0000589 if (m_bytes[0] == '$')
590 {
591 assert (checksum_idx < m_bytes.size());
592 if (::isxdigit (m_bytes[checksum_idx+0]) ||
593 ::isxdigit (m_bytes[checksum_idx+1]))
594 {
595 if (GetSendAcks ())
596 {
597 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
598 char packet_checksum = strtol (packet_checksum_cstr, NULL, 16);
599 char actual_checksum = CalculcateChecksum (packet_str.c_str(), packet_str.size());
600 success = packet_checksum == actual_checksum;
601 if (!success)
602 {
603 if (log)
604 log->Printf ("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
605 (int)(total_length),
606 m_bytes.c_str(),
607 (uint8_t)packet_checksum,
608 (uint8_t)actual_checksum);
609 }
610 // Send the ack or nack if needed
611 if (!success)
612 SendNack();
613 else
614 SendAck();
615 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000616 }
617 else
618 {
619 success = false;
620 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000621 log->Printf ("error: invalid checksum in packet: '%s'\n", m_bytes.c_str());
Greg Clayton73bf5db2011-06-17 01:22:15 +0000622 }
623 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000624
Greg Clayton73bf5db2011-06-17 01:22:15 +0000625 m_bytes.erase(0, total_length);
626 packet.SetFilePos(0);
627 return success;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000628 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000629 }
Greg Clayton73bf5db2011-06-17 01:22:15 +0000630 packet.Clear();
631 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000632}
633
Greg Clayton8b82f082011-04-12 05:54:46 +0000634Error
Greg Claytond6299802013-12-06 17:46:35 +0000635GDBRemoteCommunication::StartListenThread (const char *hostname, uint16_t port)
Greg Clayton00fe87b2013-12-05 22:58:22 +0000636{
637 Error error;
Zachary Turneracee96a2014-09-23 18:32:09 +0000638 if (m_listen_thread.IsJoinable())
Greg Clayton00fe87b2013-12-05 22:58:22 +0000639 {
640 error.SetErrorString("listen thread already running");
641 }
642 else
643 {
644 char listen_url[512];
645 if (hostname && hostname[0])
Jean-Daniel Dupas3c6774a2014-02-08 20:29:40 +0000646 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000647 else
648 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
649 m_listen_url = listen_url;
650 SetConnection(new ConnectionFileDescriptor());
Zachary Turner39de3112014-09-09 20:54:56 +0000651 m_listen_thread = ThreadLauncher::LaunchThread(listen_url, GDBRemoteCommunication::ListenThread, this, &error);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000652 }
653 return error;
654}
655
656bool
657GDBRemoteCommunication::JoinListenThread ()
658{
Zachary Turneracee96a2014-09-23 18:32:09 +0000659 if (m_listen_thread.IsJoinable())
Zachary Turner39de3112014-09-09 20:54:56 +0000660 m_listen_thread.Join(nullptr);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000661 return true;
662}
663
664lldb::thread_result_t
665GDBRemoteCommunication::ListenThread (lldb::thread_arg_t arg)
666{
667 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
668 Error error;
669 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)comm->GetConnection ();
670
671 if (connection)
672 {
673 // Do the listen on another thread so we can continue on...
674 if (connection->Connect(comm->m_listen_url.c_str(), &error) != eConnectionStatusSuccess)
675 comm->SetConnection(NULL);
676 }
677 return NULL;
678}
679
680Error
Greg Claytonfda4fab2014-01-10 22:24:11 +0000681GDBRemoteCommunication::StartDebugserverProcess (const char *hostname,
682 uint16_t in_port,
Tamas Berghammerdb264a62015-03-31 09:52:22 +0000683 ProcessLaunchInfo &launch_info,
Greg Claytonfda4fab2014-01-10 22:24:11 +0000684 uint16_t &out_port)
Greg Clayton8b82f082011-04-12 05:54:46 +0000685{
Todd Fiala015d8182014-07-22 23:41:36 +0000686 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
687 if (log)
688 log->Printf ("GDBRemoteCommunication::%s(hostname=%s, in_port=%" PRIu16 ", out_port=%" PRIu16, __FUNCTION__, hostname ? hostname : "<empty>", in_port, out_port);
689
Greg Claytonfda4fab2014-01-10 22:24:11 +0000690 out_port = in_port;
Greg Clayton8b82f082011-04-12 05:54:46 +0000691 Error error;
692 // If we locate debugserver, keep that located version around
693 static FileSpec g_debugserver_file_spec;
694
Greg Clayton8b82f082011-04-12 05:54:46 +0000695 char debugserver_path[PATH_MAX];
696 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
697
698 // Always check to see if we have an environment override for the path
699 // to the debugserver to use and use it if we do.
700 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH");
701 if (env_debugserver_path)
Todd Fiala015d8182014-07-22 23:41:36 +0000702 {
Greg Clayton8b82f082011-04-12 05:54:46 +0000703 debugserver_file_spec.SetFile (env_debugserver_path, false);
Todd Fiala015d8182014-07-22 23:41:36 +0000704 if (log)
705 log->Printf ("GDBRemoteCommunication::%s() gdb-remote stub exe path set from environment variable: %s", __FUNCTION__, env_debugserver_path);
706 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000707 else
708 debugserver_file_spec = g_debugserver_file_spec;
709 bool debugserver_exists = debugserver_file_spec.Exists();
710 if (!debugserver_exists)
711 {
712 // The debugserver binary is in the LLDB.framework/Resources
Zachary Turner42ff0ad2014-08-21 17:29:12 +0000713 // directory.
714 if (HostInfo::GetLLDBPath(ePathTypeSupportExecutableDir, debugserver_file_spec))
Greg Clayton8b82f082011-04-12 05:54:46 +0000715 {
Jason Molenda6fd86772014-08-21 23:22:33 +0000716 debugserver_file_spec.AppendPathComponent (DEBUGSERVER_BASENAME);
Greg Clayton8b82f082011-04-12 05:54:46 +0000717 debugserver_exists = debugserver_file_spec.Exists();
718 if (debugserver_exists)
719 {
Todd Fiala015d8182014-07-22 23:41:36 +0000720 if (log)
721 log->Printf ("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
722
Greg Clayton8b82f082011-04-12 05:54:46 +0000723 g_debugserver_file_spec = debugserver_file_spec;
724 }
725 else
726 {
Todd Fiala015d8182014-07-22 23:41:36 +0000727 if (log)
728 log->Printf ("GDBRemoteCommunication::%s() could not find gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec.GetPath ().c_str ());
729
Greg Clayton8b82f082011-04-12 05:54:46 +0000730 g_debugserver_file_spec.Clear();
731 debugserver_file_spec.Clear();
732 }
733 }
734 }
735
736 if (debugserver_exists)
737 {
738 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path));
739
740 Args &debugserver_args = launch_info.GetArguments();
741 debugserver_args.Clear();
742 char arg_cstr[PATH_MAX];
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000743
Greg Clayton8b82f082011-04-12 05:54:46 +0000744 // Start args with "debugserver /file/path -r --"
745 debugserver_args.AppendArgument(debugserver_path);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000746
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000747#if !defined(__APPLE__)
748 // First argument to lldb-server must be mode in which to run.
749 debugserver_args.AppendArgument("gdbserver");
750#endif
751
Greg Clayton00fe87b2013-12-05 22:58:22 +0000752 // If a host and port is supplied then use it
Greg Claytonfda4fab2014-01-10 22:24:11 +0000753 char host_and_port[128];
754 if (hostname)
755 {
756 snprintf (host_and_port, sizeof(host_and_port), "%s:%u", hostname, in_port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000757 debugserver_args.AppendArgument(host_and_port);
Greg Claytonfda4fab2014-01-10 22:24:11 +0000758 }
759 else
760 {
761 host_and_port[0] = '\0';
762 }
763
Greg Clayton8b82f082011-04-12 05:54:46 +0000764 // use native registers, not the GDB registers
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +0000765 debugserver_args.AppendArgument("--native-regs");
766
767 if (launch_info.GetLaunchInSeparateProcessGroup())
768 {
769 debugserver_args.AppendArgument("--setsid");
770 }
Greg Clayton91a9b2472013-12-04 19:19:12 +0000771
Oleksiy Vyalov4536c452015-02-05 16:29:12 +0000772 llvm::SmallString<PATH_MAX> named_pipe_path;
Chaoren Lin368c9f62015-04-27 23:20:30 +0000773 Pipe port_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000774
Greg Claytonfda4fab2014-01-10 22:24:11 +0000775 bool listen = false;
776 if (host_and_port[0])
Greg Clayton91a9b2472013-12-04 19:19:12 +0000777 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000778 // Create a temporary file to get the stdout/stderr and redirect the
779 // output of the command into this file. We will later read this file
780 // if all goes well and fill the data into "command_output_ptr"
Greg Clayton00fe87b2013-12-05 22:58:22 +0000781
Greg Claytonfda4fab2014-01-10 22:24:11 +0000782 if (in_port == 0)
Greg Clayton00fe87b2013-12-05 22:58:22 +0000783 {
Greg Claytonfda4fab2014-01-10 22:24:11 +0000784 // Binding to port zero, we need to figure out what port it ends up
785 // using using a named pipe...
Chaoren Lin368c9f62015-04-27 23:20:30 +0000786 error = port_pipe.CreateWithUniqueName("debugserver-named-pipe", false, named_pipe_path);
787 if (error.Success())
788 {
789 debugserver_args.AppendArgument("--named-pipe");
790 debugserver_args.AppendArgument(named_pipe_path.c_str());
791 }
792 else
793 {
794 if (log)
795 log->Printf("GDBRemoteCommunication::%s() "
796 "named pipe creation failed: %s",
797 __FUNCTION__, error.AsCString());
798 // let's try an unnamed pipe
799 error = port_pipe.CreateNew(true);
800 if (error.Fail())
801 {
802 if (log)
803 log->Printf("GDBRemoteCommunication::%s() "
804 "unnamed pipe creation failed: %s",
805 __FUNCTION__, error.AsCString());
806 return error;
807 }
808 int write_fd = port_pipe.GetWriteFileDescriptor();
809 debugserver_args.AppendArgument("--pipe");
810 debugserver_args.AppendArgument(std::to_string(write_fd).c_str());
811 launch_info.AppendCloseFileAction(port_pipe.GetReadFileDescriptor());
812 }
Greg Clayton91a9b2472013-12-04 19:19:12 +0000813 }
814 else
Greg Claytonfda4fab2014-01-10 22:24:11 +0000815 {
816 listen = true;
817 }
Greg Clayton91a9b2472013-12-04 19:19:12 +0000818 }
819 else
Greg Clayton00fe87b2013-12-05 22:58:22 +0000820 {
Greg Clayton00fe87b2013-12-05 22:58:22 +0000821 // No host and port given, so lets listen on our end and make the debugserver
822 // connect to us..
Greg Clayton16810922014-02-27 19:38:18 +0000823 error = StartListenThread ("127.0.0.1", 0);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000824 if (error.Fail())
825 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +0000826
Greg Clayton00fe87b2013-12-05 22:58:22 +0000827 ConnectionFileDescriptor *connection = (ConnectionFileDescriptor *)GetConnection ();
Greg Clayton16810922014-02-27 19:38:18 +0000828 // Wait for 10 seconds to resolve the bound port
Zachary Turner98688922014-08-06 18:16:26 +0000829 out_port = connection->GetListeningPort(10);
Greg Clayton16810922014-02-27 19:38:18 +0000830 if (out_port > 0)
831 {
832 char port_cstr[32];
833 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", out_port);
834 // Send the host and port down that debugserver and specify an option
835 // so that it connects back to the port we are listening to in this process
836 debugserver_args.AppendArgument("--reverse-connect");
837 debugserver_args.AppendArgument(port_cstr);
838 }
839 else
840 {
841 error.SetErrorString ("failed to bind to port 0 on 127.0.0.1");
842 return error;
843 }
Greg Clayton00fe87b2013-12-05 22:58:22 +0000844 }
Greg Clayton00fe87b2013-12-05 22:58:22 +0000845
Greg Clayton8b82f082011-04-12 05:54:46 +0000846 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE");
847 if (env_debugserver_log_file)
848 {
849 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file);
850 debugserver_args.AppendArgument(arg_cstr);
851 }
852
Vince Harron9753dd92015-05-10 15:22:09 +0000853#if defined(__APPLE__)
Greg Clayton8b82f082011-04-12 05:54:46 +0000854 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
855 if (env_debugserver_log_flags)
856 {
857 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags);
858 debugserver_args.AppendArgument(arg_cstr);
859 }
Vince Harron9753dd92015-05-10 15:22:09 +0000860#else
861 const char *env_debugserver_log_channels = getenv("LLDB_SERVER_LOG_CHANNELS");
862 if (env_debugserver_log_channels)
863 {
864 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-channels=%s", env_debugserver_log_channels);
865 debugserver_args.AppendArgument(arg_cstr);
866 }
867#endif
Todd Fiala34ba4262014-08-29 17:10:31 +0000868
869 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an env var doesn't come back.
870 uint32_t env_var_index = 1;
871 bool has_env_var;
872 do
873 {
874 char env_var_name[64];
875 snprintf (env_var_name, sizeof (env_var_name), "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
876 const char *extra_arg = getenv(env_var_name);
877 has_env_var = extra_arg != nullptr;
878
879 if (has_env_var)
880 {
881 debugserver_args.AppendArgument (extra_arg);
882 if (log)
883 log->Printf ("GDBRemoteCommunication::%s adding env var %s contents to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg);
884 }
885 } while (has_env_var);
886
Shawn Best629680e2014-11-05 00:58:55 +0000887 // Close STDIN, STDOUT and STDERR.
Greg Clayton91a9b2472013-12-04 19:19:12 +0000888 launch_info.AppendCloseFileAction (STDIN_FILENO);
889 launch_info.AppendCloseFileAction (STDOUT_FILENO);
890 launch_info.AppendCloseFileAction (STDERR_FILENO);
Shawn Best629680e2014-11-05 00:58:55 +0000891
892 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
893 launch_info.AppendSuppressFileAction (STDIN_FILENO, true, false);
894 launch_info.AppendSuppressFileAction (STDOUT_FILENO, false, true);
895 launch_info.AppendSuppressFileAction (STDERR_FILENO, false, true);
Zachary Turner9b693272014-12-04 22:06:42 +0000896
Greg Clayton8b82f082011-04-12 05:54:46 +0000897 error = Host::LaunchProcess(launch_info);
Zachary Turner9b693272014-12-04 22:06:42 +0000898
Greg Clayton3121fde2014-02-28 20:47:08 +0000899 if (error.Success() && launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
Greg Clayton91a9b2472013-12-04 19:19:12 +0000900 {
Oleksiy Vyalov4536c452015-02-05 16:29:12 +0000901 if (named_pipe_path.size() > 0)
Greg Clayton91a9b2472013-12-04 19:19:12 +0000902 {
Chaoren Lin368c9f62015-04-27 23:20:30 +0000903 error = port_pipe.OpenAsReader(named_pipe_path, false);
904 if (error.Fail())
905 if (log)
906 log->Printf("GDBRemoteCommunication::%s() "
907 "failed to open named pipe %s for reading: %s",
908 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
909 }
910
911 if (port_pipe.CanWrite())
912 port_pipe.CloseWriteFileDescriptor();
913 if (port_pipe.CanRead())
914 {
915 char port_cstr[256];
916 port_cstr[0] = '\0';
917 size_t num_bytes = sizeof(port_cstr);
918 // Read port from pipe with 10 second timeout.
919 error = port_pipe.ReadWithTimeout(port_cstr, num_bytes,
920 std::chrono::seconds{10}, num_bytes);
Greg Clayton3121fde2014-02-28 20:47:08 +0000921 if (error.Success())
922 {
Chaoren Lin368c9f62015-04-27 23:20:30 +0000923 assert(num_bytes > 0 && port_cstr[num_bytes-1] == '\0');
924 out_port = StringConvert::ToUInt32(port_cstr, 0);
925 if (log)
926 log->Printf("GDBRemoteCommunication::%s() "
927 "debugserver listens %u port",
928 __FUNCTION__, out_port);
Greg Clayton3121fde2014-02-28 20:47:08 +0000929 }
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000930 else
931 {
932 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +0000933 log->Printf("GDBRemoteCommunication::%s() "
934 "failed to read a port value from pipe %s: %s",
935 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
936
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000937 }
Chaoren Lin368c9f62015-04-27 23:20:30 +0000938 port_pipe.Close();
939 }
940
941 if (named_pipe_path.size() > 0)
942 {
943 const auto err = port_pipe.Delete(named_pipe_path);
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000944 if (err.Fail())
945 {
946 if (log)
Chaoren Lin368c9f62015-04-27 23:20:30 +0000947 log->Printf ("GDBRemoteCommunication::%s failed to delete pipe %s: %s",
948 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +0000949 }
Greg Clayton91a9b2472013-12-04 19:19:12 +0000950 }
Chaoren Lin368c9f62015-04-27 23:20:30 +0000951
952 // Make sure we actually connect with the debugserver...
953 JoinListenThread();
Greg Clayton00fe87b2013-12-05 22:58:22 +0000954 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000955 }
956 else
957 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000958 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME );
Greg Clayton8b82f082011-04-12 05:54:46 +0000959 }
960 return error;
961}
962
Greg Claytonc1422c12012-04-09 22:46:21 +0000963void
Greg Claytond451c1a2012-04-13 21:24:18 +0000964GDBRemoteCommunication::DumpHistory(Stream &strm)
Greg Claytonc1422c12012-04-09 22:46:21 +0000965{
Greg Claytond451c1a2012-04-13 21:24:18 +0000966 m_history.Dump (strm);
Greg Claytonc1422c12012-04-09 22:46:21 +0000967}
Tamas Berghammer912800c2015-02-24 10:23:39 +0000968
969GDBRemoteCommunication::ScopedTimeout::ScopedTimeout (GDBRemoteCommunication& gdb_comm,
970 uint32_t timeout) :
971 m_gdb_comm (gdb_comm)
972{
973 m_saved_timeout = m_gdb_comm.SetPacketTimeout (timeout);
974}
975
976GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout ()
977{
978 m_gdb_comm.SetPacketTimeout (m_saved_timeout);
979}