1 //===-- GDBRemoteCommunicationClient.cpp ----------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "GDBRemoteCommunicationClient.h" 10 11 #include <cmath> 12 #include <sys/stat.h> 13 14 #include <numeric> 15 #include <optional> 16 #include <sstream> 17 18 #include "lldb/Core/ModuleSpec.h" 19 #include "lldb/Host/HostInfo.h" 20 #include "lldb/Host/SafeMachO.h" 21 #include "lldb/Host/XML.h" 22 #include "lldb/Symbol/Symbol.h" 23 #include "lldb/Target/MemoryRegionInfo.h" 24 #include "lldb/Target/Target.h" 25 #include "lldb/Target/UnixSignals.h" 26 #include "lldb/Utility/Args.h" 27 #include "lldb/Utility/DataBufferHeap.h" 28 #include "lldb/Utility/LLDBAssert.h" 29 #include "lldb/Utility/LLDBLog.h" 30 #include "lldb/Utility/Log.h" 31 #include "lldb/Utility/State.h" 32 #include "lldb/Utility/StreamString.h" 33 34 #include "ProcessGDBRemote.h" 35 #include "ProcessGDBRemoteLog.h" 36 #include "lldb/Host/Config.h" 37 #include "lldb/Utility/StringExtractorGDBRemote.h" 38 39 #include "llvm/ADT/STLExtras.h" 40 #include "llvm/ADT/StringSwitch.h" 41 #include "llvm/Config/llvm-config.h" // for LLVM_ENABLE_ZLIB 42 #include "llvm/Support/JSON.h" 43 44 #if defined(HAVE_LIBCOMPRESSION) 45 #include <compression.h> 46 #endif 47 48 using namespace lldb; 49 using namespace lldb_private::process_gdb_remote; 50 using namespace lldb_private; 51 using namespace std::chrono; 52 53 llvm::raw_ostream &process_gdb_remote::operator<<(llvm::raw_ostream &os, 54 const QOffsets &offsets) { 55 return os << llvm::formatv( 56 "QOffsets({0}, [{1:@[x]}])", offsets.segments, 57 llvm::make_range(offsets.offsets.begin(), offsets.offsets.end())); 58 } 59 60 // GDBRemoteCommunicationClient constructor 61 GDBRemoteCommunicationClient::GDBRemoteCommunicationClient() 62 : GDBRemoteClientBase("gdb-remote.client"), 63 64 m_supports_qProcessInfoPID(true), m_supports_qfProcessInfo(true), 65 m_supports_qUserName(true), m_supports_qGroupName(true), 66 m_supports_qThreadStopInfo(true), m_supports_z0(true), 67 m_supports_z1(true), m_supports_z2(true), m_supports_z3(true), 68 m_supports_z4(true), m_supports_QEnvironment(true), 69 m_supports_QEnvironmentHexEncoded(true), m_supports_qSymbol(true), 70 m_qSymbol_requests_done(false), m_supports_qModuleInfo(true), 71 m_supports_jThreadsInfo(true), m_supports_jModulesInfo(true), 72 m_supports_vFileSize(true), m_supports_vFileMode(true), 73 m_supports_vFileExists(true), m_supports_vRun(true), 74 75 m_host_arch(), m_host_distribution_id(), m_process_arch(), m_os_build(), 76 m_os_kernel(), m_hostname(), m_gdb_server_name(), 77 m_default_packet_timeout(0), m_qSupported_response(), 78 m_supported_async_json_packets_sp(), m_qXfer_memory_map() {} 79 80 // Destructor 81 GDBRemoteCommunicationClient::~GDBRemoteCommunicationClient() { 82 if (IsConnected()) 83 Disconnect(); 84 } 85 86 bool GDBRemoteCommunicationClient::HandshakeWithServer(Status *error_ptr) { 87 ResetDiscoverableSettings(false); 88 89 // Start the read thread after we send the handshake ack since if we fail to 90 // send the handshake ack, there is no reason to continue... 91 std::chrono::steady_clock::time_point start_of_handshake = 92 std::chrono::steady_clock::now(); 93 if (SendAck()) { 94 // The return value from QueryNoAckModeSupported() is true if the packet 95 // was sent and _any_ response (including UNIMPLEMENTED) was received), or 96 // false if no response was received. This quickly tells us if we have a 97 // live connection to a remote GDB server... 98 if (QueryNoAckModeSupported()) { 99 return true; 100 } else { 101 std::chrono::steady_clock::time_point end_of_handshake = 102 std::chrono::steady_clock::now(); 103 auto handshake_timeout = 104 std::chrono::duration<double>(end_of_handshake - start_of_handshake) 105 .count(); 106 if (error_ptr) { 107 if (!IsConnected()) 108 *error_ptr = 109 Status::FromErrorString("Connection shut down by remote side " 110 "while waiting for reply to initial " 111 "handshake packet"); 112 else 113 *error_ptr = Status::FromErrorStringWithFormat( 114 "failed to get reply to handshake packet within timeout of " 115 "%.1f seconds", 116 handshake_timeout); 117 } 118 } 119 } else { 120 if (error_ptr) 121 *error_ptr = Status::FromErrorString("failed to send the handshake ack"); 122 } 123 return false; 124 } 125 126 bool GDBRemoteCommunicationClient::GetEchoSupported() { 127 if (m_supports_qEcho == eLazyBoolCalculate) { 128 GetRemoteQSupported(); 129 } 130 return m_supports_qEcho == eLazyBoolYes; 131 } 132 133 bool GDBRemoteCommunicationClient::GetQPassSignalsSupported() { 134 if (m_supports_QPassSignals == eLazyBoolCalculate) { 135 GetRemoteQSupported(); 136 } 137 return m_supports_QPassSignals == eLazyBoolYes; 138 } 139 140 bool GDBRemoteCommunicationClient::GetAugmentedLibrariesSVR4ReadSupported() { 141 if (m_supports_augmented_libraries_svr4_read == eLazyBoolCalculate) { 142 GetRemoteQSupported(); 143 } 144 return m_supports_augmented_libraries_svr4_read == eLazyBoolYes; 145 } 146 147 bool GDBRemoteCommunicationClient::GetQXferLibrariesSVR4ReadSupported() { 148 if (m_supports_qXfer_libraries_svr4_read == eLazyBoolCalculate) { 149 GetRemoteQSupported(); 150 } 151 return m_supports_qXfer_libraries_svr4_read == eLazyBoolYes; 152 } 153 154 bool GDBRemoteCommunicationClient::GetQXferLibrariesReadSupported() { 155 if (m_supports_qXfer_libraries_read == eLazyBoolCalculate) { 156 GetRemoteQSupported(); 157 } 158 return m_supports_qXfer_libraries_read == eLazyBoolYes; 159 } 160 161 bool GDBRemoteCommunicationClient::GetQXferAuxvReadSupported() { 162 if (m_supports_qXfer_auxv_read == eLazyBoolCalculate) { 163 GetRemoteQSupported(); 164 } 165 return m_supports_qXfer_auxv_read == eLazyBoolYes; 166 } 167 168 bool GDBRemoteCommunicationClient::GetQXferFeaturesReadSupported() { 169 if (m_supports_qXfer_features_read == eLazyBoolCalculate) { 170 GetRemoteQSupported(); 171 } 172 return m_supports_qXfer_features_read == eLazyBoolYes; 173 } 174 175 bool GDBRemoteCommunicationClient::GetQXferMemoryMapReadSupported() { 176 if (m_supports_qXfer_memory_map_read == eLazyBoolCalculate) { 177 GetRemoteQSupported(); 178 } 179 return m_supports_qXfer_memory_map_read == eLazyBoolYes; 180 } 181 182 bool GDBRemoteCommunicationClient::GetQXferSigInfoReadSupported() { 183 if (m_supports_qXfer_siginfo_read == eLazyBoolCalculate) { 184 GetRemoteQSupported(); 185 } 186 return m_supports_qXfer_siginfo_read == eLazyBoolYes; 187 } 188 189 bool GDBRemoteCommunicationClient::GetMultiprocessSupported() { 190 if (m_supports_memory_tagging == eLazyBoolCalculate) 191 GetRemoteQSupported(); 192 return m_supports_multiprocess == eLazyBoolYes; 193 } 194 195 uint64_t GDBRemoteCommunicationClient::GetRemoteMaxPacketSize() { 196 if (m_max_packet_size == 0) { 197 GetRemoteQSupported(); 198 } 199 return m_max_packet_size; 200 } 201 202 bool GDBRemoteCommunicationClient::QueryNoAckModeSupported() { 203 if (m_supports_not_sending_acks == eLazyBoolCalculate) { 204 m_send_acks = true; 205 m_supports_not_sending_acks = eLazyBoolNo; 206 207 // This is the first real packet that we'll send in a debug session and it 208 // may take a little longer than normal to receive a reply. Wait at least 209 // 6 seconds for a reply to this packet. 210 211 ScopedTimeout timeout(*this, std::max(GetPacketTimeout(), seconds(6))); 212 213 StringExtractorGDBRemote response; 214 if (SendPacketAndWaitForResponse("QStartNoAckMode", response) == 215 PacketResult::Success) { 216 if (response.IsOKResponse()) { 217 m_send_acks = false; 218 m_supports_not_sending_acks = eLazyBoolYes; 219 } 220 return true; 221 } 222 } 223 return false; 224 } 225 226 void GDBRemoteCommunicationClient::GetListThreadsInStopReplySupported() { 227 if (m_supports_threads_in_stop_reply == eLazyBoolCalculate) { 228 m_supports_threads_in_stop_reply = eLazyBoolNo; 229 230 StringExtractorGDBRemote response; 231 if (SendPacketAndWaitForResponse("QListThreadsInStopReply", response) == 232 PacketResult::Success) { 233 if (response.IsOKResponse()) 234 m_supports_threads_in_stop_reply = eLazyBoolYes; 235 } 236 } 237 } 238 239 bool GDBRemoteCommunicationClient::GetVAttachOrWaitSupported() { 240 if (m_attach_or_wait_reply == eLazyBoolCalculate) { 241 m_attach_or_wait_reply = eLazyBoolNo; 242 243 StringExtractorGDBRemote response; 244 if (SendPacketAndWaitForResponse("qVAttachOrWaitSupported", response) == 245 PacketResult::Success) { 246 if (response.IsOKResponse()) 247 m_attach_or_wait_reply = eLazyBoolYes; 248 } 249 } 250 return m_attach_or_wait_reply == eLazyBoolYes; 251 } 252 253 bool GDBRemoteCommunicationClient::GetSyncThreadStateSupported() { 254 if (m_prepare_for_reg_writing_reply == eLazyBoolCalculate) { 255 m_prepare_for_reg_writing_reply = eLazyBoolNo; 256 257 StringExtractorGDBRemote response; 258 if (SendPacketAndWaitForResponse("qSyncThreadStateSupported", response) == 259 PacketResult::Success) { 260 if (response.IsOKResponse()) 261 m_prepare_for_reg_writing_reply = eLazyBoolYes; 262 } 263 } 264 return m_prepare_for_reg_writing_reply == eLazyBoolYes; 265 } 266 267 void GDBRemoteCommunicationClient::ResetDiscoverableSettings(bool did_exec) { 268 if (!did_exec) { 269 // Hard reset everything, this is when we first connect to a GDB server 270 m_supports_not_sending_acks = eLazyBoolCalculate; 271 m_supports_thread_suffix = eLazyBoolCalculate; 272 m_supports_threads_in_stop_reply = eLazyBoolCalculate; 273 m_supports_vCont_c = eLazyBoolCalculate; 274 m_supports_vCont_C = eLazyBoolCalculate; 275 m_supports_vCont_s = eLazyBoolCalculate; 276 m_supports_vCont_S = eLazyBoolCalculate; 277 m_supports_p = eLazyBoolCalculate; 278 m_supports_x = eLazyBoolCalculate; 279 m_supports_QSaveRegisterState = eLazyBoolCalculate; 280 m_qHostInfo_is_valid = eLazyBoolCalculate; 281 m_curr_pid_is_valid = eLazyBoolCalculate; 282 m_qGDBServerVersion_is_valid = eLazyBoolCalculate; 283 m_supports_alloc_dealloc_memory = eLazyBoolCalculate; 284 m_supports_memory_region_info = eLazyBoolCalculate; 285 m_prepare_for_reg_writing_reply = eLazyBoolCalculate; 286 m_attach_or_wait_reply = eLazyBoolCalculate; 287 m_avoid_g_packets = eLazyBoolCalculate; 288 m_supports_multiprocess = eLazyBoolCalculate; 289 m_supports_qSaveCore = eLazyBoolCalculate; 290 m_supports_qXfer_auxv_read = eLazyBoolCalculate; 291 m_supports_qXfer_libraries_read = eLazyBoolCalculate; 292 m_supports_qXfer_libraries_svr4_read = eLazyBoolCalculate; 293 m_supports_qXfer_features_read = eLazyBoolCalculate; 294 m_supports_qXfer_memory_map_read = eLazyBoolCalculate; 295 m_supports_qXfer_siginfo_read = eLazyBoolCalculate; 296 m_supports_augmented_libraries_svr4_read = eLazyBoolCalculate; 297 m_uses_native_signals = eLazyBoolCalculate; 298 m_supports_qProcessInfoPID = true; 299 m_supports_qfProcessInfo = true; 300 m_supports_qUserName = true; 301 m_supports_qGroupName = true; 302 m_supports_qThreadStopInfo = true; 303 m_supports_z0 = true; 304 m_supports_z1 = true; 305 m_supports_z2 = true; 306 m_supports_z3 = true; 307 m_supports_z4 = true; 308 m_supports_QEnvironment = true; 309 m_supports_QEnvironmentHexEncoded = true; 310 m_supports_qSymbol = true; 311 m_qSymbol_requests_done = false; 312 m_supports_qModuleInfo = true; 313 m_host_arch.Clear(); 314 m_host_distribution_id.clear(); 315 m_os_version = llvm::VersionTuple(); 316 m_os_build.clear(); 317 m_os_kernel.clear(); 318 m_hostname.clear(); 319 m_gdb_server_name.clear(); 320 m_gdb_server_version = UINT32_MAX; 321 m_default_packet_timeout = seconds(0); 322 m_target_vm_page_size = 0; 323 m_max_packet_size = 0; 324 m_qSupported_response.clear(); 325 m_supported_async_json_packets_is_valid = false; 326 m_supported_async_json_packets_sp.reset(); 327 m_supports_jModulesInfo = true; 328 } 329 330 // These flags should be reset when we first connect to a GDB server and when 331 // our inferior process execs 332 m_qProcessInfo_is_valid = eLazyBoolCalculate; 333 m_process_arch.Clear(); 334 } 335 336 void GDBRemoteCommunicationClient::GetRemoteQSupported() { 337 // Clear out any capabilities we expect to see in the qSupported response 338 m_supports_qXfer_auxv_read = eLazyBoolNo; 339 m_supports_qXfer_libraries_read = eLazyBoolNo; 340 m_supports_qXfer_libraries_svr4_read = eLazyBoolNo; 341 m_supports_augmented_libraries_svr4_read = eLazyBoolNo; 342 m_supports_qXfer_features_read = eLazyBoolNo; 343 m_supports_qXfer_memory_map_read = eLazyBoolNo; 344 m_supports_qXfer_siginfo_read = eLazyBoolNo; 345 m_supports_multiprocess = eLazyBoolNo; 346 m_supports_qEcho = eLazyBoolNo; 347 m_supports_QPassSignals = eLazyBoolNo; 348 m_supports_memory_tagging = eLazyBoolNo; 349 m_supports_qSaveCore = eLazyBoolNo; 350 m_uses_native_signals = eLazyBoolNo; 351 352 m_max_packet_size = UINT64_MAX; // It's supposed to always be there, but if 353 // not, we assume no limit 354 355 // build the qSupported packet 356 std::vector<std::string> features = {"xmlRegisters=i386,arm,mips,arc", 357 "multiprocess+", 358 "fork-events+", 359 "vfork-events+", 360 "swbreak+", 361 "hwbreak+"}; 362 StreamString packet; 363 packet.PutCString("qSupported"); 364 for (uint32_t i = 0; i < features.size(); ++i) { 365 packet.PutCString(i == 0 ? ":" : ";"); 366 packet.PutCString(features[i]); 367 } 368 369 StringExtractorGDBRemote response; 370 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 371 PacketResult::Success) { 372 // Hang on to the qSupported packet, so that platforms can do custom 373 // configuration of the transport before attaching/launching the process. 374 m_qSupported_response = response.GetStringRef().str(); 375 376 for (llvm::StringRef x : llvm::split(response.GetStringRef(), ';')) { 377 if (x == "qXfer:auxv:read+") 378 m_supports_qXfer_auxv_read = eLazyBoolYes; 379 else if (x == "qXfer:libraries-svr4:read+") 380 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; 381 else if (x == "augmented-libraries-svr4-read") { 382 m_supports_qXfer_libraries_svr4_read = eLazyBoolYes; // implied 383 m_supports_augmented_libraries_svr4_read = eLazyBoolYes; 384 } else if (x == "qXfer:libraries:read+") 385 m_supports_qXfer_libraries_read = eLazyBoolYes; 386 else if (x == "qXfer:features:read+") 387 m_supports_qXfer_features_read = eLazyBoolYes; 388 else if (x == "qXfer:memory-map:read+") 389 m_supports_qXfer_memory_map_read = eLazyBoolYes; 390 else if (x == "qXfer:siginfo:read+") 391 m_supports_qXfer_siginfo_read = eLazyBoolYes; 392 else if (x == "qEcho") 393 m_supports_qEcho = eLazyBoolYes; 394 else if (x == "QPassSignals+") 395 m_supports_QPassSignals = eLazyBoolYes; 396 else if (x == "multiprocess+") 397 m_supports_multiprocess = eLazyBoolYes; 398 else if (x == "memory-tagging+") 399 m_supports_memory_tagging = eLazyBoolYes; 400 else if (x == "qSaveCore+") 401 m_supports_qSaveCore = eLazyBoolYes; 402 else if (x == "native-signals+") 403 m_uses_native_signals = eLazyBoolYes; 404 // Look for a list of compressions in the features list e.g. 405 // qXfer:features:read+;PacketSize=20000;qEcho+;SupportedCompressions=zlib- 406 // deflate,lzma 407 else if (x.consume_front("SupportedCompressions=")) { 408 llvm::SmallVector<llvm::StringRef, 4> compressions; 409 x.split(compressions, ','); 410 if (!compressions.empty()) 411 MaybeEnableCompression(compressions); 412 } else if (x.consume_front("SupportedWatchpointTypes=")) { 413 llvm::SmallVector<llvm::StringRef, 4> watchpoint_types; 414 x.split(watchpoint_types, ','); 415 m_watchpoint_types = eWatchpointHardwareFeatureUnknown; 416 for (auto wp_type : watchpoint_types) { 417 if (wp_type == "x86_64") 418 m_watchpoint_types |= eWatchpointHardwareX86; 419 if (wp_type == "aarch64-mask") 420 m_watchpoint_types |= eWatchpointHardwareArmMASK; 421 if (wp_type == "aarch64-bas") 422 m_watchpoint_types |= eWatchpointHardwareArmBAS; 423 } 424 } else if (x.consume_front("PacketSize=")) { 425 StringExtractorGDBRemote packet_response(x); 426 m_max_packet_size = 427 packet_response.GetHexMaxU64(/*little_endian=*/false, UINT64_MAX); 428 if (m_max_packet_size == 0) { 429 m_max_packet_size = UINT64_MAX; // Must have been a garbled response 430 Log *log(GetLog(GDBRLog::Process)); 431 LLDB_LOGF(log, "Garbled PacketSize spec in qSupported response"); 432 } 433 } 434 } 435 } 436 } 437 438 bool GDBRemoteCommunicationClient::GetThreadSuffixSupported() { 439 if (m_supports_thread_suffix == eLazyBoolCalculate) { 440 StringExtractorGDBRemote response; 441 m_supports_thread_suffix = eLazyBoolNo; 442 if (SendPacketAndWaitForResponse("QThreadSuffixSupported", response) == 443 PacketResult::Success) { 444 if (response.IsOKResponse()) 445 m_supports_thread_suffix = eLazyBoolYes; 446 } 447 } 448 return m_supports_thread_suffix; 449 } 450 bool GDBRemoteCommunicationClient::GetVContSupported(char flavor) { 451 if (m_supports_vCont_c == eLazyBoolCalculate) { 452 StringExtractorGDBRemote response; 453 m_supports_vCont_any = eLazyBoolNo; 454 m_supports_vCont_all = eLazyBoolNo; 455 m_supports_vCont_c = eLazyBoolNo; 456 m_supports_vCont_C = eLazyBoolNo; 457 m_supports_vCont_s = eLazyBoolNo; 458 m_supports_vCont_S = eLazyBoolNo; 459 if (SendPacketAndWaitForResponse("vCont?", response) == 460 PacketResult::Success) { 461 const char *response_cstr = response.GetStringRef().data(); 462 if (::strstr(response_cstr, ";c")) 463 m_supports_vCont_c = eLazyBoolYes; 464 465 if (::strstr(response_cstr, ";C")) 466 m_supports_vCont_C = eLazyBoolYes; 467 468 if (::strstr(response_cstr, ";s")) 469 m_supports_vCont_s = eLazyBoolYes; 470 471 if (::strstr(response_cstr, ";S")) 472 m_supports_vCont_S = eLazyBoolYes; 473 474 if (m_supports_vCont_c == eLazyBoolYes && 475 m_supports_vCont_C == eLazyBoolYes && 476 m_supports_vCont_s == eLazyBoolYes && 477 m_supports_vCont_S == eLazyBoolYes) { 478 m_supports_vCont_all = eLazyBoolYes; 479 } 480 481 if (m_supports_vCont_c == eLazyBoolYes || 482 m_supports_vCont_C == eLazyBoolYes || 483 m_supports_vCont_s == eLazyBoolYes || 484 m_supports_vCont_S == eLazyBoolYes) { 485 m_supports_vCont_any = eLazyBoolYes; 486 } 487 } 488 } 489 490 switch (flavor) { 491 case 'a': 492 return m_supports_vCont_any; 493 case 'A': 494 return m_supports_vCont_all; 495 case 'c': 496 return m_supports_vCont_c; 497 case 'C': 498 return m_supports_vCont_C; 499 case 's': 500 return m_supports_vCont_s; 501 case 'S': 502 return m_supports_vCont_S; 503 default: 504 break; 505 } 506 return false; 507 } 508 509 GDBRemoteCommunication::PacketResult 510 GDBRemoteCommunicationClient::SendThreadSpecificPacketAndWaitForResponse( 511 lldb::tid_t tid, StreamString &&payload, 512 StringExtractorGDBRemote &response) { 513 Lock lock(*this); 514 if (!lock) { 515 if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) 516 LLDB_LOGF(log, 517 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex " 518 "for %s packet.", 519 __FUNCTION__, payload.GetData()); 520 return PacketResult::ErrorNoSequenceLock; 521 } 522 523 if (GetThreadSuffixSupported()) 524 payload.Printf(";thread:%4.4" PRIx64 ";", tid); 525 else { 526 if (!SetCurrentThread(tid)) 527 return PacketResult::ErrorSendFailed; 528 } 529 530 return SendPacketAndWaitForResponseNoLock(payload.GetString(), response); 531 } 532 533 // Check if the target supports 'p' packet. It sends out a 'p' packet and 534 // checks the response. A normal packet will tell us that support is available. 535 // 536 // Takes a valid thread ID because p needs to apply to a thread. 537 bool GDBRemoteCommunicationClient::GetpPacketSupported(lldb::tid_t tid) { 538 if (m_supports_p == eLazyBoolCalculate) 539 m_supports_p = GetThreadPacketSupported(tid, "p0"); 540 return m_supports_p; 541 } 542 543 LazyBool GDBRemoteCommunicationClient::GetThreadPacketSupported( 544 lldb::tid_t tid, llvm::StringRef packetStr) { 545 StreamString payload; 546 payload.PutCString(packetStr); 547 StringExtractorGDBRemote response; 548 if (SendThreadSpecificPacketAndWaitForResponse( 549 tid, std::move(payload), response) == PacketResult::Success && 550 response.IsNormalResponse()) { 551 return eLazyBoolYes; 552 } 553 return eLazyBoolNo; 554 } 555 556 bool GDBRemoteCommunicationClient::GetSaveCoreSupported() const { 557 return m_supports_qSaveCore == eLazyBoolYes; 558 } 559 560 StructuredData::ObjectSP GDBRemoteCommunicationClient::GetThreadsInfo() { 561 // Get information on all threads at one using the "jThreadsInfo" packet 562 StructuredData::ObjectSP object_sp; 563 564 if (m_supports_jThreadsInfo) { 565 StringExtractorGDBRemote response; 566 response.SetResponseValidatorToJSON(); 567 if (SendPacketAndWaitForResponse("jThreadsInfo", response) == 568 PacketResult::Success) { 569 if (response.IsUnsupportedResponse()) { 570 m_supports_jThreadsInfo = false; 571 } else if (!response.Empty()) { 572 object_sp = StructuredData::ParseJSON(response.GetStringRef()); 573 } 574 } 575 } 576 return object_sp; 577 } 578 579 bool GDBRemoteCommunicationClient::GetThreadExtendedInfoSupported() { 580 if (m_supports_jThreadExtendedInfo == eLazyBoolCalculate) { 581 StringExtractorGDBRemote response; 582 m_supports_jThreadExtendedInfo = eLazyBoolNo; 583 if (SendPacketAndWaitForResponse("jThreadExtendedInfo:", response) == 584 PacketResult::Success) { 585 if (response.IsOKResponse()) { 586 m_supports_jThreadExtendedInfo = eLazyBoolYes; 587 } 588 } 589 } 590 return m_supports_jThreadExtendedInfo; 591 } 592 593 void GDBRemoteCommunicationClient::EnableErrorStringInPacket() { 594 if (m_supports_error_string_reply == eLazyBoolCalculate) { 595 StringExtractorGDBRemote response; 596 // We try to enable error strings in remote packets but if we fail, we just 597 // work in the older way. 598 m_supports_error_string_reply = eLazyBoolNo; 599 if (SendPacketAndWaitForResponse("QEnableErrorStrings", response) == 600 PacketResult::Success) { 601 if (response.IsOKResponse()) { 602 m_supports_error_string_reply = eLazyBoolYes; 603 } 604 } 605 } 606 } 607 608 bool GDBRemoteCommunicationClient::GetLoadedDynamicLibrariesInfosSupported() { 609 if (m_supports_jLoadedDynamicLibrariesInfos == eLazyBoolCalculate) { 610 StringExtractorGDBRemote response; 611 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolNo; 612 if (SendPacketAndWaitForResponse("jGetLoadedDynamicLibrariesInfos:", 613 response) == PacketResult::Success) { 614 if (response.IsOKResponse()) { 615 m_supports_jLoadedDynamicLibrariesInfos = eLazyBoolYes; 616 } 617 } 618 } 619 return m_supports_jLoadedDynamicLibrariesInfos; 620 } 621 622 bool GDBRemoteCommunicationClient::GetSharedCacheInfoSupported() { 623 if (m_supports_jGetSharedCacheInfo == eLazyBoolCalculate) { 624 StringExtractorGDBRemote response; 625 m_supports_jGetSharedCacheInfo = eLazyBoolNo; 626 if (SendPacketAndWaitForResponse("jGetSharedCacheInfo:", response) == 627 PacketResult::Success) { 628 if (response.IsOKResponse()) { 629 m_supports_jGetSharedCacheInfo = eLazyBoolYes; 630 } 631 } 632 } 633 return m_supports_jGetSharedCacheInfo; 634 } 635 636 bool GDBRemoteCommunicationClient::GetDynamicLoaderProcessStateSupported() { 637 if (m_supports_jGetDyldProcessState == eLazyBoolCalculate) { 638 StringExtractorGDBRemote response; 639 m_supports_jGetDyldProcessState = eLazyBoolNo; 640 if (SendPacketAndWaitForResponse("jGetDyldProcessState", response) == 641 PacketResult::Success) { 642 if (!response.IsUnsupportedResponse()) 643 m_supports_jGetDyldProcessState = eLazyBoolYes; 644 } 645 } 646 return m_supports_jGetDyldProcessState; 647 } 648 649 bool GDBRemoteCommunicationClient::GetMemoryTaggingSupported() { 650 if (m_supports_memory_tagging == eLazyBoolCalculate) { 651 GetRemoteQSupported(); 652 } 653 return m_supports_memory_tagging == eLazyBoolYes; 654 } 655 656 DataBufferSP GDBRemoteCommunicationClient::ReadMemoryTags(lldb::addr_t addr, 657 size_t len, 658 int32_t type) { 659 StreamString packet; 660 packet.Printf("qMemTags:%" PRIx64 ",%zx:%" PRIx32, addr, len, type); 661 StringExtractorGDBRemote response; 662 663 Log *log = GetLog(GDBRLog::Memory); 664 665 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 666 PacketResult::Success || 667 !response.IsNormalResponse()) { 668 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s: qMemTags packet failed", 669 __FUNCTION__); 670 return nullptr; 671 } 672 673 // We are expecting 674 // m<hex encoded bytes> 675 676 if (response.GetChar() != 'm') { 677 LLDB_LOGF(log, 678 "GDBRemoteCommunicationClient::%s: qMemTags response did not " 679 "begin with \"m\"", 680 __FUNCTION__); 681 return nullptr; 682 } 683 684 size_t expected_bytes = response.GetBytesLeft() / 2; 685 WritableDataBufferSP buffer_sp(new DataBufferHeap(expected_bytes, 0)); 686 size_t got_bytes = response.GetHexBytesAvail(buffer_sp->GetData()); 687 // Check both because in some situations chars are consumed even 688 // if the decoding fails. 689 if (response.GetBytesLeft() || (expected_bytes != got_bytes)) { 690 LLDB_LOGF( 691 log, 692 "GDBRemoteCommunicationClient::%s: Invalid data in qMemTags response", 693 __FUNCTION__); 694 return nullptr; 695 } 696 697 return buffer_sp; 698 } 699 700 Status GDBRemoteCommunicationClient::WriteMemoryTags( 701 lldb::addr_t addr, size_t len, int32_t type, 702 const std::vector<uint8_t> &tags) { 703 // Format QMemTags:address,length:type:tags 704 StreamString packet; 705 packet.Printf("QMemTags:%" PRIx64 ",%zx:%" PRIx32 ":", addr, len, type); 706 packet.PutBytesAsRawHex8(tags.data(), tags.size()); 707 708 Status status; 709 StringExtractorGDBRemote response; 710 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 711 PacketResult::Success || 712 !response.IsOKResponse()) { 713 status = Status::FromErrorString("QMemTags packet failed"); 714 } 715 return status; 716 } 717 718 bool GDBRemoteCommunicationClient::GetxPacketSupported() { 719 if (m_supports_x == eLazyBoolCalculate) { 720 StringExtractorGDBRemote response; 721 m_supports_x = eLazyBoolNo; 722 char packet[256]; 723 snprintf(packet, sizeof(packet), "x0,0"); 724 if (SendPacketAndWaitForResponse(packet, response) == 725 PacketResult::Success) { 726 if (response.IsOKResponse()) 727 m_supports_x = eLazyBoolYes; 728 } 729 } 730 return m_supports_x; 731 } 732 733 lldb::pid_t GDBRemoteCommunicationClient::GetCurrentProcessID(bool allow_lazy) { 734 if (allow_lazy && m_curr_pid_is_valid == eLazyBoolYes) 735 return m_curr_pid; 736 737 // First try to retrieve the pid via the qProcessInfo request. 738 GetCurrentProcessInfo(allow_lazy); 739 if (m_curr_pid_is_valid == eLazyBoolYes) { 740 // We really got it. 741 return m_curr_pid; 742 } else { 743 // If we don't get a response for qProcessInfo, check if $qC gives us a 744 // result. $qC only returns a real process id on older debugserver and 745 // lldb-platform stubs. The gdb remote protocol documents $qC as returning 746 // the thread id, which newer debugserver and lldb-gdbserver stubs return 747 // correctly. 748 StringExtractorGDBRemote response; 749 if (SendPacketAndWaitForResponse("qC", response) == PacketResult::Success) { 750 if (response.GetChar() == 'Q') { 751 if (response.GetChar() == 'C') { 752 m_curr_pid_run = m_curr_pid = 753 response.GetHexMaxU64(false, LLDB_INVALID_PROCESS_ID); 754 if (m_curr_pid != LLDB_INVALID_PROCESS_ID) { 755 m_curr_pid_is_valid = eLazyBoolYes; 756 return m_curr_pid; 757 } 758 } 759 } 760 } 761 762 // If we don't get a response for $qC, check if $qfThreadID gives us a 763 // result. 764 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) { 765 bool sequence_mutex_unavailable; 766 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable); 767 if (!ids.empty() && !sequence_mutex_unavailable) { 768 // If server returned an explicit PID, use that. 769 m_curr_pid_run = m_curr_pid = ids.front().first; 770 // Otherwise, use the TID of the first thread (Linux hack). 771 if (m_curr_pid == LLDB_INVALID_PROCESS_ID) 772 m_curr_pid_run = m_curr_pid = ids.front().second; 773 m_curr_pid_is_valid = eLazyBoolYes; 774 return m_curr_pid; 775 } 776 } 777 } 778 779 return LLDB_INVALID_PROCESS_ID; 780 } 781 782 llvm::Error GDBRemoteCommunicationClient::LaunchProcess(const Args &args) { 783 if (!args.GetArgumentAtIndex(0)) 784 return llvm::createStringError(llvm::inconvertibleErrorCode(), 785 "Nothing to launch"); 786 // try vRun first 787 if (m_supports_vRun) { 788 StreamString packet; 789 packet.PutCString("vRun"); 790 for (const Args::ArgEntry &arg : args) { 791 packet.PutChar(';'); 792 packet.PutStringAsRawHex8(arg.ref()); 793 } 794 795 StringExtractorGDBRemote response; 796 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 797 PacketResult::Success) 798 return llvm::createStringError(llvm::inconvertibleErrorCode(), 799 "Sending vRun packet failed"); 800 801 if (response.IsErrorResponse()) 802 return response.GetStatus().ToError(); 803 804 // vRun replies with a stop reason packet 805 // FIXME: right now we just discard the packet and LLDB queries 806 // for stop reason again 807 if (!response.IsUnsupportedResponse()) 808 return llvm::Error::success(); 809 810 m_supports_vRun = false; 811 } 812 813 // fallback to A 814 StreamString packet; 815 packet.PutChar('A'); 816 llvm::ListSeparator LS(","); 817 for (const auto &arg : llvm::enumerate(args)) { 818 packet << LS; 819 packet.Format("{0},{1},", arg.value().ref().size() * 2, arg.index()); 820 packet.PutStringAsRawHex8(arg.value().ref()); 821 } 822 823 StringExtractorGDBRemote response; 824 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 825 PacketResult::Success) { 826 return llvm::createStringError(llvm::inconvertibleErrorCode(), 827 "Sending A packet failed"); 828 } 829 if (!response.IsOKResponse()) 830 return response.GetStatus().ToError(); 831 832 if (SendPacketAndWaitForResponse("qLaunchSuccess", response) != 833 PacketResult::Success) { 834 return llvm::createStringError(llvm::inconvertibleErrorCode(), 835 "Sending qLaunchSuccess packet failed"); 836 } 837 if (response.IsOKResponse()) 838 return llvm::Error::success(); 839 if (response.GetChar() == 'E') { 840 return llvm::createStringError(llvm::inconvertibleErrorCode(), 841 response.GetStringRef().substr(1)); 842 } 843 return llvm::createStringError(llvm::inconvertibleErrorCode(), 844 "unknown error occurred launching process"); 845 } 846 847 int GDBRemoteCommunicationClient::SendEnvironment(const Environment &env) { 848 llvm::SmallVector<std::pair<llvm::StringRef, llvm::StringRef>, 0> vec; 849 for (const auto &kv : env) 850 vec.emplace_back(kv.first(), kv.second); 851 llvm::sort(vec, llvm::less_first()); 852 for (const auto &[k, v] : vec) { 853 int r = SendEnvironmentPacket((k + "=" + v).str().c_str()); 854 if (r != 0) 855 return r; 856 } 857 return 0; 858 } 859 860 int GDBRemoteCommunicationClient::SendEnvironmentPacket( 861 char const *name_equal_value) { 862 if (name_equal_value && name_equal_value[0]) { 863 bool send_hex_encoding = false; 864 for (const char *p = name_equal_value; *p != '\0' && !send_hex_encoding; 865 ++p) { 866 if (llvm::isPrint(*p)) { 867 switch (*p) { 868 case '$': 869 case '#': 870 case '*': 871 case '}': 872 send_hex_encoding = true; 873 break; 874 default: 875 break; 876 } 877 } else { 878 // We have non printable characters, lets hex encode this... 879 send_hex_encoding = true; 880 } 881 } 882 883 StringExtractorGDBRemote response; 884 // Prefer sending unencoded, if possible and the server supports it. 885 if (!send_hex_encoding && m_supports_QEnvironment) { 886 StreamString packet; 887 packet.Printf("QEnvironment:%s", name_equal_value); 888 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 889 PacketResult::Success) 890 return -1; 891 892 if (response.IsOKResponse()) 893 return 0; 894 if (response.IsUnsupportedResponse()) 895 m_supports_QEnvironment = false; 896 else { 897 uint8_t error = response.GetError(); 898 if (error) 899 return error; 900 return -1; 901 } 902 } 903 904 if (m_supports_QEnvironmentHexEncoded) { 905 StreamString packet; 906 packet.PutCString("QEnvironmentHexEncoded:"); 907 packet.PutBytesAsRawHex8(name_equal_value, strlen(name_equal_value)); 908 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 909 PacketResult::Success) 910 return -1; 911 912 if (response.IsOKResponse()) 913 return 0; 914 if (response.IsUnsupportedResponse()) 915 m_supports_QEnvironmentHexEncoded = false; 916 else { 917 uint8_t error = response.GetError(); 918 if (error) 919 return error; 920 return -1; 921 } 922 } 923 } 924 return -1; 925 } 926 927 int GDBRemoteCommunicationClient::SendLaunchArchPacket(char const *arch) { 928 if (arch && arch[0]) { 929 StreamString packet; 930 packet.Printf("QLaunchArch:%s", arch); 931 StringExtractorGDBRemote response; 932 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 933 PacketResult::Success) { 934 if (response.IsOKResponse()) 935 return 0; 936 uint8_t error = response.GetError(); 937 if (error) 938 return error; 939 } 940 } 941 return -1; 942 } 943 944 int GDBRemoteCommunicationClient::SendLaunchEventDataPacket( 945 char const *data, bool *was_supported) { 946 if (data && *data != '\0') { 947 StreamString packet; 948 packet.Printf("QSetProcessEvent:%s", data); 949 StringExtractorGDBRemote response; 950 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 951 PacketResult::Success) { 952 if (response.IsOKResponse()) { 953 if (was_supported) 954 *was_supported = true; 955 return 0; 956 } else if (response.IsUnsupportedResponse()) { 957 if (was_supported) 958 *was_supported = false; 959 return -1; 960 } else { 961 uint8_t error = response.GetError(); 962 if (was_supported) 963 *was_supported = true; 964 if (error) 965 return error; 966 } 967 } 968 } 969 return -1; 970 } 971 972 llvm::VersionTuple GDBRemoteCommunicationClient::GetOSVersion() { 973 GetHostInfo(); 974 return m_os_version; 975 } 976 977 llvm::VersionTuple GDBRemoteCommunicationClient::GetMacCatalystVersion() { 978 GetHostInfo(); 979 return m_maccatalyst_version; 980 } 981 982 std::optional<std::string> GDBRemoteCommunicationClient::GetOSBuildString() { 983 if (GetHostInfo()) { 984 if (!m_os_build.empty()) 985 return m_os_build; 986 } 987 return std::nullopt; 988 } 989 990 std::optional<std::string> 991 GDBRemoteCommunicationClient::GetOSKernelDescription() { 992 if (GetHostInfo()) { 993 if (!m_os_kernel.empty()) 994 return m_os_kernel; 995 } 996 return std::nullopt; 997 } 998 999 bool GDBRemoteCommunicationClient::GetHostname(std::string &s) { 1000 if (GetHostInfo()) { 1001 if (!m_hostname.empty()) { 1002 s = m_hostname; 1003 return true; 1004 } 1005 } 1006 s.clear(); 1007 return false; 1008 } 1009 1010 ArchSpec GDBRemoteCommunicationClient::GetSystemArchitecture() { 1011 if (GetHostInfo()) 1012 return m_host_arch; 1013 return ArchSpec(); 1014 } 1015 1016 const lldb_private::ArchSpec & 1017 GDBRemoteCommunicationClient::GetProcessArchitecture() { 1018 if (m_qProcessInfo_is_valid == eLazyBoolCalculate) 1019 GetCurrentProcessInfo(); 1020 return m_process_arch; 1021 } 1022 1023 bool GDBRemoteCommunicationClient::GetProcessStandaloneBinary( 1024 UUID &uuid, addr_t &value, bool &value_is_offset) { 1025 if (m_qProcessInfo_is_valid == eLazyBoolCalculate) 1026 GetCurrentProcessInfo(); 1027 1028 // Return true if we have a UUID or an address/offset of the 1029 // main standalone / firmware binary being used. 1030 if (!m_process_standalone_uuid.IsValid() && 1031 m_process_standalone_value == LLDB_INVALID_ADDRESS) 1032 return false; 1033 1034 uuid = m_process_standalone_uuid; 1035 value = m_process_standalone_value; 1036 value_is_offset = m_process_standalone_value_is_offset; 1037 return true; 1038 } 1039 1040 std::vector<addr_t> 1041 GDBRemoteCommunicationClient::GetProcessStandaloneBinaries() { 1042 if (m_qProcessInfo_is_valid == eLazyBoolCalculate) 1043 GetCurrentProcessInfo(); 1044 return m_binary_addresses; 1045 } 1046 1047 bool GDBRemoteCommunicationClient::GetGDBServerVersion() { 1048 if (m_qGDBServerVersion_is_valid == eLazyBoolCalculate) { 1049 m_gdb_server_name.clear(); 1050 m_gdb_server_version = 0; 1051 m_qGDBServerVersion_is_valid = eLazyBoolNo; 1052 1053 StringExtractorGDBRemote response; 1054 if (SendPacketAndWaitForResponse("qGDBServerVersion", response) == 1055 PacketResult::Success) { 1056 if (response.IsNormalResponse()) { 1057 llvm::StringRef name, value; 1058 bool success = false; 1059 while (response.GetNameColonValue(name, value)) { 1060 if (name == "name") { 1061 success = true; 1062 m_gdb_server_name = std::string(value); 1063 } else if (name == "version") { 1064 llvm::StringRef major, minor; 1065 std::tie(major, minor) = value.split('.'); 1066 if (!major.getAsInteger(0, m_gdb_server_version)) 1067 success = true; 1068 } 1069 } 1070 if (success) 1071 m_qGDBServerVersion_is_valid = eLazyBoolYes; 1072 } 1073 } 1074 } 1075 return m_qGDBServerVersion_is_valid == eLazyBoolYes; 1076 } 1077 1078 void GDBRemoteCommunicationClient::MaybeEnableCompression( 1079 llvm::ArrayRef<llvm::StringRef> supported_compressions) { 1080 CompressionType avail_type = CompressionType::None; 1081 llvm::StringRef avail_name; 1082 1083 #if defined(HAVE_LIBCOMPRESSION) 1084 if (avail_type == CompressionType::None) { 1085 for (auto compression : supported_compressions) { 1086 if (compression == "lzfse") { 1087 avail_type = CompressionType::LZFSE; 1088 avail_name = compression; 1089 break; 1090 } 1091 } 1092 } 1093 #endif 1094 1095 #if defined(HAVE_LIBCOMPRESSION) 1096 if (avail_type == CompressionType::None) { 1097 for (auto compression : supported_compressions) { 1098 if (compression == "zlib-deflate") { 1099 avail_type = CompressionType::ZlibDeflate; 1100 avail_name = compression; 1101 break; 1102 } 1103 } 1104 } 1105 #endif 1106 1107 #if LLVM_ENABLE_ZLIB 1108 if (avail_type == CompressionType::None) { 1109 for (auto compression : supported_compressions) { 1110 if (compression == "zlib-deflate") { 1111 avail_type = CompressionType::ZlibDeflate; 1112 avail_name = compression; 1113 break; 1114 } 1115 } 1116 } 1117 #endif 1118 1119 #if defined(HAVE_LIBCOMPRESSION) 1120 if (avail_type == CompressionType::None) { 1121 for (auto compression : supported_compressions) { 1122 if (compression == "lz4") { 1123 avail_type = CompressionType::LZ4; 1124 avail_name = compression; 1125 break; 1126 } 1127 } 1128 } 1129 #endif 1130 1131 #if defined(HAVE_LIBCOMPRESSION) 1132 if (avail_type == CompressionType::None) { 1133 for (auto compression : supported_compressions) { 1134 if (compression == "lzma") { 1135 avail_type = CompressionType::LZMA; 1136 avail_name = compression; 1137 break; 1138 } 1139 } 1140 } 1141 #endif 1142 1143 if (avail_type != CompressionType::None) { 1144 StringExtractorGDBRemote response; 1145 std::string packet = "QEnableCompression:type:" + avail_name.str() + ";"; 1146 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success) 1147 return; 1148 1149 if (response.IsOKResponse()) { 1150 m_compression_type = avail_type; 1151 } 1152 } 1153 } 1154 1155 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() { 1156 if (GetGDBServerVersion()) { 1157 if (!m_gdb_server_name.empty()) 1158 return m_gdb_server_name.c_str(); 1159 } 1160 return nullptr; 1161 } 1162 1163 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() { 1164 if (GetGDBServerVersion()) 1165 return m_gdb_server_version; 1166 return 0; 1167 } 1168 1169 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) { 1170 StringExtractorGDBRemote response; 1171 if (SendPacketAndWaitForResponse("qC", response) != PacketResult::Success) 1172 return false; 1173 1174 if (!response.IsNormalResponse()) 1175 return false; 1176 1177 if (response.GetChar() == 'Q' && response.GetChar() == 'C') { 1178 auto pid_tid = response.GetPidTid(0); 1179 if (!pid_tid) 1180 return false; 1181 1182 lldb::pid_t pid = pid_tid->first; 1183 // invalid 1184 if (pid == StringExtractorGDBRemote::AllProcesses) 1185 return false; 1186 1187 // if we get pid as well, update m_curr_pid 1188 if (pid != 0) { 1189 m_curr_pid_run = m_curr_pid = pid; 1190 m_curr_pid_is_valid = eLazyBoolYes; 1191 } 1192 tid = pid_tid->second; 1193 } 1194 1195 return true; 1196 } 1197 1198 static void ParseOSType(llvm::StringRef value, std::string &os_name, 1199 std::string &environment) { 1200 if (value == "iossimulator" || value == "tvossimulator" || 1201 value == "watchossimulator" || value == "xrossimulator" || 1202 value == "visionossimulator") { 1203 environment = "simulator"; 1204 os_name = value.drop_back(environment.size()).str(); 1205 } else if (value == "maccatalyst") { 1206 os_name = "ios"; 1207 environment = "macabi"; 1208 } else { 1209 os_name = value.str(); 1210 } 1211 } 1212 1213 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) { 1214 Log *log = GetLog(GDBRLog::Process); 1215 1216 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) { 1217 // host info computation can require DNS traffic and shelling out to external processes. 1218 // Increase the timeout to account for that. 1219 ScopedTimeout timeout(*this, seconds(10)); 1220 m_qHostInfo_is_valid = eLazyBoolNo; 1221 StringExtractorGDBRemote response; 1222 if (SendPacketAndWaitForResponse("qHostInfo", response) == 1223 PacketResult::Success) { 1224 if (response.IsNormalResponse()) { 1225 llvm::StringRef name; 1226 llvm::StringRef value; 1227 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1228 uint32_t sub = 0; 1229 std::string arch_name; 1230 std::string os_name; 1231 std::string environment; 1232 std::string vendor_name; 1233 std::string triple; 1234 uint32_t pointer_byte_size = 0; 1235 ByteOrder byte_order = eByteOrderInvalid; 1236 uint32_t num_keys_decoded = 0; 1237 while (response.GetNameColonValue(name, value)) { 1238 if (name == "cputype") { 1239 // exception type in big endian hex 1240 if (!value.getAsInteger(0, cpu)) 1241 ++num_keys_decoded; 1242 } else if (name == "cpusubtype") { 1243 // exception count in big endian hex 1244 if (!value.getAsInteger(0, sub)) 1245 ++num_keys_decoded; 1246 } else if (name == "arch") { 1247 arch_name = std::string(value); 1248 ++num_keys_decoded; 1249 } else if (name == "triple") { 1250 StringExtractor extractor(value); 1251 extractor.GetHexByteString(triple); 1252 ++num_keys_decoded; 1253 } else if (name == "distribution_id") { 1254 StringExtractor extractor(value); 1255 extractor.GetHexByteString(m_host_distribution_id); 1256 ++num_keys_decoded; 1257 } else if (name == "os_build") { 1258 StringExtractor extractor(value); 1259 extractor.GetHexByteString(m_os_build); 1260 ++num_keys_decoded; 1261 } else if (name == "hostname") { 1262 StringExtractor extractor(value); 1263 extractor.GetHexByteString(m_hostname); 1264 ++num_keys_decoded; 1265 } else if (name == "os_kernel") { 1266 StringExtractor extractor(value); 1267 extractor.GetHexByteString(m_os_kernel); 1268 ++num_keys_decoded; 1269 } else if (name == "ostype") { 1270 ParseOSType(value, os_name, environment); 1271 ++num_keys_decoded; 1272 } else if (name == "vendor") { 1273 vendor_name = std::string(value); 1274 ++num_keys_decoded; 1275 } else if (name == "endian") { 1276 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value) 1277 .Case("little", eByteOrderLittle) 1278 .Case("big", eByteOrderBig) 1279 .Case("pdp", eByteOrderPDP) 1280 .Default(eByteOrderInvalid); 1281 if (byte_order != eByteOrderInvalid) 1282 ++num_keys_decoded; 1283 } else if (name == "ptrsize") { 1284 if (!value.getAsInteger(0, pointer_byte_size)) 1285 ++num_keys_decoded; 1286 } else if (name == "addressing_bits") { 1287 if (!value.getAsInteger(0, m_low_mem_addressing_bits)) { 1288 ++num_keys_decoded; 1289 } 1290 } else if (name == "high_mem_addressing_bits") { 1291 if (!value.getAsInteger(0, m_high_mem_addressing_bits)) 1292 ++num_keys_decoded; 1293 } else if (name == "low_mem_addressing_bits") { 1294 if (!value.getAsInteger(0, m_low_mem_addressing_bits)) 1295 ++num_keys_decoded; 1296 } else if (name == "os_version" || 1297 name == "version") // Older debugserver binaries used 1298 // the "version" key instead of 1299 // "os_version"... 1300 { 1301 if (!m_os_version.tryParse(value)) 1302 ++num_keys_decoded; 1303 } else if (name == "maccatalyst_version") { 1304 if (!m_maccatalyst_version.tryParse(value)) 1305 ++num_keys_decoded; 1306 } else if (name == "watchpoint_exceptions_received") { 1307 m_watchpoints_trigger_after_instruction = 1308 llvm::StringSwitch<LazyBool>(value) 1309 .Case("before", eLazyBoolNo) 1310 .Case("after", eLazyBoolYes) 1311 .Default(eLazyBoolCalculate); 1312 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate) 1313 ++num_keys_decoded; 1314 } else if (name == "default_packet_timeout") { 1315 uint32_t timeout_seconds; 1316 if (!value.getAsInteger(0, timeout_seconds)) { 1317 m_default_packet_timeout = seconds(timeout_seconds); 1318 SetPacketTimeout(m_default_packet_timeout); 1319 ++num_keys_decoded; 1320 } 1321 } else if (name == "vm-page-size") { 1322 int page_size; 1323 if (!value.getAsInteger(0, page_size)) { 1324 m_target_vm_page_size = page_size; 1325 ++num_keys_decoded; 1326 } 1327 } 1328 } 1329 1330 if (num_keys_decoded > 0) 1331 m_qHostInfo_is_valid = eLazyBoolYes; 1332 1333 if (triple.empty()) { 1334 if (arch_name.empty()) { 1335 if (cpu != LLDB_INVALID_CPUTYPE) { 1336 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 1337 if (pointer_byte_size) { 1338 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1339 } 1340 if (byte_order != eByteOrderInvalid) { 1341 assert(byte_order == m_host_arch.GetByteOrder()); 1342 } 1343 1344 if (!vendor_name.empty()) 1345 m_host_arch.GetTriple().setVendorName( 1346 llvm::StringRef(vendor_name)); 1347 if (!os_name.empty()) 1348 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 1349 if (!environment.empty()) 1350 m_host_arch.GetTriple().setEnvironmentName(environment); 1351 } 1352 } else { 1353 std::string triple; 1354 triple += arch_name; 1355 if (!vendor_name.empty() || !os_name.empty()) { 1356 triple += '-'; 1357 if (vendor_name.empty()) 1358 triple += "unknown"; 1359 else 1360 triple += vendor_name; 1361 triple += '-'; 1362 if (os_name.empty()) 1363 triple += "unknown"; 1364 else 1365 triple += os_name; 1366 } 1367 m_host_arch.SetTriple(triple.c_str()); 1368 1369 llvm::Triple &host_triple = m_host_arch.GetTriple(); 1370 if (host_triple.getVendor() == llvm::Triple::Apple && 1371 host_triple.getOS() == llvm::Triple::Darwin) { 1372 switch (m_host_arch.GetMachine()) { 1373 case llvm::Triple::aarch64: 1374 case llvm::Triple::aarch64_32: 1375 case llvm::Triple::arm: 1376 case llvm::Triple::thumb: 1377 host_triple.setOS(llvm::Triple::IOS); 1378 break; 1379 default: 1380 host_triple.setOS(llvm::Triple::MacOSX); 1381 break; 1382 } 1383 } 1384 if (pointer_byte_size) { 1385 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1386 } 1387 if (byte_order != eByteOrderInvalid) { 1388 assert(byte_order == m_host_arch.GetByteOrder()); 1389 } 1390 } 1391 } else { 1392 m_host_arch.SetTriple(triple.c_str()); 1393 if (pointer_byte_size) { 1394 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1395 } 1396 if (byte_order != eByteOrderInvalid) { 1397 assert(byte_order == m_host_arch.GetByteOrder()); 1398 } 1399 1400 LLDB_LOGF(log, 1401 "GDBRemoteCommunicationClient::%s parsed host " 1402 "architecture as %s, triple as %s from triple text %s", 1403 __FUNCTION__, 1404 m_host_arch.GetArchitectureName() 1405 ? m_host_arch.GetArchitectureName() 1406 : "<null-arch-name>", 1407 m_host_arch.GetTriple().getTriple().c_str(), 1408 triple.c_str()); 1409 } 1410 } 1411 } 1412 } 1413 return m_qHostInfo_is_valid == eLazyBoolYes; 1414 } 1415 1416 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data, 1417 size_t data_len) { 1418 StreamString packet; 1419 packet.PutCString("I"); 1420 packet.PutBytesAsRawHex8(data, data_len); 1421 StringExtractorGDBRemote response; 1422 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 1423 PacketResult::Success) { 1424 return 0; 1425 } 1426 return response.GetError(); 1427 } 1428 1429 const lldb_private::ArchSpec & 1430 GDBRemoteCommunicationClient::GetHostArchitecture() { 1431 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1432 GetHostInfo(); 1433 return m_host_arch; 1434 } 1435 1436 AddressableBits GDBRemoteCommunicationClient::GetAddressableBits() { 1437 AddressableBits addressable_bits; 1438 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1439 GetHostInfo(); 1440 1441 if (m_low_mem_addressing_bits == m_high_mem_addressing_bits) 1442 addressable_bits.SetAddressableBits(m_low_mem_addressing_bits); 1443 else 1444 addressable_bits.SetAddressableBits(m_low_mem_addressing_bits, 1445 m_high_mem_addressing_bits); 1446 return addressable_bits; 1447 } 1448 1449 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() { 1450 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1451 GetHostInfo(); 1452 return m_default_packet_timeout; 1453 } 1454 1455 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size, 1456 uint32_t permissions) { 1457 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) { 1458 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1459 char packet[64]; 1460 const int packet_len = ::snprintf( 1461 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size, 1462 permissions & lldb::ePermissionsReadable ? "r" : "", 1463 permissions & lldb::ePermissionsWritable ? "w" : "", 1464 permissions & lldb::ePermissionsExecutable ? "x" : ""); 1465 assert(packet_len < (int)sizeof(packet)); 1466 UNUSED_IF_ASSERT_DISABLED(packet_len); 1467 StringExtractorGDBRemote response; 1468 if (SendPacketAndWaitForResponse(packet, response) == 1469 PacketResult::Success) { 1470 if (response.IsUnsupportedResponse()) 1471 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1472 else if (!response.IsErrorResponse()) 1473 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1474 } else { 1475 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1476 } 1477 } 1478 return LLDB_INVALID_ADDRESS; 1479 } 1480 1481 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) { 1482 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) { 1483 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1484 char packet[64]; 1485 const int packet_len = 1486 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 1487 assert(packet_len < (int)sizeof(packet)); 1488 UNUSED_IF_ASSERT_DISABLED(packet_len); 1489 StringExtractorGDBRemote response; 1490 if (SendPacketAndWaitForResponse(packet, response) == 1491 PacketResult::Success) { 1492 if (response.IsUnsupportedResponse()) 1493 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1494 else if (response.IsOKResponse()) 1495 return true; 1496 } else { 1497 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1498 } 1499 } 1500 return false; 1501 } 1502 1503 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped, 1504 lldb::pid_t pid) { 1505 Status error; 1506 lldb_private::StreamString packet; 1507 1508 packet.PutChar('D'); 1509 if (keep_stopped) { 1510 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) { 1511 char packet[64]; 1512 const int packet_len = 1513 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:"); 1514 assert(packet_len < (int)sizeof(packet)); 1515 UNUSED_IF_ASSERT_DISABLED(packet_len); 1516 StringExtractorGDBRemote response; 1517 if (SendPacketAndWaitForResponse(packet, response) == 1518 PacketResult::Success && 1519 response.IsOKResponse()) { 1520 m_supports_detach_stay_stopped = eLazyBoolYes; 1521 } else { 1522 m_supports_detach_stay_stopped = eLazyBoolNo; 1523 } 1524 } 1525 1526 if (m_supports_detach_stay_stopped == eLazyBoolNo) { 1527 error = Status::FromErrorString( 1528 "Stays stopped not supported by this target."); 1529 return error; 1530 } else { 1531 packet.PutChar('1'); 1532 } 1533 } 1534 1535 if (GetMultiprocessSupported()) { 1536 // Some servers (e.g. qemu) require specifying the PID even if only a single 1537 // process is running. 1538 if (pid == LLDB_INVALID_PROCESS_ID) 1539 pid = GetCurrentProcessID(); 1540 packet.PutChar(';'); 1541 packet.PutHex64(pid); 1542 } else if (pid != LLDB_INVALID_PROCESS_ID) { 1543 error = Status::FromErrorString( 1544 "Multiprocess extension not supported by the server."); 1545 return error; 1546 } 1547 1548 StringExtractorGDBRemote response; 1549 PacketResult packet_result = 1550 SendPacketAndWaitForResponse(packet.GetString(), response); 1551 if (packet_result != PacketResult::Success) 1552 error = Status::FromErrorString("Sending isconnect packet failed."); 1553 return error; 1554 } 1555 1556 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo( 1557 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) { 1558 Status error; 1559 region_info.Clear(); 1560 1561 if (m_supports_memory_region_info != eLazyBoolNo) { 1562 m_supports_memory_region_info = eLazyBoolYes; 1563 char packet[64]; 1564 const int packet_len = ::snprintf( 1565 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 1566 assert(packet_len < (int)sizeof(packet)); 1567 UNUSED_IF_ASSERT_DISABLED(packet_len); 1568 StringExtractorGDBRemote response; 1569 if (SendPacketAndWaitForResponse(packet, response) == 1570 PacketResult::Success && 1571 response.GetResponseType() == StringExtractorGDBRemote::eResponse) { 1572 llvm::StringRef name; 1573 llvm::StringRef value; 1574 addr_t addr_value = LLDB_INVALID_ADDRESS; 1575 bool success = true; 1576 bool saw_permissions = false; 1577 while (success && response.GetNameColonValue(name, value)) { 1578 if (name == "start") { 1579 if (!value.getAsInteger(16, addr_value)) 1580 region_info.GetRange().SetRangeBase(addr_value); 1581 } else if (name == "size") { 1582 if (!value.getAsInteger(16, addr_value)) { 1583 region_info.GetRange().SetByteSize(addr_value); 1584 if (region_info.GetRange().GetRangeEnd() < 1585 region_info.GetRange().GetRangeBase()) { 1586 // Range size overflowed, truncate it. 1587 region_info.GetRange().SetRangeEnd(LLDB_INVALID_ADDRESS); 1588 } 1589 } 1590 } else if (name == "permissions" && region_info.GetRange().IsValid()) { 1591 saw_permissions = true; 1592 if (region_info.GetRange().Contains(addr)) { 1593 if (value.contains('r')) 1594 region_info.SetReadable(MemoryRegionInfo::eYes); 1595 else 1596 region_info.SetReadable(MemoryRegionInfo::eNo); 1597 1598 if (value.contains('w')) 1599 region_info.SetWritable(MemoryRegionInfo::eYes); 1600 else 1601 region_info.SetWritable(MemoryRegionInfo::eNo); 1602 1603 if (value.contains('x')) 1604 region_info.SetExecutable(MemoryRegionInfo::eYes); 1605 else 1606 region_info.SetExecutable(MemoryRegionInfo::eNo); 1607 1608 region_info.SetMapped(MemoryRegionInfo::eYes); 1609 } else { 1610 // The reported region does not contain this address -- we're 1611 // looking at an unmapped page 1612 region_info.SetReadable(MemoryRegionInfo::eNo); 1613 region_info.SetWritable(MemoryRegionInfo::eNo); 1614 region_info.SetExecutable(MemoryRegionInfo::eNo); 1615 region_info.SetMapped(MemoryRegionInfo::eNo); 1616 } 1617 } else if (name == "name") { 1618 StringExtractorGDBRemote name_extractor(value); 1619 std::string name; 1620 name_extractor.GetHexByteString(name); 1621 region_info.SetName(name.c_str()); 1622 } else if (name == "flags") { 1623 region_info.SetMemoryTagged(MemoryRegionInfo::eNo); 1624 1625 llvm::StringRef flags = value; 1626 llvm::StringRef flag; 1627 while (flags.size()) { 1628 flags = flags.ltrim(); 1629 std::tie(flag, flags) = flags.split(' '); 1630 // To account for trailing whitespace 1631 if (flag.size()) { 1632 if (flag == "mt") { 1633 region_info.SetMemoryTagged(MemoryRegionInfo::eYes); 1634 break; 1635 } 1636 } 1637 } 1638 } else if (name == "type") { 1639 for (llvm::StringRef entry : llvm::split(value, ',')) { 1640 if (entry == "stack") 1641 region_info.SetIsStackMemory(MemoryRegionInfo::eYes); 1642 else if (entry == "heap") 1643 region_info.SetIsStackMemory(MemoryRegionInfo::eNo); 1644 } 1645 } else if (name == "error") { 1646 StringExtractorGDBRemote error_extractor(value); 1647 std::string error_string; 1648 // Now convert the HEX bytes into a string value 1649 error_extractor.GetHexByteString(error_string); 1650 error = Status::FromErrorString(error_string.c_str()); 1651 } else if (name == "dirty-pages") { 1652 std::vector<addr_t> dirty_page_list; 1653 for (llvm::StringRef x : llvm::split(value, ',')) { 1654 addr_t page; 1655 x.consume_front("0x"); 1656 if (llvm::to_integer(x, page, 16)) 1657 dirty_page_list.push_back(page); 1658 } 1659 region_info.SetDirtyPageList(dirty_page_list); 1660 } 1661 } 1662 1663 if (m_target_vm_page_size != 0) 1664 region_info.SetPageSize(m_target_vm_page_size); 1665 1666 if (region_info.GetRange().IsValid()) { 1667 // We got a valid address range back but no permissions -- which means 1668 // this is an unmapped page 1669 if (!saw_permissions) { 1670 region_info.SetReadable(MemoryRegionInfo::eNo); 1671 region_info.SetWritable(MemoryRegionInfo::eNo); 1672 region_info.SetExecutable(MemoryRegionInfo::eNo); 1673 region_info.SetMapped(MemoryRegionInfo::eNo); 1674 } 1675 } else { 1676 // We got an invalid address range back 1677 error = Status::FromErrorString("Server returned invalid range"); 1678 } 1679 } else { 1680 m_supports_memory_region_info = eLazyBoolNo; 1681 } 1682 } 1683 1684 if (m_supports_memory_region_info == eLazyBoolNo) { 1685 error = Status::FromErrorString("qMemoryRegionInfo is not supported"); 1686 } 1687 1688 // Try qXfer:memory-map:read to get region information not included in 1689 // qMemoryRegionInfo 1690 MemoryRegionInfo qXfer_region_info; 1691 Status qXfer_error = GetQXferMemoryMapRegionInfo(addr, qXfer_region_info); 1692 1693 if (error.Fail()) { 1694 // If qMemoryRegionInfo failed, but qXfer:memory-map:read succeeded, use 1695 // the qXfer result as a fallback 1696 if (qXfer_error.Success()) { 1697 region_info = qXfer_region_info; 1698 error.Clear(); 1699 } else { 1700 region_info.Clear(); 1701 } 1702 } else if (qXfer_error.Success()) { 1703 // If both qMemoryRegionInfo and qXfer:memory-map:read succeeded, and if 1704 // both regions are the same range, update the result to include the flash- 1705 // memory information that is specific to the qXfer result. 1706 if (region_info.GetRange() == qXfer_region_info.GetRange()) { 1707 region_info.SetFlash(qXfer_region_info.GetFlash()); 1708 region_info.SetBlocksize(qXfer_region_info.GetBlocksize()); 1709 } 1710 } 1711 return error; 1712 } 1713 1714 Status GDBRemoteCommunicationClient::GetQXferMemoryMapRegionInfo( 1715 lldb::addr_t addr, MemoryRegionInfo ®ion) { 1716 Status error = LoadQXferMemoryMap(); 1717 if (!error.Success()) 1718 return error; 1719 for (const auto &map_region : m_qXfer_memory_map) { 1720 if (map_region.GetRange().Contains(addr)) { 1721 region = map_region; 1722 return error; 1723 } 1724 } 1725 error = Status::FromErrorString("Region not found"); 1726 return error; 1727 } 1728 1729 Status GDBRemoteCommunicationClient::LoadQXferMemoryMap() { 1730 1731 Status error; 1732 1733 if (m_qXfer_memory_map_loaded) 1734 // Already loaded, return success 1735 return error; 1736 1737 if (!XMLDocument::XMLEnabled()) { 1738 error = Status::FromErrorString("XML is not supported"); 1739 return error; 1740 } 1741 1742 if (!GetQXferMemoryMapReadSupported()) { 1743 error = Status::FromErrorString("Memory map is not supported"); 1744 return error; 1745 } 1746 1747 llvm::Expected<std::string> xml = ReadExtFeature("memory-map", ""); 1748 if (!xml) 1749 return Status::FromError(xml.takeError()); 1750 1751 XMLDocument xml_document; 1752 1753 if (!xml_document.ParseMemory(xml->c_str(), xml->size())) { 1754 error = Status::FromErrorString("Failed to parse memory map xml"); 1755 return error; 1756 } 1757 1758 XMLNode map_node = xml_document.GetRootElement("memory-map"); 1759 if (!map_node) { 1760 error = Status::FromErrorString("Invalid root node in memory map xml"); 1761 return error; 1762 } 1763 1764 m_qXfer_memory_map.clear(); 1765 1766 map_node.ForEachChildElement([this](const XMLNode &memory_node) -> bool { 1767 if (!memory_node.IsElement()) 1768 return true; 1769 if (memory_node.GetName() != "memory") 1770 return true; 1771 auto type = memory_node.GetAttributeValue("type", ""); 1772 uint64_t start; 1773 uint64_t length; 1774 if (!memory_node.GetAttributeValueAsUnsigned("start", start)) 1775 return true; 1776 if (!memory_node.GetAttributeValueAsUnsigned("length", length)) 1777 return true; 1778 MemoryRegionInfo region; 1779 region.GetRange().SetRangeBase(start); 1780 region.GetRange().SetByteSize(length); 1781 if (type == "rom") { 1782 region.SetReadable(MemoryRegionInfo::eYes); 1783 this->m_qXfer_memory_map.push_back(region); 1784 } else if (type == "ram") { 1785 region.SetReadable(MemoryRegionInfo::eYes); 1786 region.SetWritable(MemoryRegionInfo::eYes); 1787 this->m_qXfer_memory_map.push_back(region); 1788 } else if (type == "flash") { 1789 region.SetFlash(MemoryRegionInfo::eYes); 1790 memory_node.ForEachChildElement( 1791 [®ion](const XMLNode &prop_node) -> bool { 1792 if (!prop_node.IsElement()) 1793 return true; 1794 if (prop_node.GetName() != "property") 1795 return true; 1796 auto propname = prop_node.GetAttributeValue("name", ""); 1797 if (propname == "blocksize") { 1798 uint64_t blocksize; 1799 if (prop_node.GetElementTextAsUnsigned(blocksize)) 1800 region.SetBlocksize(blocksize); 1801 } 1802 return true; 1803 }); 1804 this->m_qXfer_memory_map.push_back(region); 1805 } 1806 return true; 1807 }); 1808 1809 m_qXfer_memory_map_loaded = true; 1810 1811 return error; 1812 } 1813 1814 std::optional<uint32_t> GDBRemoteCommunicationClient::GetWatchpointSlotCount() { 1815 if (m_supports_watchpoint_support_info == eLazyBoolYes) { 1816 return m_num_supported_hardware_watchpoints; 1817 } 1818 1819 std::optional<uint32_t> num; 1820 if (m_supports_watchpoint_support_info != eLazyBoolNo) { 1821 StringExtractorGDBRemote response; 1822 if (SendPacketAndWaitForResponse("qWatchpointSupportInfo:", response) == 1823 PacketResult::Success) { 1824 m_supports_watchpoint_support_info = eLazyBoolYes; 1825 llvm::StringRef name; 1826 llvm::StringRef value; 1827 while (response.GetNameColonValue(name, value)) { 1828 if (name == "num") { 1829 value.getAsInteger(0, m_num_supported_hardware_watchpoints); 1830 num = m_num_supported_hardware_watchpoints; 1831 } 1832 } 1833 if (!num) { 1834 m_supports_watchpoint_support_info = eLazyBoolNo; 1835 } 1836 } else { 1837 m_supports_watchpoint_support_info = eLazyBoolNo; 1838 } 1839 } 1840 1841 return num; 1842 } 1843 1844 WatchpointHardwareFeature 1845 GDBRemoteCommunicationClient::GetSupportedWatchpointTypes() { 1846 return m_watchpoint_types; 1847 } 1848 1849 std::optional<bool> GDBRemoteCommunicationClient::GetWatchpointReportedAfter() { 1850 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1851 GetHostInfo(); 1852 1853 // Process determines this by target CPU, but allow for the 1854 // remote stub to override it via the qHostInfo 1855 // watchpoint_exceptions_received key, if it is present. 1856 if (m_qHostInfo_is_valid == eLazyBoolYes) { 1857 if (m_watchpoints_trigger_after_instruction == eLazyBoolNo) 1858 return false; 1859 if (m_watchpoints_trigger_after_instruction == eLazyBoolYes) 1860 return true; 1861 } 1862 1863 return std::nullopt; 1864 } 1865 1866 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) { 1867 if (file_spec) { 1868 std::string path{file_spec.GetPath(false)}; 1869 StreamString packet; 1870 packet.PutCString("QSetSTDIN:"); 1871 packet.PutStringAsRawHex8(path); 1872 1873 StringExtractorGDBRemote response; 1874 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 1875 PacketResult::Success) { 1876 if (response.IsOKResponse()) 1877 return 0; 1878 uint8_t error = response.GetError(); 1879 if (error) 1880 return error; 1881 } 1882 } 1883 return -1; 1884 } 1885 1886 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) { 1887 if (file_spec) { 1888 std::string path{file_spec.GetPath(false)}; 1889 StreamString packet; 1890 packet.PutCString("QSetSTDOUT:"); 1891 packet.PutStringAsRawHex8(path); 1892 1893 StringExtractorGDBRemote response; 1894 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 1895 PacketResult::Success) { 1896 if (response.IsOKResponse()) 1897 return 0; 1898 uint8_t error = response.GetError(); 1899 if (error) 1900 return error; 1901 } 1902 } 1903 return -1; 1904 } 1905 1906 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) { 1907 if (file_spec) { 1908 std::string path{file_spec.GetPath(false)}; 1909 StreamString packet; 1910 packet.PutCString("QSetSTDERR:"); 1911 packet.PutStringAsRawHex8(path); 1912 1913 StringExtractorGDBRemote response; 1914 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 1915 PacketResult::Success) { 1916 if (response.IsOKResponse()) 1917 return 0; 1918 uint8_t error = response.GetError(); 1919 if (error) 1920 return error; 1921 } 1922 } 1923 return -1; 1924 } 1925 1926 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) { 1927 StringExtractorGDBRemote response; 1928 if (SendPacketAndWaitForResponse("qGetWorkingDir", response) == 1929 PacketResult::Success) { 1930 if (response.IsUnsupportedResponse()) 1931 return false; 1932 if (response.IsErrorResponse()) 1933 return false; 1934 std::string cwd; 1935 response.GetHexByteString(cwd); 1936 working_dir.SetFile(cwd, GetHostArchitecture().GetTriple()); 1937 return !cwd.empty(); 1938 } 1939 return false; 1940 } 1941 1942 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) { 1943 if (working_dir) { 1944 std::string path{working_dir.GetPath(false)}; 1945 StreamString packet; 1946 packet.PutCString("QSetWorkingDir:"); 1947 packet.PutStringAsRawHex8(path); 1948 1949 StringExtractorGDBRemote response; 1950 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 1951 PacketResult::Success) { 1952 if (response.IsOKResponse()) 1953 return 0; 1954 uint8_t error = response.GetError(); 1955 if (error) 1956 return error; 1957 } 1958 } 1959 return -1; 1960 } 1961 1962 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) { 1963 char packet[32]; 1964 const int packet_len = 1965 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0); 1966 assert(packet_len < (int)sizeof(packet)); 1967 UNUSED_IF_ASSERT_DISABLED(packet_len); 1968 StringExtractorGDBRemote response; 1969 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) { 1970 if (response.IsOKResponse()) 1971 return 0; 1972 uint8_t error = response.GetError(); 1973 if (error) 1974 return error; 1975 } 1976 return -1; 1977 } 1978 1979 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) { 1980 char packet[32]; 1981 const int packet_len = ::snprintf(packet, sizeof(packet), 1982 "QSetDetachOnError:%i", enable ? 1 : 0); 1983 assert(packet_len < (int)sizeof(packet)); 1984 UNUSED_IF_ASSERT_DISABLED(packet_len); 1985 StringExtractorGDBRemote response; 1986 if (SendPacketAndWaitForResponse(packet, response) == PacketResult::Success) { 1987 if (response.IsOKResponse()) 1988 return 0; 1989 uint8_t error = response.GetError(); 1990 if (error) 1991 return error; 1992 } 1993 return -1; 1994 } 1995 1996 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse( 1997 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) { 1998 if (response.IsNormalResponse()) { 1999 llvm::StringRef name; 2000 llvm::StringRef value; 2001 StringExtractor extractor; 2002 2003 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2004 uint32_t sub = 0; 2005 std::string vendor; 2006 std::string os_type; 2007 2008 while (response.GetNameColonValue(name, value)) { 2009 if (name == "pid") { 2010 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2011 value.getAsInteger(0, pid); 2012 process_info.SetProcessID(pid); 2013 } else if (name == "ppid") { 2014 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2015 value.getAsInteger(0, pid); 2016 process_info.SetParentProcessID(pid); 2017 } else if (name == "uid") { 2018 uint32_t uid = UINT32_MAX; 2019 value.getAsInteger(0, uid); 2020 process_info.SetUserID(uid); 2021 } else if (name == "euid") { 2022 uint32_t uid = UINT32_MAX; 2023 value.getAsInteger(0, uid); 2024 process_info.SetEffectiveUserID(uid); 2025 } else if (name == "gid") { 2026 uint32_t gid = UINT32_MAX; 2027 value.getAsInteger(0, gid); 2028 process_info.SetGroupID(gid); 2029 } else if (name == "egid") { 2030 uint32_t gid = UINT32_MAX; 2031 value.getAsInteger(0, gid); 2032 process_info.SetEffectiveGroupID(gid); 2033 } else if (name == "triple") { 2034 StringExtractor extractor(value); 2035 std::string triple; 2036 extractor.GetHexByteString(triple); 2037 process_info.GetArchitecture().SetTriple(triple.c_str()); 2038 } else if (name == "name") { 2039 StringExtractor extractor(value); 2040 // The process name from ASCII hex bytes since we can't control the 2041 // characters in a process name 2042 std::string name; 2043 extractor.GetHexByteString(name); 2044 process_info.GetExecutableFile().SetFile(name, FileSpec::Style::native); 2045 } else if (name == "args") { 2046 llvm::StringRef encoded_args(value), hex_arg; 2047 2048 bool is_arg0 = true; 2049 while (!encoded_args.empty()) { 2050 std::tie(hex_arg, encoded_args) = encoded_args.split('-'); 2051 std::string arg; 2052 StringExtractor extractor(hex_arg); 2053 if (extractor.GetHexByteString(arg) * 2 != hex_arg.size()) { 2054 // In case of wrong encoding, we discard all the arguments 2055 process_info.GetArguments().Clear(); 2056 process_info.SetArg0(""); 2057 break; 2058 } 2059 if (is_arg0) 2060 process_info.SetArg0(arg); 2061 else 2062 process_info.GetArguments().AppendArgument(arg); 2063 is_arg0 = false; 2064 } 2065 } else if (name == "cputype") { 2066 value.getAsInteger(0, cpu); 2067 } else if (name == "cpusubtype") { 2068 value.getAsInteger(0, sub); 2069 } else if (name == "vendor") { 2070 vendor = std::string(value); 2071 } else if (name == "ostype") { 2072 os_type = std::string(value); 2073 } 2074 } 2075 2076 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) { 2077 if (vendor == "apple") { 2078 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu, 2079 sub); 2080 process_info.GetArchitecture().GetTriple().setVendorName( 2081 llvm::StringRef(vendor)); 2082 process_info.GetArchitecture().GetTriple().setOSName( 2083 llvm::StringRef(os_type)); 2084 } 2085 } 2086 2087 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 2088 return true; 2089 } 2090 return false; 2091 } 2092 2093 bool GDBRemoteCommunicationClient::GetProcessInfo( 2094 lldb::pid_t pid, ProcessInstanceInfo &process_info) { 2095 process_info.Clear(); 2096 2097 if (m_supports_qProcessInfoPID) { 2098 char packet[32]; 2099 const int packet_len = 2100 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid); 2101 assert(packet_len < (int)sizeof(packet)); 2102 UNUSED_IF_ASSERT_DISABLED(packet_len); 2103 StringExtractorGDBRemote response; 2104 if (SendPacketAndWaitForResponse(packet, response) == 2105 PacketResult::Success) { 2106 return DecodeProcessInfoResponse(response, process_info); 2107 } else { 2108 m_supports_qProcessInfoPID = false; 2109 return false; 2110 } 2111 } 2112 return false; 2113 } 2114 2115 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) { 2116 Log *log(GetLog(GDBRLog::Process | GDBRLog::Packets)); 2117 2118 if (allow_lazy) { 2119 if (m_qProcessInfo_is_valid == eLazyBoolYes) 2120 return true; 2121 if (m_qProcessInfo_is_valid == eLazyBoolNo) 2122 return false; 2123 } 2124 2125 GetHostInfo(); 2126 2127 StringExtractorGDBRemote response; 2128 if (SendPacketAndWaitForResponse("qProcessInfo", response) == 2129 PacketResult::Success) { 2130 if (response.IsNormalResponse()) { 2131 llvm::StringRef name; 2132 llvm::StringRef value; 2133 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2134 uint32_t sub = 0; 2135 std::string arch_name; 2136 std::string os_name; 2137 std::string environment; 2138 std::string vendor_name; 2139 std::string triple; 2140 std::string elf_abi; 2141 uint32_t pointer_byte_size = 0; 2142 StringExtractor extractor; 2143 ByteOrder byte_order = eByteOrderInvalid; 2144 uint32_t num_keys_decoded = 0; 2145 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2146 while (response.GetNameColonValue(name, value)) { 2147 if (name == "cputype") { 2148 if (!value.getAsInteger(16, cpu)) 2149 ++num_keys_decoded; 2150 } else if (name == "cpusubtype") { 2151 if (!value.getAsInteger(16, sub)) { 2152 ++num_keys_decoded; 2153 // Workaround for pre-2024 Apple debugserver, which always 2154 // returns arm64e on arm64e-capable hardware regardless of 2155 // what the process is. This can be deleted at some point 2156 // in the future. 2157 if (cpu == llvm::MachO::CPU_TYPE_ARM64 && 2158 sub == llvm::MachO::CPU_SUBTYPE_ARM64E) { 2159 if (GetGDBServerVersion()) 2160 if (m_gdb_server_version >= 1000 && 2161 m_gdb_server_version <= 1504) 2162 sub = 0; 2163 } 2164 } 2165 } else if (name == "triple") { 2166 StringExtractor extractor(value); 2167 extractor.GetHexByteString(triple); 2168 ++num_keys_decoded; 2169 } else if (name == "ostype") { 2170 ParseOSType(value, os_name, environment); 2171 ++num_keys_decoded; 2172 } else if (name == "vendor") { 2173 vendor_name = std::string(value); 2174 ++num_keys_decoded; 2175 } else if (name == "endian") { 2176 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value) 2177 .Case("little", eByteOrderLittle) 2178 .Case("big", eByteOrderBig) 2179 .Case("pdp", eByteOrderPDP) 2180 .Default(eByteOrderInvalid); 2181 if (byte_order != eByteOrderInvalid) 2182 ++num_keys_decoded; 2183 } else if (name == "ptrsize") { 2184 if (!value.getAsInteger(16, pointer_byte_size)) 2185 ++num_keys_decoded; 2186 } else if (name == "pid") { 2187 if (!value.getAsInteger(16, pid)) 2188 ++num_keys_decoded; 2189 } else if (name == "elf_abi") { 2190 elf_abi = std::string(value); 2191 ++num_keys_decoded; 2192 } else if (name == "main-binary-uuid") { 2193 m_process_standalone_uuid.SetFromStringRef(value); 2194 ++num_keys_decoded; 2195 } else if (name == "main-binary-slide") { 2196 StringExtractor extractor(value); 2197 m_process_standalone_value = 2198 extractor.GetU64(LLDB_INVALID_ADDRESS, 16); 2199 if (m_process_standalone_value != LLDB_INVALID_ADDRESS) { 2200 m_process_standalone_value_is_offset = true; 2201 ++num_keys_decoded; 2202 } 2203 } else if (name == "main-binary-address") { 2204 StringExtractor extractor(value); 2205 m_process_standalone_value = 2206 extractor.GetU64(LLDB_INVALID_ADDRESS, 16); 2207 if (m_process_standalone_value != LLDB_INVALID_ADDRESS) { 2208 m_process_standalone_value_is_offset = false; 2209 ++num_keys_decoded; 2210 } 2211 } else if (name == "binary-addresses") { 2212 m_binary_addresses.clear(); 2213 ++num_keys_decoded; 2214 for (llvm::StringRef x : llvm::split(value, ',')) { 2215 addr_t vmaddr; 2216 x.consume_front("0x"); 2217 if (llvm::to_integer(x, vmaddr, 16)) 2218 m_binary_addresses.push_back(vmaddr); 2219 } 2220 } 2221 } 2222 if (num_keys_decoded > 0) 2223 m_qProcessInfo_is_valid = eLazyBoolYes; 2224 if (pid != LLDB_INVALID_PROCESS_ID) { 2225 m_curr_pid_is_valid = eLazyBoolYes; 2226 m_curr_pid_run = m_curr_pid = pid; 2227 } 2228 2229 // Set the ArchSpec from the triple if we have it. 2230 if (!triple.empty()) { 2231 m_process_arch.SetTriple(triple.c_str()); 2232 m_process_arch.SetFlags(elf_abi); 2233 if (pointer_byte_size) { 2234 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 2235 } 2236 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && 2237 !vendor_name.empty()) { 2238 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name); 2239 if (!environment.empty()) 2240 triple.setEnvironmentName(environment); 2241 2242 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat); 2243 assert(triple.getObjectFormat() != llvm::Triple::Wasm); 2244 assert(triple.getObjectFormat() != llvm::Triple::XCOFF); 2245 switch (triple.getObjectFormat()) { 2246 case llvm::Triple::MachO: 2247 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 2248 break; 2249 case llvm::Triple::ELF: 2250 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub); 2251 break; 2252 case llvm::Triple::COFF: 2253 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub); 2254 break; 2255 case llvm::Triple::GOFF: 2256 case llvm::Triple::SPIRV: 2257 case llvm::Triple::Wasm: 2258 case llvm::Triple::XCOFF: 2259 case llvm::Triple::DXContainer: 2260 LLDB_LOGF(log, "error: not supported target architecture"); 2261 return false; 2262 case llvm::Triple::UnknownObjectFormat: 2263 LLDB_LOGF(log, "error: failed to determine target architecture"); 2264 return false; 2265 } 2266 2267 if (pointer_byte_size) { 2268 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 2269 } 2270 if (byte_order != eByteOrderInvalid) { 2271 assert(byte_order == m_process_arch.GetByteOrder()); 2272 } 2273 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name)); 2274 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 2275 m_process_arch.GetTriple().setEnvironmentName(llvm::StringRef(environment)); 2276 } 2277 return true; 2278 } 2279 } else { 2280 m_qProcessInfo_is_valid = eLazyBoolNo; 2281 } 2282 2283 return false; 2284 } 2285 2286 uint32_t GDBRemoteCommunicationClient::FindProcesses( 2287 const ProcessInstanceInfoMatch &match_info, 2288 ProcessInstanceInfoList &process_infos) { 2289 process_infos.clear(); 2290 2291 if (m_supports_qfProcessInfo) { 2292 StreamString packet; 2293 packet.PutCString("qfProcessInfo"); 2294 if (!match_info.MatchAllProcesses()) { 2295 packet.PutChar(':'); 2296 const char *name = match_info.GetProcessInfo().GetName(); 2297 bool has_name_match = false; 2298 if (name && name[0]) { 2299 has_name_match = true; 2300 NameMatch name_match_type = match_info.GetNameMatchType(); 2301 switch (name_match_type) { 2302 case NameMatch::Ignore: 2303 has_name_match = false; 2304 break; 2305 2306 case NameMatch::Equals: 2307 packet.PutCString("name_match:equals;"); 2308 break; 2309 2310 case NameMatch::Contains: 2311 packet.PutCString("name_match:contains;"); 2312 break; 2313 2314 case NameMatch::StartsWith: 2315 packet.PutCString("name_match:starts_with;"); 2316 break; 2317 2318 case NameMatch::EndsWith: 2319 packet.PutCString("name_match:ends_with;"); 2320 break; 2321 2322 case NameMatch::RegularExpression: 2323 packet.PutCString("name_match:regex;"); 2324 break; 2325 } 2326 if (has_name_match) { 2327 packet.PutCString("name:"); 2328 packet.PutBytesAsRawHex8(name, ::strlen(name)); 2329 packet.PutChar(';'); 2330 } 2331 } 2332 2333 if (match_info.GetProcessInfo().ProcessIDIsValid()) 2334 packet.Printf("pid:%" PRIu64 ";", 2335 match_info.GetProcessInfo().GetProcessID()); 2336 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 2337 packet.Printf("parent_pid:%" PRIu64 ";", 2338 match_info.GetProcessInfo().GetParentProcessID()); 2339 if (match_info.GetProcessInfo().UserIDIsValid()) 2340 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID()); 2341 if (match_info.GetProcessInfo().GroupIDIsValid()) 2342 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID()); 2343 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 2344 packet.Printf("euid:%u;", 2345 match_info.GetProcessInfo().GetEffectiveUserID()); 2346 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2347 packet.Printf("egid:%u;", 2348 match_info.GetProcessInfo().GetEffectiveGroupID()); 2349 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0); 2350 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) { 2351 const ArchSpec &match_arch = 2352 match_info.GetProcessInfo().GetArchitecture(); 2353 const llvm::Triple &triple = match_arch.GetTriple(); 2354 packet.PutCString("triple:"); 2355 packet.PutCString(triple.getTriple()); 2356 packet.PutChar(';'); 2357 } 2358 } 2359 StringExtractorGDBRemote response; 2360 // Increase timeout as the first qfProcessInfo packet takes a long time on 2361 // Android. The value of 1min was arrived at empirically. 2362 ScopedTimeout timeout(*this, minutes(1)); 2363 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 2364 PacketResult::Success) { 2365 do { 2366 ProcessInstanceInfo process_info; 2367 if (!DecodeProcessInfoResponse(response, process_info)) 2368 break; 2369 process_infos.push_back(process_info); 2370 response = StringExtractorGDBRemote(); 2371 } while (SendPacketAndWaitForResponse("qsProcessInfo", response) == 2372 PacketResult::Success); 2373 } else { 2374 m_supports_qfProcessInfo = false; 2375 return 0; 2376 } 2377 } 2378 return process_infos.size(); 2379 } 2380 2381 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid, 2382 std::string &name) { 2383 if (m_supports_qUserName) { 2384 char packet[32]; 2385 const int packet_len = 2386 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid); 2387 assert(packet_len < (int)sizeof(packet)); 2388 UNUSED_IF_ASSERT_DISABLED(packet_len); 2389 StringExtractorGDBRemote response; 2390 if (SendPacketAndWaitForResponse(packet, response) == 2391 PacketResult::Success) { 2392 if (response.IsNormalResponse()) { 2393 // Make sure we parsed the right number of characters. The response is 2394 // the hex encoded user name and should make up the entire packet. If 2395 // there are any non-hex ASCII bytes, the length won't match below.. 2396 if (response.GetHexByteString(name) * 2 == 2397 response.GetStringRef().size()) 2398 return true; 2399 } 2400 } else { 2401 m_supports_qUserName = false; 2402 return false; 2403 } 2404 } 2405 return false; 2406 } 2407 2408 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid, 2409 std::string &name) { 2410 if (m_supports_qGroupName) { 2411 char packet[32]; 2412 const int packet_len = 2413 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid); 2414 assert(packet_len < (int)sizeof(packet)); 2415 UNUSED_IF_ASSERT_DISABLED(packet_len); 2416 StringExtractorGDBRemote response; 2417 if (SendPacketAndWaitForResponse(packet, response) == 2418 PacketResult::Success) { 2419 if (response.IsNormalResponse()) { 2420 // Make sure we parsed the right number of characters. The response is 2421 // the hex encoded group name and should make up the entire packet. If 2422 // there are any non-hex ASCII bytes, the length won't match below.. 2423 if (response.GetHexByteString(name) * 2 == 2424 response.GetStringRef().size()) 2425 return true; 2426 } 2427 } else { 2428 m_supports_qGroupName = false; 2429 return false; 2430 } 2431 } 2432 return false; 2433 } 2434 2435 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, 2436 uint32_t recv_size) { 2437 packet.Clear(); 2438 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2439 uint32_t bytes_left = send_size; 2440 while (bytes_left > 0) { 2441 if (bytes_left >= 26) { 2442 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2443 bytes_left -= 26; 2444 } else { 2445 packet.Printf("%*.*s;", bytes_left, bytes_left, 2446 "abcdefghijklmnopqrstuvwxyz"); 2447 bytes_left = 0; 2448 } 2449 } 2450 } 2451 2452 duration<float> 2453 calculate_standard_deviation(const std::vector<duration<float>> &v) { 2454 if (v.size() == 0) 2455 return duration<float>::zero(); 2456 using Dur = duration<float>; 2457 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur()); 2458 Dur mean = sum / v.size(); 2459 float accum = 0; 2460 for (auto d : v) { 2461 float delta = (d - mean).count(); 2462 accum += delta * delta; 2463 }; 2464 2465 return Dur(sqrtf(accum / (v.size() - 1))); 2466 } 2467 2468 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets, 2469 uint32_t max_send, 2470 uint32_t max_recv, 2471 uint64_t recv_amount, 2472 bool json, Stream &strm) { 2473 2474 if (SendSpeedTestPacket(0, 0)) { 2475 StreamString packet; 2476 if (json) 2477 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n " 2478 "\"results\" : [", 2479 num_packets); 2480 else 2481 strm.Printf("Testing sending %u packets of various sizes:\n", 2482 num_packets); 2483 strm.Flush(); 2484 2485 uint32_t result_idx = 0; 2486 uint32_t send_size; 2487 std::vector<duration<float>> packet_times; 2488 2489 for (send_size = 0; send_size <= max_send; 2490 send_size ? send_size *= 2 : send_size = 4) { 2491 for (uint32_t recv_size = 0; recv_size <= max_recv; 2492 recv_size ? recv_size *= 2 : recv_size = 4) { 2493 MakeSpeedTestPacket(packet, send_size, recv_size); 2494 2495 packet_times.clear(); 2496 // Test how long it takes to send 'num_packets' packets 2497 const auto start_time = steady_clock::now(); 2498 for (uint32_t i = 0; i < num_packets; ++i) { 2499 const auto packet_start_time = steady_clock::now(); 2500 StringExtractorGDBRemote response; 2501 SendPacketAndWaitForResponse(packet.GetString(), response); 2502 const auto packet_end_time = steady_clock::now(); 2503 packet_times.push_back(packet_end_time - packet_start_time); 2504 } 2505 const auto end_time = steady_clock::now(); 2506 const auto total_time = end_time - start_time; 2507 2508 float packets_per_second = 2509 ((float)num_packets) / duration<float>(total_time).count(); 2510 auto average_per_packet = num_packets > 0 ? total_time / num_packets 2511 : duration<float>::zero(); 2512 const duration<float> standard_deviation = 2513 calculate_standard_deviation(packet_times); 2514 if (json) { 2515 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2516 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, " 2517 "\"standard_deviation_nsec\" : {4,9:ns-f0}}", 2518 result_idx > 0 ? "," : "", send_size, recv_size, 2519 total_time, standard_deviation); 2520 ++result_idx; 2521 } else { 2522 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for " 2523 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with " 2524 "standard deviation of {5,10:ms+f6}\n", 2525 send_size, recv_size, duration<float>(total_time), 2526 packets_per_second, duration<float>(average_per_packet), 2527 standard_deviation); 2528 } 2529 strm.Flush(); 2530 } 2531 } 2532 2533 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f); 2534 if (json) 2535 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" " 2536 ": %" PRIu64 ",\n \"results\" : [", 2537 recv_amount); 2538 else 2539 strm.Printf("Testing receiving %2.1fMB of data using varying receive " 2540 "packet sizes:\n", 2541 k_recv_amount_mb); 2542 strm.Flush(); 2543 send_size = 0; 2544 result_idx = 0; 2545 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) { 2546 MakeSpeedTestPacket(packet, send_size, recv_size); 2547 2548 // If we have a receive size, test how long it takes to receive 4MB of 2549 // data 2550 if (recv_size > 0) { 2551 const auto start_time = steady_clock::now(); 2552 uint32_t bytes_read = 0; 2553 uint32_t packet_count = 0; 2554 while (bytes_read < recv_amount) { 2555 StringExtractorGDBRemote response; 2556 SendPacketAndWaitForResponse(packet.GetString(), response); 2557 bytes_read += recv_size; 2558 ++packet_count; 2559 } 2560 const auto end_time = steady_clock::now(); 2561 const auto total_time = end_time - start_time; 2562 float mb_second = ((float)recv_amount) / 2563 duration<float>(total_time).count() / 2564 (1024.0 * 1024.0); 2565 float packets_per_second = 2566 ((float)packet_count) / duration<float>(total_time).count(); 2567 const auto average_per_packet = packet_count > 0 2568 ? total_time / packet_count 2569 : duration<float>::zero(); 2570 2571 if (json) { 2572 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2573 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}", 2574 result_idx > 0 ? "," : "", send_size, recv_size, 2575 total_time); 2576 ++result_idx; 2577 } else { 2578 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed " 2579 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for " 2580 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n", 2581 send_size, recv_size, packet_count, k_recv_amount_mb, 2582 duration<float>(total_time), mb_second, 2583 packets_per_second, duration<float>(average_per_packet)); 2584 } 2585 strm.Flush(); 2586 } 2587 } 2588 if (json) 2589 strm.Printf("\n ]\n }\n}\n"); 2590 else 2591 strm.EOL(); 2592 } 2593 } 2594 2595 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size, 2596 uint32_t recv_size) { 2597 StreamString packet; 2598 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2599 uint32_t bytes_left = send_size; 2600 while (bytes_left > 0) { 2601 if (bytes_left >= 26) { 2602 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2603 bytes_left -= 26; 2604 } else { 2605 packet.Printf("%*.*s;", bytes_left, bytes_left, 2606 "abcdefghijklmnopqrstuvwxyz"); 2607 bytes_left = 0; 2608 } 2609 } 2610 2611 StringExtractorGDBRemote response; 2612 return SendPacketAndWaitForResponse(packet.GetString(), response) == 2613 PacketResult::Success; 2614 } 2615 2616 bool GDBRemoteCommunicationClient::LaunchGDBServer( 2617 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port, 2618 std::string &socket_name) { 2619 pid = LLDB_INVALID_PROCESS_ID; 2620 port = 0; 2621 socket_name.clear(); 2622 2623 StringExtractorGDBRemote response; 2624 StreamString stream; 2625 stream.PutCString("qLaunchGDBServer;"); 2626 std::string hostname; 2627 if (remote_accept_hostname && remote_accept_hostname[0]) 2628 hostname = remote_accept_hostname; 2629 else { 2630 if (HostInfo::GetHostname(hostname)) { 2631 // Make the GDB server we launch only accept connections from this host 2632 stream.Printf("host:%s;", hostname.c_str()); 2633 } else { 2634 // Make the GDB server we launch accept connections from any host since 2635 // we can't figure out the hostname 2636 stream.Printf("host:*;"); 2637 } 2638 } 2639 // give the process a few seconds to startup 2640 ScopedTimeout timeout(*this, seconds(10)); 2641 2642 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 2643 PacketResult::Success) { 2644 if (response.IsErrorResponse()) 2645 return false; 2646 2647 llvm::StringRef name; 2648 llvm::StringRef value; 2649 while (response.GetNameColonValue(name, value)) { 2650 if (name == "port") 2651 value.getAsInteger(0, port); 2652 else if (name == "pid") 2653 value.getAsInteger(0, pid); 2654 else if (name.compare("socket_name") == 0) { 2655 StringExtractor extractor(value); 2656 extractor.GetHexByteString(socket_name); 2657 } 2658 } 2659 return true; 2660 } 2661 return false; 2662 } 2663 2664 size_t GDBRemoteCommunicationClient::QueryGDBServer( 2665 std::vector<std::pair<uint16_t, std::string>> &connection_urls) { 2666 connection_urls.clear(); 2667 2668 StringExtractorGDBRemote response; 2669 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) != 2670 PacketResult::Success) 2671 return 0; 2672 2673 StructuredData::ObjectSP data = 2674 StructuredData::ParseJSON(response.GetStringRef()); 2675 if (!data) 2676 return 0; 2677 2678 StructuredData::Array *array = data->GetAsArray(); 2679 if (!array) 2680 return 0; 2681 2682 for (size_t i = 0, count = array->GetSize(); i < count; ++i) { 2683 std::optional<StructuredData::Dictionary *> maybe_element = 2684 array->GetItemAtIndexAsDictionary(i); 2685 if (!maybe_element) 2686 continue; 2687 2688 StructuredData::Dictionary *element = *maybe_element; 2689 uint16_t port = 0; 2690 if (StructuredData::ObjectSP port_osp = 2691 element->GetValueForKey(llvm::StringRef("port"))) 2692 port = port_osp->GetUnsignedIntegerValue(0); 2693 2694 std::string socket_name; 2695 if (StructuredData::ObjectSP socket_name_osp = 2696 element->GetValueForKey(llvm::StringRef("socket_name"))) 2697 socket_name = std::string(socket_name_osp->GetStringValue()); 2698 2699 if (port != 0 || !socket_name.empty()) 2700 connection_urls.emplace_back(port, socket_name); 2701 } 2702 return connection_urls.size(); 2703 } 2704 2705 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) { 2706 StreamString stream; 2707 stream.Printf("qKillSpawnedProcess:%" PRId64, pid); 2708 2709 StringExtractorGDBRemote response; 2710 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 2711 PacketResult::Success) { 2712 if (response.IsOKResponse()) 2713 return true; 2714 } 2715 return false; 2716 } 2717 2718 std::optional<PidTid> GDBRemoteCommunicationClient::SendSetCurrentThreadPacket( 2719 uint64_t tid, uint64_t pid, char op) { 2720 lldb_private::StreamString packet; 2721 packet.PutChar('H'); 2722 packet.PutChar(op); 2723 2724 if (pid != LLDB_INVALID_PROCESS_ID) 2725 packet.Printf("p%" PRIx64 ".", pid); 2726 2727 if (tid == UINT64_MAX) 2728 packet.PutCString("-1"); 2729 else 2730 packet.Printf("%" PRIx64, tid); 2731 2732 StringExtractorGDBRemote response; 2733 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 2734 PacketResult::Success) { 2735 if (response.IsOKResponse()) 2736 return {{pid, tid}}; 2737 2738 /* 2739 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2740 * Hg packet. 2741 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2742 * which can 2743 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2744 */ 2745 if (response.IsUnsupportedResponse() && IsConnected()) 2746 return {{1, 1}}; 2747 } 2748 return std::nullopt; 2749 } 2750 2751 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid, 2752 uint64_t pid) { 2753 if (m_curr_tid == tid && 2754 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid)) 2755 return true; 2756 2757 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g'); 2758 if (ret) { 2759 if (ret->pid != LLDB_INVALID_PROCESS_ID) 2760 m_curr_pid = ret->pid; 2761 m_curr_tid = ret->tid; 2762 } 2763 return ret.has_value(); 2764 } 2765 2766 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid, 2767 uint64_t pid) { 2768 if (m_curr_tid_run == tid && 2769 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid)) 2770 return true; 2771 2772 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c'); 2773 if (ret) { 2774 if (ret->pid != LLDB_INVALID_PROCESS_ID) 2775 m_curr_pid_run = ret->pid; 2776 m_curr_tid_run = ret->tid; 2777 } 2778 return ret.has_value(); 2779 } 2780 2781 bool GDBRemoteCommunicationClient::GetStopReply( 2782 StringExtractorGDBRemote &response) { 2783 if (SendPacketAndWaitForResponse("?", response) == PacketResult::Success) 2784 return response.IsNormalResponse(); 2785 return false; 2786 } 2787 2788 bool GDBRemoteCommunicationClient::GetThreadStopInfo( 2789 lldb::tid_t tid, StringExtractorGDBRemote &response) { 2790 if (m_supports_qThreadStopInfo) { 2791 char packet[256]; 2792 int packet_len = 2793 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2794 assert(packet_len < (int)sizeof(packet)); 2795 UNUSED_IF_ASSERT_DISABLED(packet_len); 2796 if (SendPacketAndWaitForResponse(packet, response) == 2797 PacketResult::Success) { 2798 if (response.IsUnsupportedResponse()) 2799 m_supports_qThreadStopInfo = false; 2800 else if (response.IsNormalResponse()) 2801 return true; 2802 else 2803 return false; 2804 } else { 2805 m_supports_qThreadStopInfo = false; 2806 } 2807 } 2808 return false; 2809 } 2810 2811 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket( 2812 GDBStoppointType type, bool insert, addr_t addr, uint32_t length, 2813 std::chrono::seconds timeout) { 2814 Log *log = GetLog(LLDBLog::Breakpoints); 2815 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64, 2816 __FUNCTION__, insert ? "add" : "remove", addr); 2817 2818 // Check if the stub is known not to support this breakpoint type 2819 if (!SupportsGDBStoppointPacket(type)) 2820 return UINT8_MAX; 2821 // Construct the breakpoint packet 2822 char packet[64]; 2823 const int packet_len = 2824 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x", 2825 insert ? 'Z' : 'z', type, addr, length); 2826 // Check we haven't overwritten the end of the packet buffer 2827 assert(packet_len + 1 < (int)sizeof(packet)); 2828 UNUSED_IF_ASSERT_DISABLED(packet_len); 2829 StringExtractorGDBRemote response; 2830 // Make sure the response is either "OK", "EXX" where XX are two hex digits, 2831 // or "" (unsupported) 2832 response.SetResponseValidatorToOKErrorNotSupported(); 2833 // Try to send the breakpoint packet, and check that it was correctly sent 2834 if (SendPacketAndWaitForResponse(packet, response, timeout) == 2835 PacketResult::Success) { 2836 // Receive and OK packet when the breakpoint successfully placed 2837 if (response.IsOKResponse()) 2838 return 0; 2839 2840 // Status while setting breakpoint, send back specific error 2841 if (response.IsErrorResponse()) 2842 return response.GetError(); 2843 2844 // Empty packet informs us that breakpoint is not supported 2845 if (response.IsUnsupportedResponse()) { 2846 // Disable this breakpoint type since it is unsupported 2847 switch (type) { 2848 case eBreakpointSoftware: 2849 m_supports_z0 = false; 2850 break; 2851 case eBreakpointHardware: 2852 m_supports_z1 = false; 2853 break; 2854 case eWatchpointWrite: 2855 m_supports_z2 = false; 2856 break; 2857 case eWatchpointRead: 2858 m_supports_z3 = false; 2859 break; 2860 case eWatchpointReadWrite: 2861 m_supports_z4 = false; 2862 break; 2863 case eStoppointInvalid: 2864 return UINT8_MAX; 2865 } 2866 } 2867 } 2868 // Signal generic failure 2869 return UINT8_MAX; 2870 } 2871 2872 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> 2873 GDBRemoteCommunicationClient::GetCurrentProcessAndThreadIDs( 2874 bool &sequence_mutex_unavailable) { 2875 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids; 2876 2877 Lock lock(*this); 2878 if (lock) { 2879 sequence_mutex_unavailable = false; 2880 StringExtractorGDBRemote response; 2881 2882 PacketResult packet_result; 2883 for (packet_result = 2884 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response); 2885 packet_result == PacketResult::Success && response.IsNormalResponse(); 2886 packet_result = 2887 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) { 2888 char ch = response.GetChar(); 2889 if (ch == 'l') 2890 break; 2891 if (ch == 'm') { 2892 do { 2893 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID); 2894 // If we get an invalid response, break out of the loop. 2895 // If there are valid tids, they have been added to ids. 2896 // If there are no valid tids, we'll fall through to the 2897 // bare-iron target handling below. 2898 if (!pid_tid) 2899 break; 2900 2901 ids.push_back(*pid_tid); 2902 ch = response.GetChar(); // Skip the command separator 2903 } while (ch == ','); // Make sure we got a comma separator 2904 } 2905 } 2906 2907 /* 2908 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2909 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet 2910 * could 2911 * be as simple as 'S05'. There is no packet which can give us pid and/or 2912 * tid. 2913 * Assume pid=tid=1 in such cases. 2914 */ 2915 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) && 2916 ids.size() == 0 && IsConnected()) { 2917 ids.emplace_back(1, 1); 2918 } 2919 } else { 2920 Log *log(GetLog(GDBRLog::Process | GDBRLog::Packets)); 2921 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending " 2922 "packet 'qfThreadInfo'"); 2923 sequence_mutex_unavailable = true; 2924 } 2925 2926 return ids; 2927 } 2928 2929 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs( 2930 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) { 2931 lldb::pid_t pid = GetCurrentProcessID(); 2932 thread_ids.clear(); 2933 2934 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable); 2935 if (ids.empty() || sequence_mutex_unavailable) 2936 return 0; 2937 2938 for (auto id : ids) { 2939 // skip threads that do not belong to the current process 2940 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid) 2941 continue; 2942 if (id.second != LLDB_INVALID_THREAD_ID && 2943 id.second != StringExtractorGDBRemote::AllThreads) 2944 thread_ids.push_back(id.second); 2945 } 2946 2947 return thread_ids.size(); 2948 } 2949 2950 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() { 2951 StringExtractorGDBRemote response; 2952 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) != 2953 PacketResult::Success || 2954 !response.IsNormalResponse()) 2955 return LLDB_INVALID_ADDRESS; 2956 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2957 } 2958 2959 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand( 2960 llvm::StringRef command, 2961 const FileSpec & 2962 working_dir, // Pass empty FileSpec to use the current working directory 2963 int *status_ptr, // Pass NULL if you don't want the process exit status 2964 int *signo_ptr, // Pass NULL if you don't want the signal that caused the 2965 // process to exit 2966 std::string 2967 *command_output, // Pass NULL if you don't want the command output 2968 const Timeout<std::micro> &timeout) { 2969 lldb_private::StreamString stream; 2970 stream.PutCString("qPlatform_shell:"); 2971 stream.PutBytesAsRawHex8(command.data(), command.size()); 2972 stream.PutChar(','); 2973 uint32_t timeout_sec = UINT32_MAX; 2974 if (timeout) { 2975 // TODO: Use chrono version of std::ceil once c++17 is available. 2976 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count()); 2977 } 2978 stream.PutHex32(timeout_sec); 2979 if (working_dir) { 2980 std::string path{working_dir.GetPath(false)}; 2981 stream.PutChar(','); 2982 stream.PutStringAsRawHex8(path); 2983 } 2984 StringExtractorGDBRemote response; 2985 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 2986 PacketResult::Success) { 2987 if (response.GetChar() != 'F') 2988 return Status::FromErrorString("malformed reply"); 2989 if (response.GetChar() != ',') 2990 return Status::FromErrorString("malformed reply"); 2991 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 2992 if (exitcode == UINT32_MAX) 2993 return Status::FromErrorString("unable to run remote process"); 2994 else if (status_ptr) 2995 *status_ptr = exitcode; 2996 if (response.GetChar() != ',') 2997 return Status::FromErrorString("malformed reply"); 2998 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 2999 if (signo_ptr) 3000 *signo_ptr = signo; 3001 if (response.GetChar() != ',') 3002 return Status::FromErrorString("malformed reply"); 3003 std::string output; 3004 response.GetEscapedBinaryData(output); 3005 if (command_output) 3006 command_output->assign(output); 3007 return Status(); 3008 } 3009 return Status::FromErrorString("unable to send packet"); 3010 } 3011 3012 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, 3013 uint32_t file_permissions) { 3014 std::string path{file_spec.GetPath(false)}; 3015 lldb_private::StreamString stream; 3016 stream.PutCString("qPlatform_mkdir:"); 3017 stream.PutHex32(file_permissions); 3018 stream.PutChar(','); 3019 stream.PutStringAsRawHex8(path); 3020 llvm::StringRef packet = stream.GetString(); 3021 StringExtractorGDBRemote response; 3022 3023 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success) 3024 return Status::FromErrorStringWithFormat("failed to send '%s' packet", 3025 packet.str().c_str()); 3026 3027 if (response.GetChar() != 'F') 3028 return Status::FromErrorStringWithFormat("invalid response to '%s' packet", 3029 packet.str().c_str()); 3030 3031 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 3032 } 3033 3034 Status 3035 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec, 3036 uint32_t file_permissions) { 3037 std::string path{file_spec.GetPath(false)}; 3038 lldb_private::StreamString stream; 3039 stream.PutCString("qPlatform_chmod:"); 3040 stream.PutHex32(file_permissions); 3041 stream.PutChar(','); 3042 stream.PutStringAsRawHex8(path); 3043 llvm::StringRef packet = stream.GetString(); 3044 StringExtractorGDBRemote response; 3045 3046 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success) 3047 return Status::FromErrorStringWithFormat("failed to send '%s' packet", 3048 stream.GetData()); 3049 3050 if (response.GetChar() != 'F') 3051 return Status::FromErrorStringWithFormat("invalid response to '%s' packet", 3052 stream.GetData()); 3053 3054 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 3055 } 3056 3057 static int gdb_errno_to_system(int err) { 3058 switch (err) { 3059 #define HANDLE_ERRNO(name, value) \ 3060 case GDB_##name: \ 3061 return name; 3062 #include "Plugins/Process/gdb-remote/GDBRemoteErrno.def" 3063 default: 3064 return -1; 3065 } 3066 } 3067 3068 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, 3069 uint64_t fail_result, Status &error) { 3070 response.SetFilePos(0); 3071 if (response.GetChar() != 'F') 3072 return fail_result; 3073 int32_t result = response.GetS32(-2, 16); 3074 if (result == -2) 3075 return fail_result; 3076 if (response.GetChar() == ',') { 3077 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3078 if (result_errno != -1) 3079 error = Status(result_errno, eErrorTypePOSIX); 3080 else 3081 error = Status(-1, eErrorTypeGeneric); 3082 } else 3083 error.Clear(); 3084 return result; 3085 } 3086 lldb::user_id_t 3087 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec, 3088 File::OpenOptions flags, mode_t mode, 3089 Status &error) { 3090 std::string path(file_spec.GetPath(false)); 3091 lldb_private::StreamString stream; 3092 stream.PutCString("vFile:open:"); 3093 if (path.empty()) 3094 return UINT64_MAX; 3095 stream.PutStringAsRawHex8(path); 3096 stream.PutChar(','); 3097 stream.PutHex32(flags); 3098 stream.PutChar(','); 3099 stream.PutHex32(mode); 3100 StringExtractorGDBRemote response; 3101 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3102 PacketResult::Success) { 3103 return ParseHostIOPacketResponse(response, UINT64_MAX, error); 3104 } 3105 return UINT64_MAX; 3106 } 3107 3108 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, 3109 Status &error) { 3110 lldb_private::StreamString stream; 3111 stream.Printf("vFile:close:%x", (int)fd); 3112 StringExtractorGDBRemote response; 3113 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3114 PacketResult::Success) { 3115 return ParseHostIOPacketResponse(response, -1, error) == 0; 3116 } 3117 return false; 3118 } 3119 3120 std::optional<GDBRemoteFStatData> 3121 GDBRemoteCommunicationClient::FStat(lldb::user_id_t fd) { 3122 lldb_private::StreamString stream; 3123 stream.Printf("vFile:fstat:%" PRIx64, fd); 3124 StringExtractorGDBRemote response; 3125 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3126 PacketResult::Success) { 3127 if (response.GetChar() != 'F') 3128 return std::nullopt; 3129 int64_t size = response.GetS64(-1, 16); 3130 if (size > 0 && response.GetChar() == ';') { 3131 std::string buffer; 3132 if (response.GetEscapedBinaryData(buffer)) { 3133 GDBRemoteFStatData out; 3134 if (buffer.size() != sizeof(out)) 3135 return std::nullopt; 3136 memcpy(&out, buffer.data(), sizeof(out)); 3137 return out; 3138 } 3139 } 3140 } 3141 return std::nullopt; 3142 } 3143 3144 std::optional<GDBRemoteFStatData> 3145 GDBRemoteCommunicationClient::Stat(const lldb_private::FileSpec &file_spec) { 3146 Status error; 3147 lldb::user_id_t fd = OpenFile(file_spec, File::eOpenOptionReadOnly, 0, error); 3148 if (fd == UINT64_MAX) 3149 return std::nullopt; 3150 std::optional<GDBRemoteFStatData> st = FStat(fd); 3151 CloseFile(fd, error); 3152 return st; 3153 } 3154 3155 // Extension of host I/O packets to get the file size. 3156 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize( 3157 const lldb_private::FileSpec &file_spec) { 3158 if (m_supports_vFileSize) { 3159 std::string path(file_spec.GetPath(false)); 3160 lldb_private::StreamString stream; 3161 stream.PutCString("vFile:size:"); 3162 stream.PutStringAsRawHex8(path); 3163 StringExtractorGDBRemote response; 3164 if (SendPacketAndWaitForResponse(stream.GetString(), response) != 3165 PacketResult::Success) 3166 return UINT64_MAX; 3167 3168 if (!response.IsUnsupportedResponse()) { 3169 if (response.GetChar() != 'F') 3170 return UINT64_MAX; 3171 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 3172 return retcode; 3173 } 3174 m_supports_vFileSize = false; 3175 } 3176 3177 // Fallback to fstat. 3178 std::optional<GDBRemoteFStatData> st = Stat(file_spec); 3179 return st ? st->gdb_st_size : UINT64_MAX; 3180 } 3181 3182 void GDBRemoteCommunicationClient::AutoCompleteDiskFileOrDirectory( 3183 CompletionRequest &request, bool only_dir) { 3184 lldb_private::StreamString stream; 3185 stream.PutCString("qPathComplete:"); 3186 stream.PutHex32(only_dir ? 1 : 0); 3187 stream.PutChar(','); 3188 stream.PutStringAsRawHex8(request.GetCursorArgumentPrefix()); 3189 StringExtractorGDBRemote response; 3190 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3191 PacketResult::Success) { 3192 StreamString strm; 3193 char ch = response.GetChar(); 3194 if (ch != 'M') 3195 return; 3196 while (response.Peek()) { 3197 strm.Clear(); 3198 while ((ch = response.GetHexU8(0, false)) != '\0') 3199 strm.PutChar(ch); 3200 request.AddCompletion(strm.GetString()); 3201 if (response.GetChar() != ',') 3202 break; 3203 } 3204 } 3205 } 3206 3207 Status 3208 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec, 3209 uint32_t &file_permissions) { 3210 if (m_supports_vFileMode) { 3211 std::string path{file_spec.GetPath(false)}; 3212 Status error; 3213 lldb_private::StreamString stream; 3214 stream.PutCString("vFile:mode:"); 3215 stream.PutStringAsRawHex8(path); 3216 StringExtractorGDBRemote response; 3217 if (SendPacketAndWaitForResponse(stream.GetString(), response) != 3218 PacketResult::Success) { 3219 error = Status::FromErrorStringWithFormat("failed to send '%s' packet", 3220 stream.GetData()); 3221 return error; 3222 } 3223 if (!response.IsUnsupportedResponse()) { 3224 if (response.GetChar() != 'F') { 3225 error = Status::FromErrorStringWithFormat( 3226 "invalid response to '%s' packet", stream.GetData()); 3227 } else { 3228 const uint32_t mode = response.GetS32(-1, 16); 3229 if (static_cast<int32_t>(mode) == -1) { 3230 if (response.GetChar() == ',') { 3231 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3232 if (response_errno > 0) 3233 error = Status(response_errno, lldb::eErrorTypePOSIX); 3234 else 3235 error = Status::FromErrorString("unknown error"); 3236 } else 3237 error = Status::FromErrorString("unknown error"); 3238 } else { 3239 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO); 3240 } 3241 } 3242 return error; 3243 } else { // response.IsUnsupportedResponse() 3244 m_supports_vFileMode = false; 3245 } 3246 } 3247 3248 // Fallback to fstat. 3249 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) { 3250 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO); 3251 return Status(); 3252 } 3253 return Status::FromErrorString("fstat failed"); 3254 } 3255 3256 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd, 3257 uint64_t offset, void *dst, 3258 uint64_t dst_len, 3259 Status &error) { 3260 lldb_private::StreamString stream; 3261 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len, 3262 offset); 3263 StringExtractorGDBRemote response; 3264 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3265 PacketResult::Success) { 3266 if (response.GetChar() != 'F') 3267 return 0; 3268 int64_t retcode = response.GetS64(-1, 16); 3269 if (retcode == -1) { 3270 error = Status::FromErrorString("unknown error"); 3271 if (response.GetChar() == ',') { 3272 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3273 if (response_errno > 0) 3274 error = Status(response_errno, lldb::eErrorTypePOSIX); 3275 } 3276 return -1; 3277 } 3278 const char next = (response.Peek() ? *response.Peek() : 0); 3279 if (next == ',') 3280 return 0; 3281 if (next == ';') { 3282 response.GetChar(); // skip the semicolon 3283 std::string buffer; 3284 if (response.GetEscapedBinaryData(buffer)) { 3285 const uint64_t data_to_write = 3286 std::min<uint64_t>(dst_len, buffer.size()); 3287 if (data_to_write > 0) 3288 memcpy(dst, &buffer[0], data_to_write); 3289 return data_to_write; 3290 } 3291 } 3292 } 3293 return 0; 3294 } 3295 3296 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd, 3297 uint64_t offset, 3298 const void *src, 3299 uint64_t src_len, 3300 Status &error) { 3301 lldb_private::StreamGDBRemote stream; 3302 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset); 3303 stream.PutEscapedBytes(src, src_len); 3304 StringExtractorGDBRemote response; 3305 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3306 PacketResult::Success) { 3307 if (response.GetChar() != 'F') { 3308 error = Status::FromErrorStringWithFormat("write file failed"); 3309 return 0; 3310 } 3311 int64_t bytes_written = response.GetS64(-1, 16); 3312 if (bytes_written == -1) { 3313 error = Status::FromErrorString("unknown error"); 3314 if (response.GetChar() == ',') { 3315 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3316 if (response_errno > 0) 3317 error = Status(response_errno, lldb::eErrorTypePOSIX); 3318 } 3319 return -1; 3320 } 3321 return bytes_written; 3322 } else { 3323 error = Status::FromErrorString("failed to send vFile:pwrite packet"); 3324 } 3325 return 0; 3326 } 3327 3328 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, 3329 const FileSpec &dst) { 3330 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)}; 3331 Status error; 3332 lldb_private::StreamGDBRemote stream; 3333 stream.PutCString("vFile:symlink:"); 3334 // the unix symlink() command reverses its parameters where the dst if first, 3335 // so we follow suit here 3336 stream.PutStringAsRawHex8(dst_path); 3337 stream.PutChar(','); 3338 stream.PutStringAsRawHex8(src_path); 3339 StringExtractorGDBRemote response; 3340 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3341 PacketResult::Success) { 3342 if (response.GetChar() == 'F') { 3343 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX); 3344 if (result != 0) { 3345 error = Status::FromErrorString("unknown error"); 3346 if (response.GetChar() == ',') { 3347 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3348 if (response_errno > 0) 3349 error = Status(response_errno, lldb::eErrorTypePOSIX); 3350 } 3351 } 3352 } else { 3353 // Should have returned with 'F<result>[,<errno>]' 3354 error = Status::FromErrorStringWithFormat("symlink failed"); 3355 } 3356 } else { 3357 error = Status::FromErrorString("failed to send vFile:symlink packet"); 3358 } 3359 return error; 3360 } 3361 3362 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) { 3363 std::string path{file_spec.GetPath(false)}; 3364 Status error; 3365 lldb_private::StreamGDBRemote stream; 3366 stream.PutCString("vFile:unlink:"); 3367 // the unix symlink() command reverses its parameters where the dst if first, 3368 // so we follow suit here 3369 stream.PutStringAsRawHex8(path); 3370 StringExtractorGDBRemote response; 3371 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3372 PacketResult::Success) { 3373 if (response.GetChar() == 'F') { 3374 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX); 3375 if (result != 0) { 3376 error = Status::FromErrorString("unknown error"); 3377 if (response.GetChar() == ',') { 3378 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3379 if (response_errno > 0) 3380 error = Status(response_errno, lldb::eErrorTypePOSIX); 3381 } 3382 } 3383 } else { 3384 // Should have returned with 'F<result>[,<errno>]' 3385 error = Status::FromErrorStringWithFormat("unlink failed"); 3386 } 3387 } else { 3388 error = Status::FromErrorString("failed to send vFile:unlink packet"); 3389 } 3390 return error; 3391 } 3392 3393 // Extension of host I/O packets to get whether a file exists. 3394 bool GDBRemoteCommunicationClient::GetFileExists( 3395 const lldb_private::FileSpec &file_spec) { 3396 if (m_supports_vFileExists) { 3397 std::string path(file_spec.GetPath(false)); 3398 lldb_private::StreamString stream; 3399 stream.PutCString("vFile:exists:"); 3400 stream.PutStringAsRawHex8(path); 3401 StringExtractorGDBRemote response; 3402 if (SendPacketAndWaitForResponse(stream.GetString(), response) != 3403 PacketResult::Success) 3404 return false; 3405 if (!response.IsUnsupportedResponse()) { 3406 if (response.GetChar() != 'F') 3407 return false; 3408 if (response.GetChar() != ',') 3409 return false; 3410 bool retcode = (response.GetChar() != '0'); 3411 return retcode; 3412 } else 3413 m_supports_vFileExists = false; 3414 } 3415 3416 // Fallback to open. 3417 Status error; 3418 lldb::user_id_t fd = OpenFile(file_spec, File::eOpenOptionReadOnly, 0, error); 3419 if (fd == UINT64_MAX) 3420 return false; 3421 CloseFile(fd, error); 3422 return true; 3423 } 3424 3425 llvm::ErrorOr<llvm::MD5::MD5Result> GDBRemoteCommunicationClient::CalculateMD5( 3426 const lldb_private::FileSpec &file_spec) { 3427 std::string path(file_spec.GetPath(false)); 3428 lldb_private::StreamString stream; 3429 stream.PutCString("vFile:MD5:"); 3430 stream.PutStringAsRawHex8(path); 3431 StringExtractorGDBRemote response; 3432 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3433 PacketResult::Success) { 3434 if (response.GetChar() != 'F') 3435 return std::make_error_code(std::errc::illegal_byte_sequence); 3436 if (response.GetChar() != ',') 3437 return std::make_error_code(std::errc::illegal_byte_sequence); 3438 if (response.Peek() && *response.Peek() == 'x') 3439 return std::make_error_code(std::errc::no_such_file_or_directory); 3440 3441 // GDBRemoteCommunicationServerCommon::Handle_vFile_MD5 concatenates low and 3442 // high hex strings. We can't use response.GetHexMaxU64 because that can't 3443 // handle the concatenated hex string. What would happen is parsing the low 3444 // would consume the whole response packet which would give incorrect 3445 // results. Instead, we get the byte string for each low and high hex 3446 // separately, and parse them. 3447 // 3448 // An alternate way to handle this is to change the server to put a 3449 // delimiter between the low/high parts, and change the client to parse the 3450 // delimiter. However, we choose not to do this so existing lldb-servers 3451 // don't have to be patched 3452 3453 // The checksum is 128 bits encoded as hex 3454 // This means low/high are halves of 64 bits each, in otherwords, 8 bytes. 3455 // Each byte takes 2 hex characters in the response. 3456 const size_t MD5_HALF_LENGTH = sizeof(uint64_t) * 2; 3457 3458 // Get low part 3459 auto part = 3460 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH); 3461 if (part.size() != MD5_HALF_LENGTH) 3462 return std::make_error_code(std::errc::illegal_byte_sequence); 3463 response.SetFilePos(response.GetFilePos() + part.size()); 3464 3465 uint64_t low; 3466 if (part.getAsInteger(/*radix=*/16, low)) 3467 return std::make_error_code(std::errc::illegal_byte_sequence); 3468 3469 // Get high part 3470 part = 3471 response.GetStringRef().substr(response.GetFilePos(), MD5_HALF_LENGTH); 3472 if (part.size() != MD5_HALF_LENGTH) 3473 return std::make_error_code(std::errc::illegal_byte_sequence); 3474 response.SetFilePos(response.GetFilePos() + part.size()); 3475 3476 uint64_t high; 3477 if (part.getAsInteger(/*radix=*/16, high)) 3478 return std::make_error_code(std::errc::illegal_byte_sequence); 3479 3480 llvm::MD5::MD5Result result; 3481 llvm::support::endian::write<uint64_t, llvm::endianness::little>( 3482 result.data(), low); 3483 llvm::support::endian::write<uint64_t, llvm::endianness::little>( 3484 result.data() + 8, high); 3485 3486 return result; 3487 } 3488 return std::make_error_code(std::errc::operation_canceled); 3489 } 3490 3491 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) { 3492 // Some targets have issues with g/G packets and we need to avoid using them 3493 if (m_avoid_g_packets == eLazyBoolCalculate) { 3494 if (process) { 3495 m_avoid_g_packets = eLazyBoolNo; 3496 const ArchSpec &arch = process->GetTarget().GetArchitecture(); 3497 if (arch.IsValid() && 3498 arch.GetTriple().getVendor() == llvm::Triple::Apple && 3499 arch.GetTriple().getOS() == llvm::Triple::IOS && 3500 (arch.GetTriple().getArch() == llvm::Triple::aarch64 || 3501 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) { 3502 m_avoid_g_packets = eLazyBoolYes; 3503 uint32_t gdb_server_version = GetGDBServerProgramVersion(); 3504 if (gdb_server_version != 0) { 3505 const char *gdb_server_name = GetGDBServerProgramName(); 3506 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) { 3507 if (gdb_server_version >= 310) 3508 m_avoid_g_packets = eLazyBoolNo; 3509 } 3510 } 3511 } 3512 } 3513 } 3514 return m_avoid_g_packets == eLazyBoolYes; 3515 } 3516 3517 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, 3518 uint32_t reg) { 3519 StreamString payload; 3520 payload.Printf("p%x", reg); 3521 StringExtractorGDBRemote response; 3522 if (SendThreadSpecificPacketAndWaitForResponse( 3523 tid, std::move(payload), response) != PacketResult::Success || 3524 !response.IsNormalResponse()) 3525 return nullptr; 3526 3527 WritableDataBufferSP buffer_sp( 3528 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3529 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3530 return buffer_sp; 3531 } 3532 3533 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) { 3534 StreamString payload; 3535 payload.PutChar('g'); 3536 StringExtractorGDBRemote response; 3537 if (SendThreadSpecificPacketAndWaitForResponse( 3538 tid, std::move(payload), response) != PacketResult::Success || 3539 !response.IsNormalResponse()) 3540 return nullptr; 3541 3542 WritableDataBufferSP buffer_sp( 3543 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3544 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3545 return buffer_sp; 3546 } 3547 3548 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, 3549 uint32_t reg_num, 3550 llvm::ArrayRef<uint8_t> data) { 3551 StreamString payload; 3552 payload.Printf("P%x=", reg_num); 3553 payload.PutBytesAsRawHex8(data.data(), data.size(), 3554 endian::InlHostByteOrder(), 3555 endian::InlHostByteOrder()); 3556 StringExtractorGDBRemote response; 3557 return SendThreadSpecificPacketAndWaitForResponse( 3558 tid, std::move(payload), response) == PacketResult::Success && 3559 response.IsOKResponse(); 3560 } 3561 3562 bool GDBRemoteCommunicationClient::WriteAllRegisters( 3563 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) { 3564 StreamString payload; 3565 payload.PutChar('G'); 3566 payload.PutBytesAsRawHex8(data.data(), data.size(), 3567 endian::InlHostByteOrder(), 3568 endian::InlHostByteOrder()); 3569 StringExtractorGDBRemote response; 3570 return SendThreadSpecificPacketAndWaitForResponse( 3571 tid, std::move(payload), response) == PacketResult::Success && 3572 response.IsOKResponse(); 3573 } 3574 3575 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid, 3576 uint32_t &save_id) { 3577 save_id = 0; // Set to invalid save ID 3578 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3579 return false; 3580 3581 m_supports_QSaveRegisterState = eLazyBoolYes; 3582 StreamString payload; 3583 payload.PutCString("QSaveRegisterState"); 3584 StringExtractorGDBRemote response; 3585 if (SendThreadSpecificPacketAndWaitForResponse( 3586 tid, std::move(payload), response) != PacketResult::Success) 3587 return false; 3588 3589 if (response.IsUnsupportedResponse()) 3590 m_supports_QSaveRegisterState = eLazyBoolNo; 3591 3592 const uint32_t response_save_id = response.GetU32(0); 3593 if (response_save_id == 0) 3594 return false; 3595 3596 save_id = response_save_id; 3597 return true; 3598 } 3599 3600 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid, 3601 uint32_t save_id) { 3602 // We use the "m_supports_QSaveRegisterState" variable here because the 3603 // QSaveRegisterState and QRestoreRegisterState packets must both be 3604 // supported in order to be useful 3605 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3606 return false; 3607 3608 StreamString payload; 3609 payload.Printf("QRestoreRegisterState:%u", save_id); 3610 StringExtractorGDBRemote response; 3611 if (SendThreadSpecificPacketAndWaitForResponse( 3612 tid, std::move(payload), response) != PacketResult::Success) 3613 return false; 3614 3615 if (response.IsOKResponse()) 3616 return true; 3617 3618 if (response.IsUnsupportedResponse()) 3619 m_supports_QSaveRegisterState = eLazyBoolNo; 3620 return false; 3621 } 3622 3623 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) { 3624 if (!GetSyncThreadStateSupported()) 3625 return false; 3626 3627 StreamString packet; 3628 StringExtractorGDBRemote response; 3629 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid); 3630 return SendPacketAndWaitForResponse(packet.GetString(), response) == 3631 GDBRemoteCommunication::PacketResult::Success && 3632 response.IsOKResponse(); 3633 } 3634 3635 llvm::Expected<TraceSupportedResponse> 3636 GDBRemoteCommunicationClient::SendTraceSupported(std::chrono::seconds timeout) { 3637 Log *log = GetLog(GDBRLog::Process); 3638 3639 StreamGDBRemote escaped_packet; 3640 escaped_packet.PutCString("jLLDBTraceSupported"); 3641 3642 StringExtractorGDBRemote response; 3643 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3644 timeout) == 3645 GDBRemoteCommunication::PacketResult::Success) { 3646 if (response.IsErrorResponse()) 3647 return response.GetStatus().ToError(); 3648 if (response.IsUnsupportedResponse()) 3649 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3650 "jLLDBTraceSupported is unsupported"); 3651 3652 return llvm::json::parse<TraceSupportedResponse>(response.Peek(), 3653 "TraceSupportedResponse"); 3654 } 3655 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported"); 3656 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3657 "failed to send packet: jLLDBTraceSupported"); 3658 } 3659 3660 llvm::Error 3661 GDBRemoteCommunicationClient::SendTraceStop(const TraceStopRequest &request, 3662 std::chrono::seconds timeout) { 3663 Log *log = GetLog(GDBRLog::Process); 3664 3665 StreamGDBRemote escaped_packet; 3666 escaped_packet.PutCString("jLLDBTraceStop:"); 3667 3668 std::string json_string; 3669 llvm::raw_string_ostream os(json_string); 3670 os << toJSON(request); 3671 3672 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3673 3674 StringExtractorGDBRemote response; 3675 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3676 timeout) == 3677 GDBRemoteCommunication::PacketResult::Success) { 3678 if (response.IsErrorResponse()) 3679 return response.GetStatus().ToError(); 3680 if (response.IsUnsupportedResponse()) 3681 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3682 "jLLDBTraceStop is unsupported"); 3683 if (response.IsOKResponse()) 3684 return llvm::Error::success(); 3685 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3686 "Invalid jLLDBTraceStart response"); 3687 } 3688 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop"); 3689 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3690 "failed to send packet: jLLDBTraceStop '%s'", 3691 escaped_packet.GetData()); 3692 } 3693 3694 llvm::Error 3695 GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value ¶ms, 3696 std::chrono::seconds timeout) { 3697 Log *log = GetLog(GDBRLog::Process); 3698 3699 StreamGDBRemote escaped_packet; 3700 escaped_packet.PutCString("jLLDBTraceStart:"); 3701 3702 std::string json_string; 3703 llvm::raw_string_ostream os(json_string); 3704 os << params; 3705 3706 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3707 3708 StringExtractorGDBRemote response; 3709 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3710 timeout) == 3711 GDBRemoteCommunication::PacketResult::Success) { 3712 if (response.IsErrorResponse()) 3713 return response.GetStatus().ToError(); 3714 if (response.IsUnsupportedResponse()) 3715 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3716 "jLLDBTraceStart is unsupported"); 3717 if (response.IsOKResponse()) 3718 return llvm::Error::success(); 3719 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3720 "Invalid jLLDBTraceStart response"); 3721 } 3722 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart"); 3723 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3724 "failed to send packet: jLLDBTraceStart '%s'", 3725 escaped_packet.GetData()); 3726 } 3727 3728 llvm::Expected<std::string> 3729 GDBRemoteCommunicationClient::SendTraceGetState(llvm::StringRef type, 3730 std::chrono::seconds timeout) { 3731 Log *log = GetLog(GDBRLog::Process); 3732 3733 StreamGDBRemote escaped_packet; 3734 escaped_packet.PutCString("jLLDBTraceGetState:"); 3735 3736 std::string json_string; 3737 llvm::raw_string_ostream os(json_string); 3738 os << toJSON(TraceGetStateRequest{type.str()}); 3739 3740 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3741 3742 StringExtractorGDBRemote response; 3743 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3744 timeout) == 3745 GDBRemoteCommunication::PacketResult::Success) { 3746 if (response.IsErrorResponse()) 3747 return response.GetStatus().ToError(); 3748 if (response.IsUnsupportedResponse()) 3749 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3750 "jLLDBTraceGetState is unsupported"); 3751 return std::string(response.Peek()); 3752 } 3753 3754 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState"); 3755 return llvm::createStringError( 3756 llvm::inconvertibleErrorCode(), 3757 "failed to send packet: jLLDBTraceGetState '%s'", 3758 escaped_packet.GetData()); 3759 } 3760 3761 llvm::Expected<std::vector<uint8_t>> 3762 GDBRemoteCommunicationClient::SendTraceGetBinaryData( 3763 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) { 3764 Log *log = GetLog(GDBRLog::Process); 3765 3766 StreamGDBRemote escaped_packet; 3767 escaped_packet.PutCString("jLLDBTraceGetBinaryData:"); 3768 3769 std::string json_string; 3770 llvm::raw_string_ostream os(json_string); 3771 os << toJSON(request); 3772 3773 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3774 3775 StringExtractorGDBRemote response; 3776 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3777 timeout) == 3778 GDBRemoteCommunication::PacketResult::Success) { 3779 if (response.IsErrorResponse()) 3780 return response.GetStatus().ToError(); 3781 std::string data; 3782 response.GetEscapedBinaryData(data); 3783 return std::vector<uint8_t>(data.begin(), data.end()); 3784 } 3785 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData"); 3786 return llvm::createStringError( 3787 llvm::inconvertibleErrorCode(), 3788 "failed to send packet: jLLDBTraceGetBinaryData '%s'", 3789 escaped_packet.GetData()); 3790 } 3791 3792 std::optional<QOffsets> GDBRemoteCommunicationClient::GetQOffsets() { 3793 StringExtractorGDBRemote response; 3794 if (SendPacketAndWaitForResponse("qOffsets", response) != 3795 PacketResult::Success) 3796 return std::nullopt; 3797 if (!response.IsNormalResponse()) 3798 return std::nullopt; 3799 3800 QOffsets result; 3801 llvm::StringRef ref = response.GetStringRef(); 3802 const auto &GetOffset = [&] { 3803 addr_t offset; 3804 if (ref.consumeInteger(16, offset)) 3805 return false; 3806 result.offsets.push_back(offset); 3807 return true; 3808 }; 3809 3810 if (ref.consume_front("Text=")) { 3811 result.segments = false; 3812 if (!GetOffset()) 3813 return std::nullopt; 3814 if (!ref.consume_front(";Data=") || !GetOffset()) 3815 return std::nullopt; 3816 if (ref.empty()) 3817 return result; 3818 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty()) 3819 return result; 3820 } else if (ref.consume_front("TextSeg=")) { 3821 result.segments = true; 3822 if (!GetOffset()) 3823 return std::nullopt; 3824 if (ref.empty()) 3825 return result; 3826 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty()) 3827 return result; 3828 } 3829 return std::nullopt; 3830 } 3831 3832 bool GDBRemoteCommunicationClient::GetModuleInfo( 3833 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec, 3834 ModuleSpec &module_spec) { 3835 if (!m_supports_qModuleInfo) 3836 return false; 3837 3838 std::string module_path = module_file_spec.GetPath(false); 3839 if (module_path.empty()) 3840 return false; 3841 3842 StreamString packet; 3843 packet.PutCString("qModuleInfo:"); 3844 packet.PutStringAsRawHex8(module_path); 3845 packet.PutCString(";"); 3846 const auto &triple = arch_spec.GetTriple().getTriple(); 3847 packet.PutStringAsRawHex8(triple); 3848 3849 StringExtractorGDBRemote response; 3850 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 3851 PacketResult::Success) 3852 return false; 3853 3854 if (response.IsErrorResponse()) 3855 return false; 3856 3857 if (response.IsUnsupportedResponse()) { 3858 m_supports_qModuleInfo = false; 3859 return false; 3860 } 3861 3862 llvm::StringRef name; 3863 llvm::StringRef value; 3864 3865 module_spec.Clear(); 3866 module_spec.GetFileSpec() = module_file_spec; 3867 3868 while (response.GetNameColonValue(name, value)) { 3869 if (name == "uuid" || name == "md5") { 3870 StringExtractor extractor(value); 3871 std::string uuid; 3872 extractor.GetHexByteString(uuid); 3873 module_spec.GetUUID().SetFromStringRef(uuid); 3874 } else if (name == "triple") { 3875 StringExtractor extractor(value); 3876 std::string triple; 3877 extractor.GetHexByteString(triple); 3878 module_spec.GetArchitecture().SetTriple(triple.c_str()); 3879 } else if (name == "file_offset") { 3880 uint64_t ival = 0; 3881 if (!value.getAsInteger(16, ival)) 3882 module_spec.SetObjectOffset(ival); 3883 } else if (name == "file_size") { 3884 uint64_t ival = 0; 3885 if (!value.getAsInteger(16, ival)) 3886 module_spec.SetObjectSize(ival); 3887 } else if (name == "file_path") { 3888 StringExtractor extractor(value); 3889 std::string path; 3890 extractor.GetHexByteString(path); 3891 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple()); 3892 } 3893 } 3894 3895 return true; 3896 } 3897 3898 static std::optional<ModuleSpec> 3899 ParseModuleSpec(StructuredData::Dictionary *dict) { 3900 ModuleSpec result; 3901 if (!dict) 3902 return std::nullopt; 3903 3904 llvm::StringRef string; 3905 uint64_t integer; 3906 3907 if (!dict->GetValueForKeyAsString("uuid", string)) 3908 return std::nullopt; 3909 if (!result.GetUUID().SetFromStringRef(string)) 3910 return std::nullopt; 3911 3912 if (!dict->GetValueForKeyAsInteger("file_offset", integer)) 3913 return std::nullopt; 3914 result.SetObjectOffset(integer); 3915 3916 if (!dict->GetValueForKeyAsInteger("file_size", integer)) 3917 return std::nullopt; 3918 result.SetObjectSize(integer); 3919 3920 if (!dict->GetValueForKeyAsString("triple", string)) 3921 return std::nullopt; 3922 result.GetArchitecture().SetTriple(string); 3923 3924 if (!dict->GetValueForKeyAsString("file_path", string)) 3925 return std::nullopt; 3926 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple()); 3927 3928 return result; 3929 } 3930 3931 std::optional<std::vector<ModuleSpec>> 3932 GDBRemoteCommunicationClient::GetModulesInfo( 3933 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 3934 namespace json = llvm::json; 3935 3936 if (!m_supports_jModulesInfo) 3937 return std::nullopt; 3938 3939 json::Array module_array; 3940 for (const FileSpec &module_file_spec : module_file_specs) { 3941 module_array.push_back( 3942 json::Object{{"file", module_file_spec.GetPath(false)}, 3943 {"triple", triple.getTriple()}}); 3944 } 3945 StreamString unescaped_payload; 3946 unescaped_payload.PutCString("jModulesInfo:"); 3947 unescaped_payload.AsRawOstream() << std::move(module_array); 3948 3949 StreamGDBRemote payload; 3950 payload.PutEscapedBytes(unescaped_payload.GetString().data(), 3951 unescaped_payload.GetSize()); 3952 3953 // Increase the timeout for jModulesInfo since this packet can take longer. 3954 ScopedTimeout timeout(*this, std::chrono::seconds(10)); 3955 3956 StringExtractorGDBRemote response; 3957 if (SendPacketAndWaitForResponse(payload.GetString(), response) != 3958 PacketResult::Success || 3959 response.IsErrorResponse()) 3960 return std::nullopt; 3961 3962 if (response.IsUnsupportedResponse()) { 3963 m_supports_jModulesInfo = false; 3964 return std::nullopt; 3965 } 3966 3967 StructuredData::ObjectSP response_object_sp = 3968 StructuredData::ParseJSON(response.GetStringRef()); 3969 if (!response_object_sp) 3970 return std::nullopt; 3971 3972 StructuredData::Array *response_array = response_object_sp->GetAsArray(); 3973 if (!response_array) 3974 return std::nullopt; 3975 3976 std::vector<ModuleSpec> result; 3977 for (size_t i = 0; i < response_array->GetSize(); ++i) { 3978 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec( 3979 response_array->GetItemAtIndex(i)->GetAsDictionary())) 3980 result.push_back(*module_spec); 3981 } 3982 3983 return result; 3984 } 3985 3986 // query the target remote for extended information using the qXfer packet 3987 // 3988 // example: object='features', annex='target.xml' 3989 // return: <xml output> or error 3990 llvm::Expected<std::string> 3991 GDBRemoteCommunicationClient::ReadExtFeature(llvm::StringRef object, 3992 llvm::StringRef annex) { 3993 3994 std::string output; 3995 llvm::raw_string_ostream output_stream(output); 3996 StringExtractorGDBRemote chunk; 3997 3998 uint64_t size = GetRemoteMaxPacketSize(); 3999 if (size == 0) 4000 size = 0x1000; 4001 size = size - 1; // Leave space for the 'm' or 'l' character in the response 4002 int offset = 0; 4003 bool active = true; 4004 4005 // loop until all data has been read 4006 while (active) { 4007 4008 // send query extended feature packet 4009 std::string packet = 4010 ("qXfer:" + object + ":read:" + annex + ":" + 4011 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size)) 4012 .str(); 4013 4014 GDBRemoteCommunication::PacketResult res = 4015 SendPacketAndWaitForResponse(packet, chunk); 4016 4017 if (res != GDBRemoteCommunication::PacketResult::Success || 4018 chunk.GetStringRef().empty()) { 4019 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4020 "Error sending $qXfer packet"); 4021 } 4022 4023 // check packet code 4024 switch (chunk.GetStringRef()[0]) { 4025 // last chunk 4026 case ('l'): 4027 active = false; 4028 [[fallthrough]]; 4029 4030 // more chunks 4031 case ('m'): 4032 output_stream << chunk.GetStringRef().drop_front(); 4033 offset += chunk.GetStringRef().size() - 1; 4034 break; 4035 4036 // unknown chunk 4037 default: 4038 return llvm::createStringError( 4039 llvm::inconvertibleErrorCode(), 4040 "Invalid continuation code from $qXfer packet"); 4041 } 4042 } 4043 4044 return output; 4045 } 4046 4047 // Notify the target that gdb is prepared to serve symbol lookup requests. 4048 // packet: "qSymbol::" 4049 // reply: 4050 // OK The target does not need to look up any (more) symbols. 4051 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex 4052 // encoded). 4053 // LLDB may provide the value by sending another qSymbol 4054 // packet 4055 // in the form of"qSymbol:<sym_value>:<sym_name>". 4056 // 4057 // Three examples: 4058 // 4059 // lldb sends: qSymbol:: 4060 // lldb receives: OK 4061 // Remote gdb stub does not need to know the addresses of any symbols, lldb 4062 // does not 4063 // need to ask again in this session. 4064 // 4065 // lldb sends: qSymbol:: 4066 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 4067 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473 4068 // lldb receives: OK 4069 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does 4070 // not know 4071 // the address at this time. lldb needs to send qSymbol:: again when it has 4072 // more 4073 // solibs loaded. 4074 // 4075 // lldb sends: qSymbol:: 4076 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 4077 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473 4078 // lldb receives: OK 4079 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says 4080 // that it 4081 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it 4082 // does not 4083 // need any more symbols. lldb does not need to ask again in this session. 4084 4085 void GDBRemoteCommunicationClient::ServeSymbolLookups( 4086 lldb_private::Process *process) { 4087 // Set to true once we've resolved a symbol to an address for the remote 4088 // stub. If we get an 'OK' response after this, the remote stub doesn't need 4089 // any more symbols and we can stop asking. 4090 bool symbol_response_provided = false; 4091 4092 // Is this the initial qSymbol:: packet? 4093 bool first_qsymbol_query = true; 4094 4095 if (m_supports_qSymbol && !m_qSymbol_requests_done) { 4096 Lock lock(*this); 4097 if (lock) { 4098 StreamString packet; 4099 packet.PutCString("qSymbol::"); 4100 StringExtractorGDBRemote response; 4101 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) == 4102 PacketResult::Success) { 4103 if (response.IsOKResponse()) { 4104 if (symbol_response_provided || first_qsymbol_query) { 4105 m_qSymbol_requests_done = true; 4106 } 4107 4108 // We are done serving symbols requests 4109 return; 4110 } 4111 first_qsymbol_query = false; 4112 4113 if (response.IsUnsupportedResponse()) { 4114 // qSymbol is not supported by the current GDB server we are 4115 // connected to 4116 m_supports_qSymbol = false; 4117 return; 4118 } else { 4119 llvm::StringRef response_str(response.GetStringRef()); 4120 if (response_str.starts_with("qSymbol:")) { 4121 response.SetFilePos(strlen("qSymbol:")); 4122 std::string symbol_name; 4123 if (response.GetHexByteString(symbol_name)) { 4124 if (symbol_name.empty()) 4125 return; 4126 4127 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS; 4128 lldb_private::SymbolContextList sc_list; 4129 process->GetTarget().GetImages().FindSymbolsWithNameAndType( 4130 ConstString(symbol_name), eSymbolTypeAny, sc_list); 4131 for (const SymbolContext &sc : sc_list) { 4132 if (symbol_load_addr != LLDB_INVALID_ADDRESS) 4133 break; 4134 if (sc.symbol) { 4135 switch (sc.symbol->GetType()) { 4136 case eSymbolTypeInvalid: 4137 case eSymbolTypeAbsolute: 4138 case eSymbolTypeUndefined: 4139 case eSymbolTypeSourceFile: 4140 case eSymbolTypeHeaderFile: 4141 case eSymbolTypeObjectFile: 4142 case eSymbolTypeCommonBlock: 4143 case eSymbolTypeBlock: 4144 case eSymbolTypeLocal: 4145 case eSymbolTypeParam: 4146 case eSymbolTypeVariable: 4147 case eSymbolTypeVariableType: 4148 case eSymbolTypeLineEntry: 4149 case eSymbolTypeLineHeader: 4150 case eSymbolTypeScopeBegin: 4151 case eSymbolTypeScopeEnd: 4152 case eSymbolTypeAdditional: 4153 case eSymbolTypeCompiler: 4154 case eSymbolTypeInstrumentation: 4155 case eSymbolTypeTrampoline: 4156 break; 4157 4158 case eSymbolTypeCode: 4159 case eSymbolTypeResolver: 4160 case eSymbolTypeData: 4161 case eSymbolTypeRuntime: 4162 case eSymbolTypeException: 4163 case eSymbolTypeObjCClass: 4164 case eSymbolTypeObjCMetaClass: 4165 case eSymbolTypeObjCIVar: 4166 case eSymbolTypeReExported: 4167 symbol_load_addr = 4168 sc.symbol->GetLoadAddress(&process->GetTarget()); 4169 break; 4170 } 4171 } 4172 } 4173 // This is the normal path where our symbol lookup was successful 4174 // and we want to send a packet with the new symbol value and see 4175 // if another lookup needs to be done. 4176 4177 // Change "packet" to contain the requested symbol value and name 4178 packet.Clear(); 4179 packet.PutCString("qSymbol:"); 4180 if (symbol_load_addr != LLDB_INVALID_ADDRESS) { 4181 packet.Printf("%" PRIx64, symbol_load_addr); 4182 symbol_response_provided = true; 4183 } else { 4184 symbol_response_provided = false; 4185 } 4186 packet.PutCString(":"); 4187 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size()); 4188 continue; // go back to the while loop and send "packet" and wait 4189 // for another response 4190 } 4191 } 4192 } 4193 } 4194 // If we make it here, the symbol request packet response wasn't valid or 4195 // our symbol lookup failed so we must abort 4196 return; 4197 4198 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) { 4199 LLDB_LOGF(log, 4200 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", 4201 __FUNCTION__); 4202 } 4203 } 4204 } 4205 4206 StructuredData::Array * 4207 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() { 4208 if (!m_supported_async_json_packets_is_valid) { 4209 // Query the server for the array of supported asynchronous JSON packets. 4210 m_supported_async_json_packets_is_valid = true; 4211 4212 Log *log = GetLog(GDBRLog::Process); 4213 4214 // Poll it now. 4215 StringExtractorGDBRemote response; 4216 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) == 4217 PacketResult::Success) { 4218 m_supported_async_json_packets_sp = 4219 StructuredData::ParseJSON(response.GetStringRef()); 4220 if (m_supported_async_json_packets_sp && 4221 !m_supported_async_json_packets_sp->GetAsArray()) { 4222 // We were returned something other than a JSON array. This is 4223 // invalid. Clear it out. 4224 LLDB_LOGF(log, 4225 "GDBRemoteCommunicationClient::%s(): " 4226 "QSupportedAsyncJSONPackets returned invalid " 4227 "result: %s", 4228 __FUNCTION__, response.GetStringRef().data()); 4229 m_supported_async_json_packets_sp.reset(); 4230 } 4231 } else { 4232 LLDB_LOGF(log, 4233 "GDBRemoteCommunicationClient::%s(): " 4234 "QSupportedAsyncJSONPackets unsupported", 4235 __FUNCTION__); 4236 } 4237 4238 if (log && m_supported_async_json_packets_sp) { 4239 StreamString stream; 4240 m_supported_async_json_packets_sp->Dump(stream); 4241 LLDB_LOGF(log, 4242 "GDBRemoteCommunicationClient::%s(): supported async " 4243 "JSON packets: %s", 4244 __FUNCTION__, stream.GetData()); 4245 } 4246 } 4247 4248 return m_supported_async_json_packets_sp 4249 ? m_supported_async_json_packets_sp->GetAsArray() 4250 : nullptr; 4251 } 4252 4253 Status GDBRemoteCommunicationClient::SendSignalsToIgnore( 4254 llvm::ArrayRef<int32_t> signals) { 4255 // Format packet: 4256 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN> 4257 auto range = llvm::make_range(signals.begin(), signals.end()); 4258 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str(); 4259 4260 StringExtractorGDBRemote response; 4261 auto send_status = SendPacketAndWaitForResponse(packet, response); 4262 4263 if (send_status != GDBRemoteCommunication::PacketResult::Success) 4264 return Status::FromErrorString("Sending QPassSignals packet failed"); 4265 4266 if (response.IsOKResponse()) { 4267 return Status(); 4268 } else { 4269 return Status::FromErrorString( 4270 "Unknown error happened during sending QPassSignals packet."); 4271 } 4272 } 4273 4274 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( 4275 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) { 4276 Status error; 4277 4278 if (type_name.empty()) { 4279 error = Status::FromErrorString("invalid type_name argument"); 4280 return error; 4281 } 4282 4283 // Build command: Configure{type_name}: serialized config data. 4284 StreamGDBRemote stream; 4285 stream.PutCString("QConfigure"); 4286 stream.PutCString(type_name); 4287 stream.PutChar(':'); 4288 if (config_sp) { 4289 // Gather the plain-text version of the configuration data. 4290 StreamString unescaped_stream; 4291 config_sp->Dump(unescaped_stream); 4292 unescaped_stream.Flush(); 4293 4294 // Add it to the stream in escaped fashion. 4295 stream.PutEscapedBytes(unescaped_stream.GetString().data(), 4296 unescaped_stream.GetSize()); 4297 } 4298 stream.Flush(); 4299 4300 // Send the packet. 4301 StringExtractorGDBRemote response; 4302 auto result = SendPacketAndWaitForResponse(stream.GetString(), response); 4303 if (result == PacketResult::Success) { 4304 // We failed if the config result comes back other than OK. 4305 if (response.GetStringRef() == "OK") { 4306 // Okay! 4307 error.Clear(); 4308 } else { 4309 error = Status::FromErrorStringWithFormatv( 4310 "configuring StructuredData feature {0} failed with error {1}", 4311 type_name, response.GetStringRef()); 4312 } 4313 } else { 4314 // Can we get more data here on the failure? 4315 error = Status::FromErrorStringWithFormatv( 4316 "configuring StructuredData feature {0} failed when sending packet: " 4317 "PacketResult={1}", 4318 type_name, (int)result); 4319 } 4320 return error; 4321 } 4322 4323 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) { 4324 GDBRemoteClientBase::OnRunPacketSent(first); 4325 m_curr_tid = LLDB_INVALID_THREAD_ID; 4326 } 4327 4328 bool GDBRemoteCommunicationClient::UsesNativeSignals() { 4329 if (m_uses_native_signals == eLazyBoolCalculate) 4330 GetRemoteQSupported(); 4331 if (m_uses_native_signals == eLazyBoolYes) 4332 return true; 4333 4334 // If the remote didn't indicate native-signal support explicitly, 4335 // check whether it is an old version of lldb-server. 4336 return GetThreadSuffixSupported(); 4337 } 4338 4339 llvm::Expected<int> GDBRemoteCommunicationClient::KillProcess(lldb::pid_t pid) { 4340 StringExtractorGDBRemote response; 4341 GDBRemoteCommunication::ScopedTimeout(*this, seconds(3)); 4342 4343 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout()) != 4344 PacketResult::Success) 4345 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4346 "failed to send k packet"); 4347 4348 char packet_cmd = response.GetChar(0); 4349 if (packet_cmd == 'W' || packet_cmd == 'X') 4350 return response.GetHexU8(); 4351 4352 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4353 "unexpected response to k packet: %s", 4354 response.GetStringRef().str().c_str()); 4355 } 4356