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