Bug Summary

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

Annotated Source Code

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