blob: 3886b6cfe009e57643225b73a21432a9e31da2bd [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) {
891 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000892 if (m_listen_thread.IsJoinable()) {
893 error.SetErrorString("listen thread already running");
894 } else {
895 char listen_url[512];
896 if (hostname && hostname[0])
897 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname,
898 port);
Greg Clayton00fe87b2013-12-05 22:58:22 +0000899 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000900 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
901 m_listen_url = listen_url;
902 SetConnection(new ConnectionFileDescriptor());
903 m_listen_thread = ThreadLauncher::LaunchThread(
904 listen_url, GDBRemoteCommunication::ListenThread, this, &error);
905 }
906 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000907}
908
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909bool GDBRemoteCommunication::JoinListenThread() {
910 if (m_listen_thread.IsJoinable())
911 m_listen_thread.Join(nullptr);
912 return true;
Greg Clayton00fe87b2013-12-05 22:58:22 +0000913}
914
915lldb::thread_result_t
Kate Stoneb9c1b512016-09-06 20:57:50 +0000916GDBRemoteCommunication::ListenThread(lldb::thread_arg_t arg) {
917 GDBRemoteCommunication *comm = (GDBRemoteCommunication *)arg;
Zachary Turner97206d52017-05-12 04:51:55 +0000918 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000919 ConnectionFileDescriptor *connection =
920 (ConnectionFileDescriptor *)comm->GetConnection();
921
922 if (connection) {
923 // Do the listen on another thread so we can continue on...
924 if (connection->Connect(comm->m_listen_url.c_str(), &error) !=
925 eConnectionStatusSuccess)
Konrad Kleine248a1302019-05-23 11:14:47 +0000926 comm->SetConnection(nullptr);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 }
Jonas Devliegherea83bf472019-05-23 19:32:46 +0000928 return {};
Greg Clayton00fe87b2013-12-05 22:58:22 +0000929}
930
Zachary Turner97206d52017-05-12 04:51:55 +0000931Status GDBRemoteCommunication::StartDebugserverProcess(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
933 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
934 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
935 if (log)
936 log->Printf("GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",
937 __FUNCTION__, url ? url : "<empty>",
938 port ? *port : uint16_t(0));
939
Zachary Turner97206d52017-05-12 04:51:55 +0000940 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941 // If we locate debugserver, keep that located version around
942 static FileSpec g_debugserver_file_spec;
943
944 char debugserver_path[PATH_MAX];
945 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
946
Aaron Smith981e6352019-02-07 18:22:00 +0000947 Environment host_env = Host::GetEnvironment();
948
Adrian Prantl05097242018-04-30 16:49:04 +0000949 // Always check to see if we have an environment override for the path to the
950 // debugserver to use and use it if we do.
Aaron Smith981e6352019-02-07 18:22:00 +0000951 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
952 if (!env_debugserver_path.empty()) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000953 debugserver_file_spec.SetFile(env_debugserver_path,
Jonas Devlieghere937348c2018-06-13 22:08:14 +0000954 FileSpec::Style::native);
Todd Fiala015d8182014-07-22 23:41:36 +0000955 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000956 log->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
957 "from environment variable: %s",
Aaron Smith981e6352019-02-07 18:22:00 +0000958 __FUNCTION__, env_debugserver_path.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000959 } else
960 debugserver_file_spec = g_debugserver_file_spec;
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000961 bool debugserver_exists =
962 FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963 if (!debugserver_exists) {
Adrian Prantl05097242018-04-30 16:49:04 +0000964 // The debugserver binary is in the LLDB.framework/Resources directory.
Pavel Labath60f028f2018-06-19 15:09:07 +0000965 debugserver_file_spec = HostInfo::GetSupportExeDir();
966 if (debugserver_file_spec) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000967 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
Jonas Devliegheredbd7fab2018-11-01 17:09:25 +0000968 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969 if (debugserver_exists) {
Todd Fiala015d8182014-07-22 23:41:36 +0000970 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971 log->Printf(
972 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",
973 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Todd Fiala015d8182014-07-22 23:41:36 +0000974
Kate Stoneb9c1b512016-09-06 20:57:50 +0000975 g_debugserver_file_spec = debugserver_file_spec;
976 } else {
Aaron Smithbc472892019-02-14 08:59:04 +0000977 if (platform)
978 debugserver_file_spec =
979 platform->LocateExecutable(DEBUGSERVER_BASENAME);
980 else
981 debugserver_file_spec.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000982 if (debugserver_file_spec) {
983 // Platform::LocateExecutable() wouldn't return a path if it doesn't
984 // exist
985 debugserver_exists = true;
986 } else {
987 if (log)
988 log->Printf("GDBRemoteCommunication::%s() could not find "
989 "gdb-remote stub exe '%s'",
990 __FUNCTION__, debugserver_file_spec.GetPath().c_str());
Greg Clayton8b82f082011-04-12 05:54:46 +0000991 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 // Don't cache the platform specific GDB server binary as it could
Adrian Prantl05097242018-04-30 16:49:04 +0000993 // change from platform to platform
Kate Stoneb9c1b512016-09-06 20:57:50 +0000994 g_debugserver_file_spec.Clear();
995 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000996 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997 }
Greg Clayton8b82f082011-04-12 05:54:46 +0000998
Kate Stoneb9c1b512016-09-06 20:57:50 +0000999 if (debugserver_exists) {
1000 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001001
Kate Stoneb9c1b512016-09-06 20:57:50 +00001002 Args &debugserver_args = launch_info.GetArguments();
1003 debugserver_args.Clear();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001004
1005 // Start args with "debugserver /file/path -r --"
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001006 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
Greg Clayton00fe87b2013-12-05 22:58:22 +00001007
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001008#if !defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 // First argument to lldb-server must be mode in which to run.
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001010 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
Tamas Berghammerc2c3d712015-02-18 15:39:41 +00001011#endif
1012
Kate Stoneb9c1b512016-09-06 20:57:50 +00001013 // If a url is supplied then use it
1014 if (url)
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001015 debugserver_args.AppendArgument(llvm::StringRef(url));
Greg Claytonfda4fab2014-01-10 22:24:11 +00001016
Kate Stoneb9c1b512016-09-06 20:57:50 +00001017 if (pass_comm_fd >= 0) {
1018 StreamString fd_arg;
1019 fd_arg.Printf("--fd=%i", pass_comm_fd);
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001020 debugserver_args.AppendArgument(fd_arg.GetString());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001021 // Send "pass_comm_fd" down to the inferior so it can use it to
1022 // communicate back with this process
1023 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
1024 }
Greg Claytonc6c420f2016-08-12 16:46:18 +00001025
Kate Stoneb9c1b512016-09-06 20:57:50 +00001026 // use native registers, not the GDB registers
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001027 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
Oleksiy Vyalovf8ce61c2015-01-28 17:36:59 +00001028
Kate Stoneb9c1b512016-09-06 20:57:50 +00001029 if (launch_info.GetLaunchInSeparateProcessGroup()) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001030 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001031 }
Greg Clayton91a9b2472013-12-04 19:19:12 +00001032
Stella Stamenovab3f44ad2018-12-10 17:23:28 +00001033 llvm::SmallString<128> named_pipe_path;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001034 // socket_pipe is used by debug server to communicate back either
1035 // TCP port or domain socket name which it listens on.
1036 // The second purpose of the pipe to serve as a synchronization point -
1037 // once data is written to the pipe, debug server is up and running.
1038 Pipe socket_pipe;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001039
Adrian Prantl05097242018-04-30 16:49:04 +00001040 // port is null when debug server should listen on domain socket - we're
1041 // not interested in port value but rather waiting for debug server to
1042 // become available.
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001043 if (pass_comm_fd == -1) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001044 if (url) {
Adrian Prantl05097242018-04-30 16:49:04 +00001045// Create a temporary file to get the stdout/stderr and redirect the output of
1046// the command into this file. We will later read this file if all goes well
1047// and fill the data into "command_output_ptr"
Chaoren Lin46951b52015-07-30 17:48:44 +00001048#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001049 // Binding to port zero, we need to figure out what port it ends up
1050 // using using a named pipe...
1051 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1052 false, named_pipe_path);
1053 if (error.Fail()) {
1054 if (log)
1055 log->Printf("GDBRemoteCommunication::%s() "
1056 "named pipe creation failed: %s",
1057 __FUNCTION__, error.AsCString());
1058 return error;
1059 }
Sean Callanan1355f472016-09-19 22:06:12 +00001060 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
Zachary Turner9a4e3012016-09-21 16:01:43 +00001061 debugserver_args.AppendArgument(named_pipe_path);
Chaoren Lin46951b52015-07-30 17:48:44 +00001062#else
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063 // Binding to port zero, we need to figure out what port it ends up
1064 // using using an unnamed pipe...
1065 error = socket_pipe.CreateNew(true);
1066 if (error.Fail()) {
1067 if (log)
1068 log->Printf("GDBRemoteCommunication::%s() "
1069 "unnamed pipe creation failed: %s",
1070 __FUNCTION__, error.AsCString());
1071 return error;
1072 }
Aaron Smithe55850b2019-01-10 00:46:09 +00001073 pipe_t write = socket_pipe.GetWritePipe();
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001074 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
Aaron Smithe55850b2019-01-10 00:46:09 +00001075 debugserver_args.AppendArgument(llvm::to_string(write));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
Chaoren Lin46951b52015-07-30 17:48:44 +00001077#endif
Kate Stoneb9c1b512016-09-06 20:57:50 +00001078 } else {
1079 // No host and port given, so lets listen on our end and make the
Adrian Prantl05097242018-04-30 16:49:04 +00001080 // debugserver connect to us..
Kate Stoneb9c1b512016-09-06 20:57:50 +00001081 error = StartListenThread("127.0.0.1", 0);
1082 if (error.Fail()) {
1083 if (log)
1084 log->Printf("GDBRemoteCommunication::%s() unable to start listen "
1085 "thread: %s",
1086 __FUNCTION__, error.AsCString());
1087 return error;
Greg Clayton00fe87b2013-12-05 22:58:22 +00001088 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089
1090 ConnectionFileDescriptor *connection =
1091 (ConnectionFileDescriptor *)GetConnection();
1092 // Wait for 10 seconds to resolve the bound port
Pavel Labath3879fe02018-05-09 14:29:30 +00001093 uint16_t port_ = connection->GetListeningPort(std::chrono::seconds(10));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001094 if (port_ > 0) {
1095 char port_cstr[32];
1096 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1097 // Send the host and port down that debugserver and specify an option
1098 // so that it connects back to the port we are listening to in this
1099 // process
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001100 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1101 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001102 if (port)
1103 *port = port_;
1104 } else {
1105 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1106 if (log)
1107 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1108 error.AsCString());
1109 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001110 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001111 }
1112 }
Aaron Smith981e6352019-02-07 18:22:00 +00001113 std::string env_debugserver_log_file =
1114 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1115 if (!env_debugserver_log_file.empty()) {
1116 debugserver_args.AppendArgument(
1117 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001118 }
1119
Vince Harron9753dd92015-05-10 15:22:09 +00001120#if defined(__APPLE__)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001121 const char *env_debugserver_log_flags =
1122 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1123 if (env_debugserver_log_flags) {
Aaron Smith981e6352019-02-07 18:22:00 +00001124 debugserver_args.AppendArgument(
1125 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001126 }
Vince Harron9753dd92015-05-10 15:22:09 +00001127#else
Aaron Smith981e6352019-02-07 18:22:00 +00001128 std::string env_debugserver_log_channels =
1129 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1130 if (!env_debugserver_log_channels.empty()) {
1131 debugserver_args.AppendArgument(
1132 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1133 .str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001134 }
Vince Harron9753dd92015-05-10 15:22:09 +00001135#endif
Todd Fiala34ba4262014-08-29 17:10:31 +00001136
Kate Stoneb9c1b512016-09-06 20:57:50 +00001137 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1138 // env var doesn't come back.
1139 uint32_t env_var_index = 1;
1140 bool has_env_var;
1141 do {
1142 char env_var_name[64];
1143 snprintf(env_var_name, sizeof(env_var_name),
1144 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);
Aaron Smith981e6352019-02-07 18:22:00 +00001145 std::string extra_arg = host_env.lookup(env_var_name);
1146 has_env_var = !extra_arg.empty();
Todd Fiala34ba4262014-08-29 17:10:31 +00001147
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 if (has_env_var) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001149 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
Todd Fiala7aa4d972016-05-31 18:32:20 +00001150 if (log)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001151 log->Printf("GDBRemoteCommunication::%s adding env var %s contents "
1152 "to stub command line (%s)",
Aaron Smith981e6352019-02-07 18:22:00 +00001153 __FUNCTION__, env_var_name, extra_arg.c_str());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001154 }
1155 } while (has_env_var);
1156
1157 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
Zachary Turnerecbb0bb2016-09-19 17:54:06 +00001158 debugserver_args.AppendArgument(llvm::StringRef("--"));
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159 debugserver_args.AppendArguments(*inferior_args);
1160 }
1161
1162 // Copy the current environment to the gdbserver/debugserver instance
Aaron Smith981e6352019-02-07 18:22:00 +00001163 launch_info.GetEnvironment() = host_env;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001164
1165 // Close STDIN, STDOUT and STDERR.
1166 launch_info.AppendCloseFileAction(STDIN_FILENO);
1167 launch_info.AppendCloseFileAction(STDOUT_FILENO);
1168 launch_info.AppendCloseFileAction(STDERR_FILENO);
1169
1170 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1171 launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);
1172 launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
1173 launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);
1174
1175 if (log) {
1176 StreamString string_stream;
1177 Platform *const platform = nullptr;
1178 launch_info.Dump(string_stream, platform);
1179 log->Printf("launch info for gdb-remote stub:\n%s",
Zachary Turnerc1564272016-11-16 21:15:24 +00001180 string_stream.GetData());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001181 }
1182 error = Host::LaunchProcess(launch_info);
1183
1184 if (error.Success() &&
1185 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&
1186 pass_comm_fd == -1) {
1187 if (named_pipe_path.size() > 0) {
1188 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1189 if (error.Fail())
1190 if (log)
1191 log->Printf("GDBRemoteCommunication::%s() "
1192 "failed to open named pipe %s for reading: %s",
1193 __FUNCTION__, named_pipe_path.c_str(),
1194 error.AsCString());
1195 }
1196
1197 if (socket_pipe.CanWrite())
1198 socket_pipe.CloseWriteFileDescriptor();
1199 if (socket_pipe.CanRead()) {
1200 char port_cstr[PATH_MAX] = {0};
1201 port_cstr[0] = '\0';
1202 size_t num_bytes = sizeof(port_cstr);
1203 // Read port from pipe with 10 second timeout.
1204 error = socket_pipe.ReadWithTimeout(
1205 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1206 if (error.Success() && (port != nullptr)) {
1207 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');
Howard Hellyer8cfa0562017-02-23 08:49:49 +00001208 uint16_t child_port = StringConvert::ToUInt32(port_cstr, 0);
1209 if (*port == 0 || *port == child_port) {
1210 *port = child_port;
1211 if (log)
1212 log->Printf("GDBRemoteCommunication::%s() "
1213 "debugserver listens %u port",
1214 __FUNCTION__, *port);
1215 } else {
1216 if (log)
1217 log->Printf("GDBRemoteCommunication::%s() "
1218 "debugserver listening on port "
1219 "%d but requested port was %d",
1220 __FUNCTION__, (uint32_t)child_port,
1221 (uint32_t)(*port));
1222 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001223 } else {
1224 if (log)
1225 log->Printf("GDBRemoteCommunication::%s() "
1226 "failed to read a port value from pipe %s: %s",
1227 __FUNCTION__, named_pipe_path.c_str(),
1228 error.AsCString());
Todd Fiala7aa4d972016-05-31 18:32:20 +00001229 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001230 socket_pipe.Close();
1231 }
Chaoren Lin368c9f62015-04-27 23:20:30 +00001232
Kate Stoneb9c1b512016-09-06 20:57:50 +00001233 if (named_pipe_path.size() > 0) {
1234 const auto err = socket_pipe.Delete(named_pipe_path);
1235 if (err.Fail()) {
1236 if (log)
1237 log->Printf(
1238 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",
1239 __FUNCTION__, named_pipe_path.c_str(), err.AsCString());
Greg Clayton00fe87b2013-12-05 22:58:22 +00001240 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001241 }
1242
1243 // Make sure we actually connect with the debugserver...
1244 JoinListenThread();
Greg Clayton8b82f082011-04-12 05:54:46 +00001245 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001246 } else {
1247 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);
1248 }
Vince Harron8b335672015-05-12 01:10:56 +00001249
Kate Stoneb9c1b512016-09-06 20:57:50 +00001250 if (error.Fail()) {
1251 if (log)
1252 log->Printf("GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,
1253 error.AsCString());
1254 }
Vince Harron8b335672015-05-12 01:10:56 +00001255
Kate Stoneb9c1b512016-09-06 20:57:50 +00001256 return error;
Greg Clayton8b82f082011-04-12 05:54:46 +00001257}
1258
Kate Stoneb9c1b512016-09-06 20:57:50 +00001259void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1260
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001261void GDBRemoteCommunication::SetHistoryStream(llvm::raw_ostream *strm) {
1262 m_history.SetStream(strm);
Zachary Turner52f8f342019-01-29 22:55:21 +00001263}
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001264
1265llvm::Error
1266GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1267 GDBRemoteCommunication &server) {
1268 const bool child_processes_inherit = false;
1269 const int backlog = 5;
1270 TCPSocket listen_socket(true, child_processes_inherit);
1271 if (llvm::Error error =
1272 listen_socket.Listen("127.0.0.1:0", backlog).ToError())
1273 return error;
1274
1275 Socket *accept_socket;
1276 std::future<Status> accept_status = std::async(
1277 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1278
1279 llvm::SmallString<32> remote_addr;
1280 llvm::raw_svector_ostream(remote_addr)
Michal Gornye39ec432019-03-03 12:42:43 +00001281 << "connect://127.0.0.1:" << listen_socket.GetLocalPortNumber();
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001282
1283 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1284 new ConnectionFileDescriptor());
Pavel Labath9d723b82019-02-18 10:36:23 +00001285 Status status;
1286 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1287 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1288 "Unable to connect: %s", status.AsCString());
Jonas Devlieghere9e046f02018-11-13 19:18:16 +00001289
1290 client.SetConnection(conn_up.release());
1291 if (llvm::Error error = accept_status.get().ToError())
1292 return error;
1293
1294 server.SetConnection(new ConnectionFileDescriptor(accept_socket));
1295 return llvm::Error::success();
1296}
1297
Kate Stoneb9c1b512016-09-06 20:57:50 +00001298GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
Pavel Labath3aa04912016-10-31 17:19:42 +00001299 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
Aaron Smith981e6352019-02-07 18:22:00 +00001300 : m_gdb_comm(gdb_comm), m_timeout_modified(false) {
1301 auto curr_timeout = gdb_comm.GetPacketTimeout();
1302 // Only update the timeout if the timeout is greater than the current
1303 // timeout. If the current timeout is larger, then just use that.
1304 if (curr_timeout < timeout) {
1305 m_timeout_modified = true;
1306 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1307 }
Greg Claytonc1422c12012-04-09 22:46:21 +00001308}
Tamas Berghammer912800c2015-02-24 10:23:39 +00001309
Kate Stoneb9c1b512016-09-06 20:57:50 +00001310GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
Greg Clayton84577092017-04-17 16:20:22 +00001311 // Only restore the timeout if we set it in the constructor.
1312 if (m_timeout_modified)
1313 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
Tamas Berghammer912800c2015-02-24 10:23:39 +00001314}
1315
Kate Stoneb9c1b512016-09-06 20:57:50 +00001316// This function is called via the Communications class read thread when bytes
Adrian Prantl05097242018-04-30 16:49:04 +00001317// become available for this connection. This function will consume all
1318// incoming bytes and try to parse whole packets as they become available. Full
1319// packets are placed in a queue, so that all packet requests can simply pop
1320// from this queue. Async notification packets will be dispatched immediately
1321// to the ProcessGDBRemote Async thread via an event.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001322void GDBRemoteCommunication::AppendBytesToCache(const uint8_t *bytes,
1323 size_t len, bool broadcast,
1324 lldb::ConnectionStatus status) {
1325 StringExtractorGDBRemote packet;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001326
Kate Stoneb9c1b512016-09-06 20:57:50 +00001327 while (true) {
1328 PacketType type = CheckForPacket(bytes, len, packet);
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001329
Adrian Prantl05097242018-04-30 16:49:04 +00001330 // scrub the data so we do not pass it back to CheckForPacket on future
1331 // passes of the loop
Kate Stoneb9c1b512016-09-06 20:57:50 +00001332 bytes = nullptr;
1333 len = 0;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001334
Kate Stoneb9c1b512016-09-06 20:57:50 +00001335 // we may have received no packet so lets bail out
1336 if (type == PacketType::Invalid)
1337 break;
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001338
Kate Stoneb9c1b512016-09-06 20:57:50 +00001339 if (type == PacketType::Standard) {
1340 // scope for the mutex
1341 {
1342 // lock down the packet queue
1343 std::lock_guard<std::mutex> guard(m_packet_queue_mutex);
1344 // push a new packet into the queue
1345 m_packet_queue.push(packet);
1346 // Signal condition variable that we have a packet
1347 m_condition_queue_not_empty.notify_one();
1348 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001349 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001350
1351 if (type == PacketType::Notify) {
1352 // put this packet into an event
1353 const char *pdata = packet.GetStringRef().c_str();
1354
Adrian Prantl05097242018-04-30 16:49:04 +00001355 // as the communication class, we are a broadcaster and the async thread
1356 // is tuned to listen to us
Kate Stoneb9c1b512016-09-06 20:57:50 +00001357 BroadcastEvent(eBroadcastBitGdbReadThreadGotNotify,
1358 new EventDataBytes(pdata));
1359 }
1360 }
Ewan Crawfordfab40d32015-06-16 15:50:18 +00001361}
Pavel Labath1ebc85f2017-11-09 15:45:09 +00001362
1363void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1364 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1365 StringRef Style) {
1366 using PacketResult = GDBRemoteCommunication::PacketResult;
1367
1368 switch (result) {
1369 case PacketResult::Success:
1370 Stream << "Success";
1371 break;
1372 case PacketResult::ErrorSendFailed:
1373 Stream << "ErrorSendFailed";
1374 break;
1375 case PacketResult::ErrorSendAck:
1376 Stream << "ErrorSendAck";
1377 break;
1378 case PacketResult::ErrorReplyFailed:
1379 Stream << "ErrorReplyFailed";
1380 break;
1381 case PacketResult::ErrorReplyTimeout:
1382 Stream << "ErrorReplyTimeout";
1383 break;
1384 case PacketResult::ErrorReplyInvalid:
1385 Stream << "ErrorReplyInvalid";
1386 break;
1387 case PacketResult::ErrorReplyAck:
1388 Stream << "ErrorReplyAck";
1389 break;
1390 case PacketResult::ErrorDisconnected:
1391 Stream << "ErrorDisconnected";
1392 break;
1393 case PacketResult::ErrorNoSequenceLock:
1394 Stream << "ErrorNoSequenceLock";
1395 break;
1396 }
1397}