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