Bug Summary

File:build/source/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp
Warning:line 819, column 11
Value stored to 'success' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name GDBRemoteCommunication.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-17/lib/clang/17 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/Process/gdb-remote -I /build/source/lldb/source/Plugins/Process/gdb-remote -I /build/source/lldb/include -I tools/lldb/include -I include -I /build/source/llvm/include -I /usr/include/python3.9 -I /build/source/clang/include -I tools/lldb/../clang/include -I /build/source/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/source/= -source-date-epoch 1683717183 -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp
1//===-- GDBRemoteCommunication.cpp ----------------------------------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8
9#include "GDBRemoteCommunication.h"
10
11#include <climits>
12#include <cstring>
13#include <future>
14#include <sys/stat.h>
15
16#include "lldb/Core/StreamFile.h"
17#include "lldb/Host/Config.h"
18#include "lldb/Host/ConnectionFileDescriptor.h"
19#include "lldb/Host/FileSystem.h"
20#include "lldb/Host/Host.h"
21#include "lldb/Host/HostInfo.h"
22#include "lldb/Host/Pipe.h"
23#include "lldb/Host/ProcessLaunchInfo.h"
24#include "lldb/Host/Socket.h"
25#include "lldb/Host/ThreadLauncher.h"
26#include "lldb/Host/common/TCPSocket.h"
27#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"
28#include "lldb/Target/Platform.h"
29#include "lldb/Utility/Event.h"
30#include "lldb/Utility/FileSpec.h"
31#include "lldb/Utility/Log.h"
32#include "lldb/Utility/RegularExpression.h"
33#include "lldb/Utility/StreamString.h"
34#include "llvm/ADT/SmallString.h"
35#include "llvm/Support/ScopedPrinter.h"
36#include "llvm/Config/llvm-config.h"
37
38#include "ProcessGDBRemoteLog.h"
39
40#if defined(__APPLE__)
41#define DEBUGSERVER_BASENAME"lldb-server-" "17.0.0" "debugserver"
42#elif defined(_WIN32)
43#define DEBUGSERVER_BASENAME"lldb-server-" "17.0.0" "lldb-server.exe"
44#else
45# define DEBUGSERVER_BASENAME"lldb-server-" "17.0.0" "lldb-server-" LLVM_VERSION_STRING"17.0.0"
46#endif
47
48#if defined(HAVE_LIBCOMPRESSION)
49#include <compression.h>
50#endif
51
52#if LLVM_ENABLE_ZLIB1
53#include <zlib.h>
54#endif
55
56using namespace lldb;
57using namespace lldb_private;
58using namespace lldb_private::process_gdb_remote;
59
60// GDBRemoteCommunication constructor
61GDBRemoteCommunication::GDBRemoteCommunication()
62 : Communication(),
63#ifdef LLDB_CONFIGURATION_DEBUG
64 m_packet_timeout(1000),
65#else
66 m_packet_timeout(1),
67#endif
68 m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),
69 m_send_acks(true), m_is_platform(false),
70 m_compression_type(CompressionType::None), m_listen_url() {
71}
72
73// Destructor
74GDBRemoteCommunication::~GDBRemoteCommunication() {
75 if (IsConnected()) {
76 Disconnect();
77 }
78
79#if defined(HAVE_LIBCOMPRESSION)
80 if (m_decompression_scratch)
81 free (m_decompression_scratch);
82#endif
83}
84
85char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {
86 int checksum = 0;
87
88 for (char c : payload)
89 checksum += c;
90
91 return checksum & 255;
92}
93
94size_t GDBRemoteCommunication::SendAck() {
95 Log *log = GetLog(GDBRLog::Packets);
96 ConnectionStatus status = eConnectionStatusSuccess;
97 char ch = '+';
98 const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
99 LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" "> send packet: %c"
, (uint64_t)bytes_written, ch); } while (0)
;
100 m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
101 return bytes_written;
102}
103
104size_t GDBRemoteCommunication::SendNack() {
105 Log *log = GetLog(GDBRLog::Packets);
106 ConnectionStatus status = eConnectionStatusSuccess;
107 char ch = '-';
108 const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);
109 LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" "> send packet: %c"
, (uint64_t)bytes_written, ch); } while (0)
;
110 m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);
111 return bytes_written;
112}
113
114GDBRemoteCommunication::PacketResult
115GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {
116 StreamString packet(0, 4, eByteOrderBig);
117 packet.PutChar('$');
118 packet.Write(payload.data(), payload.size());
119 packet.PutChar('#');
120 packet.PutHex8(CalculcateChecksum(payload));
121 std::string packet_str = std::string(packet.GetString());
122
123 return SendRawPacketNoLock(packet_str);
124}
125
126GDBRemoteCommunication::PacketResult
127GDBRemoteCommunication::SendNotificationPacketNoLock(
128 llvm::StringRef notify_type, std::deque<std::string> &queue,
129 llvm::StringRef payload) {
130 PacketResult ret = PacketResult::Success;
131
132 // If there are no notification in the queue, send the notification
133 // packet.
134 if (queue.empty()) {
135 StreamString packet(0, 4, eByteOrderBig);
136 packet.PutChar('%');
137 packet.Write(notify_type.data(), notify_type.size());
138 packet.PutChar(':');
139 packet.Write(payload.data(), payload.size());
140 packet.PutChar('#');
141 packet.PutHex8(CalculcateChecksum(payload));
142 ret = SendRawPacketNoLock(packet.GetString(), true);
143 }
144
145 queue.push_back(payload.str());
146 return ret;
147}
148
149GDBRemoteCommunication::PacketResult
150GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,
151 bool skip_ack) {
152 if (IsConnected()) {
153 Log *log = GetLog(GDBRLog::Packets);
154 ConnectionStatus status = eConnectionStatusSuccess;
155 const char *packet_data = packet.data();
156 const size_t packet_length = packet.size();
157 size_t bytes_written = WriteAll(packet_data, packet_length, status, nullptr);
158 if (log) {
159 size_t binary_start_offset = 0;
160 if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==
161 0) {
162 const char *first_comma = strchr(packet_data, ',');
163 if (first_comma) {
164 const char *second_comma = strchr(first_comma + 1, ',');
165 if (second_comma)
166 binary_start_offset = second_comma - packet_data + 1;
167 }
168 }
169
170 // If logging was just enabled and we have history, then dump out what we
171 // have to the log so we get the historical context. The Dump() call that
172 // logs all of the packet will set a boolean so that we don't dump this
173 // more than once
174 if (!m_history.DidDumpToLog())
175 m_history.Dump(log);
176
177 if (binary_start_offset) {
178 StreamString strm;
179 // Print non binary data header
180 strm.Printf("<%4" PRIu64"l" "u" "> send packet: %.*s", (uint64_t)bytes_written,
181 (int)binary_start_offset, packet_data);
182 const uint8_t *p;
183 // Print binary data exactly as sent
184 for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';
185 ++p)
186 strm.Printf("\\x%2.2x", *p);
187 // Print the checksum
188 strm.Printf("%*s", (int)3, p);
189 log->PutString(strm.GetString());
190 } else
191 LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %.*s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" "> send packet: %.*s"
, (uint64_t)bytes_written, (int)packet_length, packet_data); }
while (0)
192 (uint64_t)bytes_written, (int)packet_length, packet_data)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" "> send packet: %.*s"
, (uint64_t)bytes_written, (int)packet_length, packet_data); }
while (0)
;
193 }
194
195 m_history.AddPacket(packet.str(), packet_length,
196 GDBRemotePacket::ePacketTypeSend, bytes_written);
197
198 if (bytes_written == packet_length) {
199 if (!skip_ack && GetSendAcks())
200 return GetAck();
201 else
202 return PacketResult::Success;
203 } else {
204 LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: failed to send packet: %.*s"
, (int)packet_length, packet_data); } while (0)
205 packet_data)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: failed to send packet: %.*s"
, (int)packet_length, packet_data); } while (0)
;
206 }
207 }
208 return PacketResult::ErrorSendFailed;
209}
210
211GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {
212 StringExtractorGDBRemote packet;
213 PacketResult result = WaitForPacketNoLock(packet, GetPacketTimeout(), false);
214 if (result == PacketResult::Success) {
215 if (packet.GetResponseType() ==
216 StringExtractorGDBRemote::ResponseType::eAck)
217 return PacketResult::Success;
218 else
219 return PacketResult::ErrorSendAck;
220 }
221 return result;
222}
223
224GDBRemoteCommunication::PacketResult
225GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,
226 Timeout<std::micro> timeout,
227 bool sync_on_timeout) {
228 using ResponseType = StringExtractorGDBRemote::ResponseType;
229
230 Log *log = GetLog(GDBRLog::Packets);
231 for (;;) {
232 PacketResult result =
233 WaitForPacketNoLock(response, timeout, sync_on_timeout);
234 if (result != PacketResult::Success ||
235 (response.GetResponseType() != ResponseType::eAck &&
236 response.GetResponseType() != ResponseType::eNack))
237 return result;
238 LLDB_LOG(log, "discarding spurious `{0}` packet", response.GetStringRef())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, __func__, "discarding spurious `{0}` packet", response.GetStringRef
()); } while (0)
;
239 }
240}
241
242GDBRemoteCommunication::PacketResult
243GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,
244 Timeout<std::micro> timeout,
245 bool sync_on_timeout) {
246 uint8_t buffer[8192];
247 Status error;
248
249 Log *log = GetLog(GDBRLog::Packets);
250
251 // Check for a packet from our cache first without trying any reading...
252 if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)
253 return PacketResult::Success;
254
255 bool timed_out = false;
256 bool disconnected = false;
257 while (IsConnected() && !timed_out) {
258 lldb::ConnectionStatus status = eConnectionStatusNoConnection;
259 size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);
260
261 LLDB_LOGV(log,do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, __func__, "Read(buffer, sizeof(buffer), timeout = {0}, " "status = {1}, error = {2}) => bytes_read = {3}"
, timeout, Communication::ConnectionStatusAsString(status), error
, bytes_read); } while (0)
262 "Read(buffer, sizeof(buffer), timeout = {0}, "do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, __func__, "Read(buffer, sizeof(buffer), timeout = {0}, " "status = {1}, error = {2}) => bytes_read = {3}"
, timeout, Communication::ConnectionStatusAsString(status), error
, bytes_read); } while (0)
263 "status = {1}, error = {2}) => bytes_read = {3}",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, __func__, "Read(buffer, sizeof(buffer), timeout = {0}, " "status = {1}, error = {2}) => bytes_read = {3}"
, timeout, Communication::ConnectionStatusAsString(status), error
, bytes_read); } while (0)
264 timeout, Communication::ConnectionStatusAsString(status), error,do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, __func__, "Read(buffer, sizeof(buffer), timeout = {0}, " "status = {1}, error = {2}) => bytes_read = {3}"
, timeout, Communication::ConnectionStatusAsString(status), error
, bytes_read); } while (0)
265 bytes_read)do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, __func__, "Read(buffer, sizeof(buffer), timeout = {0}, " "status = {1}, error = {2}) => bytes_read = {3}"
, timeout, Communication::ConnectionStatusAsString(status), error
, bytes_read); } while (0)
;
266
267 if (bytes_read > 0) {
268 if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)
269 return PacketResult::Success;
270 } else {
271 switch (status) {
272 case eConnectionStatusTimedOut:
273 case eConnectionStatusInterrupted:
274 if (sync_on_timeout) {
275 /// Sync the remote GDB server and make sure we get a response that
276 /// corresponds to what we send.
277 ///
278 /// Sends a "qEcho" packet and makes sure it gets the exact packet
279 /// echoed back. If the qEcho packet isn't supported, we send a qC
280 /// packet and make sure we get a valid thread ID back. We use the
281 /// "qC" packet since its response if very unique: is responds with
282 /// "QC%x" where %x is the thread ID of the current thread. This
283 /// makes the response unique enough from other packet responses to
284 /// ensure we are back on track.
285 ///
286 /// This packet is needed after we time out sending a packet so we
287 /// can ensure that we are getting the response for the packet we
288 /// are sending. There are no sequence IDs in the GDB remote
289 /// protocol (there used to be, but they are not supported anymore)
290 /// so if you timeout sending packet "abc", you might then send
291 /// packet "cde" and get the response for the previous "abc" packet.
292 /// Many responses are "OK" or "" (unsupported) or "EXX" (error) so
293 /// many responses for packets can look like responses for other
294 /// packets. So if we timeout, we need to ensure that we can get
295 /// back on track. If we can't get back on track, we must
296 /// disconnect.
297 bool sync_success = false;
298 bool got_actual_response = false;
299 // We timed out, we need to sync back up with the
300 char echo_packet[32];
301 int echo_packet_len = 0;
302 RegularExpression response_regex;
303
304 if (m_supports_qEcho == eLazyBoolYes) {
305 echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),
306 "qEcho:%u", ++m_echo_number);
307 std::string regex_str = "^";
308 regex_str += echo_packet;
309 regex_str += "$";
310 response_regex = RegularExpression(regex_str);
311 } else {
312 echo_packet_len =
313 ::snprintf(echo_packet, sizeof(echo_packet), "qC");
314 response_regex =
315 RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));
316 }
317
318 PacketResult echo_packet_result =
319 SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));
320 if (echo_packet_result == PacketResult::Success) {
321 const uint32_t max_retries = 3;
322 uint32_t successful_responses = 0;
323 for (uint32_t i = 0; i < max_retries; ++i) {
324 StringExtractorGDBRemote echo_response;
325 echo_packet_result =
326 WaitForPacketNoLock(echo_response, timeout, false);
327 if (echo_packet_result == PacketResult::Success) {
328 ++successful_responses;
329 if (response_regex.Execute(echo_response.GetStringRef())) {
330 sync_success = true;
331 break;
332 } else if (successful_responses == 1) {
333 // We got something else back as the first successful
334 // response, it probably is the response to the packet we
335 // actually wanted, so copy it over if this is the first
336 // success and continue to try to get the qEcho response
337 packet = echo_response;
338 got_actual_response = true;
339 }
340 } else if (echo_packet_result == PacketResult::ErrorReplyTimeout)
341 continue; // Packet timed out, continue waiting for a response
342 else
343 break; // Something else went wrong getting the packet back, we
344 // failed and are done trying
345 }
346 }
347
348 // We weren't able to sync back up with the server, we must abort
349 // otherwise all responses might not be from the right packets...
350 if (sync_success) {
351 // We timed out, but were able to recover
352 if (got_actual_response) {
353 // We initially timed out, but we did get a response that came in
354 // before the successful reply to our qEcho packet, so lets say
355 // everything is fine...
356 return PacketResult::Success;
357 }
358 } else {
359 disconnected = true;
360 Disconnect();
361 }
362 }
363 timed_out = true;
364 break;
365 case eConnectionStatusSuccess:
366 // printf ("status = success but error = %s\n",
367 // error.AsCString("<invalid>"));
368 break;
369
370 case eConnectionStatusEndOfFile:
371 case eConnectionStatusNoConnection:
372 case eConnectionStatusLostConnection:
373 case eConnectionStatusError:
374 disconnected = true;
375 Disconnect();
376 break;
377 }
378 }
379 }
380 packet.Clear();
381 if (disconnected)
382 return PacketResult::ErrorDisconnected;
383 if (timed_out)
384 return PacketResult::ErrorReplyTimeout;
385 else
386 return PacketResult::ErrorReplyFailed;
387}
388
389bool GDBRemoteCommunication::DecompressPacket() {
390 Log *log = GetLog(GDBRLog::Packets);
391
392 if (!CompressionIsEnabled())
393 return true;
394
395 size_t pkt_size = m_bytes.size();
396
397 // Smallest possible compressed packet is $N#00 - an uncompressed empty
398 // reply, most commonly indicating an unsupported packet. Anything less than
399 // 5 characters, it's definitely not a compressed packet.
400 if (pkt_size < 5)
401 return true;
402
403 if (m_bytes[0] != '$' && m_bytes[0] != '%')
404 return true;
405 if (m_bytes[1] != 'C' && m_bytes[1] != 'N')
406 return true;
407
408 size_t hash_mark_idx = m_bytes.find('#');
409 if (hash_mark_idx == std::string::npos)
410 return true;
411 if (hash_mark_idx + 2 >= m_bytes.size())
412 return true;
413
414 if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||
415 !::isxdigit(m_bytes[hash_mark_idx + 2]))
416 return true;
417
418 size_t content_length =
419 pkt_size -
420 5; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars
421 size_t content_start = 2; // The first character of the
422 // compressed/not-compressed text of the packet
423 size_t checksum_idx =
424 hash_mark_idx +
425 1; // The first character of the two hex checksum characters
426
427 // Normally size_of_first_packet == m_bytes.size() but m_bytes may contain
428 // multiple packets. size_of_first_packet is the size of the initial packet
429 // which we'll replace with the decompressed version of, leaving the rest of
430 // m_bytes unmodified.
431 size_t size_of_first_packet = hash_mark_idx + 3;
432
433 // Compressed packets ("$C") start with a base10 number which is the size of
434 // the uncompressed payload, then a : and then the compressed data. e.g.
435 // $C1024:<binary>#00 Update content_start and content_length to only include
436 // the <binary> part of the packet.
437
438 uint64_t decompressed_bufsize = ULONG_MAX(9223372036854775807L *2UL+1UL);
439 if (m_bytes[1] == 'C') {
440 size_t i = content_start;
441 while (i < hash_mark_idx && isdigit(m_bytes[i]))
442 i++;
443 if (i < hash_mark_idx && m_bytes[i] == ':') {
444 i++;
445 content_start = i;
446 content_length = hash_mark_idx - content_start;
447 std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);
448 errno(*__errno_location ()) = 0;
449 decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);
450 if (errno(*__errno_location ()) != 0 || decompressed_bufsize == ULONG_MAX(9223372036854775807L *2UL+1UL)) {
451 m_bytes.erase(0, size_of_first_packet);
452 return false;
453 }
454 }
455 }
456
457 if (GetSendAcks()) {
458 char packet_checksum_cstr[3];
459 packet_checksum_cstr[0] = m_bytes[checksum_idx];
460 packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];
461 packet_checksum_cstr[2] = '\0';
462 long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
463
464 long actual_checksum = CalculcateChecksum(
465 llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));
466 bool success = packet_checksum == actual_checksum;
467 if (!success) {
468 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x"
, (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
(uint8_t)actual_checksum); } while (0)
469 "error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x"
, (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
(uint8_t)actual_checksum); } while (0)
470 (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x"
, (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
(uint8_t)actual_checksum); } while (0)
471 (uint8_t)actual_checksum)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x"
, (int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,
(uint8_t)actual_checksum); } while (0)
;
472 }
473 // Send the ack or nack if needed
474 if (!success) {
475 SendNack();
476 m_bytes.erase(0, size_of_first_packet);
477 return false;
478 } else {
479 SendAck();
480 }
481 }
482
483 if (m_bytes[1] == 'N') {
484 // This packet was not compressed -- delete the 'N' character at the start
485 // and the packet may be processed as-is.
486 m_bytes.erase(1, 1);
487 return true;
488 }
489
490 // Reverse the gdb-remote binary escaping that was done to the compressed
491 // text to guard characters like '$', '#', '}', etc.
492 std::vector<uint8_t> unescaped_content;
493 unescaped_content.reserve(content_length);
494 size_t i = content_start;
495 while (i < hash_mark_idx) {
496 if (m_bytes[i] == '}') {
497 i++;
498 unescaped_content.push_back(m_bytes[i] ^ 0x20);
499 } else {
500 unescaped_content.push_back(m_bytes[i]);
501 }
502 i++;
503 }
504
505 uint8_t *decompressed_buffer = nullptr;
506 size_t decompressed_bytes = 0;
507
508 if (decompressed_bufsize != ULONG_MAX(9223372036854775807L *2UL+1UL)) {
509 decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);
510 if (decompressed_buffer == nullptr) {
511 m_bytes.erase(0, size_of_first_packet);
512 return false;
513 }
514 }
515
516#if defined(HAVE_LIBCOMPRESSION)
517 if (m_compression_type == CompressionType::ZlibDeflate ||
518 m_compression_type == CompressionType::LZFSE ||
519 m_compression_type == CompressionType::LZ4 ||
520 m_compression_type == CompressionType::LZMA) {
521 compression_algorithm compression_type;
522 if (m_compression_type == CompressionType::LZFSE)
523 compression_type = COMPRESSION_LZFSE;
524 else if (m_compression_type == CompressionType::ZlibDeflate)
525 compression_type = COMPRESSION_ZLIB;
526 else if (m_compression_type == CompressionType::LZ4)
527 compression_type = COMPRESSION_LZ4_RAW;
528 else if (m_compression_type == CompressionType::LZMA)
529 compression_type = COMPRESSION_LZMA;
530
531 if (m_decompression_scratch_type != m_compression_type) {
532 if (m_decompression_scratch) {
533 free (m_decompression_scratch);
534 m_decompression_scratch = nullptr;
535 }
536 size_t scratchbuf_size = 0;
537 if (m_compression_type == CompressionType::LZFSE)
538 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
539 else if (m_compression_type == CompressionType::LZ4)
540 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);
541 else if (m_compression_type == CompressionType::ZlibDeflate)
542 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);
543 else if (m_compression_type == CompressionType::LZMA)
544 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZMA);
545 else if (m_compression_type == CompressionType::LZFSE)
546 scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);
547 if (scratchbuf_size > 0) {
548 m_decompression_scratch = (void*) malloc (scratchbuf_size);
549 m_decompression_scratch_type = m_compression_type;
550 }
551 }
552
553 if (decompressed_bufsize != ULONG_MAX(9223372036854775807L *2UL+1UL) && decompressed_buffer != nullptr) {
554 decompressed_bytes = compression_decode_buffer(
555 decompressed_buffer, decompressed_bufsize,
556 (uint8_t *)unescaped_content.data(), unescaped_content.size(),
557 m_decompression_scratch, compression_type);
558 }
559 }
560#endif
561
562#if LLVM_ENABLE_ZLIB1
563 if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX(9223372036854775807L *2UL+1UL) &&
564 decompressed_buffer != nullptr &&
565 m_compression_type == CompressionType::ZlibDeflate) {
566 z_stream stream;
567 memset(&stream, 0, sizeof(z_stream));
568 stream.next_in = (Bytef *)unescaped_content.data();
569 stream.avail_in = (uInt)unescaped_content.size();
570 stream.total_in = 0;
571 stream.next_out = (Bytef *)decompressed_buffer;
572 stream.avail_out = decompressed_bufsize;
573 stream.total_out = 0;
574 stream.zalloc = Z_NULL0;
575 stream.zfree = Z_NULL0;
576 stream.opaque = Z_NULL0;
577
578 if (inflateInit2(&stream, -15)inflateInit2_((&stream), (-15), "1.2.11", (int)sizeof(z_stream
))
== Z_OK0) {
579 int status = inflate(&stream, Z_NO_FLUSH0);
580 inflateEnd(&stream);
581 if (status == Z_STREAM_END1) {
582 decompressed_bytes = stream.total_out;
583 }
584 }
585 }
586#endif
587
588 if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {
589 if (decompressed_buffer)
590 free(decompressed_buffer);
591 m_bytes.erase(0, size_of_first_packet);
592 return false;
593 }
594
595 std::string new_packet;
596 new_packet.reserve(decompressed_bytes + 6);
597 new_packet.push_back(m_bytes[0]);
598 new_packet.append((const char *)decompressed_buffer, decompressed_bytes);
599 new_packet.push_back('#');
600 if (GetSendAcks()) {
601 uint8_t decompressed_checksum = CalculcateChecksum(
602 llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));
603 char decompressed_checksum_str[3];
604 snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);
605 new_packet.append(decompressed_checksum_str);
606 } else {
607 new_packet.push_back('0');
608 new_packet.push_back('0');
609 }
610
611 m_bytes.replace(0, size_of_first_packet, new_packet.data(),
612 new_packet.size());
613
614 free(decompressed_buffer);
615 return true;
616}
617
618GDBRemoteCommunication::PacketType
619GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,
620 StringExtractorGDBRemote &packet) {
621 // Put the packet data into the buffer in a thread safe fashion
622 std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);
623
624 Log *log = GetLog(GDBRLog::Packets);
625
626 if (src && src_len > 0) {
627 if (log && log->GetVerbose()) {
628 StreamString s;
629 LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s"
, __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src); }
while (0)
630 __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s adding %u bytes: %.*s"
, __FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src); }
while (0)
;
631 }
632 m_bytes.append((const char *)src, src_len);
633 }
634
635 bool isNotifyPacket = false;
636
637 // Parse up the packets into gdb remote packets
638 if (!m_bytes.empty()) {
639 // end_idx must be one past the last valid packet byte. Start it off with
640 // an invalid value that is the same as the current index.
641 size_t content_start = 0;
642 size_t content_length = 0;
643 size_t total_length = 0;
644 size_t checksum_idx = std::string::npos;
645
646 // Size of packet before it is decompressed, for logging purposes
647 size_t original_packet_size = m_bytes.size();
648 if (CompressionIsEnabled()) {
649 if (!DecompressPacket()) {
650 packet.Clear();
651 return GDBRemoteCommunication::PacketType::Standard;
652 }
653 }
654
655 switch (m_bytes[0]) {
656 case '+': // Look for ack
657 case '-': // Look for cancel
658 case '\x03': // ^C to halt target
659 content_length = total_length = 1; // The command is one byte long...
660 break;
661
662 case '%': // Async notify packet
663 isNotifyPacket = true;
664 [[fallthrough]];
665
666 case '$':
667 // Look for a standard gdb packet?
668 {
669 size_t hash_pos = m_bytes.find('#');
670 if (hash_pos != std::string::npos) {
671 if (hash_pos + 2 < m_bytes.size()) {
672 checksum_idx = hash_pos + 1;
673 // Skip the dollar sign
674 content_start = 1;
675 // Don't include the # in the content or the $ in the content
676 // length
677 content_length = hash_pos - 1;
678
679 total_length =
680 hash_pos + 3; // Skip the # and the two hex checksum bytes
681 } else {
682 // Checksum bytes aren't all here yet
683 content_length = std::string::npos;
684 }
685 }
686 }
687 break;
688
689 default: {
690 // We have an unexpected byte and we need to flush all bad data that is
691 // in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'
692 // (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet
693 // header) or of course, the end of the data in m_bytes...
694 const size_t bytes_len = m_bytes.size();
695 bool done = false;
696 uint32_t idx;
697 for (idx = 1; !done && idx < bytes_len; ++idx) {
698 switch (m_bytes[idx]) {
699 case '+':
700 case '-':
701 case '\x03':
702 case '%':
703 case '$':
704 done = true;
705 break;
706
707 default:
708 break;
709 }
710 }
711 LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'"
, __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str()); } while (
0)
712 __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'"
, __FUNCTION__, idx - 1, idx - 1, m_bytes.c_str()); } while (
0)
;
713 m_bytes.erase(0, idx - 1);
714 } break;
715 }
716
717 if (content_length == std::string::npos) {
718 packet.Clear();
719 return GDBRemoteCommunication::PacketType::Invalid;
720 } else if (total_length > 0) {
721
722 // We have a valid packet...
723 assert(content_length <= m_bytes.size())(static_cast <bool> (content_length <= m_bytes.size(
)) ? void (0) : __assert_fail ("content_length <= m_bytes.size()"
, "lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, 723, __extension__ __PRETTY_FUNCTION__))
;
724 assert(total_length <= m_bytes.size())(static_cast <bool> (total_length <= m_bytes.size())
? void (0) : __assert_fail ("total_length <= m_bytes.size()"
, "lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, 724, __extension__ __PRETTY_FUNCTION__))
;
725 assert(content_length <= total_length)(static_cast <bool> (content_length <= total_length)
? void (0) : __assert_fail ("content_length <= total_length"
, "lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, 725, __extension__ __PRETTY_FUNCTION__))
;
726 size_t content_end = content_start + content_length;
727
728 bool success = true;
729 if (log) {
730 // If logging was just enabled and we have history, then dump out what
731 // we have to the log so we get the historical context. The Dump() call
732 // that logs all of the packet will set a boolean so that we don't dump
733 // this more than once
734 if (!m_history.DidDumpToLog())
735 m_history.Dump(log);
736
737 bool binary = false;
738 // Only detect binary for packets that start with a '$' and have a
739 // '#CC' checksum
740 if (m_bytes[0] == '$' && total_length > 4) {
741 for (size_t i = 0; !binary && i < total_length; ++i) {
742 unsigned char c = m_bytes[i];
743 if (!llvm::isPrint(c) && !llvm::isSpace(c)) {
744 binary = true;
745 }
746 }
747 }
748 if (binary) {
749 StreamString strm;
750 // Packet header...
751 if (CompressionIsEnabled())
752 strm.Printf("<%4" PRIu64"l" "u" ":%" PRIu64"l" "u" "> read packet: %c",
753 (uint64_t)original_packet_size, (uint64_t)total_length,
754 m_bytes[0]);
755 else
756 strm.Printf("<%4" PRIu64"l" "u" "> read packet: %c",
757 (uint64_t)total_length, m_bytes[0]);
758 for (size_t i = content_start; i < content_end; ++i) {
759 // Remove binary escaped bytes when displaying the packet...
760 const char ch = m_bytes[i];
761 if (ch == 0x7d) {
762 // 0x7d is the escape character. The next character is to be
763 // XOR'd with 0x20.
764 const char escapee = m_bytes[++i] ^ 0x20;
765 strm.Printf("%2.2x", escapee);
766 } else {
767 strm.Printf("%2.2x", (uint8_t)ch);
768 }
769 }
770 // Packet footer...
771 strm.Printf("%c%c%c", m_bytes[total_length - 3],
772 m_bytes[total_length - 2], m_bytes[total_length - 1]);
773 log->PutString(strm.GetString());
774 } else {
775 if (CompressionIsEnabled())
776 LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" ":%" "l" "u" "> read packet: %.*s"
, (uint64_t)original_packet_size, (uint64_t)total_length, (int
)(total_length), m_bytes.c_str()); } while (0)
777 (uint64_t)original_packet_size, (uint64_t)total_length,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" ":%" "l" "u" "> read packet: %.*s"
, (uint64_t)original_packet_size, (uint64_t)total_length, (int
)(total_length), m_bytes.c_str()); } while (0)
778 (int)(total_length), m_bytes.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" ":%" "l" "u" "> read packet: %.*s"
, (uint64_t)original_packet_size, (uint64_t)total_length, (int
)(total_length), m_bytes.c_str()); } while (0)
;
779 else
780 LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" "> read packet: %.*s"
, (uint64_t)total_length, (int)(total_length), m_bytes.c_str(
)); } while (0)
781 (uint64_t)total_length, (int)(total_length),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" "> read packet: %.*s"
, (uint64_t)total_length, (int)(total_length), m_bytes.c_str(
)); } while (0)
782 m_bytes.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("<%4" "l" "u" "> read packet: %.*s"
, (uint64_t)total_length, (int)(total_length), m_bytes.c_str(
)); } while (0)
;
783 }
784 }
785
786 m_history.AddPacket(m_bytes, total_length,
787 GDBRemotePacket::ePacketTypeRecv, total_length);
788
789 // Copy the packet from m_bytes to packet_str expanding the run-length
790 // encoding in the process.
791 std ::string packet_str =
792 ExpandRLE(m_bytes.substr(content_start, content_end - content_start));
793 packet = StringExtractorGDBRemote(packet_str);
794
795 if (m_bytes[0] == '$' || m_bytes[0] == '%') {
796 assert(checksum_idx < m_bytes.size())(static_cast <bool> (checksum_idx < m_bytes.size()) ?
void (0) : __assert_fail ("checksum_idx < m_bytes.size()"
, "lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, 796, __extension__ __PRETTY_FUNCTION__))
;
797 if (::isxdigit(m_bytes[checksum_idx + 0]) ||
798 ::isxdigit(m_bytes[checksum_idx + 1])) {
799 if (GetSendAcks()) {
800 const char *packet_checksum_cstr = &m_bytes[checksum_idx];
801 char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);
802 char actual_checksum = CalculcateChecksum(
803 llvm::StringRef(m_bytes).slice(content_start, content_end));
804 success = packet_checksum == actual_checksum;
805 if (!success) {
806 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
"got 0x%2.2x", (int)(total_length), m_bytes.c_str(), (uint8_t
)packet_checksum, (uint8_t)actual_checksum); } while (0)
807 "error: checksum mismatch: %.*s expected 0x%2.2x, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
"got 0x%2.2x", (int)(total_length), m_bytes.c_str(), (uint8_t
)packet_checksum, (uint8_t)actual_checksum); } while (0)
808 "got 0x%2.2x",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
"got 0x%2.2x", (int)(total_length), m_bytes.c_str(), (uint8_t
)packet_checksum, (uint8_t)actual_checksum); } while (0)
809 (int)(total_length), m_bytes.c_str(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
"got 0x%2.2x", (int)(total_length), m_bytes.c_str(), (uint8_t
)packet_checksum, (uint8_t)actual_checksum); } while (0)
810 (uint8_t)packet_checksum, (uint8_t)actual_checksum)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: checksum mismatch: %.*s expected 0x%2.2x, "
"got 0x%2.2x", (int)(total_length), m_bytes.c_str(), (uint8_t
)packet_checksum, (uint8_t)actual_checksum); } while (0)
;
811 }
812 // Send the ack or nack if needed
813 if (!success)
814 SendNack();
815 else
816 SendAck();
817 }
818 } else {
819 success = false;
Value stored to 'success' is never read
820 LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: invalid checksum in packet: '%s'\n"
, m_bytes.c_str()); } while (0)
821 m_bytes.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("error: invalid checksum in packet: '%s'\n"
, m_bytes.c_str()); } while (0)
;
822 }
823 }
824
825 m_bytes.erase(0, total_length);
826 packet.SetFilePos(0);
827
828 if (isNotifyPacket)
829 return GDBRemoteCommunication::PacketType::Notify;
830 else
831 return GDBRemoteCommunication::PacketType::Standard;
832 }
833 }
834 packet.Clear();
835 return GDBRemoteCommunication::PacketType::Invalid;
836}
837
838Status GDBRemoteCommunication::StartListenThread(const char *hostname,
839 uint16_t port) {
840 if (m_listen_thread.IsJoinable())
841 return Status("listen thread already running");
842
843 char listen_url[512];
844 if (hostname && hostname[0])
845 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
846 else
847 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
848 m_listen_url = listen_url;
849 SetConnection(std::make_unique<ConnectionFileDescriptor>());
850 llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(
851 listen_url, [this] { return GDBRemoteCommunication::ListenThread(); });
852 if (!listen_thread)
853 return Status(listen_thread.takeError());
854 m_listen_thread = *listen_thread;
855
856 return Status();
857}
858
859bool GDBRemoteCommunication::JoinListenThread() {
860 if (m_listen_thread.IsJoinable())
861 m_listen_thread.Join(nullptr);
862 return true;
863}
864
865lldb::thread_result_t GDBRemoteCommunication::ListenThread() {
866 Status error;
867 ConnectionFileDescriptor *connection =
868 (ConnectionFileDescriptor *)GetConnection();
869
870 if (connection) {
871 // Do the listen on another thread so we can continue on...
872 if (connection->Connect(
873 m_listen_url.c_str(),
874 [this](llvm::StringRef port_str) {
875 uint16_t port = 0;
876 llvm::to_integer(port_str, port, 10);
877 m_port_promise.set_value(port);
878 },
879 &error) != eConnectionStatusSuccess)
880 SetConnection(nullptr);
881 }
882 return {};
883}
884
885Status GDBRemoteCommunication::StartDebugserverProcess(
886 const char *url, Platform *platform, ProcessLaunchInfo &launch_info,
887 uint16_t *port, const Args *inferior_args, int pass_comm_fd) {
888 Log *log = GetLog(GDBRLog::Process);
889 LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s(url=%s, port=%"
"u" ")", __FUNCTION__, url ? url : "<empty>", port ? *
port : uint16_t(0)); } while (0)
890 __FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s(url=%s, port=%"
"u" ")", __FUNCTION__, url ? url : "<empty>", port ? *
port : uint16_t(0)); } while (0)
;
891
892 Status error;
893 // If we locate debugserver, keep that located version around
894 static FileSpec g_debugserver_file_spec;
895
896 char debugserver_path[PATH_MAX4096];
897 FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();
898
899 Environment host_env = Host::GetEnvironment();
900
901 // Always check to see if we have an environment override for the path to the
902 // debugserver to use and use it if we do.
903 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
904 if (!env_debugserver_path.empty()) {
905 debugserver_file_spec.SetFile(env_debugserver_path,
906 FileSpec::Style::native);
907 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
"from environment variable: %s", __FUNCTION__, env_debugserver_path
.c_str()); } while (0)
908 "GDBRemoteCommunication::%s() gdb-remote stub exe path set "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
"from environment variable: %s", __FUNCTION__, env_debugserver_path
.c_str()); } while (0)
909 "from environment variable: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
"from environment variable: %s", __FUNCTION__, env_debugserver_path
.c_str()); } while (0)
910 __FUNCTION__, env_debugserver_path.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() gdb-remote stub exe path set "
"from environment variable: %s", __FUNCTION__, env_debugserver_path
.c_str()); } while (0)
;
911 } else
912 debugserver_file_spec = g_debugserver_file_spec;
913 bool debugserver_exists =
914 FileSystem::Instance().Exists(debugserver_file_spec);
915 if (!debugserver_exists) {
916 // The debugserver binary is in the LLDB.framework/Resources directory.
917 debugserver_file_spec = HostInfo::GetSupportExeDir();
918 if (debugserver_file_spec) {
919 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME"lldb-server-" "17.0.0");
920 debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);
921 if (debugserver_exists) {
922 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'"
, __FUNCTION__, debugserver_file_spec.GetPath().c_str()); } while
(0)
923 "GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'"
, __FUNCTION__, debugserver_file_spec.GetPath().c_str()); } while
(0)
924 __FUNCTION__, debugserver_file_spec.GetPath().c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'"
, __FUNCTION__, debugserver_file_spec.GetPath().c_str()); } while
(0)
;
925
926 g_debugserver_file_spec = debugserver_file_spec;
927 } else {
928 if (platform)
929 debugserver_file_spec =
930 platform->LocateExecutable(DEBUGSERVER_BASENAME"lldb-server-" "17.0.0");
931 else
932 debugserver_file_spec.Clear();
933 if (debugserver_file_spec) {
934 // Platform::LocateExecutable() wouldn't return a path if it doesn't
935 // exist
936 debugserver_exists = true;
937 } else {
938 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() could not find "
"gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec
.GetPath().c_str()); } while (0)
939 "GDBRemoteCommunication::%s() could not find "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() could not find "
"gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec
.GetPath().c_str()); } while (0)
940 "gdb-remote stub exe '%s'",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() could not find "
"gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec
.GetPath().c_str()); } while (0)
941 __FUNCTION__, debugserver_file_spec.GetPath().c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() could not find "
"gdb-remote stub exe '%s'", __FUNCTION__, debugserver_file_spec
.GetPath().c_str()); } while (0)
;
942 }
943 // Don't cache the platform specific GDB server binary as it could
944 // change from platform to platform
945 g_debugserver_file_spec.Clear();
946 }
947 }
948 }
949
950 if (debugserver_exists) {
951 debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));
952
953 Args &debugserver_args = launch_info.GetArguments();
954 debugserver_args.Clear();
955
956 // Start args with "debugserver /file/path -r --"
957 debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));
958
959#if !defined(__APPLE__)
960 // First argument to lldb-server must be mode in which to run.
961 debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));
962#endif
963
964 // If a url is supplied then use it
965 if (url)
966 debugserver_args.AppendArgument(llvm::StringRef(url));
967
968 if (pass_comm_fd >= 0) {
969 StreamString fd_arg;
970 fd_arg.Printf("--fd=%i", pass_comm_fd);
971 debugserver_args.AppendArgument(fd_arg.GetString());
972 // Send "pass_comm_fd" down to the inferior so it can use it to
973 // communicate back with this process
974 launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);
975 }
976
977 // use native registers, not the GDB registers
978 debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));
979
980 if (launch_info.GetLaunchInSeparateProcessGroup()) {
981 debugserver_args.AppendArgument(llvm::StringRef("--setsid"));
982 }
983
984 llvm::SmallString<128> named_pipe_path;
985 // socket_pipe is used by debug server to communicate back either
986 // TCP port or domain socket name which it listens on.
987 // The second purpose of the pipe to serve as a synchronization point -
988 // once data is written to the pipe, debug server is up and running.
989 Pipe socket_pipe;
990
991 // port is null when debug server should listen on domain socket - we're
992 // not interested in port value but rather waiting for debug server to
993 // become available.
994 if (pass_comm_fd == -1) {
995 if (url) {
996// Create a temporary file to get the stdout/stderr and redirect the output of
997// the command into this file. We will later read this file if all goes well
998// and fill the data into "command_output_ptr"
999#if defined(__APPLE__)
1000 // Binding to port zero, we need to figure out what port it ends up
1001 // using using a named pipe...
1002 error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",
1003 false, named_pipe_path);
1004 if (error.Fail()) {
1005 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "named pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1006 "GDBRemoteCommunication::%s() "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "named pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1007 "named pipe creation failed: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "named pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1008 __FUNCTION__, error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "named pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
;
1009 return error;
1010 }
1011 debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));
1012 debugserver_args.AppendArgument(named_pipe_path);
1013#else
1014 // Binding to port zero, we need to figure out what port it ends up
1015 // using using an unnamed pipe...
1016 error = socket_pipe.CreateNew(true);
1017 if (error.Fail()) {
1018 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "unnamed pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1019 "GDBRemoteCommunication::%s() "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "unnamed pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1020 "unnamed pipe creation failed: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "unnamed pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1021 __FUNCTION__, error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "unnamed pipe creation failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
;
1022 return error;
1023 }
1024 pipe_t write = socket_pipe.GetWritePipe();
1025 debugserver_args.AppendArgument(llvm::StringRef("--pipe"));
1026 debugserver_args.AppendArgument(llvm::to_string(write));
1027 launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());
1028#endif
1029 } else {
1030 // No host and port given, so lets listen on our end and make the
1031 // debugserver connect to us..
1032 error = StartListenThread("127.0.0.1", 0);
1033 if (error.Fail()) {
1034 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() unable to start listen "
"thread: %s", __FUNCTION__, error.AsCString()); } while (0)
1035 "GDBRemoteCommunication::%s() unable to start listen "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() unable to start listen "
"thread: %s", __FUNCTION__, error.AsCString()); } while (0)
1036 "thread: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() unable to start listen "
"thread: %s", __FUNCTION__, error.AsCString()); } while (0)
1037 __FUNCTION__, error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() unable to start listen "
"thread: %s", __FUNCTION__, error.AsCString()); } while (0)
;
1038 return error;
1039 }
1040
1041 // Wait for 10 seconds to resolve the bound port
1042 std::future<uint16_t> port_future = m_port_promise.get_future();
1043 uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==
1044 std::future_status::ready
1045 ? port_future.get()
1046 : 0;
1047 if (port_ > 0) {
1048 char port_cstr[32];
1049 snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);
1050 // Send the host and port down that debugserver and specify an option
1051 // so that it connects back to the port we are listening to in this
1052 // process
1053 debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));
1054 debugserver_args.AppendArgument(llvm::StringRef(port_cstr));
1055 if (port)
1056 *port = port_;
1057 } else {
1058 error.SetErrorString("failed to bind to port 0 on 127.0.0.1");
1059 LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1060 __FUNCTION__, error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
;
1061 return error;
1062 }
1063 }
1064 }
1065 std::string env_debugserver_log_file =
1066 host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");
1067 if (!env_debugserver_log_file.empty()) {
1068 debugserver_args.AppendArgument(
1069 llvm::formatv("--log-file={0}", env_debugserver_log_file).str());
1070 }
1071
1072#if defined(__APPLE__)
1073 const char *env_debugserver_log_flags =
1074 getenv("LLDB_DEBUGSERVER_LOG_FLAGS");
1075 if (env_debugserver_log_flags) {
1076 debugserver_args.AppendArgument(
1077 llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());
1078 }
1079#else
1080 std::string env_debugserver_log_channels =
1081 host_env.lookup("LLDB_SERVER_LOG_CHANNELS");
1082 if (!env_debugserver_log_channels.empty()) {
1083 debugserver_args.AppendArgument(
1084 llvm::formatv("--log-channels={0}", env_debugserver_log_channels)
1085 .str());
1086 }
1087#endif
1088
1089 // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an
1090 // env var doesn't come back.
1091 uint32_t env_var_index = 1;
1092 bool has_env_var;
1093 do {
1094 char env_var_name[64];
1095 snprintf(env_var_name, sizeof(env_var_name),
1096 "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32"u", env_var_index++);
1097 std::string extra_arg = host_env.lookup(env_var_name);
1098 has_env_var = !extra_arg.empty();
1099
1100 if (has_env_var) {
1101 debugserver_args.AppendArgument(llvm::StringRef(extra_arg));
1102 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s adding env var %s contents "
"to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg
.c_str()); } while (0)
1103 "GDBRemoteCommunication::%s adding env var %s contents "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s adding env var %s contents "
"to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg
.c_str()); } while (0)
1104 "to stub command line (%s)",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s adding env var %s contents "
"to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg
.c_str()); } while (0)
1105 __FUNCTION__, env_var_name, extra_arg.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s adding env var %s contents "
"to stub command line (%s)", __FUNCTION__, env_var_name, extra_arg
.c_str()); } while (0)
;
1106 }
1107 } while (has_env_var);
1108
1109 if (inferior_args && inferior_args->GetArgumentCount() > 0) {
1110 debugserver_args.AppendArgument(llvm::StringRef("--"));
1111 debugserver_args.AppendArguments(*inferior_args);
1112 }
1113
1114 // Copy the current environment to the gdbserver/debugserver instance
1115 launch_info.GetEnvironment() = host_env;
1116
1117 // Close STDIN, STDOUT and STDERR.
1118 launch_info.AppendCloseFileAction(STDIN_FILENO0);
1119 launch_info.AppendCloseFileAction(STDOUT_FILENO1);
1120 launch_info.AppendCloseFileAction(STDERR_FILENO2);
1121
1122 // Redirect STDIN, STDOUT and STDERR to "/dev/null".
1123 launch_info.AppendSuppressFileAction(STDIN_FILENO0, true, false);
1124 launch_info.AppendSuppressFileAction(STDOUT_FILENO1, false, true);
1125 launch_info.AppendSuppressFileAction(STDERR_FILENO2, false, true);
1126
1127 if (log) {
1128 StreamString string_stream;
1129 Platform *const platform = nullptr;
1130 launch_info.Dump(string_stream, platform);
1131 LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("launch info for gdb-remote stub:\n%s"
, string_stream.GetData()); } while (0)
1132 string_stream.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("launch info for gdb-remote stub:\n%s"
, string_stream.GetData()); } while (0)
;
1133 }
1134 error = Host::LaunchProcess(launch_info);
1135
1136 if (error.Success() &&
1137 (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID0) &&
1138 pass_comm_fd == -1) {
1139 if (named_pipe_path.size() > 0) {
1140 error = socket_pipe.OpenAsReader(named_pipe_path, false);
1141 if (error.Fail())
1142 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to open named pipe %s for reading: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
1143 "GDBRemoteCommunication::%s() "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to open named pipe %s for reading: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
1144 "failed to open named pipe %s for reading: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to open named pipe %s for reading: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
1145 __FUNCTION__, named_pipe_path.c_str(), error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to open named pipe %s for reading: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
;
1146 }
1147
1148 if (socket_pipe.CanWrite())
1149 socket_pipe.CloseWriteFileDescriptor();
1150 if (socket_pipe.CanRead()) {
1151 char port_cstr[PATH_MAX4096] = {0};
1152 port_cstr[0] = '\0';
1153 size_t num_bytes = sizeof(port_cstr);
1154 // Read port from pipe with 10 second timeout.
1155 error = socket_pipe.ReadWithTimeout(
1156 port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);
1157 if (error.Success() && (port != nullptr)) {
1158 assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0')(static_cast <bool> (num_bytes > 0 && port_cstr
[num_bytes - 1] == '\0') ? void (0) : __assert_fail ("num_bytes > 0 && port_cstr[num_bytes - 1] == '\\0'"
, "lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp"
, 1158, __extension__ __PRETTY_FUNCTION__))
;
1159 uint16_t child_port = 0;
1160 // FIXME: improve error handling
1161 llvm::to_integer(port_cstr, child_port);
1162 if (*port == 0 || *port == child_port) {
1163 *port = child_port;
1164 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listens %u port"
, __FUNCTION__, *port); } while (0)
1165 "GDBRemoteCommunication::%s() "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listens %u port"
, __FUNCTION__, *port); } while (0)
1166 "debugserver listens %u port",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listens %u port"
, __FUNCTION__, *port); } while (0)
1167 __FUNCTION__, *port)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listens %u port"
, __FUNCTION__, *port); } while (0)
;
1168 } else {
1169 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listening on port "
"%d but requested port was %d", __FUNCTION__, (uint32_t)child_port
, (uint32_t)(*port)); } while (0)
1170 "GDBRemoteCommunication::%s() "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listening on port "
"%d but requested port was %d", __FUNCTION__, (uint32_t)child_port
, (uint32_t)(*port)); } while (0)
1171 "debugserver listening on port "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listening on port "
"%d but requested port was %d", __FUNCTION__, (uint32_t)child_port
, (uint32_t)(*port)); } while (0)
1172 "%d but requested port was %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listening on port "
"%d but requested port was %d", __FUNCTION__, (uint32_t)child_port
, (uint32_t)(*port)); } while (0)
1173 __FUNCTION__, (uint32_t)child_port, (uint32_t)(*port))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "debugserver listening on port "
"%d but requested port was %d", __FUNCTION__, (uint32_t)child_port
, (uint32_t)(*port)); } while (0)
;
1174 }
1175 } else {
1176 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to read a port value from pipe %s: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
1177 "GDBRemoteCommunication::%s() "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to read a port value from pipe %s: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
1178 "failed to read a port value from pipe %s: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to read a port value from pipe %s: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
1179 __FUNCTION__, named_pipe_path.c_str(), error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() " "failed to read a port value from pipe %s: %s"
, __FUNCTION__, named_pipe_path.c_str(), error.AsCString()); }
while (0)
;
1180 }
1181 socket_pipe.Close();
1182 }
1183
1184 if (named_pipe_path.size() > 0) {
1185 const auto err = socket_pipe.Delete(named_pipe_path);
1186 if (err.Fail()) {
1187 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s failed to delete pipe %s: %s"
, __FUNCTION__, named_pipe_path.c_str(), err.AsCString()); } while
(0)
1188 "GDBRemoteCommunication::%s failed to delete pipe %s: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s failed to delete pipe %s: %s"
, __FUNCTION__, named_pipe_path.c_str(), err.AsCString()); } while
(0)
1189 __FUNCTION__, named_pipe_path.c_str(), err.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s failed to delete pipe %s: %s"
, __FUNCTION__, named_pipe_path.c_str(), err.AsCString()); } while
(0)
;
1190 }
1191 }
1192
1193 // Make sure we actually connect with the debugserver...
1194 JoinListenThread();
1195 }
1196 } else {
1197 error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME"lldb-server-" "17.0.0");
1198 }
1199
1200 if (error.Fail()) {
1201 LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
1202 error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunication::%s() failed: %s"
, __FUNCTION__, error.AsCString()); } while (0)
;
1203 }
1204
1205 return error;
1206}
1207
1208void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }
1209
1210llvm::Error
1211GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,
1212 GDBRemoteCommunication &server) {
1213 const bool child_processes_inherit = false;
1214 const int backlog = 5;
1215 TCPSocket listen_socket(true, child_processes_inherit);
1216 if (llvm::Error error =
1217 listen_socket.Listen("localhost:0", backlog).ToError())
1218 return error;
1219
1220 Socket *accept_socket = nullptr;
1221 std::future<Status> accept_status = std::async(
1222 std::launch::async, [&] { return listen_socket.Accept(accept_socket); });
1223
1224 llvm::SmallString<32> remote_addr;
1225 llvm::raw_svector_ostream(remote_addr)
1226 << "connect://localhost:" << listen_socket.GetLocalPortNumber();
1227
1228 std::unique_ptr<ConnectionFileDescriptor> conn_up(
1229 new ConnectionFileDescriptor());
1230 Status status;
1231 if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)
1232 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1233 "Unable to connect: %s", status.AsCString());
1234
1235 client.SetConnection(std::move(conn_up));
1236 if (llvm::Error error = accept_status.get().ToError())
1237 return error;
1238
1239 server.SetConnection(
1240 std::make_unique<ConnectionFileDescriptor>(accept_socket));
1241 return llvm::Error::success();
1242}
1243
1244GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(
1245 GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)
1246 : m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {
1247 auto curr_timeout = gdb_comm.GetPacketTimeout();
1248 // Only update the timeout if the timeout is greater than the current
1249 // timeout. If the current timeout is larger, then just use that.
1250 if (curr_timeout < timeout) {
1251 m_timeout_modified = true;
1252 m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);
1253 }
1254}
1255
1256GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {
1257 // Only restore the timeout if we set it in the constructor.
1258 if (m_timeout_modified)
1259 m_gdb_comm.SetPacketTimeout(m_saved_timeout);
1260}
1261
1262void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(
1263 const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,
1264 StringRef Style) {
1265 using PacketResult = GDBRemoteCommunication::PacketResult;
1266
1267 switch (result) {
1268 case PacketResult::Success:
1269 Stream << "Success";
1270 break;
1271 case PacketResult::ErrorSendFailed:
1272 Stream << "ErrorSendFailed";
1273 break;
1274 case PacketResult::ErrorSendAck:
1275 Stream << "ErrorSendAck";
1276 break;
1277 case PacketResult::ErrorReplyFailed:
1278 Stream << "ErrorReplyFailed";
1279 break;
1280 case PacketResult::ErrorReplyTimeout:
1281 Stream << "ErrorReplyTimeout";
1282 break;
1283 case PacketResult::ErrorReplyInvalid:
1284 Stream << "ErrorReplyInvalid";
1285 break;
1286 case PacketResult::ErrorReplyAck:
1287 Stream << "ErrorReplyAck";
1288 break;
1289 case PacketResult::ErrorDisconnected:
1290 Stream << "ErrorDisconnected";
1291 break;
1292 case PacketResult::ErrorNoSequenceLock:
1293 Stream << "ErrorNoSequenceLock";
1294 break;
1295 }
1296}
1297
1298std::string GDBRemoteCommunication::ExpandRLE(std::string packet) {
1299 // Reserve enough byte for the most common case (no RLE used).
1300 std::string decoded;
1301 decoded.reserve(packet.size());
1302 for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {
1303 if (*c == '*') {
1304 // '*' indicates RLE. Next character will give us the repeat count and
1305 // previous character is what is to be repeated.
1306 char char_to_repeat = decoded.back();
1307 // Number of time the previous character is repeated.
1308 int repeat_count = *++c + 3 - ' ';
1309 // We have the char_to_repeat and repeat_count. Now push it in the
1310 // packet.
1311 for (int i = 0; i < repeat_count; ++i)
1312 decoded.push_back(char_to_repeat);
1313 } else if (*c == 0x7d) {
1314 // 0x7d is the escape character. The next character is to be XOR'd with
1315 // 0x20.
1316 char escapee = *++c ^ 0x20;
1317 decoded.push_back(escapee);
1318 } else {
1319 decoded.push_back(*c);
1320 }
1321 }
1322 return decoded;
1323}