Bug Summary

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