File: | build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp |
Warning: | line 815, column 11 Value stored to 'success' is never read |
Press '?' to see keyboard shortcuts
Keyboard shortcuts:
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-" "15.0.0" "debugserver" |
43 | #elif defined(_WIN32) |
44 | #define DEBUGSERVER_BASENAME"lldb-server-" "15.0.0" "lldb-server.exe" |
45 | #else |
46 | # define DEBUGSERVER_BASENAME"lldb-server-" "15.0.0" "lldb-server-" LLVM_VERSION_STRING"15.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 | |
57 | using namespace lldb; |
58 | using namespace lldb_private; |
59 | using namespace lldb_private::process_gdb_remote; |
60 | |
61 | // GDBRemoteCommunication constructor |
62 | GDBRemoteCommunication::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 |
76 | GDBRemoteCommunication::~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 | |
87 | char 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 | |
96 | size_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 | |
106 | size_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 | |
116 | GDBRemoteCommunication::PacketResult |
117 | GDBRemoteCommunication::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 | |
128 | GDBRemoteCommunication::PacketResult |
129 | GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet, |
130 | bool skip_ack) { |
131 | if (IsConnected()) { |
132 | Log *log = GetLog(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 | |
190 | GDBRemoteCommunication::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 | |
203 | GDBRemoteCommunication::PacketResult |
204 | GDBRemoteCommunication::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 | |
220 | GDBRemoteCommunication::PacketResult |
221 | GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response, |
222 | Timeout<std::micro> timeout, |
223 | bool sync_on_timeout) { |
224 | using ResponseType = StringExtractorGDBRemote::ResponseType; |
225 | |
226 | Log *log = GetLog(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 | |
238 | GDBRemoteCommunication::PacketResult |
239 | GDBRemoteCommunication::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 = GetLog(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 | |
385 | bool GDBRemoteCommunication::DecompressPacket() { |
386 | Log *log = GetLog(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_ZLIB1 |
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_NULL0; |
571 | stream.zfree = Z_NULL0; |
572 | stream.opaque = Z_NULL0; |
573 | |
574 | if (inflateInit2(&stream, -15)inflateInit2_((&stream), (-15), "1.2.11", (int)sizeof(z_stream )) == Z_OK0) { |
575 | int status = inflate(&stream, Z_NO_FLUSH0); |
576 | inflateEnd(&stream); |
577 | if (status == Z_STREAM_END1) { |
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 | |
614 | GDBRemoteCommunication::PacketType |
615 | GDBRemoteCommunication::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 = GetLog(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 | |
834 | Status 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, [this] { return GDBRemoteCommunication::ListenThread(); }); |
848 | if (!listen_thread) |
849 | return Status(listen_thread.takeError()); |
850 | m_listen_thread = *listen_thread; |
851 | |
852 | return Status(); |
853 | } |
854 | |
855 | bool GDBRemoteCommunication::JoinListenThread() { |
856 | if (m_listen_thread.IsJoinable()) |
857 | m_listen_thread.Join(nullptr); |
858 | return true; |
859 | } |
860 | |
861 | lldb::thread_result_t GDBRemoteCommunication::ListenThread() { |
862 | Status error; |
863 | ConnectionFileDescriptor *connection = |
864 | (ConnectionFileDescriptor *)GetConnection(); |
865 | |
866 | if (connection) { |
867 | // Do the listen on another thread so we can continue on... |
868 | if (connection->Connect( |
869 | m_listen_url.c_str(), |
870 | [this](llvm::StringRef port_str) { |
871 | uint16_t port = 0; |
872 | llvm::to_integer(port_str, port, 10); |
873 | m_port_promise.set_value(port); |
874 | }, |
875 | &error) != eConnectionStatusSuccess) |
876 | SetConnection(nullptr); |
877 | } |
878 | return {}; |
879 | } |
880 | |
881 | Status GDBRemoteCommunication::StartDebugserverProcess( |
882 | const char *url, Platform *platform, ProcessLaunchInfo &launch_info, |
883 | uint16_t *port, const Args *inferior_args, int pass_comm_fd) { |
884 | Log *log = GetLog(GDBRLog::Process); |
885 | 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) |
886 | __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); |
887 | |
888 | Status error; |
889 | // If we locate debugserver, keep that located version around |
890 | static FileSpec g_debugserver_file_spec; |
891 | |
892 | char debugserver_path[PATH_MAX4096]; |
893 | FileSpec &debugserver_file_spec = launch_info.GetExecutableFile(); |
894 | |
895 | Environment host_env = Host::GetEnvironment(); |
896 | |
897 | // Always check to see if we have an environment override for the path to the |
898 | // debugserver to use and use it if we do. |
899 | std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH"); |
900 | if (!env_debugserver_path.empty()) { |
901 | debugserver_file_spec.SetFile(env_debugserver_path, |
902 | FileSpec::Style::native); |
903 | 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) |
904 | "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) |
905 | "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) |
906 | __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); |
907 | } else |
908 | debugserver_file_spec = g_debugserver_file_spec; |
909 | bool debugserver_exists = |
910 | FileSystem::Instance().Exists(debugserver_file_spec); |
911 | if (!debugserver_exists) { |
912 | // The debugserver binary is in the LLDB.framework/Resources directory. |
913 | debugserver_file_spec = HostInfo::GetSupportExeDir(); |
914 | if (debugserver_file_spec) { |
915 | debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME"lldb-server-" "15.0.0"); |
916 | debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec); |
917 | if (debugserver_exists) { |
918 | 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) |
919 | "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) |
920 | __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); |
921 | |
922 | g_debugserver_file_spec = debugserver_file_spec; |
923 | } else { |
924 | if (platform) |
925 | debugserver_file_spec = |
926 | platform->LocateExecutable(DEBUGSERVER_BASENAME"lldb-server-" "15.0.0"); |
927 | else |
928 | debugserver_file_spec.Clear(); |
929 | if (debugserver_file_spec) { |
930 | // Platform::LocateExecutable() wouldn't return a path if it doesn't |
931 | // exist |
932 | debugserver_exists = true; |
933 | } else { |
934 | 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) |
935 | "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) |
936 | "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) |
937 | __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); |
938 | } |
939 | // Don't cache the platform specific GDB server binary as it could |
940 | // change from platform to platform |
941 | g_debugserver_file_spec.Clear(); |
942 | } |
943 | } |
944 | } |
945 | |
946 | if (debugserver_exists) { |
947 | debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path)); |
948 | |
949 | Args &debugserver_args = launch_info.GetArguments(); |
950 | debugserver_args.Clear(); |
951 | |
952 | // Start args with "debugserver /file/path -r --" |
953 | debugserver_args.AppendArgument(llvm::StringRef(debugserver_path)); |
954 | |
955 | #if !defined(__APPLE__) |
956 | // First argument to lldb-server must be mode in which to run. |
957 | debugserver_args.AppendArgument(llvm::StringRef("gdbserver")); |
958 | #endif |
959 | |
960 | // If a url is supplied then use it |
961 | if (url) |
962 | debugserver_args.AppendArgument(llvm::StringRef(url)); |
963 | |
964 | if (pass_comm_fd >= 0) { |
965 | StreamString fd_arg; |
966 | fd_arg.Printf("--fd=%i", pass_comm_fd); |
967 | debugserver_args.AppendArgument(fd_arg.GetString()); |
968 | // Send "pass_comm_fd" down to the inferior so it can use it to |
969 | // communicate back with this process |
970 | launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd); |
971 | } |
972 | |
973 | // use native registers, not the GDB registers |
974 | debugserver_args.AppendArgument(llvm::StringRef("--native-regs")); |
975 | |
976 | if (launch_info.GetLaunchInSeparateProcessGroup()) { |
977 | debugserver_args.AppendArgument(llvm::StringRef("--setsid")); |
978 | } |
979 | |
980 | llvm::SmallString<128> named_pipe_path; |
981 | // socket_pipe is used by debug server to communicate back either |
982 | // TCP port or domain socket name which it listens on. |
983 | // The second purpose of the pipe to serve as a synchronization point - |
984 | // once data is written to the pipe, debug server is up and running. |
985 | Pipe socket_pipe; |
986 | |
987 | // port is null when debug server should listen on domain socket - we're |
988 | // not interested in port value but rather waiting for debug server to |
989 | // become available. |
990 | if (pass_comm_fd == -1) { |
991 | if (url) { |
992 | // Create a temporary file to get the stdout/stderr and redirect the output of |
993 | // the command into this file. We will later read this file if all goes well |
994 | // and fill the data into "command_output_ptr" |
995 | #if defined(__APPLE__) |
996 | // Binding to port zero, we need to figure out what port it ends up |
997 | // using using a named pipe... |
998 | error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe", |
999 | false, named_pipe_path); |
1000 | if (error.Fail()) { |
1001 | 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) |
1002 | "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) |
1003 | "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) |
1004 | __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); |
1005 | return error; |
1006 | } |
1007 | debugserver_args.AppendArgument(llvm::StringRef("--named-pipe")); |
1008 | debugserver_args.AppendArgument(named_pipe_path); |
1009 | #else |
1010 | // Binding to port zero, we need to figure out what port it ends up |
1011 | // using using an unnamed pipe... |
1012 | error = socket_pipe.CreateNew(true); |
1013 | if (error.Fail()) { |
1014 | 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) |
1015 | "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) |
1016 | "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) |
1017 | __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); |
1018 | return error; |
1019 | } |
1020 | pipe_t write = socket_pipe.GetWritePipe(); |
1021 | debugserver_args.AppendArgument(llvm::StringRef("--pipe")); |
1022 | debugserver_args.AppendArgument(llvm::to_string(write)); |
1023 | launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor()); |
1024 | #endif |
1025 | } else { |
1026 | // No host and port given, so lets listen on our end and make the |
1027 | // debugserver connect to us.. |
1028 | error = StartListenThread("127.0.0.1", 0); |
1029 | if (error.Fail()) { |
1030 | 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) |
1031 | "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) |
1032 | "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) |
1033 | __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); |
1034 | return error; |
1035 | } |
1036 | |
1037 | // Wait for 10 seconds to resolve the bound port |
1038 | std::future<uint16_t> port_future = m_port_promise.get_future(); |
1039 | uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) == |
1040 | std::future_status::ready |
1041 | ? port_future.get() |
1042 | : 0; |
1043 | if (port_ > 0) { |
1044 | char port_cstr[32]; |
1045 | snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_); |
1046 | // Send the host and port down that debugserver and specify an option |
1047 | // so that it connects back to the port we are listening to in this |
1048 | // process |
1049 | debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect")); |
1050 | debugserver_args.AppendArgument(llvm::StringRef(port_cstr)); |
1051 | if (port) |
1052 | *port = port_; |
1053 | } else { |
1054 | error.SetErrorString("failed to bind to port 0 on 127.0.0.1"); |
1055 | 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) |
1056 | __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); |
1057 | return error; |
1058 | } |
1059 | } |
1060 | } |
1061 | std::string env_debugserver_log_file = |
1062 | host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE"); |
1063 | if (!env_debugserver_log_file.empty()) { |
1064 | debugserver_args.AppendArgument( |
1065 | llvm::formatv("--log-file={0}", env_debugserver_log_file).str()); |
1066 | } |
1067 | |
1068 | #if defined(__APPLE__) |
1069 | const char *env_debugserver_log_flags = |
1070 | getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); |
1071 | if (env_debugserver_log_flags) { |
1072 | debugserver_args.AppendArgument( |
1073 | llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str()); |
1074 | } |
1075 | #else |
1076 | std::string env_debugserver_log_channels = |
1077 | host_env.lookup("LLDB_SERVER_LOG_CHANNELS"); |
1078 | if (!env_debugserver_log_channels.empty()) { |
1079 | debugserver_args.AppendArgument( |
1080 | llvm::formatv("--log-channels={0}", env_debugserver_log_channels) |
1081 | .str()); |
1082 | } |
1083 | #endif |
1084 | |
1085 | // Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an |
1086 | // env var doesn't come back. |
1087 | uint32_t env_var_index = 1; |
1088 | bool has_env_var; |
1089 | do { |
1090 | char env_var_name[64]; |
1091 | snprintf(env_var_name, sizeof(env_var_name), |
1092 | "LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32"u", env_var_index++); |
1093 | std::string extra_arg = host_env.lookup(env_var_name); |
1094 | has_env_var = !extra_arg.empty(); |
1095 | |
1096 | if (has_env_var) { |
1097 | debugserver_args.AppendArgument(llvm::StringRef(extra_arg)); |
1098 | 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) |
1099 | "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) |
1100 | "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) |
1101 | __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); |
1102 | } |
1103 | } while (has_env_var); |
1104 | |
1105 | if (inferior_args && inferior_args->GetArgumentCount() > 0) { |
1106 | debugserver_args.AppendArgument(llvm::StringRef("--")); |
1107 | debugserver_args.AppendArguments(*inferior_args); |
1108 | } |
1109 | |
1110 | // Copy the current environment to the gdbserver/debugserver instance |
1111 | launch_info.GetEnvironment() = host_env; |
1112 | |
1113 | // Close STDIN, STDOUT and STDERR. |
1114 | launch_info.AppendCloseFileAction(STDIN_FILENO0); |
1115 | launch_info.AppendCloseFileAction(STDOUT_FILENO1); |
1116 | launch_info.AppendCloseFileAction(STDERR_FILENO2); |
1117 | |
1118 | // Redirect STDIN, STDOUT and STDERR to "/dev/null". |
1119 | launch_info.AppendSuppressFileAction(STDIN_FILENO0, true, false); |
1120 | launch_info.AppendSuppressFileAction(STDOUT_FILENO1, false, true); |
1121 | launch_info.AppendSuppressFileAction(STDERR_FILENO2, false, true); |
1122 | |
1123 | if (log) { |
1124 | StreamString string_stream; |
1125 | Platform *const platform = nullptr; |
1126 | launch_info.Dump(string_stream, platform); |
1127 | 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) |
1128 | 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); |
1129 | } |
1130 | error = Host::LaunchProcess(launch_info); |
1131 | |
1132 | if (error.Success() && |
1133 | (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID0) && |
1134 | pass_comm_fd == -1) { |
1135 | if (named_pipe_path.size() > 0) { |
1136 | error = socket_pipe.OpenAsReader(named_pipe_path, false); |
1137 | if (error.Fail()) |
1138 | 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) |
1139 | "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) |
1140 | "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) |
1141 | __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); |
1142 | } |
1143 | |
1144 | if (socket_pipe.CanWrite()) |
1145 | socket_pipe.CloseWriteFileDescriptor(); |
1146 | if (socket_pipe.CanRead()) { |
1147 | char port_cstr[PATH_MAX4096] = {0}; |
1148 | port_cstr[0] = '\0'; |
1149 | size_t num_bytes = sizeof(port_cstr); |
1150 | // Read port from pipe with 10 second timeout. |
1151 | error = socket_pipe.ReadWithTimeout( |
1152 | port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes); |
1153 | if (error.Success() && (port != nullptr)) { |
1154 | 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" , 1154, __extension__ __PRETTY_FUNCTION__)); |
1155 | uint16_t child_port = 0; |
1156 | // FIXME: improve error handling |
1157 | llvm::to_integer(port_cstr, child_port); |
1158 | if (*port == 0 || *port == child_port) { |
1159 | *port = child_port; |
1160 | 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) |
1161 | "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) |
1162 | "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) |
1163 | __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); |
1164 | } else { |
1165 | 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) |
1166 | "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) |
1167 | "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) |
1168 | "%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) |
1169 | __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); |
1170 | } |
1171 | } else { |
1172 | 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) |
1173 | "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) |
1174 | "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) |
1175 | __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); |
1176 | } |
1177 | socket_pipe.Close(); |
1178 | } |
1179 | |
1180 | if (named_pipe_path.size() > 0) { |
1181 | const auto err = socket_pipe.Delete(named_pipe_path); |
1182 | if (err.Fail()) { |
1183 | 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) |
1184 | "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) |
1185 | __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); |
1186 | } |
1187 | } |
1188 | |
1189 | // Make sure we actually connect with the debugserver... |
1190 | JoinListenThread(); |
1191 | } |
1192 | } else { |
1193 | error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME"lldb-server-" "15.0.0"); |
1194 | } |
1195 | |
1196 | if (error.Fail()) { |
1197 | 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) |
1198 | error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private ) log_private->Printf("GDBRemoteCommunication::%s() failed: %s" , __FUNCTION__, error.AsCString()); } while (0); |
1199 | } |
1200 | |
1201 | return error; |
1202 | } |
1203 | |
1204 | void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); } |
1205 | |
1206 | void GDBRemoteCommunication::SetPacketRecorder( |
1207 | repro::PacketRecorder *recorder) { |
1208 | m_history.SetRecorder(recorder); |
1209 | } |
1210 | |
1211 | llvm::Error |
1212 | GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client, |
1213 | GDBRemoteCommunication &server) { |
1214 | const bool child_processes_inherit = false; |
1215 | const int backlog = 5; |
1216 | TCPSocket listen_socket(true, child_processes_inherit); |
1217 | if (llvm::Error error = |
1218 | listen_socket.Listen("localhost:0", backlog).ToError()) |
1219 | return error; |
1220 | |
1221 | Socket *accept_socket; |
1222 | std::future<Status> accept_status = std::async( |
1223 | std::launch::async, [&] { return listen_socket.Accept(accept_socket); }); |
1224 | |
1225 | llvm::SmallString<32> remote_addr; |
1226 | llvm::raw_svector_ostream(remote_addr) |
1227 | << "connect://localhost:" << listen_socket.GetLocalPortNumber(); |
1228 | |
1229 | std::unique_ptr<ConnectionFileDescriptor> conn_up( |
1230 | new ConnectionFileDescriptor()); |
1231 | Status status; |
1232 | if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess) |
1233 | return llvm::createStringError(llvm::inconvertibleErrorCode(), |
1234 | "Unable to connect: %s", status.AsCString()); |
1235 | |
1236 | client.SetConnection(std::move(conn_up)); |
1237 | if (llvm::Error error = accept_status.get().ToError()) |
1238 | return error; |
1239 | |
1240 | server.SetConnection( |
1241 | std::make_unique<ConnectionFileDescriptor>(accept_socket)); |
1242 | return llvm::Error::success(); |
1243 | } |
1244 | |
1245 | GDBRemoteCommunication::ScopedTimeout::ScopedTimeout( |
1246 | GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout) |
1247 | : m_gdb_comm(gdb_comm), m_timeout_modified(false) { |
1248 | auto curr_timeout = gdb_comm.GetPacketTimeout(); |
1249 | // Only update the timeout if the timeout is greater than the current |
1250 | // timeout. If the current timeout is larger, then just use that. |
1251 | if (curr_timeout < timeout) { |
1252 | m_timeout_modified = true; |
1253 | m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout); |
1254 | } |
1255 | } |
1256 | |
1257 | GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() { |
1258 | // Only restore the timeout if we set it in the constructor. |
1259 | if (m_timeout_modified) |
1260 | m_gdb_comm.SetPacketTimeout(m_saved_timeout); |
1261 | } |
1262 | |
1263 | void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format( |
1264 | const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream, |
1265 | StringRef Style) { |
1266 | using PacketResult = GDBRemoteCommunication::PacketResult; |
1267 | |
1268 | switch (result) { |
1269 | case PacketResult::Success: |
1270 | Stream << "Success"; |
1271 | break; |
1272 | case PacketResult::ErrorSendFailed: |
1273 | Stream << "ErrorSendFailed"; |
1274 | break; |
1275 | case PacketResult::ErrorSendAck: |
1276 | Stream << "ErrorSendAck"; |
1277 | break; |
1278 | case PacketResult::ErrorReplyFailed: |
1279 | Stream << "ErrorReplyFailed"; |
1280 | break; |
1281 | case PacketResult::ErrorReplyTimeout: |
1282 | Stream << "ErrorReplyTimeout"; |
1283 | break; |
1284 | case PacketResult::ErrorReplyInvalid: |
1285 | Stream << "ErrorReplyInvalid"; |
1286 | break; |
1287 | case PacketResult::ErrorReplyAck: |
1288 | Stream << "ErrorReplyAck"; |
1289 | break; |
1290 | case PacketResult::ErrorDisconnected: |
1291 | Stream << "ErrorDisconnected"; |
1292 | break; |
1293 | case PacketResult::ErrorNoSequenceLock: |
1294 | Stream << "ErrorNoSequenceLock"; |
1295 | break; |
1296 | } |
1297 | } |
1298 | |
1299 | std::string GDBRemoteCommunication::ExpandRLE(std::string packet) { |
1300 | // Reserve enough byte for the most common case (no RLE used). |
1301 | std::string decoded; |
1302 | decoded.reserve(packet.size()); |
1303 | for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) { |
1304 | if (*c == '*') { |
1305 | // '*' indicates RLE. Next character will give us the repeat count and |
1306 | // previous character is what is to be repeated. |
1307 | char char_to_repeat = decoded.back(); |
1308 | // Number of time the previous character is repeated. |
1309 | int repeat_count = *++c + 3 - ' '; |
1310 | // We have the char_to_repeat and repeat_count. Now push it in the |
1311 | // packet. |
1312 | for (int i = 0; i < repeat_count; ++i) |
1313 | decoded.push_back(char_to_repeat); |
1314 | } else if (*c == 0x7d) { |
1315 | // 0x7d is the escape character. The next character is to be XOR'd with |
1316 | // 0x20. |
1317 | char escapee = *++c ^ 0x20; |
1318 | decoded.push_back(escapee); |
1319 | } else { |
1320 | decoded.push_back(*c); |
1321 | } |
1322 | } |
1323 | return decoded; |
1324 | } |