Bug Summary

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