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