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