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