blob: 144ae103faa4ba9a02268eb6154e3980fac3b2f0 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- GDBRemoteCommunication.cpp ------------------------------*- C++ -*-===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
Chris Lattner30fdc8d2010-06-08 16:52:24 +00009#include "GDBRemoteCommunication.h"
10
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000011#include <future>
Johnny Chena5663552011-05-13 20:07:25 +000012#include <limits.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000013#include <string.h>
Greg Clayton91a9b2472013-12-04 19:19:12 +000014#include <sys/stat.h>
Stephen Wilsona78867b2011-03-25 18:16:28 +000015
Greg Claytonc1422c12012-04-09 22:46:21 +000016#include "lldb/Core/StreamFile.h"
Haibo Huang7debc932019-08-08 21:42:33 +000017#include "lldb/Host/Config.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000018#include "lldb/Host/ConnectionFileDescriptor.h"
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +000019#include "lldb/Host/FileSystem.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000020#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000021#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000022#include "lldb/Host/Pipe.h"
Saleem Abdulrasoolbd689b92019-05-02 18:15:03 +000023#include "lldb/Host/ProcessLaunchInfo.h"
Zachary Turner98688922014-08-06 18:16:26 +000024#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000025#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000026#include "lldb/Host/ThreadLauncher.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000027#include "lldb/Host/common/TCPSocket.h"
28#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
Greg Clayton6988abc2015-10-19 20:44:01 +000029#include "lldb/Target/Platform.h"
Saleem Abdulrasoolbd689b92019-05-02 18:15:03 +000030#include "lldb/Utility/Event.h"
Zachary Turner5713a052017-03-22 18:40:07 +000031#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000032#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000033#include "lldb/Utility/RegularExpression.h"
34#include "lldb/Utility/StreamString.h"
Oleksiy Vyalov4536c452015-02-05 16:29:12 +000035#include "llvm/ADT/SmallString.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000036#include "llvm/Support/ScopedPrinter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037
Chris Lattner30fdc8d2010-06-08 16:52:24 +000038#include "ProcessGDBRemoteLog.h"
39
Todd Fiala015d8182014-07-22 23:41:36 +000040#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +000041#define DEBUGSERVER_BASENAME "debugserver"
Aaron Smith216944e2019-08-13 23:50:54 +000042#elif defined(_WIN32)
43#define DEBUGSERVER_BASENAME "lldb-server.exe"
Todd Fiala015d8182014-07-22 23:41:36 +000044#else
Kate Stoneb9c1b512016-09-06 20:57:50 +000045#define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000046#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000047
Raphael Isemann46508f62019-01-25 08:21:47 +000048#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000049#include <compression.h>
50#endif
51
Kate Stoneb9c1b512016-09-06 20:57:50 +000052#if defined(HAVE_LIBZ)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000053#include <zlib.h>
54#endif
55
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056using namespace lldb;
57using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000058using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000059
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060// GDBRemoteCommunication constructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000061GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
62 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000063 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +000064#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000065 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +000066#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000067 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +000068#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +000069 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
70 m_send_acks(true), m_compression_type(CompressionType::None),
Raphael Isemann46508f62019-01-25 08:21:47 +000071 m_listen_url() {
Chris Lattner30fdc8d2010-06-08 16:52:24 +000072}
73
Chris Lattner30fdc8d2010-06-08 16:52:24 +000074// Destructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000075GDBRemoteCommunication::~GDBRemoteCommunication() {
76 if (IsConnected()) {
77 Disconnect();
78 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +000079
Raphael Isemann46508f62019-01-25 08:21:47 +000080#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda8460bb02018-12-18 23:45:45 +000081 if (m_decompression_scratch)
82 free (m_decompression_scratch);
Raphael Isemann46508f62019-01-25 08:21:47 +000083#endif
Jason Molenda8460bb02018-12-18 23:45:45 +000084
Adrian Prantl05097242018-04-30 16:49:04 +000085 // Stop the communications read thread which is used to parse all incoming
86 // packets. This function will block until the read thread returns.
Kate Stoneb9c1b512016-09-06 20:57:50 +000087 if (m_read_thread_enabled)
88 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000089}
90
Kate Stoneb9c1b512016-09-06 20:57:50 +000091char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
92 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 for (char c : payload)
95 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +000096
Kate Stoneb9c1b512016-09-06 20:57:50 +000097 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000098}
99
Kate Stoneb9c1b512016-09-06 20:57:50 +0000100size_t GDBRemoteCommunication::SendAck() {
101 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
102 ConnectionStatus status = eConnectionStatusSuccess;
103 char ch = '+';
Konrad Kleine248a1302019-05-23 11:14:47 +0000104 const size_t bytes_written = Write(&ch, 1, status, nullptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000105 LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghereff5225b2019-09-13 23:14:10 +0000106 m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000107 return bytes_written;
108}
109
110size_t GDBRemoteCommunication::SendNack() {
111 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
112 ConnectionStatus status = eConnectionStatusSuccess;
113 char ch = '-';
Konrad Kleine248a1302019-05-23 11:14:47 +0000114 const size_t bytes_written = Write(&ch, 1, status, nullptr);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000115 LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghereff5225b2019-09-13 23:14:10 +0000116 m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117 return bytes_written;
118}
119
120GDBRemoteCommunication::PacketResult
121GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
Aaron Smith981e6352019-02-07 18:22:00 +0000122 StreamString packet(0, 4, eByteOrderBig);
123 packet.PutChar('$');
124 packet.Write(payload.data(), payload.size());
125 packet.PutChar('#');
126 packet.PutHex8(CalculcateChecksum(payload));
127 std::string packet_str = packet.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000128
Aaron Smith981e6352019-02-07 18:22:00 +0000129 return SendRawPacketNoLock(packet_str);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000130}
131
132GDBRemoteCommunication::PacketResult
133GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
134 bool skip_ack) {
135 if (IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000136 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000137 ConnectionStatus status = eConnectionStatusSuccess;
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000138 const char *packet_data = packet.data();
139 const size_t packet_length = packet.size();
Konrad Kleine248a1302019-05-23 11:14:47 +0000140 size_t bytes_written = Write(packet_data, packet_length, status, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 if (log) {
142 size_t binary_start_offset = 0;
143 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
144 0) {
145 const char *first_comma = strchr(packet_data, ',');
146 if (first_comma) {
147 const char *second_comma = strchr(first_comma + 1, ',');
148 if (second_comma)
149 binary_start_offset = second_comma - packet_data + 1;
Greg Claytonc1422c12012-04-09 22:46:21 +0000150 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000152
Adrian Prantl05097242018-04-30 16:49:04 +0000153 // If logging was just enabled and we have history, then dump out what we
154 // have to the log so we get the historical context. The Dump() call that
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155 // logs all of the packet will set a boolean so that we don't dump this
Adrian Prantl05097242018-04-30 16:49:04 +0000156 // more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000157 if (!m_history.DidDumpToLog())
158 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000159
Kate Stoneb9c1b512016-09-06 20:57:50 +0000160 if (binary_start_offset) {
161 StreamString strm;
162 // Print non binary data header
163 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
164 (int)binary_start_offset, packet_data);
165 const uint8_t *p;
166 // Print binary data exactly as sent
167 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
168 ++p)
169 strm.Printf("\\x%2.2x", *p);
170 // Print the checksum
171 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000172 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173 } else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000174 LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %.*s",
175 (uint64_t)bytes_written, (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000176 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000177
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000178 m_history.AddPacket(packet.str(), packet_length,
Jonas Devlieghereff5225b2019-09-13 23:14:10 +0000179 GDBRemotePacket::ePacketTypeSend, bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000180
181 if (bytes_written == packet_length) {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000182 if (!skip_ack && GetSendAcks())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000183 return GetAck();
184 else
185 return PacketResult::Success;
186 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000187 LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,
188 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000189 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000190 }
191 return PacketResult::ErrorSendFailed;
192}
193
194GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
195 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000196 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 if (result == PacketResult::Success) {
198 if (packet.GetResponseType() ==
199 StringExtractorGDBRemote::ResponseType::eAck)
200 return PacketResult::Success;
201 else
202 return PacketResult::ErrorSendAck;
203 }
204 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000205}
206
Greg Clayton3dedae12013-12-06 21:45:27 +0000207GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000208GDBRemoteCommunication::ReadPacketWithOutputSupport(
209 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
210 bool sync_on_timeout,
211 llvm::function_ref<void(llvm::StringRef)> output_callback) {
212 auto result = ReadPacket(response, timeout, sync_on_timeout);
213 while (result == PacketResult::Success && response.IsNormalResponse() &&
214 response.PeekChar() == 'O') {
215 response.GetChar();
216 std::string output;
217 if (response.GetHexByteString(output))
218 output_callback(output);
219 result = ReadPacket(response, timeout, sync_on_timeout);
220 }
221 return result;
222}
223
224GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000225GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000226 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227 bool sync_on_timeout) {
228 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000229 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000231 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000232}
233
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000234// This function is called when a packet is requested.
235// A whole packet is popped from the packet queue and returned to the caller.
Adrian Prantl05097242018-04-30 16:49:04 +0000236// Packets are placed into this queue from the communication read thread. See
237// GDBRemoteCommunication::AppendBytesToCache.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000238GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000240 Timeout<std::micro> timeout) {
241 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
242 // lock down the packet queue
243 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000244
Pavel Labath1eff73c2016-11-24 10:54:49 +0000245 if (!timeout)
246 m_condition_queue_not_empty.wait(lock, pred);
247 else {
248 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
249 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000250 if (!IsConnected())
251 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000252 }
253
Pavel Labath1eff73c2016-11-24 10:54:49 +0000254 // get the front element of the queue
255 response = m_packet_queue.front();
256
257 // remove the front element
258 m_packet_queue.pop();
259
260 // we got a packet
261 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000263
264GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000265GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
266 Timeout<std::micro> timeout,
267 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000269 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000270
Pavel Labathe8a7b982017-02-06 19:31:09 +0000271 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000272
Kate Stoneb9c1b512016-09-06 20:57:50 +0000273 // Check for a packet from our cache first without trying any reading...
Konrad Kleine248a1302019-05-23 11:14:47 +0000274 if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000275 return PacketResult::Success;
276
277 bool timed_out = false;
278 bool disconnected = false;
279 while (IsConnected() && !timed_out) {
280 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000281 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000282
Pavel Labathe8a7b982017-02-06 19:31:09 +0000283 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000284 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000285 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000286 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000287 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000288
289 if (bytes_read > 0) {
290 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000291 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000292 } else {
293 switch (status) {
294 case eConnectionStatusTimedOut:
295 case eConnectionStatusInterrupted:
296 if (sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000297 /// Sync the remote GDB server and make sure we get a response that
298 /// corresponds to what we send.
299 ///
300 /// Sends a "qEcho" packet and makes sure it gets the exact packet
301 /// echoed back. If the qEcho packet isn't supported, we send a qC
302 /// packet and make sure we get a valid thread ID back. We use the
303 /// "qC" packet since its response if very unique: is responds with
304 /// "QC%x" where %x is the thread ID of the current thread. This
305 /// makes the response unique enough from other packet responses to
306 /// ensure we are back on track.
307 ///
308 /// This packet is needed after we time out sending a packet so we
309 /// can ensure that we are getting the response for the packet we
310 /// are sending. There are no sequence IDs in the GDB remote
311 /// protocol (there used to be, but they are not supported anymore)
312 /// so if you timeout sending packet "abc", you might then send
313 /// packet "cde" and get the response for the previous "abc" packet.
314 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
315 /// many responses for packets can look like responses for other
316 /// packets. So if we timeout, we need to ensure that we can get
317 /// back on track. If we can't get back on track, we must
318 /// disconnect.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000319 bool sync_success = false;
320 bool got_actual_response = false;
321 // We timed out, we need to sync back up with the
322 char echo_packet[32];
323 int echo_packet_len = 0;
324 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000325
Kate Stoneb9c1b512016-09-06 20:57:50 +0000326 if (m_supports_qEcho == eLazyBoolYes) {
327 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
328 "qEcho:%u", ++m_echo_number);
329 std::string regex_str = "^";
330 regex_str += echo_packet;
331 regex_str += "$";
Jan Kratochvilf9d90bc2019-08-20 09:24:20 +0000332 response_regex = RegularExpression(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000333 } else {
334 echo_packet_len =
335 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Jan Kratochvilf9d90bc2019-08-20 09:24:20 +0000336 response_regex =
337 RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338 }
Greg Clayton644247c2011-07-07 01:59:51 +0000339
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 PacketResult echo_packet_result =
341 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
342 if (echo_packet_result == PacketResult::Success) {
343 const uint32_t max_retries = 3;
344 uint32_t successful_responses = 0;
345 for (uint32_t i = 0; i < max_retries; ++i) {
346 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000347 echo_packet_result =
348 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 if (echo_packet_result == PacketResult::Success) {
350 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000351 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000352 sync_success = true;
353 break;
354 } else if (successful_responses == 1) {
355 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000356 // response, it probably is the response to the packet we
357 // actually wanted, so copy it over if this is the first
358 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000359 packet = echo_response;
360 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000361 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
363 continue; // Packet timed out, continue waiting for a response
364 else
365 break; // Something else went wrong getting the packet back, we
366 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 }
369
370 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000371 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000372 if (sync_success) {
373 // We timed out, but were able to recover
374 if (got_actual_response) {
375 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000376 // before the successful reply to our qEcho packet, so lets say
377 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378 return PacketResult::Success;
379 }
380 } else {
381 disconnected = true;
382 Disconnect();
383 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000384 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000385 timed_out = true;
386 break;
387 case eConnectionStatusSuccess:
388 // printf ("status = success but error = %s\n",
389 // error.AsCString("<invalid>"));
390 break;
391
392 case eConnectionStatusEndOfFile:
393 case eConnectionStatusNoConnection:
394 case eConnectionStatusLostConnection:
395 case eConnectionStatusError:
396 disconnected = true;
397 Disconnect();
398 break;
399 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 }
402 packet.Clear();
403 if (disconnected)
404 return PacketResult::ErrorDisconnected;
405 if (timed_out)
406 return PacketResult::ErrorReplyTimeout;
407 else
408 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000409}
410
Kate Stoneb9c1b512016-09-06 20:57:50 +0000411bool GDBRemoteCommunication::DecompressPacket() {
412 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000413
Kate Stoneb9c1b512016-09-06 20:57:50 +0000414 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000415 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416
417 size_t pkt_size = m_bytes.size();
418
Adrian Prantl05097242018-04-30 16:49:04 +0000419 // Smallest possible compressed packet is $N#00 - an uncompressed empty
420 // reply, most commonly indicating an unsupported packet. Anything less than
421 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000422 if (pkt_size < 5)
423 return true;
424
425 if (m_bytes[0] != '$' && m_bytes[0] != '%')
426 return true;
427 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
428 return true;
429
430 size_t hash_mark_idx = m_bytes.find('#');
431 if (hash_mark_idx == std::string::npos)
432 return true;
433 if (hash_mark_idx + 2 >= m_bytes.size())
434 return true;
435
436 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
437 !::isxdigit(m_bytes[hash_mark_idx + 2]))
438 return true;
439
440 size_t content_length =
441 pkt_size -
442 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
443 size_t content_start = 2; // The first character of the
444 // compressed/not-compressed text of the packet
445 size_t checksum_idx =
446 hash_mark_idx +
447 1; // The first character of the two hex checksum characters
448
449 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000450 // multiple packets. size_of_first_packet is the size of the initial packet
451 // which we'll replace with the decompressed version of, leaving the rest of
452 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000453 size_t size_of_first_packet = hash_mark_idx + 3;
454
455 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000456 // the uncompressed payload, then a : and then the compressed data. e.g.
457 // $C1024:<binary>#00 Update content_start and content_length to only include
458 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000459
460 uint64_t decompressed_bufsize = ULONG_MAX;
461 if (m_bytes[1] == 'C') {
462 size_t i = content_start;
463 while (i < hash_mark_idx && isdigit(m_bytes[i]))
464 i++;
465 if (i < hash_mark_idx && m_bytes[i] == ':') {
466 i++;
467 content_start = i;
468 content_length = hash_mark_idx - content_start;
469 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
470 errno = 0;
Konrad Kleine248a1302019-05-23 11:14:47 +0000471 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000472 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
473 m_bytes.erase(0, size_of_first_packet);
474 return false;
475 }
476 }
477 }
478
479 if (GetSendAcks()) {
480 char packet_checksum_cstr[3];
481 packet_checksum_cstr[0] = m_bytes[checksum_idx];
482 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
483 packet_checksum_cstr[2] = '\0';
Konrad Kleine248a1302019-05-23 11:14:47 +0000484 long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000485
486 long actual_checksum = CalculcateChecksum(
487 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
488 bool success = packet_checksum == actual_checksum;
489 if (!success) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000490 LLDB_LOGF(log,
491 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
492 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
493 (uint8_t)actual_checksum);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000494 }
495 // Send the ack or nack if needed
496 if (!success) {
497 SendNack();
498 m_bytes.erase(0, size_of_first_packet);
499 return false;
500 } else {
501 SendAck();
502 }
503 }
504
505 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000506 // This packet was not compressed -- delete the 'N' character at the start
507 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000508 m_bytes.erase(1, 1);
509 return true;
510 }
511
Adrian Prantl05097242018-04-30 16:49:04 +0000512 // Reverse the gdb-remote binary escaping that was done to the compressed
513 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000514 std::vector<uint8_t> unescaped_content;
515 unescaped_content.reserve(content_length);
516 size_t i = content_start;
517 while (i < hash_mark_idx) {
518 if (m_bytes[i] == '}') {
519 i++;
520 unescaped_content.push_back(m_bytes[i] ^ 0x20);
521 } else {
522 unescaped_content.push_back(m_bytes[i]);
523 }
524 i++;
525 }
526
527 uint8_t *decompressed_buffer = nullptr;
528 size_t decompressed_bytes = 0;
529
530 if (decompressed_bufsize != ULONG_MAX) {
Jason Molenda4a793c82018-12-18 23:02:50 +0000531 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 if (decompressed_buffer == nullptr) {
533 m_bytes.erase(0, size_of_first_packet);
534 return false;
535 }
536 }
537
538#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +0000539 if (m_compression_type == CompressionType::ZlibDeflate ||
540 m_compression_type == CompressionType::LZFSE ||
Jonas Devliegherea83bf472019-05-23 19:32:46 +0000541 m_compression_type == CompressionType::LZ4 ||
Jason Molenda4a793c82018-12-18 23:02:50 +0000542 m_compression_type == CompressionType::LZMA) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000543 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000544 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000545 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000546 else if (m_compression_type == CompressionType::ZlibDeflate)
547 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 else if (m_compression_type == CompressionType::LZ4)
549 compression_type = COMPRESSION_LZ4_RAW;
550 else if (m_compression_type == CompressionType::LZMA)
551 compression_type = COMPRESSION_LZMA;
552
Jason Molenda4a793c82018-12-18 23:02:50 +0000553 if (m_decompression_scratch_type != m_compression_type) {
554 if (m_decompression_scratch) {
555 free (m_decompression_scratch);
556 m_decompression_scratch = nullptr;
557 }
558 size_t scratchbuf_size = 0;
559 if (m_compression_type == CompressionType::LZFSE)
560 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
561 else if (m_compression_type == CompressionType::LZ4)
562 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
563 else if (m_compression_type == CompressionType::ZlibDeflate)
564 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
565 else if (m_compression_type == CompressionType::LZMA)
566 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
567 else if (m_compression_type == CompressionType::LZFSE)
568 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
569 if (scratchbuf_size > 0) {
570 m_decompression_scratch = (void*) malloc (scratchbuf_size);
571 m_decompression_scratch_type = m_compression_type;
572 }
573 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574
575 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
576 decompressed_bytes = compression_decode_buffer(
Jason Molenda4a793c82018-12-18 23:02:50 +0000577 decompressed_buffer, decompressed_bufsize,
Jonas Devliegherea83bf472019-05-23 19:32:46 +0000578 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
Jason Molenda4a793c82018-12-18 23:02:50 +0000579 m_decompression_scratch, compression_type);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000580 }
581 }
582#endif
583
584#if defined(HAVE_LIBZ)
585 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
586 decompressed_buffer != nullptr &&
587 m_compression_type == CompressionType::ZlibDeflate) {
588 z_stream stream;
589 memset(&stream, 0, sizeof(z_stream));
590 stream.next_in = (Bytef *)unescaped_content.data();
591 stream.avail_in = (uInt)unescaped_content.size();
592 stream.total_in = 0;
593 stream.next_out = (Bytef *)decompressed_buffer;
594 stream.avail_out = decompressed_bufsize;
595 stream.total_out = 0;
596 stream.zalloc = Z_NULL;
597 stream.zfree = Z_NULL;
598 stream.opaque = Z_NULL;
599
600 if (inflateInit2(&stream, -15) == Z_OK) {
601 int status = inflate(&stream, Z_NO_FLUSH);
602 inflateEnd(&stream);
603 if (status == Z_STREAM_END) {
604 decompressed_bytes = stream.total_out;
605 }
606 }
607 }
608#endif
609
610 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
611 if (decompressed_buffer)
612 free(decompressed_buffer);
613 m_bytes.erase(0, size_of_first_packet);
614 return false;
615 }
616
617 std::string new_packet;
618 new_packet.reserve(decompressed_bytes + 6);
619 new_packet.push_back(m_bytes[0]);
620 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
621 new_packet.push_back('#');
622 if (GetSendAcks()) {
623 uint8_t decompressed_checksum = CalculcateChecksum(
624 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
625 char decompressed_checksum_str[3];
626 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
627 new_packet.append(decompressed_checksum_str);
628 } else {
629 new_packet.push_back('0');
630 new_packet.push_back('0');
631 }
632
633 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
634 new_packet.size());
635
636 free(decompressed_buffer);
637 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000638}
639
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000640GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
642 StringExtractorGDBRemote &packet) {
643 // Put the packet data into the buffer in a thread safe fashion
644 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000645
Kate Stoneb9c1b512016-09-06 20:57:50 +0000646 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000647
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 if (src && src_len > 0) {
649 if (log && log->GetVerbose()) {
650 StreamString s;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000651 LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",
652 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000653 }
654 m_bytes.append((const char *)src, src_len);
655 }
656
657 bool isNotifyPacket = false;
658
659 // Parse up the packets into gdb remote packets
660 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000661 // end_idx must be one past the last valid packet byte. Start it off with
662 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 size_t content_start = 0;
664 size_t content_length = 0;
665 size_t total_length = 0;
666 size_t checksum_idx = std::string::npos;
667
668 // Size of packet before it is decompressed, for logging purposes
669 size_t original_packet_size = m_bytes.size();
670 if (CompressionIsEnabled()) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000671 if (!DecompressPacket()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 packet.Clear();
673 return GDBRemoteCommunication::PacketType::Standard;
674 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000675 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000676
Kate Stoneb9c1b512016-09-06 20:57:50 +0000677 switch (m_bytes[0]) {
678 case '+': // Look for ack
679 case '-': // Look for cancel
680 case '\x03': // ^C to halt target
681 content_length = total_length = 1; // The command is one byte long...
682 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000683
Kate Stoneb9c1b512016-09-06 20:57:50 +0000684 case '%': // Async notify packet
685 isNotifyPacket = true;
686 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000687
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 case '$':
689 // Look for a standard gdb packet?
690 {
691 size_t hash_pos = m_bytes.find('#');
692 if (hash_pos != std::string::npos) {
693 if (hash_pos + 2 < m_bytes.size()) {
694 checksum_idx = hash_pos + 1;
695 // Skip the dollar sign
696 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000697 // Don't include the # in the content or the $ in the content
698 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 content_length = hash_pos - 1;
700
701 total_length =
702 hash_pos + 3; // Skip the # and the two hex checksum bytes
703 } else {
704 // Checksum bytes aren't all here yet
705 content_length = std::string::npos;
706 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000707 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 }
709 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000712 // We have an unexpected byte and we need to flush all bad data that is
713 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
714 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
715 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 const size_t bytes_len = m_bytes.size();
717 bool done = false;
718 uint32_t idx;
719 for (idx = 1; !done && idx < bytes_len; ++idx) {
720 switch (m_bytes[idx]) {
721 case '+':
722 case '-':
723 case '\x03':
724 case '%':
725 case '$':
726 done = true;
727 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000728
Kate Stoneb9c1b512016-09-06 20:57:50 +0000729 default:
730 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 }
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000733 LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
734 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 m_bytes.erase(0, idx - 1);
736 } break;
737 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000738
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 if (content_length == std::string::npos) {
740 packet.Clear();
741 return GDBRemoteCommunication::PacketType::Invalid;
742 } else if (total_length > 0) {
743
744 // We have a valid packet...
745 assert(content_length <= m_bytes.size());
746 assert(total_length <= m_bytes.size());
747 assert(content_length <= total_length);
748 size_t content_end = content_start + content_length;
749
750 bool success = true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000751 if (log) {
752 // If logging was just enabled and we have history, then dump out what
753 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000754 // that logs all of the packet will set a boolean so that we don't dump
755 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000756 if (!m_history.DidDumpToLog())
757 m_history.Dump(log);
758
759 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000760 // Only detect binary for packets that start with a '$' and have a
761 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762 if (m_bytes[0] == '$' && total_length > 4) {
763 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000764 unsigned char c = m_bytes[i];
765 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000766 binary = true;
767 }
768 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000769 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770 if (binary) {
771 StreamString strm;
772 // Packet header...
773 if (CompressionIsEnabled())
774 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
775 (uint64_t)original_packet_size, (uint64_t)total_length,
776 m_bytes[0]);
777 else
778 strm.Printf("<%4" PRIu64 "> read packet: %c",
779 (uint64_t)total_length, m_bytes[0]);
780 for (size_t i = content_start; i < content_end; ++i) {
781 // Remove binary escaped bytes when displaying the packet...
782 const char ch = m_bytes[i];
783 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000784 // 0x7d is the escape character. The next character is to be
785 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786 const char escapee = m_bytes[++i] ^ 0x20;
787 strm.Printf("%2.2x", escapee);
788 } else {
789 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000790 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 }
792 // Packet footer...
793 strm.Printf("%c%c%c", m_bytes[total_length - 3],
794 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000795 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 } else {
797 if (CompressionIsEnabled())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000798 LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
799 (uint64_t)original_packet_size, (uint64_t)total_length,
800 (int)(total_length), m_bytes.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 else
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000802 LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",
803 (uint64_t)total_length, (int)(total_length),
804 m_bytes.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000805 }
806 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000807
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000808 m_history.AddPacket(m_bytes, total_length,
Jonas Devlieghereff5225b2019-09-13 23:14:10 +0000809 GDBRemotePacket::ePacketTypeRecv, total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000810
Adrian Prantl05097242018-04-30 16:49:04 +0000811 // Copy the packet from m_bytes to packet_str expanding the run-length
812 // encoding in the process. Reserve enough byte for the most common case
813 // (no RLE used)
Jonas Devlieghered35b42f2019-08-21 04:55:56 +0000814 std ::string packet_str;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 packet_str.reserve(m_bytes.length());
816 for (std::string::const_iterator c = m_bytes.begin() + content_start;
817 c != m_bytes.begin() + content_end; ++c) {
818 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000819 // '*' indicates RLE. Next character will give us the repeat count
820 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000821 char char_to_repeat = packet_str.back();
822 // Number of time the previous character is repeated
823 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000824 // We have the char_to_repeat and repeat_count. Now push it in the
825 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 for (int i = 0; i < repeat_count; ++i)
827 packet_str.push_back(char_to_repeat);
828 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000829 // 0x7d is the escape character. The next character is to be XOR'd
830 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000831 char escapee = *++c ^ 0x20;
832 packet_str.push_back(escapee);
833 } else {
834 packet_str.push_back(*c);
835 }
836 }
Jonas Devlieghered35b42f2019-08-21 04:55:56 +0000837 packet = StringExtractorGDBRemote(packet_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838
839 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
840 assert(checksum_idx < m_bytes.size());
841 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
842 ::isxdigit(m_bytes[checksum_idx + 1])) {
843 if (GetSendAcks()) {
844 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
Konrad Kleine248a1302019-05-23 11:14:47 +0000845 char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
Pavel Labath5a841232018-03-28 10:19:10 +0000846 char actual_checksum = CalculcateChecksum(
847 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000848 success = packet_checksum == actual_checksum;
849 if (!success) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000850 LLDB_LOGF(log,
851 "error: checksum mismatch: %.*s expected 0x%2.2x, "
852 "got 0x%2.2x",
853 (int)(total_length), m_bytes.c_str(),
854 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000855 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000856 // Send the ack or nack if needed
857 if (!success)
858 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000859 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000860 SendAck();
861 }
862 } else {
863 success = false;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000864 LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",
865 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000866 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000867 }
868
869 m_bytes.erase(0, total_length);
870 packet.SetFilePos(0);
871
872 if (isNotifyPacket)
873 return GDBRemoteCommunication::PacketType::Notify;
874 else
875 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000876 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000877 }
878 packet.Clear();
879 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000880}
881
Zachary Turner97206d52017-05-12 04:51:55 +0000882Status GDBRemoteCommunication::StartListenThread(const char *hostname,
883 uint16_t port) {
Jonas Devliegheref39c2e12019-07-05 17:42:08 +0000884 if (m_listen_thread.IsJoinable())
885 return Status("listen thread already running");
886
887 char listen_url[512];
888 if (hostname && hostname[0])
889 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
890 else
891 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
892 m_listen_url = listen_url;
893 SetConnection(new ConnectionFileDescriptor());
894 llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
895 listen_url, GDBRemoteCommunication::ListenThread, this);
896 if (!listen_thread)
897 return Status(listen_thread.takeError());
898 m_listen_thread = *listen_thread;
899
900 return Status();
Greg Clayton00fe87b2013-12-05 22:58:22 +0000901}
902
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903bool GDBRemoteCommunication::JoinListenThread() {
904 if (m_listen_thread.IsJoinable())
905 m_listen_thread.Join(nullptr);
906 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000907}
908
909lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
911 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000912 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000913 ConnectionFileDescriptor *connection =
914 (ConnectionFileDescriptor *)comm->GetConnection();
915
916 if (connection) {
917 // Do the listen on another thread so we can continue on...
918 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
919 eConnectionStatusSuccess)
Konrad Kleine248a1302019-05-23 11:14:47 +0000920 comm->SetConnection(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921 }
Jonas Devliegherea83bf472019-05-23 19:32:46 +0000922 return {};
Greg Clayton00fe87b2013-12-05 22:58:22 +0000923}
924
Zachary Turner97206d52017-05-12 04:51:55 +0000925Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000926 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
927 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
928 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000929 LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
930 __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000931
Zachary Turner97206d52017-05-12 04:51:55 +0000932 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 // If we locate debugserver, keep that located version around
934 static FileSpec g_debugserver_file_spec;
935
936 char debugserver_path[PATH_MAX];
937 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
938
Aaron Smith981e6352019-02-07 18:22:00 +0000939 Environment host_env = Host::GetEnvironment();
940
Adrian Prantl05097242018-04-30 16:49:04 +0000941 // Always check to see if we have an environment override for the path to the
942 // debugserver to use and use it if we do.
Aaron Smith981e6352019-02-07 18:22:00 +0000943 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
944 if (!env_debugserver_path.empty()) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000945 debugserver_file_spec.SetFile(env_debugserver_path,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000946 FileSpec::Style::native);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000947 LLDB_LOGF(log,
948 "GDBRemoteCommunication::%s() gdb-remote stub exe path set "
949 "from environment variable: %s",
950 __FUNCTION__, env_debugserver_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951 } else
952 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000953 bool debugserver_exists =
954 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +0000956 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +0000957 debugserver_file_spec = HostInfo::GetSupportExeDir();
958 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000960 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 if (debugserver_exists) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000962 LLDB_LOGF(log,
963 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
964 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +0000965
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 g_debugserver_file_spec = debugserver_file_spec;
967 } else {
Aaron Smithbc472892019-02-14 08:59:04 +0000968 if (platform)
969 debugserver_file_spec =
970 platform->LocateExecutable(DEBUGSERVER_BASENAME);
971 else
972 debugserver_file_spec.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000973 if (debugserver_file_spec) {
974 // Platform::LocateExecutable() wouldn't return a path if it doesn't
975 // exist
976 debugserver_exists = true;
977 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +0000978 LLDB_LOGF(log,
979 "GDBRemoteCommunication::%s() could not find "
980 "gdb-remote stub exe '%s'",
981 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +0000982 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +0000984 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 g_debugserver_file_spec.Clear();
986 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000987 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000988 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 if (debugserver_exists) {
991 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 Args &debugserver_args = launch_info.GetArguments();
994 debugserver_args.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995
996 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +0000997 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +0000998
Tamas Berghammerc2c3d712015-02-18 15:39:41 +0000999#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001001 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001002#endif
1003
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004 // If a url is supplied then use it
1005 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001006 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001007
Kate Stoneb9c1b512016-09-06 20:57:50 +00001008 if (pass_comm_fd >= 0) {
1009 StreamString fd_arg;
1010 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001011 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012 // Send "pass_comm_fd" down to the inferior so it can use it to
1013 // communicate back with this process
1014 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1015 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001016
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001018 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001019
Kate Stoneb9c1b512016-09-06 20:57:50 +00001020 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001021 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001023
Stella Stamenovab3f44ad2018-12-10 17:23:28 +00001024 llvm::SmallString<128> named_pipe_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001025 // socket_pipe is used by debug server to communicate back either
1026 // TCP port or domain socket name which it listens on.
1027 // The second purpose of the pipe to serve as a synchronization point -
1028 // once data is written to the pipe, debug server is up and running.
1029 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001030
Adrian Prantl05097242018-04-30 16:49:04 +00001031 // port is null when debug server should listen on domain socket - we're
1032 // not interested in port value but rather waiting for debug server to
1033 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001034 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001036// Create a temporary file to get the stdout/stderr and redirect the output of
1037// the command into this file. We will later read this file if all goes well
1038// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001039#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001040 // Binding to port zero, we need to figure out what port it ends up
1041 // using using a named pipe...
1042 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1043 false, named_pipe_path);
1044 if (error.Fail()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001045 LLDB_LOGF(log,
1046 "GDBRemoteCommunication::%s() "
1047 "named pipe creation failed: %s",
1048 __FUNCTION__, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 return error;
1050 }
Sean Callanan1355f472016-09-19 22:06:12 +00001051 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001052 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001053#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001054 // Binding to port zero, we need to figure out what port it ends up
1055 // using using an unnamed pipe...
1056 error = socket_pipe.CreateNew(true);
1057 if (error.Fail()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001058 LLDB_LOGF(log,
1059 "GDBRemoteCommunication::%s() "
1060 "unnamed pipe creation failed: %s",
1061 __FUNCTION__, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062 return error;
1063 }
Aaron Smithe55850b2019-01-10 00:46:09 +00001064 pipe_t write = socket_pipe.GetWritePipe();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001065 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
Aaron Smithe55850b2019-01-10 00:46:09 +00001066 debugserver_args.AppendArgument(llvm::to_string(write));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001068#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001069 } else {
1070 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001071 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001072 error = StartListenThread("127.0.0.1", 0);
1073 if (error.Fail()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001074 LLDB_LOGF(log,
1075 "GDBRemoteCommunication::%s() unable to start listen "
1076 "thread: %s",
1077 __FUNCTION__, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001079 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080
1081 ConnectionFileDescriptor *connection =
1082 (ConnectionFileDescriptor *)GetConnection();
1083 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001084 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001085 if (port_ > 0) {
1086 char port_cstr[32];
1087 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1088 // Send the host and port down that debugserver and specify an option
1089 // so that it connects back to the port we are listening to in this
1090 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001091 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1092 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001093 if (port)
1094 *port = port_;
1095 } else {
1096 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001097 LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",
1098 __FUNCTION__, error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001100 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001101 }
1102 }
Aaron Smith981e6352019-02-07 18:22:00 +00001103 std::string env_debugserver_log_file =
1104 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1105 if (!env_debugserver_log_file.empty()) {
1106 debugserver_args.AppendArgument(
1107 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 }
1109
Vince Harron9753dd92015-05-10 15:22:09 +00001110#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 const char *env_debugserver_log_flags =
1112 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1113 if (env_debugserver_log_flags) {
Aaron Smith981e6352019-02-07 18:22:00 +00001114 debugserver_args.AppendArgument(
1115 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001116 }
Vince Harron9753dd92015-05-10 15:22:09 +00001117#else
Aaron Smith981e6352019-02-07 18:22:00 +00001118 std::string env_debugserver_log_channels =
1119 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1120 if (!env_debugserver_log_channels.empty()) {
1121 debugserver_args.AppendArgument(
1122 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1123 .str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 }
Vince Harron9753dd92015-05-10 15:22:09 +00001125#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001126
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1128 // env var doesn't come back.
1129 uint32_t env_var_index = 1;
1130 bool has_env_var;
1131 do {
1132 char env_var_name[64];
1133 snprintf(env_var_name, sizeof(env_var_name),
1134 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
Aaron Smith981e6352019-02-07 18:22:00 +00001135 std::string extra_arg = host_env.lookup(env_var_name);
1136 has_env_var = !extra_arg.empty();
Todd Fiala34ba4262014-08-29 17:10:31 +00001137
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001139 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001140 LLDB_LOGF(log,
1141 "GDBRemoteCommunication::%s adding env var %s contents "
1142 "to stub command line (%s)",
1143 __FUNCTION__, env_var_name, extra_arg.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001144 }
1145 } while (has_env_var);
1146
1147 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001148 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 debugserver_args.AppendArguments(*inferior_args);
1150 }
1151
1152 // Copy the current environment to the gdbserver/debugserver instance
Aaron Smith981e6352019-02-07 18:22:00 +00001153 launch_info.GetEnvironment() = host_env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001154
1155 // Close STDIN, STDOUT and STDERR.
1156 launch_info.AppendCloseFileAction(STDIN_FILENO);
1157 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1158 launch_info.AppendCloseFileAction(STDERR_FILENO);
1159
1160 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1161 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1162 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1163 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1164
1165 if (log) {
1166 StreamString string_stream;
1167 Platform *const platform = nullptr;
1168 launch_info.Dump(string_stream, platform);
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001169 LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",
1170 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171 }
1172 error = Host::LaunchProcess(launch_info);
1173
1174 if (error.Success() &&
1175 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1176 pass_comm_fd == -1) {
1177 if (named_pipe_path.size() > 0) {
1178 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1179 if (error.Fail())
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001180 LLDB_LOGF(log,
1181 "GDBRemoteCommunication::%s() "
1182 "failed to open named pipe %s for reading: %s",
1183 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001184 }
1185
1186 if (socket_pipe.CanWrite())
1187 socket_pipe.CloseWriteFileDescriptor();
1188 if (socket_pipe.CanRead()) {
1189 char port_cstr[PATH_MAX] = {0};
1190 port_cstr[0] = '\0';
1191 size_t num_bytes = sizeof(port_cstr);
1192 // Read port from pipe with 10 second timeout.
1193 error = socket_pipe.ReadWithTimeout(
1194 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1195 if (error.Success() && (port != nullptr)) {
1196 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001197 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1198 if (*port == 0 || *port == child_port) {
1199 *port = child_port;
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001200 LLDB_LOGF(log,
1201 "GDBRemoteCommunication::%s() "
1202 "debugserver listens %u port",
1203 __FUNCTION__, *port);
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001204 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001205 LLDB_LOGF(log,
1206 "GDBRemoteCommunication::%s() "
1207 "debugserver listening on port "
1208 "%d but requested port was %d",
1209 __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001210 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001211 } else {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001212 LLDB_LOGF(log,
1213 "GDBRemoteCommunication::%s() "
1214 "failed to read a port value from pipe %s: %s",
1215 __FUNCTION__, named_pipe_path.c_str(), error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001216 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001217 socket_pipe.Close();
1218 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001219
Kate Stoneb9c1b512016-09-06 20:57:50 +00001220 if (named_pipe_path.size() > 0) {
1221 const auto err = socket_pipe.Delete(named_pipe_path);
1222 if (err.Fail()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001223 LLDB_LOGF(log,
1224 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1225 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001226 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001227 }
1228
1229 // Make sure we actually connect with the debugserver...
1230 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001231 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001232 } else {
1233 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1234 }
Vince Harron8b335672015-05-12 01:10:56 +00001235
Kate Stoneb9c1b512016-09-06 20:57:50 +00001236 if (error.Fail()) {
Jonas Devlieghere63e5fb72019-07-24 17:56:10 +00001237 LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1238 error.AsCString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001239 }
Vince Harron8b335672015-05-12 01:10:56 +00001240
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001242}
1243
Kate Stoneb9c1b512016-09-06 20:57:50 +00001244void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1245
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001246void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1247 m_history.SetStream(strm);
Zachary Turner52f8f342019-01-29 22:55:21 +00001248}
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001249
1250llvm::Error
1251GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1252 GDBRemoteCommunication &server) {
1253 const bool child_processes_inherit = false;
1254 const int backlog = 5;
1255 TCPSocket listen_socket(true, child_processes_inherit);
1256 if (llvm::Error error =
1257 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1258 return error;
1259
1260 Socket *accept_socket;
1261 std::future<Status> accept_status = std::async(
1262 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1263
1264 llvm::SmallString<32> remote_addr;
1265 llvm::raw_svector_ostream(remote_addr)
Michal Gornye39ec432019-03-03 12:42:43 +00001266 << "connect://127.0.0.1:" << listen_socket.GetLocalPortNumber();
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001267
1268 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1269 new ConnectionFileDescriptor());
Pavel Labath9d723b82019-02-18 10:36:23 +00001270 Status status;
1271 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1272 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1273 "Unable to connect: %s", status.AsCString());
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001274
1275 client.SetConnection(conn_up.release());
1276 if (llvm::Error error = accept_status.get().ToError())
1277 return error;
1278
1279 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1280 return llvm::Error::success();
1281}
1282
Kate Stoneb9c1b512016-09-06 20:57:50 +00001283GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001284 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Aaron Smith981e6352019-02-07 18:22:00 +00001285 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1286 auto curr_timeout = gdb_comm.GetPacketTimeout();
1287 // Only update the timeout if the timeout is greater than the current
1288 // timeout. If the current timeout is larger, then just use that.
1289 if (curr_timeout < timeout) {
1290 m_timeout_modified = true;
1291 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1292 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001293}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001294
Kate Stoneb9c1b512016-09-06 20:57:50 +00001295GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001296 // Only restore the timeout if we set it in the constructor.
1297 if (m_timeout_modified)
1298 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001299}
1300
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001302// become available for this connection. This function will consume all
1303// incoming bytes and try to parse whole packets as they become available. Full
1304// packets are placed in a queue, so that all packet requests can simply pop
1305// from this queue. Async notification packets will be dispatched immediately
1306// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001307void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1308 size_t len, bool broadcast,
1309 lldb::ConnectionStatus status) {
1310 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001311
Kate Stoneb9c1b512016-09-06 20:57:50 +00001312 while (true) {
1313 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001314
Adrian Prantl05097242018-04-30 16:49:04 +00001315 // scrub the data so we do not pass it back to CheckForPacket on future
1316 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317 bytes = nullptr;
1318 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001319
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 // we may have received no packet so lets bail out
1321 if (type == PacketType::Invalid)
1322 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001323
Kate Stoneb9c1b512016-09-06 20:57:50 +00001324 if (type == PacketType::Standard) {
1325 // scope for the mutex
1326 {
1327 // lock down the packet queue
1328 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1329 // push a new packet into the queue
1330 m_packet_queue.push(packet);
1331 // Signal condition variable that we have a packet
1332 m_condition_queue_not_empty.notify_one();
1333 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001334 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335
1336 if (type == PacketType::Notify) {
1337 // put this packet into an event
Jonas Devlieghered35b42f2019-08-21 04:55:56 +00001338 const char *pdata = packet.GetStringRef().data();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339
Adrian Prantl05097242018-04-30 16:49:04 +00001340 // as the communication class, we are a broadcaster and the async thread
1341 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001342 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1343 new EventDataBytes(pdata));
1344 }
1345 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001346}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001347
1348void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1349 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1350 StringRef Style) {
1351 using PacketResult = GDBRemoteCommunication::PacketResult;
1352
1353 switch (result) {
1354 case PacketResult::Success:
1355 Stream << "Success";
1356 break;
1357 case PacketResult::ErrorSendFailed:
1358 Stream << "ErrorSendFailed";
1359 break;
1360 case PacketResult::ErrorSendAck:
1361 Stream << "ErrorSendAck";
1362 break;
1363 case PacketResult::ErrorReplyFailed:
1364 Stream << "ErrorReplyFailed";
1365 break;
1366 case PacketResult::ErrorReplyTimeout:
1367 Stream << "ErrorReplyTimeout";
1368 break;
1369 case PacketResult::ErrorReplyInvalid:
1370 Stream << "ErrorReplyInvalid";
1371 break;
1372 case PacketResult::ErrorReplyAck:
1373 Stream << "ErrorReplyAck";
1374 break;
1375 case PacketResult::ErrorDisconnected:
1376 Stream << "ErrorDisconnected";
1377 break;
1378 case PacketResult::ErrorNoSequenceLock:
1379 Stream << "ErrorNoSequenceLock";
1380 break;
1381 }
1382}