blob: 11052eff948f9efbd3f652d4aee4ab817bde702b [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"
Zachary Turner93a66fc2014-10-06 21:22:36 +000017#include "lldb/Host/ConnectionFileDescriptor.h"
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +000018#include "lldb/Host/FileSystem.h"
Greg Clayton8b82f082011-04-12 05:54:46 +000019#include "lldb/Host/Host.h"
Zachary Turner42ff0ad2014-08-21 17:29:12 +000020#include "lldb/Host/HostInfo.h"
Oleksiy Vyalovd5f8b6a2015-01-13 23:19:40 +000021#include "lldb/Host/Pipe.h"
Saleem Abdulrasoolbd689b92019-05-02 18:15:03 +000022#include "lldb/Host/ProcessLaunchInfo.h"
Zachary Turner98688922014-08-06 18:16:26 +000023#include "lldb/Host/Socket.h"
Vince Harron5275aaa2015-01-15 20:08:35 +000024#include "lldb/Host/StringConvert.h"
Zachary Turner39de3112014-09-09 20:54:56 +000025#include "lldb/Host/ThreadLauncher.h"
Jonas Devlieghere9e046f02018-11-13 19:18:16 +000026#include "lldb/Host/common/TCPSocket.h"
27#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
Greg Clayton6988abc2015-10-19 20:44:01 +000028#include "lldb/Target/Platform.h"
Saleem Abdulrasoolbd689b92019-05-02 18:15:03 +000029#include "lldb/Utility/Event.h"
Zachary Turner5713a052017-03-22 18:40:07 +000030#include "lldb/Utility/FileSpec.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000031#include "lldb/Utility/Log.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000032#include "lldb/Utility/RegularExpression.h"
33#include "lldb/Utility/StreamString.h"
Oleksiy Vyalov4536c452015-02-05 16:29:12 +000034#include "llvm/ADT/SmallString.h"
Pavel Labath1eb0d422016-08-08 12:54:36 +000035#include "llvm/Support/ScopedPrinter.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036
Chris Lattner30fdc8d2010-06-08 16:52:24 +000037#include "ProcessGDBRemoteLog.h"
38
Todd Fiala015d8182014-07-22 23:41:36 +000039#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +000040#define DEBUGSERVER_BASENAME "debugserver"
Todd Fiala015d8182014-07-22 23:41:36 +000041#else
Kate Stoneb9c1b512016-09-06 20:57:50 +000042#define DEBUGSERVER_BASENAME "lldb-server"
Todd Fiala015d8182014-07-22 23:41:36 +000043#endif
Greg Clayton8b82f082011-04-12 05:54:46 +000044
Raphael Isemann46508f62019-01-25 08:21:47 +000045#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000046#include <compression.h>
47#endif
48
Kate Stoneb9c1b512016-09-06 20:57:50 +000049#if defined(HAVE_LIBZ)
Jason Molenda91ffe0a2015-06-18 21:46:06 +000050#include <zlib.h>
51#endif
52
Chris Lattner30fdc8d2010-06-08 16:52:24 +000053using namespace lldb;
54using namespace lldb_private;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000055using namespace lldb_private::process_gdb_remote;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000056
Chris Lattner30fdc8d2010-06-08 16:52:24 +000057// GDBRemoteCommunication constructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000058GDBRemoteCommunication::GDBRemoteCommunication(const char *comm_name,
59 const char *listener_name)
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000060 : Communication(comm_name),
Daniel Maleae0f8f572013-08-26 23:57:52 +000061#ifdef LLDB_CONFIGURATION_DEBUG
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000062 m_packet_timeout(1000),
Daniel Maleae0f8f572013-08-26 23:57:52 +000063#else
Saleem Abdulrasool2d6a9ec2016-07-28 17:32:20 +000064 m_packet_timeout(1),
Daniel Maleae0f8f572013-08-26 23:57:52 +000065#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +000066 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
67 m_send_acks(true), m_compression_type(CompressionType::None),
Raphael Isemann46508f62019-01-25 08:21:47 +000068 m_listen_url() {
Chris Lattner30fdc8d2010-06-08 16:52:24 +000069}
70
Chris Lattner30fdc8d2010-06-08 16:52:24 +000071// Destructor
Kate Stoneb9c1b512016-09-06 20:57:50 +000072GDBRemoteCommunication::~GDBRemoteCommunication() {
73 if (IsConnected()) {
74 Disconnect();
75 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +000076
Raphael Isemann46508f62019-01-25 08:21:47 +000077#if defined(HAVE_LIBCOMPRESSION)
Jason Molenda8460bb02018-12-18 23:45:45 +000078 if (m_decompression_scratch)
79 free (m_decompression_scratch);
Raphael Isemann46508f62019-01-25 08:21:47 +000080#endif
Jason Molenda8460bb02018-12-18 23:45:45 +000081
Adrian Prantl05097242018-04-30 16:49:04 +000082 // Stop the communications read thread which is used to parse all incoming
83 // packets. This function will block until the read thread returns.
Kate Stoneb9c1b512016-09-06 20:57:50 +000084 if (m_read_thread_enabled)
85 StopReadThread();
Chris Lattner30fdc8d2010-06-08 16:52:24 +000086}
87
Kate Stoneb9c1b512016-09-06 20:57:50 +000088char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
89 int checksum = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000090
Kate Stoneb9c1b512016-09-06 20:57:50 +000091 for (char c : payload)
92 checksum += c;
Ed Mastea6b4c772013-08-20 14:12:58 +000093
Kate Stoneb9c1b512016-09-06 20:57:50 +000094 return checksum & 255;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000095}
96
Kate Stoneb9c1b512016-09-06 20:57:50 +000097size_t GDBRemoteCommunication::SendAck() {
98 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
99 ConnectionStatus status = eConnectionStatusSuccess;
100 char ch = '+';
Konrad Kleine248a1302019-05-23 11:14:47 +0000101 const size_t bytes_written = Write(&ch, 1, status, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000102 if (log)
103 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000104 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
105 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000106 return bytes_written;
107}
108
109size_t GDBRemoteCommunication::SendNack() {
110 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
111 ConnectionStatus status = eConnectionStatusSuccess;
112 char ch = '-';
Konrad Kleine248a1302019-05-23 11:14:47 +0000113 const size_t bytes_written = Write(&ch, 1, status, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000114 if (log)
115 log->Printf("<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000116 m_history.AddPacket(ch, GDBRemoteCommunicationHistory::ePacketTypeSend,
117 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 return bytes_written;
119}
120
121GDBRemoteCommunication::PacketResult
122GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
Aaron Smith981e6352019-02-07 18:22:00 +0000123 StreamString packet(0, 4, eByteOrderBig);
124 packet.PutChar('$');
125 packet.Write(payload.data(), payload.size());
126 packet.PutChar('#');
127 packet.PutHex8(CalculcateChecksum(payload));
128 std::string packet_str = packet.GetString();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129
Aaron Smith981e6352019-02-07 18:22:00 +0000130 return SendRawPacketNoLock(packet_str);
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000131}
132
133GDBRemoteCommunication::PacketResult
134GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
135 bool skip_ack) {
136 if (IsConnected()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000138 ConnectionStatus status = eConnectionStatusSuccess;
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000139 const char *packet_data = packet.data();
140 const size_t packet_length = packet.size();
Konrad Kleine248a1302019-05-23 11:14:47 +0000141 size_t bytes_written = Write(packet_data, packet_length, status, nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000142 if (log) {
143 size_t binary_start_offset = 0;
144 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
145 0) {
146 const char *first_comma = strchr(packet_data, ',');
147 if (first_comma) {
148 const char *second_comma = strchr(first_comma + 1, ',');
149 if (second_comma)
150 binary_start_offset = second_comma - packet_data + 1;
Greg Claytonc1422c12012-04-09 22:46:21 +0000151 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000153
Adrian Prantl05097242018-04-30 16:49:04 +0000154 // If logging was just enabled and we have history, then dump out what we
155 // have to the log so we get the historical context. The Dump() call that
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 // logs all of the packet will set a boolean so that we don't dump this
Adrian Prantl05097242018-04-30 16:49:04 +0000157 // more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158 if (!m_history.DidDumpToLog())
159 m_history.Dump(log);
Greg Claytonc1422c12012-04-09 22:46:21 +0000160
Kate Stoneb9c1b512016-09-06 20:57:50 +0000161 if (binary_start_offset) {
162 StreamString strm;
163 // Print non binary data header
164 strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
165 (int)binary_start_offset, packet_data);
166 const uint8_t *p;
167 // Print binary data exactly as sent
168 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
169 ++p)
170 strm.Printf("\\x%2.2x", *p);
171 // Print the checksum
172 strm.Printf("%*s", (int)3, p);
Zachary Turnerc1564272016-11-16 21:15:24 +0000173 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000174 } else
175 log->Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,
176 (int)packet_length, packet_data);
Greg Claytonf5e56de2010-09-14 23:36:40 +0000177 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000178
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000179 m_history.AddPacket(packet.str(), packet_length,
180 GDBRemoteCommunicationHistory::ePacketTypeSend,
181 bytes_written);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182
183 if (bytes_written == packet_length) {
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000184 if (!skip_ack && GetSendAcks())
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185 return GetAck();
186 else
187 return PacketResult::Success;
188 } else {
189 if (log)
190 log->Printf("error: failed to send packet: %.*s", (int)packet_length,
191 packet_data);
Greg Clayton3dedae12013-12-06 21:45:27 +0000192 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000193 }
194 return PacketResult::ErrorSendFailed;
195}
196
197GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
198 StringExtractorGDBRemote packet;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000199 PacketResult result = ReadPacket(packet, GetPacketTimeout(), false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000200 if (result == PacketResult::Success) {
201 if (packet.GetResponseType() ==
202 StringExtractorGDBRemote::ResponseType::eAck)
203 return PacketResult::Success;
204 else
205 return PacketResult::ErrorSendAck;
206 }
207 return result;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000208}
209
Greg Clayton3dedae12013-12-06 21:45:27 +0000210GDBRemoteCommunication::PacketResult
Pavel Labath7da84752018-01-10 14:39:08 +0000211GDBRemoteCommunication::ReadPacketWithOutputSupport(
212 StringExtractorGDBRemote &response, Timeout<std::micro> timeout,
213 bool sync_on_timeout,
214 llvm::function_ref<void(llvm::StringRef)> output_callback) {
215 auto result = ReadPacket(response, timeout, sync_on_timeout);
216 while (result == PacketResult::Success && response.IsNormalResponse() &&
217 response.PeekChar() == 'O') {
218 response.GetChar();
219 std::string output;
220 if (response.GetHexByteString(output))
221 output_callback(output);
222 result = ReadPacket(response, timeout, sync_on_timeout);
223 }
224 return result;
225}
226
227GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000228GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000229 Timeout<std::micro> timeout,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230 bool sync_on_timeout) {
231 if (m_read_thread_enabled)
Pavel Labath1eff73c2016-11-24 10:54:49 +0000232 return PopPacketFromQueue(response, timeout);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000233 else
Pavel Labath1eff73c2016-11-24 10:54:49 +0000234 return WaitForPacketNoLock(response, timeout, sync_on_timeout);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000235}
236
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000237// This function is called when a packet is requested.
238// A whole packet is popped from the packet queue and returned to the caller.
Adrian Prantl05097242018-04-30 16:49:04 +0000239// Packets are placed into this queue from the communication read thread. See
240// GDBRemoteCommunication::AppendBytesToCache.
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000241GDBRemoteCommunication::PacketResult
Kate Stoneb9c1b512016-09-06 20:57:50 +0000242GDBRemoteCommunication::PopPacketFromQueue(StringExtractorGDBRemote &response,
Pavel Labath1eff73c2016-11-24 10:54:49 +0000243 Timeout<std::micro> timeout) {
244 auto pred = [&] { return !m_packet_queue.empty() && IsConnected(); };
245 // lock down the packet queue
246 std::unique_lock<std::mutex> lock(m_packet_queue_mutex);
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000247
Pavel Labath1eff73c2016-11-24 10:54:49 +0000248 if (!timeout)
249 m_condition_queue_not_empty.wait(lock, pred);
250 else {
251 if (!m_condition_queue_not_empty.wait_for(lock, *timeout, pred))
252 return PacketResult::ErrorReplyTimeout;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000253 if (!IsConnected())
254 return PacketResult::ErrorDisconnected;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000255 }
256
Pavel Labath1eff73c2016-11-24 10:54:49 +0000257 // get the front element of the queue
258 response = m_packet_queue.front();
259
260 // remove the front element
261 m_packet_queue.pop();
262
263 // we got a packet
264 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265}
Ewan Crawfordfab40d32015-06-16 15:50:18 +0000266
267GDBRemoteCommunication::PacketResult
Pavel Labath1eff73c2016-11-24 10:54:49 +0000268GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
269 Timeout<std::micro> timeout,
270 bool sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 uint8_t buffer[8192];
Zachary Turner97206d52017-05-12 04:51:55 +0000272 Status error;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000273
Pavel Labathe8a7b982017-02-06 19:31:09 +0000274 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton644247c2011-07-07 01:59:51 +0000275
Kate Stoneb9c1b512016-09-06 20:57:50 +0000276 // Check for a packet from our cache first without trying any reading...
Konrad Kleine248a1302019-05-23 11:14:47 +0000277 if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000278 return PacketResult::Success;
279
280 bool timed_out = false;
281 bool disconnected = false;
282 while (IsConnected() && !timed_out) {
283 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
Pavel Labathc4063ee2016-11-25 11:58:44 +0000284 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000285
Pavel Labathe8a7b982017-02-06 19:31:09 +0000286 LLDB_LOGV(log,
Pavel Labathd02b1c82017-02-10 11:49:33 +0000287 "Read(buffer, sizeof(buffer), timeout = {0}, "
Pavel Labathe8a7b982017-02-06 19:31:09 +0000288 "status = {1}, error = {2}) => bytes_read = {3}",
Pavel Labathd02b1c82017-02-10 11:49:33 +0000289 timeout, Communication::ConnectionStatusAsCString(status), error,
Pavel Labathe8a7b982017-02-06 19:31:09 +0000290 bytes_read);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000291
292 if (bytes_read > 0) {
293 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
Greg Clayton3dedae12013-12-06 21:45:27 +0000294 return PacketResult::Success;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 } else {
296 switch (status) {
297 case eConnectionStatusTimedOut:
298 case eConnectionStatusInterrupted:
299 if (sync_on_timeout) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000300 /// Sync the remote GDB server and make sure we get a response that
301 /// corresponds to what we send.
302 ///
303 /// Sends a "qEcho" packet and makes sure it gets the exact packet
304 /// echoed back. If the qEcho packet isn't supported, we send a qC
305 /// packet and make sure we get a valid thread ID back. We use the
306 /// "qC" packet since its response if very unique: is responds with
307 /// "QC%x" where %x is the thread ID of the current thread. This
308 /// makes the response unique enough from other packet responses to
309 /// ensure we are back on track.
310 ///
311 /// This packet is needed after we time out sending a packet so we
312 /// can ensure that we are getting the response for the packet we
313 /// are sending. There are no sequence IDs in the GDB remote
314 /// protocol (there used to be, but they are not supported anymore)
315 /// so if you timeout sending packet "abc", you might then send
316 /// packet "cde" and get the response for the previous "abc" packet.
317 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
318 /// many responses for packets can look like responses for other
319 /// packets. So if we timeout, we need to ensure that we can get
320 /// back on track. If we can't get back on track, we must
321 /// disconnect.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 bool sync_success = false;
323 bool got_actual_response = false;
324 // We timed out, we need to sync back up with the
325 char echo_packet[32];
326 int echo_packet_len = 0;
327 RegularExpression response_regex;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 if (m_supports_qEcho == eLazyBoolYes) {
330 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
331 "qEcho:%u", ++m_echo_number);
332 std::string regex_str = "^";
333 regex_str += echo_packet;
334 regex_str += "$";
Zachary Turner95eae422016-09-21 16:01:28 +0000335 response_regex.Compile(regex_str);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000336 } else {
337 echo_packet_len =
338 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
Zachary Turner95eae422016-09-21 16:01:28 +0000339 response_regex.Compile(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000340 }
Greg Clayton644247c2011-07-07 01:59:51 +0000341
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 PacketResult echo_packet_result =
343 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
344 if (echo_packet_result == PacketResult::Success) {
345 const uint32_t max_retries = 3;
346 uint32_t successful_responses = 0;
347 for (uint32_t i = 0; i < max_retries; ++i) {
348 StringExtractorGDBRemote echo_response;
Pavel Labath1eff73c2016-11-24 10:54:49 +0000349 echo_packet_result =
350 WaitForPacketNoLock(echo_response, timeout, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351 if (echo_packet_result == PacketResult::Success) {
352 ++successful_responses;
Zachary Turner95eae422016-09-21 16:01:28 +0000353 if (response_regex.Execute(echo_response.GetStringRef())) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000354 sync_success = true;
355 break;
356 } else if (successful_responses == 1) {
357 // We got something else back as the first successful
Adrian Prantl05097242018-04-30 16:49:04 +0000358 // response, it probably is the response to the packet we
359 // actually wanted, so copy it over if this is the first
360 // success and continue to try to get the qEcho response
Kate Stoneb9c1b512016-09-06 20:57:50 +0000361 packet = echo_response;
362 got_actual_response = true;
Greg Claytonb30c50c2015-05-29 00:01:55 +0000363 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
365 continue; // Packet timed out, continue waiting for a response
366 else
367 break; // Something else went wrong getting the packet back, we
368 // failed and are done trying
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000369 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000370 }
371
372 // We weren't able to sync back up with the server, we must abort
Adrian Prantl05097242018-04-30 16:49:04 +0000373 // otherwise all responses might not be from the right packets...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 if (sync_success) {
375 // We timed out, but were able to recover
376 if (got_actual_response) {
377 // We initially timed out, but we did get a response that came in
Adrian Prantl05097242018-04-30 16:49:04 +0000378 // before the successful reply to our qEcho packet, so lets say
379 // everything is fine...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 return PacketResult::Success;
381 }
382 } else {
383 disconnected = true;
384 Disconnect();
385 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000386 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000387 timed_out = true;
388 break;
389 case eConnectionStatusSuccess:
390 // printf ("status = success but error = %s\n",
391 // error.AsCString("<invalid>"));
392 break;
393
394 case eConnectionStatusEndOfFile:
395 case eConnectionStatusNoConnection:
396 case eConnectionStatusLostConnection:
397 case eConnectionStatusError:
398 disconnected = true;
399 Disconnect();
400 break;
401 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000402 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000403 }
404 packet.Clear();
405 if (disconnected)
406 return PacketResult::ErrorDisconnected;
407 if (timed_out)
408 return PacketResult::ErrorReplyTimeout;
409 else
410 return PacketResult::ErrorReplyFailed;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000411}
412
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413bool GDBRemoteCommunication::DecompressPacket() {
414 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000415
Kate Stoneb9c1b512016-09-06 20:57:50 +0000416 if (!CompressionIsEnabled())
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000417 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418
419 size_t pkt_size = m_bytes.size();
420
Adrian Prantl05097242018-04-30 16:49:04 +0000421 // Smallest possible compressed packet is $N#00 - an uncompressed empty
422 // reply, most commonly indicating an unsupported packet. Anything less than
423 // 5 characters, it's definitely not a compressed packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000424 if (pkt_size < 5)
425 return true;
426
427 if (m_bytes[0] != '$' && m_bytes[0] != '%')
428 return true;
429 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
430 return true;
431
432 size_t hash_mark_idx = m_bytes.find('#');
433 if (hash_mark_idx == std::string::npos)
434 return true;
435 if (hash_mark_idx + 2 >= m_bytes.size())
436 return true;
437
438 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
439 !::isxdigit(m_bytes[hash_mark_idx + 2]))
440 return true;
441
442 size_t content_length =
443 pkt_size -
444 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
445 size_t content_start = 2; // The first character of the
446 // compressed/not-compressed text of the packet
447 size_t checksum_idx =
448 hash_mark_idx +
449 1; // The first character of the two hex checksum characters
450
451 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
Adrian Prantl05097242018-04-30 16:49:04 +0000452 // multiple packets. size_of_first_packet is the size of the initial packet
453 // which we'll replace with the decompressed version of, leaving the rest of
454 // m_bytes unmodified.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000455 size_t size_of_first_packet = hash_mark_idx + 3;
456
457 // Compressed packets ("$C") start with a base10 number which is the size of
Adrian Prantl05097242018-04-30 16:49:04 +0000458 // the uncompressed payload, then a : and then the compressed data. e.g.
459 // $C1024:<binary>#00 Update content_start and content_length to only include
460 // the <binary> part of the packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000461
462 uint64_t decompressed_bufsize = ULONG_MAX;
463 if (m_bytes[1] == 'C') {
464 size_t i = content_start;
465 while (i < hash_mark_idx && isdigit(m_bytes[i]))
466 i++;
467 if (i < hash_mark_idx && m_bytes[i] == ':') {
468 i++;
469 content_start = i;
470 content_length = hash_mark_idx - content_start;
471 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
472 errno = 0;
Konrad Kleine248a1302019-05-23 11:14:47 +0000473 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000474 if (errno != 0 || decompressed_bufsize == ULONG_MAX) {
475 m_bytes.erase(0, size_of_first_packet);
476 return false;
477 }
478 }
479 }
480
481 if (GetSendAcks()) {
482 char packet_checksum_cstr[3];
483 packet_checksum_cstr[0] = m_bytes[checksum_idx];
484 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
485 packet_checksum_cstr[2] = '\0';
Konrad Kleine248a1302019-05-23 11:14:47 +0000486 long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487
488 long actual_checksum = CalculcateChecksum(
489 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
490 bool success = packet_checksum == actual_checksum;
491 if (!success) {
492 if (log)
493 log->Printf(
494 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",
495 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
496 (uint8_t)actual_checksum);
497 }
498 // Send the ack or nack if needed
499 if (!success) {
500 SendNack();
501 m_bytes.erase(0, size_of_first_packet);
502 return false;
503 } else {
504 SendAck();
505 }
506 }
507
508 if (m_bytes[1] == 'N') {
Adrian Prantl05097242018-04-30 16:49:04 +0000509 // This packet was not compressed -- delete the 'N' character at the start
510 // and the packet may be processed as-is.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511 m_bytes.erase(1, 1);
512 return true;
513 }
514
Adrian Prantl05097242018-04-30 16:49:04 +0000515 // Reverse the gdb-remote binary escaping that was done to the compressed
516 // text to guard characters like '$', '#', '}', etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 std::vector<uint8_t> unescaped_content;
518 unescaped_content.reserve(content_length);
519 size_t i = content_start;
520 while (i < hash_mark_idx) {
521 if (m_bytes[i] == '}') {
522 i++;
523 unescaped_content.push_back(m_bytes[i] ^ 0x20);
524 } else {
525 unescaped_content.push_back(m_bytes[i]);
526 }
527 i++;
528 }
529
530 uint8_t *decompressed_buffer = nullptr;
531 size_t decompressed_bytes = 0;
532
533 if (decompressed_bufsize != ULONG_MAX) {
Jason Molenda4a793c82018-12-18 23:02:50 +0000534 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000535 if (decompressed_buffer == nullptr) {
536 m_bytes.erase(0, size_of_first_packet);
537 return false;
538 }
539 }
540
541#if defined(HAVE_LIBCOMPRESSION)
Vedant Kumar606908a2017-12-06 19:21:10 +0000542 if (m_compression_type == CompressionType::ZlibDeflate ||
543 m_compression_type == CompressionType::LZFSE ||
Jonas Devliegherea83bf472019-05-23 19:32:46 +0000544 m_compression_type == CompressionType::LZ4 ||
Jason Molenda4a793c82018-12-18 23:02:50 +0000545 m_compression_type == CompressionType::LZMA) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000546 compression_algorithm compression_type;
Jason Molenda73039d22017-01-24 05:06:14 +0000547 if (m_compression_type == CompressionType::LZFSE)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 compression_type = COMPRESSION_LZFSE;
Jason Molenda73039d22017-01-24 05:06:14 +0000549 else if (m_compression_type == CompressionType::ZlibDeflate)
550 compression_type = COMPRESSION_ZLIB;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000551 else if (m_compression_type == CompressionType::LZ4)
552 compression_type = COMPRESSION_LZ4_RAW;
553 else if (m_compression_type == CompressionType::LZMA)
554 compression_type = COMPRESSION_LZMA;
555
Jason Molenda4a793c82018-12-18 23:02:50 +0000556 if (m_decompression_scratch_type != m_compression_type) {
557 if (m_decompression_scratch) {
558 free (m_decompression_scratch);
559 m_decompression_scratch = nullptr;
560 }
561 size_t scratchbuf_size = 0;
562 if (m_compression_type == CompressionType::LZFSE)
563 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
564 else if (m_compression_type == CompressionType::LZ4)
565 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
566 else if (m_compression_type == CompressionType::ZlibDeflate)
567 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
568 else if (m_compression_type == CompressionType::LZMA)
569 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
570 else if (m_compression_type == CompressionType::LZFSE)
571 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
572 if (scratchbuf_size > 0) {
573 m_decompression_scratch = (void*) malloc (scratchbuf_size);
574 m_decompression_scratch_type = m_compression_type;
575 }
576 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000577
578 if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {
579 decompressed_bytes = compression_decode_buffer(
Jason Molenda4a793c82018-12-18 23:02:50 +0000580 decompressed_buffer, decompressed_bufsize,
Jonas Devliegherea83bf472019-05-23 19:32:46 +0000581 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
Jason Molenda4a793c82018-12-18 23:02:50 +0000582 m_decompression_scratch, compression_type);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000583 }
584 }
585#endif
586
587#if defined(HAVE_LIBZ)
588 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&
589 decompressed_buffer != nullptr &&
590 m_compression_type == CompressionType::ZlibDeflate) {
591 z_stream stream;
592 memset(&stream, 0, sizeof(z_stream));
593 stream.next_in = (Bytef *)unescaped_content.data();
594 stream.avail_in = (uInt)unescaped_content.size();
595 stream.total_in = 0;
596 stream.next_out = (Bytef *)decompressed_buffer;
597 stream.avail_out = decompressed_bufsize;
598 stream.total_out = 0;
599 stream.zalloc = Z_NULL;
600 stream.zfree = Z_NULL;
601 stream.opaque = Z_NULL;
602
603 if (inflateInit2(&stream, -15) == Z_OK) {
604 int status = inflate(&stream, Z_NO_FLUSH);
605 inflateEnd(&stream);
606 if (status == Z_STREAM_END) {
607 decompressed_bytes = stream.total_out;
608 }
609 }
610 }
611#endif
612
613 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
614 if (decompressed_buffer)
615 free(decompressed_buffer);
616 m_bytes.erase(0, size_of_first_packet);
617 return false;
618 }
619
620 std::string new_packet;
621 new_packet.reserve(decompressed_bytes + 6);
622 new_packet.push_back(m_bytes[0]);
623 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
624 new_packet.push_back('#');
625 if (GetSendAcks()) {
626 uint8_t decompressed_checksum = CalculcateChecksum(
627 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
628 char decompressed_checksum_str[3];
629 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
630 new_packet.append(decompressed_checksum_str);
631 } else {
632 new_packet.push_back('0');
633 new_packet.push_back('0');
634 }
635
636 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
637 new_packet.size());
638
639 free(decompressed_buffer);
640 return true;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000641}
642
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000643GDBRemoteCommunication::PacketType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
645 StringExtractorGDBRemote &packet) {
646 // Put the packet data into the buffer in a thread safe fashion
647 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
Saleem Abdulrasool16ff8602016-05-18 01:59:10 +0000648
Kate Stoneb9c1b512016-09-06 20:57:50 +0000649 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PACKETS));
Greg Clayton197bacf2011-07-02 21:07:54 +0000650
Kate Stoneb9c1b512016-09-06 20:57:50 +0000651 if (src && src_len > 0) {
652 if (log && log->GetVerbose()) {
653 StreamString s;
654 log->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s",
655 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);
656 }
657 m_bytes.append((const char *)src, src_len);
658 }
659
660 bool isNotifyPacket = false;
661
662 // Parse up the packets into gdb remote packets
663 if (!m_bytes.empty()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000664 // end_idx must be one past the last valid packet byte. Start it off with
665 // an invalid value that is the same as the current index.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000666 size_t content_start = 0;
667 size_t content_length = 0;
668 size_t total_length = 0;
669 size_t checksum_idx = std::string::npos;
670
671 // Size of packet before it is decompressed, for logging purposes
672 size_t original_packet_size = m_bytes.size();
673 if (CompressionIsEnabled()) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +0000674 if (!DecompressPacket()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000675 packet.Clear();
676 return GDBRemoteCommunication::PacketType::Standard;
677 }
Greg Clayton197bacf2011-07-02 21:07:54 +0000678 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000679
Kate Stoneb9c1b512016-09-06 20:57:50 +0000680 switch (m_bytes[0]) {
681 case '+': // Look for ack
682 case '-': // Look for cancel
683 case '\x03': // ^C to halt target
684 content_length = total_length = 1; // The command is one byte long...
685 break;
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000686
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 case '%': // Async notify packet
688 isNotifyPacket = true;
689 LLVM_FALLTHROUGH;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000690
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 case '$':
692 // Look for a standard gdb packet?
693 {
694 size_t hash_pos = m_bytes.find('#');
695 if (hash_pos != std::string::npos) {
696 if (hash_pos + 2 < m_bytes.size()) {
697 checksum_idx = hash_pos + 1;
698 // Skip the dollar sign
699 content_start = 1;
Adrian Prantl05097242018-04-30 16:49:04 +0000700 // Don't include the # in the content or the $ in the content
701 // length
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 content_length = hash_pos - 1;
703
704 total_length =
705 hash_pos + 3; // Skip the # and the two hex checksum bytes
706 } else {
707 // Checksum bytes aren't all here yet
708 content_length = std::string::npos;
709 }
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000710 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 }
712 break;
Jason Molenda91ffe0a2015-06-18 21:46:06 +0000713
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 default: {
Adrian Prantl05097242018-04-30 16:49:04 +0000715 // We have an unexpected byte and we need to flush all bad data that is
716 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
717 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
718 // header) or of course, the end of the data in m_bytes...
Kate Stoneb9c1b512016-09-06 20:57:50 +0000719 const size_t bytes_len = m_bytes.size();
720 bool done = false;
721 uint32_t idx;
722 for (idx = 1; !done && idx < bytes_len; ++idx) {
723 switch (m_bytes[idx]) {
724 case '+':
725 case '-':
726 case '\x03':
727 case '%':
728 case '$':
729 done = true;
730 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000731
Kate Stoneb9c1b512016-09-06 20:57:50 +0000732 default:
733 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000734 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000735 }
736 if (log)
737 log->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",
738 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());
739 m_bytes.erase(0, idx - 1);
740 } break;
741 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000742
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 if (content_length == std::string::npos) {
744 packet.Clear();
745 return GDBRemoteCommunication::PacketType::Invalid;
746 } else if (total_length > 0) {
747
748 // We have a valid packet...
749 assert(content_length <= m_bytes.size());
750 assert(total_length <= m_bytes.size());
751 assert(content_length <= total_length);
752 size_t content_end = content_start + content_length;
753
754 bool success = true;
755 std::string &packet_str = packet.GetStringRef();
756 if (log) {
757 // If logging was just enabled and we have history, then dump out what
758 // we have to the log so we get the historical context. The Dump() call
Adrian Prantl05097242018-04-30 16:49:04 +0000759 // that logs all of the packet will set a boolean so that we don't dump
760 // this more than once
Kate Stoneb9c1b512016-09-06 20:57:50 +0000761 if (!m_history.DidDumpToLog())
762 m_history.Dump(log);
763
764 bool binary = false;
Adrian Prantl05097242018-04-30 16:49:04 +0000765 // Only detect binary for packets that start with a '$' and have a
766 // '#CC' checksum
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767 if (m_bytes[0] == '$' && total_length > 4) {
768 for (size_t i = 0; !binary && i < total_length; ++i) {
Jason Molendafba547d2017-08-18 22:57:59 +0000769 unsigned char c = m_bytes[i];
770 if (isprint(c) == 0 && isspace(c) == 0) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000771 binary = true;
772 }
773 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000775 if (binary) {
776 StreamString strm;
777 // Packet header...
778 if (CompressionIsEnabled())
779 strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",
780 (uint64_t)original_packet_size, (uint64_t)total_length,
781 m_bytes[0]);
782 else
783 strm.Printf("<%4" PRIu64 "> read packet: %c",
784 (uint64_t)total_length, m_bytes[0]);
785 for (size_t i = content_start; i < content_end; ++i) {
786 // Remove binary escaped bytes when displaying the packet...
787 const char ch = m_bytes[i];
788 if (ch == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000789 // 0x7d is the escape character. The next character is to be
790 // XOR'd with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791 const char escapee = m_bytes[++i] ^ 0x20;
792 strm.Printf("%2.2x", escapee);
793 } else {
794 strm.Printf("%2.2x", (uint8_t)ch);
Greg Claytonc1422c12012-04-09 22:46:21 +0000795 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000796 }
797 // Packet footer...
798 strm.Printf("%c%c%c", m_bytes[total_length - 3],
799 m_bytes[total_length - 2], m_bytes[total_length - 1]);
Zachary Turnerc1564272016-11-16 21:15:24 +0000800 log->PutString(strm.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000801 } else {
802 if (CompressionIsEnabled())
803 log->Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",
804 (uint64_t)original_packet_size, (uint64_t)total_length,
805 (int)(total_length), m_bytes.c_str());
806 else
807 log->Printf("<%4" PRIu64 "> read packet: %.*s",
808 (uint64_t)total_length, (int)(total_length),
809 m_bytes.c_str());
810 }
811 }
Greg Claytonc1422c12012-04-09 22:46:21 +0000812
Jonas Devlieghere9e046f02018-11-13 19:18:16 +0000813 m_history.AddPacket(m_bytes, total_length,
814 GDBRemoteCommunicationHistory::ePacketTypeRecv,
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000815 total_length);
Greg Claytonc1422c12012-04-09 22:46:21 +0000816
Kate Stoneb9c1b512016-09-06 20:57:50 +0000817 // Clear packet_str in case there is some existing data in it.
818 packet_str.clear();
Adrian Prantl05097242018-04-30 16:49:04 +0000819 // Copy the packet from m_bytes to packet_str expanding the run-length
820 // encoding in the process. Reserve enough byte for the most common case
821 // (no RLE used)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000822 packet_str.reserve(m_bytes.length());
823 for (std::string::const_iterator c = m_bytes.begin() + content_start;
824 c != m_bytes.begin() + content_end; ++c) {
825 if (*c == '*') {
Adrian Prantl05097242018-04-30 16:49:04 +0000826 // '*' indicates RLE. Next character will give us the repeat count
827 // and previous character is what is to be repeated.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000828 char char_to_repeat = packet_str.back();
829 // Number of time the previous character is repeated
830 int repeat_count = *++c + 3 - ' ';
Adrian Prantl05097242018-04-30 16:49:04 +0000831 // We have the char_to_repeat and repeat_count. Now push it in the
832 // packet.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000833 for (int i = 0; i < repeat_count; ++i)
834 packet_str.push_back(char_to_repeat);
835 } else if (*c == 0x7d) {
Adrian Prantl05097242018-04-30 16:49:04 +0000836 // 0x7d is the escape character. The next character is to be XOR'd
837 // with 0x20.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000838 char escapee = *++c ^ 0x20;
839 packet_str.push_back(escapee);
840 } else {
841 packet_str.push_back(*c);
842 }
843 }
844
845 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
846 assert(checksum_idx < m_bytes.size());
847 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
848 ::isxdigit(m_bytes[checksum_idx + 1])) {
849 if (GetSendAcks()) {
850 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
Konrad Kleine248a1302019-05-23 11:14:47 +0000851 char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
Pavel Labath5a841232018-03-28 10:19:10 +0000852 char actual_checksum = CalculcateChecksum(
853 llvm::StringRef(m_bytes).slice(content_start, content_end));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000854 success = packet_checksum == actual_checksum;
855 if (!success) {
856 if (log)
857 log->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
858 "got 0x%2.2x",
859 (int)(total_length), m_bytes.c_str(),
860 (uint8_t)packet_checksum, (uint8_t)actual_checksum);
Hafiz Abid Qadeerda96ef22013-08-28 10:31:52 +0000861 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000862 // Send the ack or nack if needed
863 if (!success)
864 SendNack();
Ewan Crawford9aa2da002015-05-27 14:12:34 +0000865 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000866 SendAck();
867 }
868 } else {
869 success = false;
870 if (log)
871 log->Printf("error: invalid checksum in packet: '%s'\n",
872 m_bytes.c_str());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000873 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 }
875
876 m_bytes.erase(0, total_length);
877 packet.SetFilePos(0);
878
879 if (isNotifyPacket)
880 return GDBRemoteCommunication::PacketType::Notify;
881 else
882 return GDBRemoteCommunication::PacketType::Standard;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000883 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000884 }
885 packet.Clear();
886 return GDBRemoteCommunication::PacketType::Invalid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000887}
888
Zachary Turner97206d52017-05-12 04:51:55 +0000889Status GDBRemoteCommunication::StartListenThread(const char *hostname,
890 uint16_t port) {
Jonas Devliegheref39c2e12019-07-05 17:42:08 +0000891 if (m_listen_thread.IsJoinable())
892 return Status("listen thread already running");
893
894 char listen_url[512];
895 if (hostname && hostname[0])
896 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
897 else
898 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
899 m_listen_url = listen_url;
900 SetConnection(new ConnectionFileDescriptor());
901 llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
902 listen_url, GDBRemoteCommunication::ListenThread, this);
903 if (!listen_thread)
904 return Status(listen_thread.takeError());
905 m_listen_thread = *listen_thread;
906
907 return Status();
Greg Clayton00fe87b2013-12-05 22:58:22 +0000908}
909
Kate Stoneb9c1b512016-09-06 20:57:50 +0000910bool GDBRemoteCommunication::JoinListenThread() {
911 if (m_listen_thread.IsJoinable())
912 m_listen_thread.Join(nullptr);
913 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000914}
915
916lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000917GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
918 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000919 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000920 ConnectionFileDescriptor *connection =
921 (ConnectionFileDescriptor *)comm->GetConnection();
922
923 if (connection) {
924 // Do the listen on another thread so we can continue on...
925 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
926 eConnectionStatusSuccess)
Konrad Kleine248a1302019-05-23 11:14:47 +0000927 comm->SetConnection(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000928 }
Jonas Devliegherea83bf472019-05-23 19:32:46 +0000929 return {};
Greg Clayton00fe87b2013-12-05 22:58:22 +0000930}
931
Zachary Turner97206d52017-05-12 04:51:55 +0000932Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000933 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
934 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
935 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
936 if (log)
937 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
938 __FUNCTION__, url ? url : "<empty>",
939 port ? *port : uint16_t(0));
940
Zachary Turner97206d52017-05-12 04:51:55 +0000941 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000942 // If we locate debugserver, keep that located version around
943 static FileSpec g_debugserver_file_spec;
944
945 char debugserver_path[PATH_MAX];
946 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
947
Aaron Smith981e6352019-02-07 18:22:00 +0000948 Environment host_env = Host::GetEnvironment();
949
Adrian Prantl05097242018-04-30 16:49:04 +0000950 // Always check to see if we have an environment override for the path to the
951 // debugserver to use and use it if we do.
Aaron Smith981e6352019-02-07 18:22:00 +0000952 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
953 if (!env_debugserver_path.empty()) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000954 debugserver_file_spec.SetFile(env_debugserver_path,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000955 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +0000956 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
958 "from environment variable: %s",
Aaron Smith981e6352019-02-07 18:22:00 +0000959 __FUNCTION__, env_debugserver_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 } else
961 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000962 bool debugserver_exists =
963 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000964 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +0000965 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +0000966 debugserver_file_spec = HostInfo::GetSupportExeDir();
967 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000968 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000969 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000970 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +0000971 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972 log->Printf(
973 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
974 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +0000975
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 g_debugserver_file_spec = debugserver_file_spec;
977 } else {
Aaron Smithbc472892019-02-14 08:59:04 +0000978 if (platform)
979 debugserver_file_spec =
980 platform->LocateExecutable(DEBUGSERVER_BASENAME);
981 else
982 debugserver_file_spec.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000983 if (debugserver_file_spec) {
984 // Platform::LocateExecutable() wouldn't return a path if it doesn't
985 // exist
986 debugserver_exists = true;
987 } else {
988 if (log)
989 log->Printf("GDBRemoteCommunication::%s() could not find "
990 "gdb-remote stub exe '%s'",
991 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +0000992 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +0000994 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 g_debugserver_file_spec.Clear();
996 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000997 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000998 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000999
Kate Stoneb9c1b512016-09-06 20:57:50 +00001000 if (debugserver_exists) {
1001 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001002
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 Args &debugserver_args = launch_info.GetArguments();
1004 debugserver_args.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001005
1006 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001007 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001008
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001009#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001010 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001011 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001012#endif
1013
Kate Stoneb9c1b512016-09-06 20:57:50 +00001014 // If a url is supplied then use it
1015 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001016 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001017
Kate Stoneb9c1b512016-09-06 20:57:50 +00001018 if (pass_comm_fd >= 0) {
1019 StreamString fd_arg;
1020 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001021 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001022 // Send "pass_comm_fd" down to the inferior so it can use it to
1023 // communicate back with this process
1024 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1025 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001026
Kate Stoneb9c1b512016-09-06 20:57:50 +00001027 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001028 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001029
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001031 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001032 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001033
Stella Stamenovab3f44ad2018-12-10 17:23:28 +00001034 llvm::SmallString<128> named_pipe_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001035 // socket_pipe is used by debug server to communicate back either
1036 // TCP port or domain socket name which it listens on.
1037 // The second purpose of the pipe to serve as a synchronization point -
1038 // once data is written to the pipe, debug server is up and running.
1039 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001040
Adrian Prantl05097242018-04-30 16:49:04 +00001041 // port is null when debug server should listen on domain socket - we're
1042 // not interested in port value but rather waiting for debug server to
1043 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001044 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001045 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001046// Create a temporary file to get the stdout/stderr and redirect the output of
1047// the command into this file. We will later read this file if all goes well
1048// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001049#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001050 // Binding to port zero, we need to figure out what port it ends up
1051 // using using a named pipe...
1052 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1053 false, named_pipe_path);
1054 if (error.Fail()) {
1055 if (log)
1056 log->Printf("GDBRemoteCommunication::%s() "
1057 "named pipe creation failed: %s",
1058 __FUNCTION__, error.AsCString());
1059 return error;
1060 }
Sean Callanan1355f472016-09-19 22:06:12 +00001061 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001062 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001063#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001064 // Binding to port zero, we need to figure out what port it ends up
1065 // using using an unnamed pipe...
1066 error = socket_pipe.CreateNew(true);
1067 if (error.Fail()) {
1068 if (log)
1069 log->Printf("GDBRemoteCommunication::%s() "
1070 "unnamed pipe creation failed: %s",
1071 __FUNCTION__, error.AsCString());
1072 return error;
1073 }
Aaron Smithe55850b2019-01-10 00:46:09 +00001074 pipe_t write = socket_pipe.GetWritePipe();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001075 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
Aaron Smithe55850b2019-01-10 00:46:09 +00001076 debugserver_args.AppendArgument(llvm::to_string(write));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001077 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001078#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079 } else {
1080 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001081 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001082 error = StartListenThread("127.0.0.1", 0);
1083 if (error.Fail()) {
1084 if (log)
1085 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1086 "thread: %s",
1087 __FUNCTION__, error.AsCString());
1088 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001089 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001090
1091 ConnectionFileDescriptor *connection =
1092 (ConnectionFileDescriptor *)GetConnection();
1093 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001094 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001095 if (port_ > 0) {
1096 char port_cstr[32];
1097 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1098 // Send the host and port down that debugserver and specify an option
1099 // so that it connects back to the port we are listening to in this
1100 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001101 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1102 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001103 if (port)
1104 *port = port_;
1105 } else {
1106 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1107 if (log)
1108 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1109 error.AsCString());
1110 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001111 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001112 }
1113 }
Aaron Smith981e6352019-02-07 18:22:00 +00001114 std::string env_debugserver_log_file =
1115 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1116 if (!env_debugserver_log_file.empty()) {
1117 debugserver_args.AppendArgument(
1118 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 }
1120
Vince Harron9753dd92015-05-10 15:22:09 +00001121#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001122 const char *env_debugserver_log_flags =
1123 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1124 if (env_debugserver_log_flags) {
Aaron Smith981e6352019-02-07 18:22:00 +00001125 debugserver_args.AppendArgument(
1126 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001127 }
Vince Harron9753dd92015-05-10 15:22:09 +00001128#else
Aaron Smith981e6352019-02-07 18:22:00 +00001129 std::string env_debugserver_log_channels =
1130 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1131 if (!env_debugserver_log_channels.empty()) {
1132 debugserver_args.AppendArgument(
1133 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1134 .str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001135 }
Vince Harron9753dd92015-05-10 15:22:09 +00001136#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001137
Kate Stoneb9c1b512016-09-06 20:57:50 +00001138 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1139 // env var doesn't come back.
1140 uint32_t env_var_index = 1;
1141 bool has_env_var;
1142 do {
1143 char env_var_name[64];
1144 snprintf(env_var_name, sizeof(env_var_name),
1145 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
Aaron Smith981e6352019-02-07 18:22:00 +00001146 std::string extra_arg = host_env.lookup(env_var_name);
1147 has_env_var = !extra_arg.empty();
Todd Fiala34ba4262014-08-29 17:10:31 +00001148
Kate Stoneb9c1b512016-09-06 20:57:50 +00001149 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001150 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001151 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001152 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1153 "to stub command line (%s)",
Aaron Smith981e6352019-02-07 18:22:00 +00001154 __FUNCTION__, env_var_name, extra_arg.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155 }
1156 } while (has_env_var);
1157
1158 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001159 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001160 debugserver_args.AppendArguments(*inferior_args);
1161 }
1162
1163 // Copy the current environment to the gdbserver/debugserver instance
Aaron Smith981e6352019-02-07 18:22:00 +00001164 launch_info.GetEnvironment() = host_env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165
1166 // Close STDIN, STDOUT and STDERR.
1167 launch_info.AppendCloseFileAction(STDIN_FILENO);
1168 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1169 launch_info.AppendCloseFileAction(STDERR_FILENO);
1170
1171 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1172 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1173 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1174 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1175
1176 if (log) {
1177 StreamString string_stream;
1178 Platform *const platform = nullptr;
1179 launch_info.Dump(string_stream, platform);
1180 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001181 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 }
1183 error = Host::LaunchProcess(launch_info);
1184
1185 if (error.Success() &&
1186 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1187 pass_comm_fd == -1) {
1188 if (named_pipe_path.size() > 0) {
1189 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1190 if (error.Fail())
1191 if (log)
1192 log->Printf("GDBRemoteCommunication::%s() "
1193 "failed to open named pipe %s for reading: %s",
1194 __FUNCTION__, named_pipe_path.c_str(),
1195 error.AsCString());
1196 }
1197
1198 if (socket_pipe.CanWrite())
1199 socket_pipe.CloseWriteFileDescriptor();
1200 if (socket_pipe.CanRead()) {
1201 char port_cstr[PATH_MAX] = {0};
1202 port_cstr[0] = '\0';
1203 size_t num_bytes = sizeof(port_cstr);
1204 // Read port from pipe with 10 second timeout.
1205 error = socket_pipe.ReadWithTimeout(
1206 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1207 if (error.Success() && (port != nullptr)) {
1208 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001209 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1210 if (*port == 0 || *port == child_port) {
1211 *port = child_port;
1212 if (log)
1213 log->Printf("GDBRemoteCommunication::%s() "
1214 "debugserver listens %u port",
1215 __FUNCTION__, *port);
1216 } else {
1217 if (log)
1218 log->Printf("GDBRemoteCommunication::%s() "
1219 "debugserver listening on port "
1220 "%d but requested port was %d",
1221 __FUNCTION__, (uint32_t)child_port,
1222 (uint32_t)(*port));
1223 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001224 } else {
1225 if (log)
1226 log->Printf("GDBRemoteCommunication::%s() "
1227 "failed to read a port value from pipe %s: %s",
1228 __FUNCTION__, named_pipe_path.c_str(),
1229 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001230 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001231 socket_pipe.Close();
1232 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001233
Kate Stoneb9c1b512016-09-06 20:57:50 +00001234 if (named_pipe_path.size() > 0) {
1235 const auto err = socket_pipe.Delete(named_pipe_path);
1236 if (err.Fail()) {
1237 if (log)
1238 log->Printf(
1239 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1240 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001241 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001242 }
1243
1244 // Make sure we actually connect with the debugserver...
1245 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001246 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001247 } else {
1248 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1249 }
Vince Harron8b335672015-05-12 01:10:56 +00001250
Kate Stoneb9c1b512016-09-06 20:57:50 +00001251 if (error.Fail()) {
1252 if (log)
1253 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1254 error.AsCString());
1255 }
Vince Harron8b335672015-05-12 01:10:56 +00001256
Kate Stoneb9c1b512016-09-06 20:57:50 +00001257 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001258}
1259
Kate Stoneb9c1b512016-09-06 20:57:50 +00001260void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1261
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001262void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1263 m_history.SetStream(strm);
Zachary Turner52f8f342019-01-29 22:55:21 +00001264}
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001265
1266llvm::Error
1267GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1268 GDBRemoteCommunication &server) {
1269 const bool child_processes_inherit = false;
1270 const int backlog = 5;
1271 TCPSocket listen_socket(true, child_processes_inherit);
1272 if (llvm::Error error =
1273 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1274 return error;
1275
1276 Socket *accept_socket;
1277 std::future<Status> accept_status = std::async(
1278 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1279
1280 llvm::SmallString<32> remote_addr;
1281 llvm::raw_svector_ostream(remote_addr)
Michal Gornye39ec432019-03-03 12:42:43 +00001282 << "connect://127.0.0.1:" << listen_socket.GetLocalPortNumber();
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001283
1284 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1285 new ConnectionFileDescriptor());
Pavel Labath9d723b82019-02-18 10:36:23 +00001286 Status status;
1287 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1288 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1289 "Unable to connect: %s", status.AsCString());
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001290
1291 client.SetConnection(conn_up.release());
1292 if (llvm::Error error = accept_status.get().ToError())
1293 return error;
1294
1295 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1296 return llvm::Error::success();
1297}
1298
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001300 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Aaron Smith981e6352019-02-07 18:22:00 +00001301 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1302 auto curr_timeout = gdb_comm.GetPacketTimeout();
1303 // Only update the timeout if the timeout is greater than the current
1304 // timeout. If the current timeout is larger, then just use that.
1305 if (curr_timeout < timeout) {
1306 m_timeout_modified = true;
1307 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1308 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001309}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001310
Kate Stoneb9c1b512016-09-06 20:57:50 +00001311GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001312 // Only restore the timeout if we set it in the constructor.
1313 if (m_timeout_modified)
1314 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001315}
1316
Kate Stoneb9c1b512016-09-06 20:57:50 +00001317// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001318// become available for this connection. This function will consume all
1319// incoming bytes and try to parse whole packets as they become available. Full
1320// packets are placed in a queue, so that all packet requests can simply pop
1321// from this queue. Async notification packets will be dispatched immediately
1322// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001323void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1324 size_t len, bool broadcast,
1325 lldb::ConnectionStatus status) {
1326 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001327
Kate Stoneb9c1b512016-09-06 20:57:50 +00001328 while (true) {
1329 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001330
Adrian Prantl05097242018-04-30 16:49:04 +00001331 // scrub the data so we do not pass it back to CheckForPacket on future
1332 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 bytes = nullptr;
1334 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001335
Kate Stoneb9c1b512016-09-06 20:57:50 +00001336 // we may have received no packet so lets bail out
1337 if (type == PacketType::Invalid)
1338 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001339
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 if (type == PacketType::Standard) {
1341 // scope for the mutex
1342 {
1343 // lock down the packet queue
1344 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1345 // push a new packet into the queue
1346 m_packet_queue.push(packet);
1347 // Signal condition variable that we have a packet
1348 m_condition_queue_not_empty.notify_one();
1349 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001350 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001351
1352 if (type == PacketType::Notify) {
1353 // put this packet into an event
1354 const char *pdata = packet.GetStringRef().c_str();
1355
Adrian Prantl05097242018-04-30 16:49:04 +00001356 // as the communication class, we are a broadcaster and the async thread
1357 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001358 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1359 new EventDataBytes(pdata));
1360 }
1361 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001362}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001363
1364void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1365 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1366 StringRef Style) {
1367 using PacketResult = GDBRemoteCommunication::PacketResult;
1368
1369 switch (result) {
1370 case PacketResult::Success:
1371 Stream << "Success";
1372 break;
1373 case PacketResult::ErrorSendFailed:
1374 Stream << "ErrorSendFailed";
1375 break;
1376 case PacketResult::ErrorSendAck:
1377 Stream << "ErrorSendAck";
1378 break;
1379 case PacketResult::ErrorReplyFailed:
1380 Stream << "ErrorReplyFailed";
1381 break;
1382 case PacketResult::ErrorReplyTimeout:
1383 Stream << "ErrorReplyTimeout";
1384 break;
1385 case PacketResult::ErrorReplyInvalid:
1386 Stream << "ErrorReplyInvalid";
1387 break;
1388 case PacketResult::ErrorReplyAck:
1389 Stream << "ErrorReplyAck";
1390 break;
1391 case PacketResult::ErrorDisconnected:
1392 Stream << "ErrorDisconnected";
1393 break;
1394 case PacketResult::ErrorNoSequenceLock:
1395 Stream << "ErrorNoSequenceLock";
1396 break;
1397 }
1398}