Path: blob/main/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/GDBRemoteCommunication.cpp
39642 views
//===-- GDBRemoteCommunication.cpp ----------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "GDBRemoteCommunication.h"910#include <climits>11#include <cstring>12#include <future>13#include <sys/stat.h>1415#include "lldb/Host/Config.h"16#include "lldb/Host/ConnectionFileDescriptor.h"17#include "lldb/Host/FileSystem.h"18#include "lldb/Host/Host.h"19#include "lldb/Host/HostInfo.h"20#include "lldb/Host/Pipe.h"21#include "lldb/Host/ProcessLaunchInfo.h"22#include "lldb/Host/Socket.h"23#include "lldb/Host/ThreadLauncher.h"24#include "lldb/Host/common/TCPSocket.h"25#include "lldb/Host/posix/ConnectionFileDescriptorPosix.h"26#include "lldb/Target/Platform.h"27#include "lldb/Utility/Event.h"28#include "lldb/Utility/FileSpec.h"29#include "lldb/Utility/Log.h"30#include "lldb/Utility/RegularExpression.h"31#include "lldb/Utility/StreamString.h"32#include "llvm/ADT/SmallString.h"33#include "llvm/Support/ScopedPrinter.h"3435#include "ProcessGDBRemoteLog.h"3637#if defined(__APPLE__)38#define DEBUGSERVER_BASENAME "debugserver"39#elif defined(_WIN32)40#define DEBUGSERVER_BASENAME "lldb-server.exe"41#else42#define DEBUGSERVER_BASENAME "lldb-server"43#endif4445#if defined(HAVE_LIBCOMPRESSION)46#include <compression.h>47#endif4849#if LLVM_ENABLE_ZLIB50#include <zlib.h>51#endif5253using namespace lldb;54using namespace lldb_private;55using namespace lldb_private::process_gdb_remote;5657// GDBRemoteCommunication constructor58GDBRemoteCommunication::GDBRemoteCommunication()59: Communication(),60#ifdef LLDB_CONFIGURATION_DEBUG61m_packet_timeout(1000),62#else63m_packet_timeout(1),64#endif65m_echo_number(0), m_supports_qEcho(eLazyBoolCalculate), m_history(512),66m_send_acks(true), m_is_platform(false),67m_compression_type(CompressionType::None), m_listen_url() {68}6970// Destructor71GDBRemoteCommunication::~GDBRemoteCommunication() {72if (IsConnected()) {73Disconnect();74}7576#if defined(HAVE_LIBCOMPRESSION)77if (m_decompression_scratch)78free (m_decompression_scratch);79#endif80}8182char GDBRemoteCommunication::CalculcateChecksum(llvm::StringRef payload) {83int checksum = 0;8485for (char c : payload)86checksum += c;8788return checksum & 255;89}9091size_t GDBRemoteCommunication::SendAck() {92Log *log = GetLog(GDBRLog::Packets);93ConnectionStatus status = eConnectionStatusSuccess;94char ch = '+';95const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);96LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);97m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);98return bytes_written;99}100101size_t GDBRemoteCommunication::SendNack() {102Log *log = GetLog(GDBRLog::Packets);103ConnectionStatus status = eConnectionStatusSuccess;104char ch = '-';105const size_t bytes_written = WriteAll(&ch, 1, status, nullptr);106LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %c", (uint64_t)bytes_written, ch);107m_history.AddPacket(ch, GDBRemotePacket::ePacketTypeSend, bytes_written);108return bytes_written;109}110111GDBRemoteCommunication::PacketResult112GDBRemoteCommunication::SendPacketNoLock(llvm::StringRef payload) {113StreamString packet(0, 4, eByteOrderBig);114packet.PutChar('$');115packet.Write(payload.data(), payload.size());116packet.PutChar('#');117packet.PutHex8(CalculcateChecksum(payload));118std::string packet_str = std::string(packet.GetString());119120return SendRawPacketNoLock(packet_str);121}122123GDBRemoteCommunication::PacketResult124GDBRemoteCommunication::SendNotificationPacketNoLock(125llvm::StringRef notify_type, std::deque<std::string> &queue,126llvm::StringRef payload) {127PacketResult ret = PacketResult::Success;128129// If there are no notification in the queue, send the notification130// packet.131if (queue.empty()) {132StreamString packet(0, 4, eByteOrderBig);133packet.PutChar('%');134packet.Write(notify_type.data(), notify_type.size());135packet.PutChar(':');136packet.Write(payload.data(), payload.size());137packet.PutChar('#');138packet.PutHex8(CalculcateChecksum(payload));139ret = SendRawPacketNoLock(packet.GetString(), true);140}141142queue.push_back(payload.str());143return ret;144}145146GDBRemoteCommunication::PacketResult147GDBRemoteCommunication::SendRawPacketNoLock(llvm::StringRef packet,148bool skip_ack) {149if (IsConnected()) {150Log *log = GetLog(GDBRLog::Packets);151ConnectionStatus status = eConnectionStatusSuccess;152const char *packet_data = packet.data();153const size_t packet_length = packet.size();154size_t bytes_written = WriteAll(packet_data, packet_length, status, nullptr);155if (log) {156size_t binary_start_offset = 0;157if (strncmp(packet_data, "$vFile:pwrite:", strlen("$vFile:pwrite:")) ==1580) {159const char *first_comma = strchr(packet_data, ',');160if (first_comma) {161const char *second_comma = strchr(first_comma + 1, ',');162if (second_comma)163binary_start_offset = second_comma - packet_data + 1;164}165}166167// If logging was just enabled and we have history, then dump out what we168// have to the log so we get the historical context. The Dump() call that169// logs all of the packet will set a boolean so that we don't dump this170// more than once171if (!m_history.DidDumpToLog())172m_history.Dump(log);173174if (binary_start_offset) {175StreamString strm;176// Print non binary data header177strm.Printf("<%4" PRIu64 "> send packet: %.*s", (uint64_t)bytes_written,178(int)binary_start_offset, packet_data);179const uint8_t *p;180// Print binary data exactly as sent181for (p = (const uint8_t *)packet_data + binary_start_offset; *p != '#';182++p)183strm.Printf("\\x%2.2x", *p);184// Print the checksum185strm.Printf("%*s", (int)3, p);186log->PutString(strm.GetString());187} else188LLDB_LOGF(log, "<%4" PRIu64 "> send packet: %.*s",189(uint64_t)bytes_written, (int)packet_length, packet_data);190}191192m_history.AddPacket(packet.str(), packet_length,193GDBRemotePacket::ePacketTypeSend, bytes_written);194195if (bytes_written == packet_length) {196if (!skip_ack && GetSendAcks())197return GetAck();198else199return PacketResult::Success;200} else {201LLDB_LOGF(log, "error: failed to send packet: %.*s", (int)packet_length,202packet_data);203}204}205return PacketResult::ErrorSendFailed;206}207208GDBRemoteCommunication::PacketResult GDBRemoteCommunication::GetAck() {209StringExtractorGDBRemote packet;210PacketResult result = WaitForPacketNoLock(packet, GetPacketTimeout(), false);211if (result == PacketResult::Success) {212if (packet.GetResponseType() ==213StringExtractorGDBRemote::ResponseType::eAck)214return PacketResult::Success;215else216return PacketResult::ErrorSendAck;217}218return result;219}220221GDBRemoteCommunication::PacketResult222GDBRemoteCommunication::ReadPacket(StringExtractorGDBRemote &response,223Timeout<std::micro> timeout,224bool sync_on_timeout) {225using ResponseType = StringExtractorGDBRemote::ResponseType;226227Log *log = GetLog(GDBRLog::Packets);228for (;;) {229PacketResult result =230WaitForPacketNoLock(response, timeout, sync_on_timeout);231if (result != PacketResult::Success ||232(response.GetResponseType() != ResponseType::eAck &&233response.GetResponseType() != ResponseType::eNack))234return result;235LLDB_LOG(log, "discarding spurious `{0}` packet", response.GetStringRef());236}237}238239GDBRemoteCommunication::PacketResult240GDBRemoteCommunication::WaitForPacketNoLock(StringExtractorGDBRemote &packet,241Timeout<std::micro> timeout,242bool sync_on_timeout) {243uint8_t buffer[8192];244Status error;245246Log *log = GetLog(GDBRLog::Packets);247248// Check for a packet from our cache first without trying any reading...249if (CheckForPacket(nullptr, 0, packet) != PacketType::Invalid)250return PacketResult::Success;251252bool timed_out = false;253bool disconnected = false;254while (IsConnected() && !timed_out) {255lldb::ConnectionStatus status = eConnectionStatusNoConnection;256size_t bytes_read = Read(buffer, sizeof(buffer), timeout, status, &error);257258LLDB_LOGV(log,259"Read(buffer, sizeof(buffer), timeout = {0}, "260"status = {1}, error = {2}) => bytes_read = {3}",261timeout, Communication::ConnectionStatusAsString(status), error,262bytes_read);263264if (bytes_read > 0) {265if (CheckForPacket(buffer, bytes_read, packet) != PacketType::Invalid)266return PacketResult::Success;267} else {268switch (status) {269case eConnectionStatusTimedOut:270case eConnectionStatusInterrupted:271if (sync_on_timeout) {272/// Sync the remote GDB server and make sure we get a response that273/// corresponds to what we send.274///275/// Sends a "qEcho" packet and makes sure it gets the exact packet276/// echoed back. If the qEcho packet isn't supported, we send a qC277/// packet and make sure we get a valid thread ID back. We use the278/// "qC" packet since its response if very unique: is responds with279/// "QC%x" where %x is the thread ID of the current thread. This280/// makes the response unique enough from other packet responses to281/// ensure we are back on track.282///283/// This packet is needed after we time out sending a packet so we284/// can ensure that we are getting the response for the packet we285/// are sending. There are no sequence IDs in the GDB remote286/// protocol (there used to be, but they are not supported anymore)287/// so if you timeout sending packet "abc", you might then send288/// packet "cde" and get the response for the previous "abc" packet.289/// Many responses are "OK" or "" (unsupported) or "EXX" (error) so290/// many responses for packets can look like responses for other291/// packets. So if we timeout, we need to ensure that we can get292/// back on track. If we can't get back on track, we must293/// disconnect.294bool sync_success = false;295bool got_actual_response = false;296// We timed out, we need to sync back up with the297char echo_packet[32];298int echo_packet_len = 0;299RegularExpression response_regex;300301if (m_supports_qEcho == eLazyBoolYes) {302echo_packet_len = ::snprintf(echo_packet, sizeof(echo_packet),303"qEcho:%u", ++m_echo_number);304std::string regex_str = "^";305regex_str += echo_packet;306regex_str += "$";307response_regex = RegularExpression(regex_str);308} else {309echo_packet_len =310::snprintf(echo_packet, sizeof(echo_packet), "qC");311response_regex =312RegularExpression(llvm::StringRef("^QC[0-9A-Fa-f]+$"));313}314315PacketResult echo_packet_result =316SendPacketNoLock(llvm::StringRef(echo_packet, echo_packet_len));317if (echo_packet_result == PacketResult::Success) {318const uint32_t max_retries = 3;319uint32_t successful_responses = 0;320for (uint32_t i = 0; i < max_retries; ++i) {321StringExtractorGDBRemote echo_response;322echo_packet_result =323WaitForPacketNoLock(echo_response, timeout, false);324if (echo_packet_result == PacketResult::Success) {325++successful_responses;326if (response_regex.Execute(echo_response.GetStringRef())) {327sync_success = true;328break;329} else if (successful_responses == 1) {330// We got something else back as the first successful331// response, it probably is the response to the packet we332// actually wanted, so copy it over if this is the first333// success and continue to try to get the qEcho response334packet = echo_response;335got_actual_response = true;336}337} else if (echo_packet_result == PacketResult::ErrorReplyTimeout)338continue; // Packet timed out, continue waiting for a response339else340break; // Something else went wrong getting the packet back, we341// failed and are done trying342}343}344345// We weren't able to sync back up with the server, we must abort346// otherwise all responses might not be from the right packets...347if (sync_success) {348// We timed out, but were able to recover349if (got_actual_response) {350// We initially timed out, but we did get a response that came in351// before the successful reply to our qEcho packet, so lets say352// everything is fine...353return PacketResult::Success;354}355} else {356disconnected = true;357Disconnect();358}359}360timed_out = true;361break;362case eConnectionStatusSuccess:363// printf ("status = success but error = %s\n",364// error.AsCString("<invalid>"));365break;366367case eConnectionStatusEndOfFile:368case eConnectionStatusNoConnection:369case eConnectionStatusLostConnection:370case eConnectionStatusError:371disconnected = true;372Disconnect();373break;374}375}376}377packet.Clear();378if (disconnected)379return PacketResult::ErrorDisconnected;380if (timed_out)381return PacketResult::ErrorReplyTimeout;382else383return PacketResult::ErrorReplyFailed;384}385386bool GDBRemoteCommunication::DecompressPacket() {387Log *log = GetLog(GDBRLog::Packets);388389if (!CompressionIsEnabled())390return true;391392size_t pkt_size = m_bytes.size();393394// Smallest possible compressed packet is $N#00 - an uncompressed empty395// reply, most commonly indicating an unsupported packet. Anything less than396// 5 characters, it's definitely not a compressed packet.397if (pkt_size < 5)398return true;399400if (m_bytes[0] != '$' && m_bytes[0] != '%')401return true;402if (m_bytes[1] != 'C' && m_bytes[1] != 'N')403return true;404405size_t hash_mark_idx = m_bytes.find('#');406if (hash_mark_idx == std::string::npos)407return true;408if (hash_mark_idx + 2 >= m_bytes.size())409return true;410411if (!::isxdigit(m_bytes[hash_mark_idx + 1]) ||412!::isxdigit(m_bytes[hash_mark_idx + 2]))413return true;414415size_t content_length =416pkt_size -4175; // not counting '$', 'C' | 'N', '#', & the two hex checksum chars418size_t content_start = 2; // The first character of the419// compressed/not-compressed text of the packet420size_t checksum_idx =421hash_mark_idx +4221; // The first character of the two hex checksum characters423424// Normally size_of_first_packet == m_bytes.size() but m_bytes may contain425// multiple packets. size_of_first_packet is the size of the initial packet426// which we'll replace with the decompressed version of, leaving the rest of427// m_bytes unmodified.428size_t size_of_first_packet = hash_mark_idx + 3;429430// Compressed packets ("$C") start with a base10 number which is the size of431// the uncompressed payload, then a : and then the compressed data. e.g.432// $C1024:<binary>#00 Update content_start and content_length to only include433// the <binary> part of the packet.434435uint64_t decompressed_bufsize = ULONG_MAX;436if (m_bytes[1] == 'C') {437size_t i = content_start;438while (i < hash_mark_idx && isdigit(m_bytes[i]))439i++;440if (i < hash_mark_idx && m_bytes[i] == ':') {441i++;442content_start = i;443content_length = hash_mark_idx - content_start;444std::string bufsize_str(m_bytes.data() + 2, i - 2 - 1);445errno = 0;446decompressed_bufsize = ::strtoul(bufsize_str.c_str(), nullptr, 10);447if (errno != 0 || decompressed_bufsize == ULONG_MAX) {448m_bytes.erase(0, size_of_first_packet);449return false;450}451}452}453454if (GetSendAcks()) {455char packet_checksum_cstr[3];456packet_checksum_cstr[0] = m_bytes[checksum_idx];457packet_checksum_cstr[1] = m_bytes[checksum_idx + 1];458packet_checksum_cstr[2] = '\0';459long packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);460461long actual_checksum = CalculcateChecksum(462llvm::StringRef(m_bytes).substr(1, hash_mark_idx - 1));463bool success = packet_checksum == actual_checksum;464if (!success) {465LLDB_LOGF(log,466"error: checksum mismatch: %.*s expected 0x%2.2x, got 0x%2.2x",467(int)(pkt_size), m_bytes.c_str(), (uint8_t)packet_checksum,468(uint8_t)actual_checksum);469}470// Send the ack or nack if needed471if (!success) {472SendNack();473m_bytes.erase(0, size_of_first_packet);474return false;475} else {476SendAck();477}478}479480if (m_bytes[1] == 'N') {481// This packet was not compressed -- delete the 'N' character at the start482// and the packet may be processed as-is.483m_bytes.erase(1, 1);484return true;485}486487// Reverse the gdb-remote binary escaping that was done to the compressed488// text to guard characters like '$', '#', '}', etc.489std::vector<uint8_t> unescaped_content;490unescaped_content.reserve(content_length);491size_t i = content_start;492while (i < hash_mark_idx) {493if (m_bytes[i] == '}') {494i++;495unescaped_content.push_back(m_bytes[i] ^ 0x20);496} else {497unescaped_content.push_back(m_bytes[i]);498}499i++;500}501502uint8_t *decompressed_buffer = nullptr;503size_t decompressed_bytes = 0;504505if (decompressed_bufsize != ULONG_MAX) {506decompressed_buffer = (uint8_t *)malloc(decompressed_bufsize);507if (decompressed_buffer == nullptr) {508m_bytes.erase(0, size_of_first_packet);509return false;510}511}512513#if defined(HAVE_LIBCOMPRESSION)514if (m_compression_type == CompressionType::ZlibDeflate ||515m_compression_type == CompressionType::LZFSE ||516m_compression_type == CompressionType::LZ4 ||517m_compression_type == CompressionType::LZMA) {518compression_algorithm compression_type;519if (m_compression_type == CompressionType::LZFSE)520compression_type = COMPRESSION_LZFSE;521else if (m_compression_type == CompressionType::ZlibDeflate)522compression_type = COMPRESSION_ZLIB;523else if (m_compression_type == CompressionType::LZ4)524compression_type = COMPRESSION_LZ4_RAW;525else if (m_compression_type == CompressionType::LZMA)526compression_type = COMPRESSION_LZMA;527528if (m_decompression_scratch_type != m_compression_type) {529if (m_decompression_scratch) {530free (m_decompression_scratch);531m_decompression_scratch = nullptr;532}533size_t scratchbuf_size = 0;534if (m_compression_type == CompressionType::LZFSE)535scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZFSE);536else if (m_compression_type == CompressionType::LZ4)537scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_LZ4_RAW);538else if (m_compression_type == CompressionType::ZlibDeflate)539scratchbuf_size = compression_decode_scratch_buffer_size (COMPRESSION_ZLIB);540else if (m_compression_type == CompressionType::LZMA)541scratchbuf_size =542compression_decode_scratch_buffer_size(COMPRESSION_LZMA);543if (scratchbuf_size > 0) {544m_decompression_scratch = (void*) malloc (scratchbuf_size);545m_decompression_scratch_type = m_compression_type;546}547}548549if (decompressed_bufsize != ULONG_MAX && decompressed_buffer != nullptr) {550decompressed_bytes = compression_decode_buffer(551decompressed_buffer, decompressed_bufsize,552(uint8_t *)unescaped_content.data(), unescaped_content.size(),553m_decompression_scratch, compression_type);554}555}556#endif557558#if LLVM_ENABLE_ZLIB559if (decompressed_bytes == 0 && decompressed_bufsize != ULONG_MAX &&560decompressed_buffer != nullptr &&561m_compression_type == CompressionType::ZlibDeflate) {562z_stream stream;563memset(&stream, 0, sizeof(z_stream));564stream.next_in = (Bytef *)unescaped_content.data();565stream.avail_in = (uInt)unescaped_content.size();566stream.total_in = 0;567stream.next_out = (Bytef *)decompressed_buffer;568stream.avail_out = decompressed_bufsize;569stream.total_out = 0;570stream.zalloc = Z_NULL;571stream.zfree = Z_NULL;572stream.opaque = Z_NULL;573574if (inflateInit2(&stream, -15) == Z_OK) {575int status = inflate(&stream, Z_NO_FLUSH);576inflateEnd(&stream);577if (status == Z_STREAM_END) {578decompressed_bytes = stream.total_out;579}580}581}582#endif583584if (decompressed_bytes == 0 || decompressed_buffer == nullptr) {585if (decompressed_buffer)586free(decompressed_buffer);587m_bytes.erase(0, size_of_first_packet);588return false;589}590591std::string new_packet;592new_packet.reserve(decompressed_bytes + 6);593new_packet.push_back(m_bytes[0]);594new_packet.append((const char *)decompressed_buffer, decompressed_bytes);595new_packet.push_back('#');596if (GetSendAcks()) {597uint8_t decompressed_checksum = CalculcateChecksum(598llvm::StringRef((const char *)decompressed_buffer, decompressed_bytes));599char decompressed_checksum_str[3];600snprintf(decompressed_checksum_str, 3, "%02x", decompressed_checksum);601new_packet.append(decompressed_checksum_str);602} else {603new_packet.push_back('0');604new_packet.push_back('0');605}606607m_bytes.replace(0, size_of_first_packet, new_packet.data(),608new_packet.size());609610free(decompressed_buffer);611return true;612}613614GDBRemoteCommunication::PacketType615GDBRemoteCommunication::CheckForPacket(const uint8_t *src, size_t src_len,616StringExtractorGDBRemote &packet) {617// Put the packet data into the buffer in a thread safe fashion618std::lock_guard<std::recursive_mutex> guard(m_bytes_mutex);619620Log *log = GetLog(GDBRLog::Packets);621622if (src && src_len > 0) {623if (log && log->GetVerbose()) {624StreamString s;625LLDB_LOGF(log, "GDBRemoteCommunication::%s adding %u bytes: %.*s",626__FUNCTION__, (uint32_t)src_len, (uint32_t)src_len, src);627}628m_bytes.append((const char *)src, src_len);629}630631bool isNotifyPacket = false;632633// Parse up the packets into gdb remote packets634if (!m_bytes.empty()) {635// end_idx must be one past the last valid packet byte. Start it off with636// an invalid value that is the same as the current index.637size_t content_start = 0;638size_t content_length = 0;639size_t total_length = 0;640size_t checksum_idx = std::string::npos;641642// Size of packet before it is decompressed, for logging purposes643size_t original_packet_size = m_bytes.size();644if (CompressionIsEnabled()) {645if (!DecompressPacket()) {646packet.Clear();647return GDBRemoteCommunication::PacketType::Standard;648}649}650651switch (m_bytes[0]) {652case '+': // Look for ack653case '-': // Look for cancel654case '\x03': // ^C to halt target655content_length = total_length = 1; // The command is one byte long...656break;657658case '%': // Async notify packet659isNotifyPacket = true;660[[fallthrough]];661662case '$':663// Look for a standard gdb packet?664{665size_t hash_pos = m_bytes.find('#');666if (hash_pos != std::string::npos) {667if (hash_pos + 2 < m_bytes.size()) {668checksum_idx = hash_pos + 1;669// Skip the dollar sign670content_start = 1;671// Don't include the # in the content or the $ in the content672// length673content_length = hash_pos - 1;674675total_length =676hash_pos + 3; // Skip the # and the two hex checksum bytes677} else {678// Checksum bytes aren't all here yet679content_length = std::string::npos;680}681}682}683break;684685default: {686// We have an unexpected byte and we need to flush all bad data that is687// in m_bytes, so we need to find the first byte that is a '+' (ACK), '-'688// (NACK), \x03 (CTRL+C interrupt), or '$' character (start of packet689// header) or of course, the end of the data in m_bytes...690const size_t bytes_len = m_bytes.size();691bool done = false;692uint32_t idx;693for (idx = 1; !done && idx < bytes_len; ++idx) {694switch (m_bytes[idx]) {695case '+':696case '-':697case '\x03':698case '%':699case '$':700done = true;701break;702703default:704break;705}706}707LLDB_LOGF(log, "GDBRemoteCommunication::%s tossing %u junk bytes: '%.*s'",708__FUNCTION__, idx - 1, idx - 1, m_bytes.c_str());709m_bytes.erase(0, idx - 1);710} break;711}712713if (content_length == std::string::npos) {714packet.Clear();715return GDBRemoteCommunication::PacketType::Invalid;716} else if (total_length > 0) {717718// We have a valid packet...719assert(content_length <= m_bytes.size());720assert(total_length <= m_bytes.size());721assert(content_length <= total_length);722size_t content_end = content_start + content_length;723724bool success = true;725if (log) {726// If logging was just enabled and we have history, then dump out what727// we have to the log so we get the historical context. The Dump() call728// that logs all of the packet will set a boolean so that we don't dump729// this more than once730if (!m_history.DidDumpToLog())731m_history.Dump(log);732733bool binary = false;734// Only detect binary for packets that start with a '$' and have a735// '#CC' checksum736if (m_bytes[0] == '$' && total_length > 4) {737for (size_t i = 0; !binary && i < total_length; ++i) {738unsigned char c = m_bytes[i];739if (!llvm::isPrint(c) && !llvm::isSpace(c)) {740binary = true;741}742}743}744if (binary) {745StreamString strm;746// Packet header...747if (CompressionIsEnabled())748strm.Printf("<%4" PRIu64 ":%" PRIu64 "> read packet: %c",749(uint64_t)original_packet_size, (uint64_t)total_length,750m_bytes[0]);751else752strm.Printf("<%4" PRIu64 "> read packet: %c",753(uint64_t)total_length, m_bytes[0]);754for (size_t i = content_start; i < content_end; ++i) {755// Remove binary escaped bytes when displaying the packet...756const char ch = m_bytes[i];757if (ch == 0x7d) {758// 0x7d is the escape character. The next character is to be759// XOR'd with 0x20.760const char escapee = m_bytes[++i] ^ 0x20;761strm.Printf("%2.2x", escapee);762} else {763strm.Printf("%2.2x", (uint8_t)ch);764}765}766// Packet footer...767strm.Printf("%c%c%c", m_bytes[total_length - 3],768m_bytes[total_length - 2], m_bytes[total_length - 1]);769log->PutString(strm.GetString());770} else {771if (CompressionIsEnabled())772LLDB_LOGF(log, "<%4" PRIu64 ":%" PRIu64 "> read packet: %.*s",773(uint64_t)original_packet_size, (uint64_t)total_length,774(int)(total_length), m_bytes.c_str());775else776LLDB_LOGF(log, "<%4" PRIu64 "> read packet: %.*s",777(uint64_t)total_length, (int)(total_length),778m_bytes.c_str());779}780}781782m_history.AddPacket(m_bytes, total_length,783GDBRemotePacket::ePacketTypeRecv, total_length);784785// Copy the packet from m_bytes to packet_str expanding the run-length786// encoding in the process.787std ::string packet_str =788ExpandRLE(m_bytes.substr(content_start, content_end - content_start));789packet = StringExtractorGDBRemote(packet_str);790791if (m_bytes[0] == '$' || m_bytes[0] == '%') {792assert(checksum_idx < m_bytes.size());793if (::isxdigit(m_bytes[checksum_idx + 0]) ||794::isxdigit(m_bytes[checksum_idx + 1])) {795if (GetSendAcks()) {796const char *packet_checksum_cstr = &m_bytes[checksum_idx];797char packet_checksum = strtol(packet_checksum_cstr, nullptr, 16);798char actual_checksum = CalculcateChecksum(799llvm::StringRef(m_bytes).slice(content_start, content_end));800success = packet_checksum == actual_checksum;801if (!success) {802LLDB_LOGF(log,803"error: checksum mismatch: %.*s expected 0x%2.2x, "804"got 0x%2.2x",805(int)(total_length), m_bytes.c_str(),806(uint8_t)packet_checksum, (uint8_t)actual_checksum);807}808// Send the ack or nack if needed809if (!success)810SendNack();811else812SendAck();813}814} else {815success = false;816LLDB_LOGF(log, "error: invalid checksum in packet: '%s'\n",817m_bytes.c_str());818}819}820821m_bytes.erase(0, total_length);822packet.SetFilePos(0);823824if (isNotifyPacket)825return GDBRemoteCommunication::PacketType::Notify;826else827return GDBRemoteCommunication::PacketType::Standard;828}829}830packet.Clear();831return GDBRemoteCommunication::PacketType::Invalid;832}833834Status GDBRemoteCommunication::StartListenThread(const char *hostname,835uint16_t port) {836if (m_listen_thread.IsJoinable())837return Status("listen thread already running");838839char listen_url[512];840if (hostname && hostname[0])841snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);842else843snprintf(listen_url, sizeof(listen_url), "listen://%i", port);844m_listen_url = listen_url;845SetConnection(std::make_unique<ConnectionFileDescriptor>());846llvm::Expected<HostThread> listen_thread = ThreadLauncher::LaunchThread(847listen_url, [this] { return GDBRemoteCommunication::ListenThread(); });848if (!listen_thread)849return Status(listen_thread.takeError());850m_listen_thread = *listen_thread;851852return Status();853}854855bool GDBRemoteCommunication::JoinListenThread() {856if (m_listen_thread.IsJoinable())857m_listen_thread.Join(nullptr);858return true;859}860861lldb::thread_result_t GDBRemoteCommunication::ListenThread() {862Status error;863ConnectionFileDescriptor *connection =864(ConnectionFileDescriptor *)GetConnection();865866if (connection) {867// Do the listen on another thread so we can continue on...868if (connection->Connect(869m_listen_url.c_str(),870[this](llvm::StringRef port_str) {871uint16_t port = 0;872llvm::to_integer(port_str, port, 10);873m_port_promise.set_value(port);874},875&error) != eConnectionStatusSuccess)876SetConnection(nullptr);877}878return {};879}880881Status GDBRemoteCommunication::StartDebugserverProcess(882const char *url, Platform *platform, ProcessLaunchInfo &launch_info,883uint16_t *port, const Args *inferior_args, int pass_comm_fd) {884Log *log = GetLog(GDBRLog::Process);885LLDB_LOGF(log, "GDBRemoteCommunication::%s(url=%s, port=%" PRIu16 ")",886__FUNCTION__, url ? url : "<empty>", port ? *port : uint16_t(0));887888Status error;889// If we locate debugserver, keep that located version around890static FileSpec g_debugserver_file_spec;891892char debugserver_path[PATH_MAX];893FileSpec &debugserver_file_spec = launch_info.GetExecutableFile();894895Environment host_env = Host::GetEnvironment();896897// Always check to see if we have an environment override for the path to the898// debugserver to use and use it if we do.899std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");900if (!env_debugserver_path.empty()) {901debugserver_file_spec.SetFile(env_debugserver_path,902FileSpec::Style::native);903LLDB_LOGF(log,904"GDBRemoteCommunication::%s() gdb-remote stub exe path set "905"from environment variable: %s",906__FUNCTION__, env_debugserver_path.c_str());907} else908debugserver_file_spec = g_debugserver_file_spec;909bool debugserver_exists =910FileSystem::Instance().Exists(debugserver_file_spec);911if (!debugserver_exists) {912// The debugserver binary is in the LLDB.framework/Resources directory.913debugserver_file_spec = HostInfo::GetSupportExeDir();914if (debugserver_file_spec) {915debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);916debugserver_exists = FileSystem::Instance().Exists(debugserver_file_spec);917if (debugserver_exists) {918LLDB_LOGF(log,919"GDBRemoteCommunication::%s() found gdb-remote stub exe '%s'",920__FUNCTION__, debugserver_file_spec.GetPath().c_str());921922g_debugserver_file_spec = debugserver_file_spec;923} else {924if (platform)925debugserver_file_spec =926platform->LocateExecutable(DEBUGSERVER_BASENAME);927else928debugserver_file_spec.Clear();929if (debugserver_file_spec) {930// Platform::LocateExecutable() wouldn't return a path if it doesn't931// exist932debugserver_exists = true;933} else {934LLDB_LOGF(log,935"GDBRemoteCommunication::%s() could not find "936"gdb-remote stub exe '%s'",937__FUNCTION__, debugserver_file_spec.GetPath().c_str());938}939// Don't cache the platform specific GDB server binary as it could940// change from platform to platform941g_debugserver_file_spec.Clear();942}943}944}945946if (debugserver_exists) {947debugserver_file_spec.GetPath(debugserver_path, sizeof(debugserver_path));948949Args &debugserver_args = launch_info.GetArguments();950debugserver_args.Clear();951952// Start args with "debugserver /file/path -r --"953debugserver_args.AppendArgument(llvm::StringRef(debugserver_path));954955#if !defined(__APPLE__)956// First argument to lldb-server must be mode in which to run.957debugserver_args.AppendArgument(llvm::StringRef("gdbserver"));958#endif959960// If a url is supplied then use it961if (url)962debugserver_args.AppendArgument(llvm::StringRef(url));963964if (pass_comm_fd >= 0) {965StreamString fd_arg;966fd_arg.Printf("--fd=%i", pass_comm_fd);967debugserver_args.AppendArgument(fd_arg.GetString());968// Send "pass_comm_fd" down to the inferior so it can use it to969// communicate back with this process970launch_info.AppendDuplicateFileAction(pass_comm_fd, pass_comm_fd);971}972973// use native registers, not the GDB registers974debugserver_args.AppendArgument(llvm::StringRef("--native-regs"));975976if (launch_info.GetLaunchInSeparateProcessGroup()) {977debugserver_args.AppendArgument(llvm::StringRef("--setsid"));978}979980llvm::SmallString<128> named_pipe_path;981// socket_pipe is used by debug server to communicate back either982// TCP port or domain socket name which it listens on.983// The second purpose of the pipe to serve as a synchronization point -984// once data is written to the pipe, debug server is up and running.985Pipe socket_pipe;986987// port is null when debug server should listen on domain socket - we're988// not interested in port value but rather waiting for debug server to989// become available.990if (pass_comm_fd == -1) {991if (url) {992// Create a temporary file to get the stdout/stderr and redirect the output of993// the command into this file. We will later read this file if all goes well994// and fill the data into "command_output_ptr"995#if defined(__APPLE__)996// Binding to port zero, we need to figure out what port it ends up997// using using a named pipe...998error = socket_pipe.CreateWithUniqueName("debugserver-named-pipe",999false, named_pipe_path);1000if (error.Fail()) {1001LLDB_LOGF(log,1002"GDBRemoteCommunication::%s() "1003"named pipe creation failed: %s",1004__FUNCTION__, error.AsCString());1005return error;1006}1007debugserver_args.AppendArgument(llvm::StringRef("--named-pipe"));1008debugserver_args.AppendArgument(named_pipe_path);1009#else1010// Binding to port zero, we need to figure out what port it ends up1011// using using an unnamed pipe...1012error = socket_pipe.CreateNew(true);1013if (error.Fail()) {1014LLDB_LOGF(log,1015"GDBRemoteCommunication::%s() "1016"unnamed pipe creation failed: %s",1017__FUNCTION__, error.AsCString());1018return error;1019}1020pipe_t write = socket_pipe.GetWritePipe();1021debugserver_args.AppendArgument(llvm::StringRef("--pipe"));1022debugserver_args.AppendArgument(llvm::to_string(write));1023launch_info.AppendCloseFileAction(socket_pipe.GetReadFileDescriptor());1024#endif1025} else {1026// No host and port given, so lets listen on our end and make the1027// debugserver connect to us..1028error = StartListenThread("127.0.0.1", 0);1029if (error.Fail()) {1030LLDB_LOGF(log,1031"GDBRemoteCommunication::%s() unable to start listen "1032"thread: %s",1033__FUNCTION__, error.AsCString());1034return error;1035}10361037// Wait for 10 seconds to resolve the bound port1038std::future<uint16_t> port_future = m_port_promise.get_future();1039uint16_t port_ = port_future.wait_for(std::chrono::seconds(10)) ==1040std::future_status::ready1041? port_future.get()1042: 0;1043if (port_ > 0) {1044char port_cstr[32];1045snprintf(port_cstr, sizeof(port_cstr), "127.0.0.1:%i", port_);1046// Send the host and port down that debugserver and specify an option1047// so that it connects back to the port we are listening to in this1048// process1049debugserver_args.AppendArgument(llvm::StringRef("--reverse-connect"));1050debugserver_args.AppendArgument(llvm::StringRef(port_cstr));1051if (port)1052*port = port_;1053} else {1054error.SetErrorString("failed to bind to port 0 on 127.0.0.1");1055LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s",1056__FUNCTION__, error.AsCString());1057return error;1058}1059}1060}1061std::string env_debugserver_log_file =1062host_env.lookup("LLDB_DEBUGSERVER_LOG_FILE");1063if (!env_debugserver_log_file.empty()) {1064debugserver_args.AppendArgument(1065llvm::formatv("--log-file={0}", env_debugserver_log_file).str());1066}10671068#if defined(__APPLE__)1069const char *env_debugserver_log_flags =1070getenv("LLDB_DEBUGSERVER_LOG_FLAGS");1071if (env_debugserver_log_flags) {1072debugserver_args.AppendArgument(1073llvm::formatv("--log-flags={0}", env_debugserver_log_flags).str());1074}1075#else1076std::string env_debugserver_log_channels =1077host_env.lookup("LLDB_SERVER_LOG_CHANNELS");1078if (!env_debugserver_log_channels.empty()) {1079debugserver_args.AppendArgument(1080llvm::formatv("--log-channels={0}", env_debugserver_log_channels)1081.str());1082}1083#endif10841085// Add additional args, starting with LLDB_DEBUGSERVER_EXTRA_ARG_1 until an1086// env var doesn't come back.1087uint32_t env_var_index = 1;1088bool has_env_var;1089do {1090char env_var_name[64];1091snprintf(env_var_name, sizeof(env_var_name),1092"LLDB_DEBUGSERVER_EXTRA_ARG_%" PRIu32, env_var_index++);1093std::string extra_arg = host_env.lookup(env_var_name);1094has_env_var = !extra_arg.empty();10951096if (has_env_var) {1097debugserver_args.AppendArgument(llvm::StringRef(extra_arg));1098LLDB_LOGF(log,1099"GDBRemoteCommunication::%s adding env var %s contents "1100"to stub command line (%s)",1101__FUNCTION__, env_var_name, extra_arg.c_str());1102}1103} while (has_env_var);11041105if (inferior_args && inferior_args->GetArgumentCount() > 0) {1106debugserver_args.AppendArgument(llvm::StringRef("--"));1107debugserver_args.AppendArguments(*inferior_args);1108}11091110// Copy the current environment to the gdbserver/debugserver instance1111launch_info.GetEnvironment() = host_env;11121113// Close STDIN, STDOUT and STDERR.1114launch_info.AppendCloseFileAction(STDIN_FILENO);1115launch_info.AppendCloseFileAction(STDOUT_FILENO);1116launch_info.AppendCloseFileAction(STDERR_FILENO);11171118// Redirect STDIN, STDOUT and STDERR to "/dev/null".1119launch_info.AppendSuppressFileAction(STDIN_FILENO, true, false);1120launch_info.AppendSuppressFileAction(STDOUT_FILENO, false, true);1121launch_info.AppendSuppressFileAction(STDERR_FILENO, false, true);11221123if (log) {1124StreamString string_stream;1125Platform *const platform = nullptr;1126launch_info.Dump(string_stream, platform);1127LLDB_LOGF(log, "launch info for gdb-remote stub:\n%s",1128string_stream.GetData());1129}1130error = Host::LaunchProcess(launch_info);11311132if (error.Success() &&1133(launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) &&1134pass_comm_fd == -1) {1135if (named_pipe_path.size() > 0) {1136error = socket_pipe.OpenAsReader(named_pipe_path, false);1137if (error.Fail())1138LLDB_LOGF(log,1139"GDBRemoteCommunication::%s() "1140"failed to open named pipe %s for reading: %s",1141__FUNCTION__, named_pipe_path.c_str(), error.AsCString());1142}11431144if (socket_pipe.CanWrite())1145socket_pipe.CloseWriteFileDescriptor();1146if (socket_pipe.CanRead()) {1147char port_cstr[PATH_MAX] = {0};1148port_cstr[0] = '\0';1149size_t num_bytes = sizeof(port_cstr);1150// Read port from pipe with 10 second timeout.1151error = socket_pipe.ReadWithTimeout(1152port_cstr, num_bytes, std::chrono::seconds{10}, num_bytes);1153if (error.Success() && (port != nullptr)) {1154assert(num_bytes > 0 && port_cstr[num_bytes - 1] == '\0');1155uint16_t child_port = 0;1156// FIXME: improve error handling1157llvm::to_integer(port_cstr, child_port);1158if (*port == 0 || *port == child_port) {1159*port = child_port;1160LLDB_LOGF(log,1161"GDBRemoteCommunication::%s() "1162"debugserver listens %u port",1163__FUNCTION__, *port);1164} else {1165LLDB_LOGF(log,1166"GDBRemoteCommunication::%s() "1167"debugserver listening on port "1168"%d but requested port was %d",1169__FUNCTION__, (uint32_t)child_port, (uint32_t)(*port));1170}1171} else {1172LLDB_LOGF(log,1173"GDBRemoteCommunication::%s() "1174"failed to read a port value from pipe %s: %s",1175__FUNCTION__, named_pipe_path.c_str(), error.AsCString());1176}1177socket_pipe.Close();1178}11791180if (named_pipe_path.size() > 0) {1181const auto err = socket_pipe.Delete(named_pipe_path);1182if (err.Fail()) {1183LLDB_LOGF(log,1184"GDBRemoteCommunication::%s failed to delete pipe %s: %s",1185__FUNCTION__, named_pipe_path.c_str(), err.AsCString());1186}1187}11881189// Make sure we actually connect with the debugserver...1190JoinListenThread();1191}1192} else {1193error.SetErrorStringWithFormat("unable to locate " DEBUGSERVER_BASENAME);1194}11951196if (error.Fail()) {1197LLDB_LOGF(log, "GDBRemoteCommunication::%s() failed: %s", __FUNCTION__,1198error.AsCString());1199}12001201return error;1202}12031204void GDBRemoteCommunication::DumpHistory(Stream &strm) { m_history.Dump(strm); }12051206llvm::Error1207GDBRemoteCommunication::ConnectLocally(GDBRemoteCommunication &client,1208GDBRemoteCommunication &server) {1209const bool child_processes_inherit = false;1210const int backlog = 5;1211TCPSocket listen_socket(true, child_processes_inherit);1212if (llvm::Error error =1213listen_socket.Listen("localhost:0", backlog).ToError())1214return error;12151216Socket *accept_socket = nullptr;1217std::future<Status> accept_status = std::async(1218std::launch::async, [&] { return listen_socket.Accept(accept_socket); });12191220llvm::SmallString<32> remote_addr;1221llvm::raw_svector_ostream(remote_addr)1222<< "connect://localhost:" << listen_socket.GetLocalPortNumber();12231224std::unique_ptr<ConnectionFileDescriptor> conn_up(1225new ConnectionFileDescriptor());1226Status status;1227if (conn_up->Connect(remote_addr, &status) != lldb::eConnectionStatusSuccess)1228return llvm::createStringError(llvm::inconvertibleErrorCode(),1229"Unable to connect: %s", status.AsCString());12301231client.SetConnection(std::move(conn_up));1232if (llvm::Error error = accept_status.get().ToError())1233return error;12341235server.SetConnection(1236std::make_unique<ConnectionFileDescriptor>(accept_socket));1237return llvm::Error::success();1238}12391240GDBRemoteCommunication::ScopedTimeout::ScopedTimeout(1241GDBRemoteCommunication &gdb_comm, std::chrono::seconds timeout)1242: m_gdb_comm(gdb_comm), m_saved_timeout(0), m_timeout_modified(false) {1243auto curr_timeout = gdb_comm.GetPacketTimeout();1244// Only update the timeout if the timeout is greater than the current1245// timeout. If the current timeout is larger, then just use that.1246if (curr_timeout < timeout) {1247m_timeout_modified = true;1248m_saved_timeout = m_gdb_comm.SetPacketTimeout(timeout);1249}1250}12511252GDBRemoteCommunication::ScopedTimeout::~ScopedTimeout() {1253// Only restore the timeout if we set it in the constructor.1254if (m_timeout_modified)1255m_gdb_comm.SetPacketTimeout(m_saved_timeout);1256}12571258void llvm::format_provider<GDBRemoteCommunication::PacketResult>::format(1259const GDBRemoteCommunication::PacketResult &result, raw_ostream &Stream,1260StringRef Style) {1261using PacketResult = GDBRemoteCommunication::PacketResult;12621263switch (result) {1264case PacketResult::Success:1265Stream << "Success";1266break;1267case PacketResult::ErrorSendFailed:1268Stream << "ErrorSendFailed";1269break;1270case PacketResult::ErrorSendAck:1271Stream << "ErrorSendAck";1272break;1273case PacketResult::ErrorReplyFailed:1274Stream << "ErrorReplyFailed";1275break;1276case PacketResult::ErrorReplyTimeout:1277Stream << "ErrorReplyTimeout";1278break;1279case PacketResult::ErrorReplyInvalid:1280Stream << "ErrorReplyInvalid";1281break;1282case PacketResult::ErrorReplyAck:1283Stream << "ErrorReplyAck";1284break;1285case PacketResult::ErrorDisconnected:1286Stream << "ErrorDisconnected";1287break;1288case PacketResult::ErrorNoSequenceLock:1289Stream << "ErrorNoSequenceLock";1290break;1291}1292}12931294std::string GDBRemoteCommunication::ExpandRLE(std::string packet) {1295// Reserve enough byte for the most common case (no RLE used).1296std::string decoded;1297decoded.reserve(packet.size());1298for (std::string::const_iterator c = packet.begin(); c != packet.end(); ++c) {1299if (*c == '*') {1300// '*' indicates RLE. Next character will give us the repeat count and1301// previous character is what is to be repeated.1302char char_to_repeat = decoded.back();1303// Number of time the previous character is repeated.1304int repeat_count = *++c + 3 - ' ';1305// We have the char_to_repeat and repeat_count. Now push it in the1306// packet.1307for (int i = 0; i < repeat_count; ++i)1308decoded.push_back(char_to_repeat);1309} else if (*c == 0x7d) {1310// 0x7d is the escape character. The next character is to be XOR'd with1311// 0x20.1312char escapee = *++c ^ 0x20;1313decoded.push_back(escapee);1314} else {1315decoded.push_back(*c);1316}1317}1318return decoded;1319}132013211322