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