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