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 llvm::StringRef name; 2594 llvm::StringRef value; 2595 while (response.GetNameColonValue(name, value)) { 2596 if (name.equals("port")) 2597 value.getAsInteger(0, port); 2598 else if (name.equals("pid")) 2599 value.getAsInteger(0, pid); 2600 else if (name.compare("socket_name") == 0) { 2601 StringExtractor extractor(value); 2602 extractor.GetHexByteString(socket_name); 2603 } 2604 } 2605 return true; 2606 } 2607 return false; 2608 } 2609 2610 size_t GDBRemoteCommunicationClient::QueryGDBServer( 2611 std::vector<std::pair<uint16_t, std::string>> &connection_urls) { 2612 connection_urls.clear(); 2613 2614 StringExtractorGDBRemote response; 2615 if (SendPacketAndWaitForResponse("qQueryGDBServer", response) != 2616 PacketResult::Success) 2617 return 0; 2618 2619 StructuredData::ObjectSP data = 2620 StructuredData::ParseJSON(response.GetStringRef()); 2621 if (!data) 2622 return 0; 2623 2624 StructuredData::Array *array = data->GetAsArray(); 2625 if (!array) 2626 return 0; 2627 2628 for (size_t i = 0, count = array->GetSize(); i < count; ++i) { 2629 StructuredData::Dictionary *element = nullptr; 2630 if (!array->GetItemAtIndexAsDictionary(i, element)) 2631 continue; 2632 2633 uint16_t port = 0; 2634 if (StructuredData::ObjectSP port_osp = 2635 element->GetValueForKey(llvm::StringRef("port"))) 2636 port = port_osp->GetUnsignedIntegerValue(0); 2637 2638 std::string socket_name; 2639 if (StructuredData::ObjectSP socket_name_osp = 2640 element->GetValueForKey(llvm::StringRef("socket_name"))) 2641 socket_name = std::string(socket_name_osp->GetStringValue()); 2642 2643 if (port != 0 || !socket_name.empty()) 2644 connection_urls.emplace_back(port, socket_name); 2645 } 2646 return connection_urls.size(); 2647 } 2648 2649 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) { 2650 StreamString stream; 2651 stream.Printf("qKillSpawnedProcess:%" PRId64, pid); 2652 2653 StringExtractorGDBRemote response; 2654 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 2655 PacketResult::Success) { 2656 if (response.IsOKResponse()) 2657 return true; 2658 } 2659 return false; 2660 } 2661 2662 std::optional<PidTid> GDBRemoteCommunicationClient::SendSetCurrentThreadPacket( 2663 uint64_t tid, uint64_t pid, char op) { 2664 lldb_private::StreamString packet; 2665 packet.PutChar('H'); 2666 packet.PutChar(op); 2667 2668 if (pid != LLDB_INVALID_PROCESS_ID) 2669 packet.Printf("p%" PRIx64 ".", pid); 2670 2671 if (tid == UINT64_MAX) 2672 packet.PutCString("-1"); 2673 else 2674 packet.Printf("%" PRIx64, tid); 2675 2676 StringExtractorGDBRemote response; 2677 if (SendPacketAndWaitForResponse(packet.GetString(), response) == 2678 PacketResult::Success) { 2679 if (response.IsOKResponse()) 2680 return {{pid, tid}}; 2681 2682 /* 2683 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2684 * Hg packet. 2685 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2686 * which can 2687 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2688 */ 2689 if (response.IsUnsupportedResponse() && IsConnected()) 2690 return {{1, 1}}; 2691 } 2692 return std::nullopt; 2693 } 2694 2695 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid, 2696 uint64_t pid) { 2697 if (m_curr_tid == tid && 2698 (m_curr_pid == pid || LLDB_INVALID_PROCESS_ID == pid)) 2699 return true; 2700 2701 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'g'); 2702 if (ret) { 2703 if (ret->pid != LLDB_INVALID_PROCESS_ID) 2704 m_curr_pid = ret->pid; 2705 m_curr_tid = ret->tid; 2706 } 2707 return ret.has_value(); 2708 } 2709 2710 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid, 2711 uint64_t pid) { 2712 if (m_curr_tid_run == tid && 2713 (m_curr_pid_run == pid || LLDB_INVALID_PROCESS_ID == pid)) 2714 return true; 2715 2716 std::optional<PidTid> ret = SendSetCurrentThreadPacket(tid, pid, 'c'); 2717 if (ret) { 2718 if (ret->pid != LLDB_INVALID_PROCESS_ID) 2719 m_curr_pid_run = ret->pid; 2720 m_curr_tid_run = ret->tid; 2721 } 2722 return ret.has_value(); 2723 } 2724 2725 bool GDBRemoteCommunicationClient::GetStopReply( 2726 StringExtractorGDBRemote &response) { 2727 if (SendPacketAndWaitForResponse("?", response) == PacketResult::Success) 2728 return response.IsNormalResponse(); 2729 return false; 2730 } 2731 2732 bool GDBRemoteCommunicationClient::GetThreadStopInfo( 2733 lldb::tid_t tid, StringExtractorGDBRemote &response) { 2734 if (m_supports_qThreadStopInfo) { 2735 char packet[256]; 2736 int packet_len = 2737 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2738 assert(packet_len < (int)sizeof(packet)); 2739 UNUSED_IF_ASSERT_DISABLED(packet_len); 2740 if (SendPacketAndWaitForResponse(packet, response) == 2741 PacketResult::Success) { 2742 if (response.IsUnsupportedResponse()) 2743 m_supports_qThreadStopInfo = false; 2744 else if (response.IsNormalResponse()) 2745 return true; 2746 else 2747 return false; 2748 } else { 2749 m_supports_qThreadStopInfo = false; 2750 } 2751 } 2752 return false; 2753 } 2754 2755 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket( 2756 GDBStoppointType type, bool insert, addr_t addr, uint32_t length, 2757 std::chrono::seconds timeout) { 2758 Log *log = GetLog(LLDBLog::Breakpoints); 2759 LLDB_LOGF(log, "GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64, 2760 __FUNCTION__, insert ? "add" : "remove", addr); 2761 2762 // Check if the stub is known not to support this breakpoint type 2763 if (!SupportsGDBStoppointPacket(type)) 2764 return UINT8_MAX; 2765 // Construct the breakpoint packet 2766 char packet[64]; 2767 const int packet_len = 2768 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x", 2769 insert ? 'Z' : 'z', type, addr, length); 2770 // Check we haven't overwritten the end of the packet buffer 2771 assert(packet_len + 1 < (int)sizeof(packet)); 2772 UNUSED_IF_ASSERT_DISABLED(packet_len); 2773 StringExtractorGDBRemote response; 2774 // Make sure the response is either "OK", "EXX" where XX are two hex digits, 2775 // or "" (unsupported) 2776 response.SetResponseValidatorToOKErrorNotSupported(); 2777 // Try to send the breakpoint packet, and check that it was correctly sent 2778 if (SendPacketAndWaitForResponse(packet, response, timeout) == 2779 PacketResult::Success) { 2780 // Receive and OK packet when the breakpoint successfully placed 2781 if (response.IsOKResponse()) 2782 return 0; 2783 2784 // Status while setting breakpoint, send back specific error 2785 if (response.IsErrorResponse()) 2786 return response.GetError(); 2787 2788 // Empty packet informs us that breakpoint is not supported 2789 if (response.IsUnsupportedResponse()) { 2790 // Disable this breakpoint type since it is unsupported 2791 switch (type) { 2792 case eBreakpointSoftware: 2793 m_supports_z0 = false; 2794 break; 2795 case eBreakpointHardware: 2796 m_supports_z1 = false; 2797 break; 2798 case eWatchpointWrite: 2799 m_supports_z2 = false; 2800 break; 2801 case eWatchpointRead: 2802 m_supports_z3 = false; 2803 break; 2804 case eWatchpointReadWrite: 2805 m_supports_z4 = false; 2806 break; 2807 case eStoppointInvalid: 2808 return UINT8_MAX; 2809 } 2810 } 2811 } 2812 // Signal generic failure 2813 return UINT8_MAX; 2814 } 2815 2816 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> 2817 GDBRemoteCommunicationClient::GetCurrentProcessAndThreadIDs( 2818 bool &sequence_mutex_unavailable) { 2819 std::vector<std::pair<lldb::pid_t, lldb::tid_t>> ids; 2820 2821 Lock lock(*this); 2822 if (lock) { 2823 sequence_mutex_unavailable = false; 2824 StringExtractorGDBRemote response; 2825 2826 PacketResult packet_result; 2827 for (packet_result = 2828 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response); 2829 packet_result == PacketResult::Success && response.IsNormalResponse(); 2830 packet_result = 2831 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) { 2832 char ch = response.GetChar(); 2833 if (ch == 'l') 2834 break; 2835 if (ch == 'm') { 2836 do { 2837 auto pid_tid = response.GetPidTid(LLDB_INVALID_PROCESS_ID); 2838 // If we get an invalid response, break out of the loop. 2839 // If there are valid tids, they have been added to ids. 2840 // If there are no valid tids, we'll fall through to the 2841 // bare-iron target handling below. 2842 if (!pid_tid) 2843 break; 2844 2845 ids.push_back(*pid_tid); 2846 ch = response.GetChar(); // Skip the command separator 2847 } while (ch == ','); // Make sure we got a comma separator 2848 } 2849 } 2850 2851 /* 2852 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2853 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet 2854 * could 2855 * be as simple as 'S05'. There is no packet which can give us pid and/or 2856 * tid. 2857 * Assume pid=tid=1 in such cases. 2858 */ 2859 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) && 2860 ids.size() == 0 && IsConnected()) { 2861 ids.emplace_back(1, 1); 2862 } 2863 } else { 2864 Log *log(GetLog(GDBRLog::Process | GDBRLog::Packets)); 2865 LLDB_LOG(log, "error: failed to get packet sequence mutex, not sending " 2866 "packet 'qfThreadInfo'"); 2867 sequence_mutex_unavailable = true; 2868 } 2869 2870 return ids; 2871 } 2872 2873 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs( 2874 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) { 2875 lldb::pid_t pid = GetCurrentProcessID(); 2876 thread_ids.clear(); 2877 2878 auto ids = GetCurrentProcessAndThreadIDs(sequence_mutex_unavailable); 2879 if (ids.empty() || sequence_mutex_unavailable) 2880 return 0; 2881 2882 for (auto id : ids) { 2883 // skip threads that do not belong to the current process 2884 if (id.first != LLDB_INVALID_PROCESS_ID && id.first != pid) 2885 continue; 2886 if (id.second != LLDB_INVALID_THREAD_ID && 2887 id.second != StringExtractorGDBRemote::AllThreads) 2888 thread_ids.push_back(id.second); 2889 } 2890 2891 return thread_ids.size(); 2892 } 2893 2894 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() { 2895 StringExtractorGDBRemote response; 2896 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response) != 2897 PacketResult::Success || 2898 !response.IsNormalResponse()) 2899 return LLDB_INVALID_ADDRESS; 2900 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2901 } 2902 2903 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand( 2904 llvm::StringRef command, 2905 const FileSpec & 2906 working_dir, // Pass empty FileSpec to use the current working directory 2907 int *status_ptr, // Pass NULL if you don't want the process exit status 2908 int *signo_ptr, // Pass NULL if you don't want the signal that caused the 2909 // process to exit 2910 std::string 2911 *command_output, // Pass NULL if you don't want the command output 2912 const Timeout<std::micro> &timeout) { 2913 lldb_private::StreamString stream; 2914 stream.PutCString("qPlatform_shell:"); 2915 stream.PutBytesAsRawHex8(command.data(), command.size()); 2916 stream.PutChar(','); 2917 uint32_t timeout_sec = UINT32_MAX; 2918 if (timeout) { 2919 // TODO: Use chrono version of std::ceil once c++17 is available. 2920 timeout_sec = std::ceil(std::chrono::duration<double>(*timeout).count()); 2921 } 2922 stream.PutHex32(timeout_sec); 2923 if (working_dir) { 2924 std::string path{working_dir.GetPath(false)}; 2925 stream.PutChar(','); 2926 stream.PutStringAsRawHex8(path); 2927 } 2928 StringExtractorGDBRemote response; 2929 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 2930 PacketResult::Success) { 2931 if (response.GetChar() != 'F') 2932 return Status("malformed reply"); 2933 if (response.GetChar() != ',') 2934 return Status("malformed reply"); 2935 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 2936 if (exitcode == UINT32_MAX) 2937 return Status("unable to run remote process"); 2938 else if (status_ptr) 2939 *status_ptr = exitcode; 2940 if (response.GetChar() != ',') 2941 return Status("malformed reply"); 2942 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 2943 if (signo_ptr) 2944 *signo_ptr = signo; 2945 if (response.GetChar() != ',') 2946 return Status("malformed reply"); 2947 std::string output; 2948 response.GetEscapedBinaryData(output); 2949 if (command_output) 2950 command_output->assign(output); 2951 return Status(); 2952 } 2953 return Status("unable to send packet"); 2954 } 2955 2956 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, 2957 uint32_t file_permissions) { 2958 std::string path{file_spec.GetPath(false)}; 2959 lldb_private::StreamString stream; 2960 stream.PutCString("qPlatform_mkdir:"); 2961 stream.PutHex32(file_permissions); 2962 stream.PutChar(','); 2963 stream.PutStringAsRawHex8(path); 2964 llvm::StringRef packet = stream.GetString(); 2965 StringExtractorGDBRemote response; 2966 2967 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success) 2968 return Status("failed to send '%s' packet", packet.str().c_str()); 2969 2970 if (response.GetChar() != 'F') 2971 return Status("invalid response to '%s' packet", packet.str().c_str()); 2972 2973 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 2974 } 2975 2976 Status 2977 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec, 2978 uint32_t file_permissions) { 2979 std::string path{file_spec.GetPath(false)}; 2980 lldb_private::StreamString stream; 2981 stream.PutCString("qPlatform_chmod:"); 2982 stream.PutHex32(file_permissions); 2983 stream.PutChar(','); 2984 stream.PutStringAsRawHex8(path); 2985 llvm::StringRef packet = stream.GetString(); 2986 StringExtractorGDBRemote response; 2987 2988 if (SendPacketAndWaitForResponse(packet, response) != PacketResult::Success) 2989 return Status("failed to send '%s' packet", stream.GetData()); 2990 2991 if (response.GetChar() != 'F') 2992 return Status("invalid response to '%s' packet", stream.GetData()); 2993 2994 return Status(response.GetHexMaxU32(false, UINT32_MAX), eErrorTypePOSIX); 2995 } 2996 2997 static int gdb_errno_to_system(int err) { 2998 switch (err) { 2999 #define HANDLE_ERRNO(name, value) \ 3000 case GDB_##name: \ 3001 return name; 3002 #include "Plugins/Process/gdb-remote/GDBRemoteErrno.def" 3003 default: 3004 return -1; 3005 } 3006 } 3007 3008 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, 3009 uint64_t fail_result, Status &error) { 3010 response.SetFilePos(0); 3011 if (response.GetChar() != 'F') 3012 return fail_result; 3013 int32_t result = response.GetS32(-2, 16); 3014 if (result == -2) 3015 return fail_result; 3016 if (response.GetChar() == ',') { 3017 int result_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3018 if (result_errno != -1) 3019 error.SetError(result_errno, eErrorTypePOSIX); 3020 else 3021 error.SetError(-1, eErrorTypeGeneric); 3022 } else 3023 error.Clear(); 3024 return result; 3025 } 3026 lldb::user_id_t 3027 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec, 3028 File::OpenOptions flags, mode_t mode, 3029 Status &error) { 3030 std::string path(file_spec.GetPath(false)); 3031 lldb_private::StreamString stream; 3032 stream.PutCString("vFile:open:"); 3033 if (path.empty()) 3034 return UINT64_MAX; 3035 stream.PutStringAsRawHex8(path); 3036 stream.PutChar(','); 3037 stream.PutHex32(flags); 3038 stream.PutChar(','); 3039 stream.PutHex32(mode); 3040 StringExtractorGDBRemote response; 3041 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3042 PacketResult::Success) { 3043 return ParseHostIOPacketResponse(response, UINT64_MAX, error); 3044 } 3045 return UINT64_MAX; 3046 } 3047 3048 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, 3049 Status &error) { 3050 lldb_private::StreamString stream; 3051 stream.Printf("vFile:close:%x", (int)fd); 3052 StringExtractorGDBRemote response; 3053 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3054 PacketResult::Success) { 3055 return ParseHostIOPacketResponse(response, -1, error) == 0; 3056 } 3057 return false; 3058 } 3059 3060 std::optional<GDBRemoteFStatData> 3061 GDBRemoteCommunicationClient::FStat(lldb::user_id_t fd) { 3062 lldb_private::StreamString stream; 3063 stream.Printf("vFile:fstat:%" PRIx64, fd); 3064 StringExtractorGDBRemote response; 3065 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3066 PacketResult::Success) { 3067 if (response.GetChar() != 'F') 3068 return std::nullopt; 3069 int64_t size = response.GetS64(-1, 16); 3070 if (size > 0 && response.GetChar() == ';') { 3071 std::string buffer; 3072 if (response.GetEscapedBinaryData(buffer)) { 3073 GDBRemoteFStatData out; 3074 if (buffer.size() != sizeof(out)) 3075 return std::nullopt; 3076 memcpy(&out, buffer.data(), sizeof(out)); 3077 return out; 3078 } 3079 } 3080 } 3081 return std::nullopt; 3082 } 3083 3084 std::optional<GDBRemoteFStatData> 3085 GDBRemoteCommunicationClient::Stat(const lldb_private::FileSpec &file_spec) { 3086 Status error; 3087 lldb::user_id_t fd = OpenFile(file_spec, File::eOpenOptionReadOnly, 0, error); 3088 if (fd == UINT64_MAX) 3089 return std::nullopt; 3090 std::optional<GDBRemoteFStatData> st = FStat(fd); 3091 CloseFile(fd, error); 3092 return st; 3093 } 3094 3095 // Extension of host I/O packets to get the file size. 3096 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize( 3097 const lldb_private::FileSpec &file_spec) { 3098 if (m_supports_vFileSize) { 3099 std::string path(file_spec.GetPath(false)); 3100 lldb_private::StreamString stream; 3101 stream.PutCString("vFile:size:"); 3102 stream.PutStringAsRawHex8(path); 3103 StringExtractorGDBRemote response; 3104 if (SendPacketAndWaitForResponse(stream.GetString(), response) != 3105 PacketResult::Success) 3106 return UINT64_MAX; 3107 3108 if (!response.IsUnsupportedResponse()) { 3109 if (response.GetChar() != 'F') 3110 return UINT64_MAX; 3111 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 3112 return retcode; 3113 } 3114 m_supports_vFileSize = false; 3115 } 3116 3117 // Fallback to fstat. 3118 std::optional<GDBRemoteFStatData> st = Stat(file_spec); 3119 return st ? st->gdb_st_size : UINT64_MAX; 3120 } 3121 3122 void GDBRemoteCommunicationClient::AutoCompleteDiskFileOrDirectory( 3123 CompletionRequest &request, bool only_dir) { 3124 lldb_private::StreamString stream; 3125 stream.PutCString("qPathComplete:"); 3126 stream.PutHex32(only_dir ? 1 : 0); 3127 stream.PutChar(','); 3128 stream.PutStringAsRawHex8(request.GetCursorArgumentPrefix()); 3129 StringExtractorGDBRemote response; 3130 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3131 PacketResult::Success) { 3132 StreamString strm; 3133 char ch = response.GetChar(); 3134 if (ch != 'M') 3135 return; 3136 while (response.Peek()) { 3137 strm.Clear(); 3138 while ((ch = response.GetHexU8(0, false)) != '\0') 3139 strm.PutChar(ch); 3140 request.AddCompletion(strm.GetString()); 3141 if (response.GetChar() != ',') 3142 break; 3143 } 3144 } 3145 } 3146 3147 Status 3148 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec, 3149 uint32_t &file_permissions) { 3150 if (m_supports_vFileMode) { 3151 std::string path{file_spec.GetPath(false)}; 3152 Status error; 3153 lldb_private::StreamString stream; 3154 stream.PutCString("vFile:mode:"); 3155 stream.PutStringAsRawHex8(path); 3156 StringExtractorGDBRemote response; 3157 if (SendPacketAndWaitForResponse(stream.GetString(), response) != 3158 PacketResult::Success) { 3159 error.SetErrorStringWithFormat("failed to send '%s' packet", 3160 stream.GetData()); 3161 return error; 3162 } 3163 if (!response.IsUnsupportedResponse()) { 3164 if (response.GetChar() != 'F') { 3165 error.SetErrorStringWithFormat("invalid response to '%s' packet", 3166 stream.GetData()); 3167 } else { 3168 const uint32_t mode = response.GetS32(-1, 16); 3169 if (static_cast<int32_t>(mode) == -1) { 3170 if (response.GetChar() == ',') { 3171 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3172 if (response_errno > 0) 3173 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3174 else 3175 error.SetErrorToGenericError(); 3176 } else 3177 error.SetErrorToGenericError(); 3178 } else { 3179 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO); 3180 } 3181 } 3182 return error; 3183 } else { // response.IsUnsupportedResponse() 3184 m_supports_vFileMode = false; 3185 } 3186 } 3187 3188 // Fallback to fstat. 3189 if (std::optional<GDBRemoteFStatData> st = Stat(file_spec)) { 3190 file_permissions = st->gdb_st_mode & (S_IRWXU | S_IRWXG | S_IRWXO); 3191 return Status(); 3192 } 3193 return Status("fstat failed"); 3194 } 3195 3196 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd, 3197 uint64_t offset, void *dst, 3198 uint64_t dst_len, 3199 Status &error) { 3200 lldb_private::StreamString stream; 3201 stream.Printf("vFile:pread:%x,%" PRIx64 ",%" PRIx64, (int)fd, dst_len, 3202 offset); 3203 StringExtractorGDBRemote response; 3204 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3205 PacketResult::Success) { 3206 if (response.GetChar() != 'F') 3207 return 0; 3208 int64_t retcode = response.GetS64(-1, 16); 3209 if (retcode == -1) { 3210 error.SetErrorToGenericError(); 3211 if (response.GetChar() == ',') { 3212 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3213 if (response_errno > 0) 3214 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3215 } 3216 return -1; 3217 } 3218 const char next = (response.Peek() ? *response.Peek() : 0); 3219 if (next == ',') 3220 return 0; 3221 if (next == ';') { 3222 response.GetChar(); // skip the semicolon 3223 std::string buffer; 3224 if (response.GetEscapedBinaryData(buffer)) { 3225 const uint64_t data_to_write = 3226 std::min<uint64_t>(dst_len, buffer.size()); 3227 if (data_to_write > 0) 3228 memcpy(dst, &buffer[0], data_to_write); 3229 return data_to_write; 3230 } 3231 } 3232 } 3233 return 0; 3234 } 3235 3236 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd, 3237 uint64_t offset, 3238 const void *src, 3239 uint64_t src_len, 3240 Status &error) { 3241 lldb_private::StreamGDBRemote stream; 3242 stream.Printf("vFile:pwrite:%x,%" PRIx64 ",", (int)fd, offset); 3243 stream.PutEscapedBytes(src, src_len); 3244 StringExtractorGDBRemote response; 3245 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3246 PacketResult::Success) { 3247 if (response.GetChar() != 'F') { 3248 error.SetErrorStringWithFormat("write file failed"); 3249 return 0; 3250 } 3251 int64_t bytes_written = response.GetS64(-1, 16); 3252 if (bytes_written == -1) { 3253 error.SetErrorToGenericError(); 3254 if (response.GetChar() == ',') { 3255 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3256 if (response_errno > 0) 3257 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3258 } 3259 return -1; 3260 } 3261 return bytes_written; 3262 } else { 3263 error.SetErrorString("failed to send vFile:pwrite packet"); 3264 } 3265 return 0; 3266 } 3267 3268 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, 3269 const FileSpec &dst) { 3270 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)}; 3271 Status error; 3272 lldb_private::StreamGDBRemote stream; 3273 stream.PutCString("vFile:symlink:"); 3274 // the unix symlink() command reverses its parameters where the dst if first, 3275 // so we follow suit here 3276 stream.PutStringAsRawHex8(dst_path); 3277 stream.PutChar(','); 3278 stream.PutStringAsRawHex8(src_path); 3279 StringExtractorGDBRemote response; 3280 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3281 PacketResult::Success) { 3282 if (response.GetChar() == 'F') { 3283 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX); 3284 if (result != 0) { 3285 error.SetErrorToGenericError(); 3286 if (response.GetChar() == ',') { 3287 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3288 if (response_errno > 0) 3289 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3290 } 3291 } 3292 } else { 3293 // Should have returned with 'F<result>[,<errno>]' 3294 error.SetErrorStringWithFormat("symlink failed"); 3295 } 3296 } else { 3297 error.SetErrorString("failed to send vFile:symlink packet"); 3298 } 3299 return error; 3300 } 3301 3302 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) { 3303 std::string path{file_spec.GetPath(false)}; 3304 Status error; 3305 lldb_private::StreamGDBRemote stream; 3306 stream.PutCString("vFile:unlink:"); 3307 // the unix symlink() command reverses its parameters where the dst if first, 3308 // so we follow suit here 3309 stream.PutStringAsRawHex8(path); 3310 StringExtractorGDBRemote response; 3311 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3312 PacketResult::Success) { 3313 if (response.GetChar() == 'F') { 3314 uint32_t result = response.GetHexMaxU32(false, UINT32_MAX); 3315 if (result != 0) { 3316 error.SetErrorToGenericError(); 3317 if (response.GetChar() == ',') { 3318 int response_errno = gdb_errno_to_system(response.GetS32(-1, 16)); 3319 if (response_errno > 0) 3320 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3321 } 3322 } 3323 } else { 3324 // Should have returned with 'F<result>[,<errno>]' 3325 error.SetErrorStringWithFormat("unlink failed"); 3326 } 3327 } else { 3328 error.SetErrorString("failed to send vFile:unlink packet"); 3329 } 3330 return error; 3331 } 3332 3333 // Extension of host I/O packets to get whether a file exists. 3334 bool GDBRemoteCommunicationClient::GetFileExists( 3335 const lldb_private::FileSpec &file_spec) { 3336 if (m_supports_vFileExists) { 3337 std::string path(file_spec.GetPath(false)); 3338 lldb_private::StreamString stream; 3339 stream.PutCString("vFile:exists:"); 3340 stream.PutStringAsRawHex8(path); 3341 StringExtractorGDBRemote response; 3342 if (SendPacketAndWaitForResponse(stream.GetString(), response) != 3343 PacketResult::Success) 3344 return false; 3345 if (!response.IsUnsupportedResponse()) { 3346 if (response.GetChar() != 'F') 3347 return false; 3348 if (response.GetChar() != ',') 3349 return false; 3350 bool retcode = (response.GetChar() != '0'); 3351 return retcode; 3352 } else 3353 m_supports_vFileExists = false; 3354 } 3355 3356 // Fallback to open. 3357 Status error; 3358 lldb::user_id_t fd = OpenFile(file_spec, File::eOpenOptionReadOnly, 0, error); 3359 if (fd == UINT64_MAX) 3360 return false; 3361 CloseFile(fd, error); 3362 return true; 3363 } 3364 3365 bool GDBRemoteCommunicationClient::CalculateMD5( 3366 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) { 3367 std::string path(file_spec.GetPath(false)); 3368 lldb_private::StreamString stream; 3369 stream.PutCString("vFile:MD5:"); 3370 stream.PutStringAsRawHex8(path); 3371 StringExtractorGDBRemote response; 3372 if (SendPacketAndWaitForResponse(stream.GetString(), response) == 3373 PacketResult::Success) { 3374 if (response.GetChar() != 'F') 3375 return false; 3376 if (response.GetChar() != ',') 3377 return false; 3378 if (response.Peek() && *response.Peek() == 'x') 3379 return false; 3380 low = response.GetHexMaxU64(false, UINT64_MAX); 3381 high = response.GetHexMaxU64(false, UINT64_MAX); 3382 return true; 3383 } 3384 return false; 3385 } 3386 3387 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) { 3388 // Some targets have issues with g/G packets and we need to avoid using them 3389 if (m_avoid_g_packets == eLazyBoolCalculate) { 3390 if (process) { 3391 m_avoid_g_packets = eLazyBoolNo; 3392 const ArchSpec &arch = process->GetTarget().GetArchitecture(); 3393 if (arch.IsValid() && 3394 arch.GetTriple().getVendor() == llvm::Triple::Apple && 3395 arch.GetTriple().getOS() == llvm::Triple::IOS && 3396 (arch.GetTriple().getArch() == llvm::Triple::aarch64 || 3397 arch.GetTriple().getArch() == llvm::Triple::aarch64_32)) { 3398 m_avoid_g_packets = eLazyBoolYes; 3399 uint32_t gdb_server_version = GetGDBServerProgramVersion(); 3400 if (gdb_server_version != 0) { 3401 const char *gdb_server_name = GetGDBServerProgramName(); 3402 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) { 3403 if (gdb_server_version >= 310) 3404 m_avoid_g_packets = eLazyBoolNo; 3405 } 3406 } 3407 } 3408 } 3409 } 3410 return m_avoid_g_packets == eLazyBoolYes; 3411 } 3412 3413 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, 3414 uint32_t reg) { 3415 StreamString payload; 3416 payload.Printf("p%x", reg); 3417 StringExtractorGDBRemote response; 3418 if (SendThreadSpecificPacketAndWaitForResponse( 3419 tid, std::move(payload), response) != PacketResult::Success || 3420 !response.IsNormalResponse()) 3421 return nullptr; 3422 3423 WritableDataBufferSP buffer_sp( 3424 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3425 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3426 return buffer_sp; 3427 } 3428 3429 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) { 3430 StreamString payload; 3431 payload.PutChar('g'); 3432 StringExtractorGDBRemote response; 3433 if (SendThreadSpecificPacketAndWaitForResponse( 3434 tid, std::move(payload), response) != PacketResult::Success || 3435 !response.IsNormalResponse()) 3436 return nullptr; 3437 3438 WritableDataBufferSP buffer_sp( 3439 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3440 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3441 return buffer_sp; 3442 } 3443 3444 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, 3445 uint32_t reg_num, 3446 llvm::ArrayRef<uint8_t> data) { 3447 StreamString payload; 3448 payload.Printf("P%x=", reg_num); 3449 payload.PutBytesAsRawHex8(data.data(), data.size(), 3450 endian::InlHostByteOrder(), 3451 endian::InlHostByteOrder()); 3452 StringExtractorGDBRemote response; 3453 return SendThreadSpecificPacketAndWaitForResponse( 3454 tid, std::move(payload), response) == PacketResult::Success && 3455 response.IsOKResponse(); 3456 } 3457 3458 bool GDBRemoteCommunicationClient::WriteAllRegisters( 3459 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) { 3460 StreamString payload; 3461 payload.PutChar('G'); 3462 payload.PutBytesAsRawHex8(data.data(), data.size(), 3463 endian::InlHostByteOrder(), 3464 endian::InlHostByteOrder()); 3465 StringExtractorGDBRemote response; 3466 return SendThreadSpecificPacketAndWaitForResponse( 3467 tid, std::move(payload), response) == PacketResult::Success && 3468 response.IsOKResponse(); 3469 } 3470 3471 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid, 3472 uint32_t &save_id) { 3473 save_id = 0; // Set to invalid save ID 3474 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3475 return false; 3476 3477 m_supports_QSaveRegisterState = eLazyBoolYes; 3478 StreamString payload; 3479 payload.PutCString("QSaveRegisterState"); 3480 StringExtractorGDBRemote response; 3481 if (SendThreadSpecificPacketAndWaitForResponse( 3482 tid, std::move(payload), response) != PacketResult::Success) 3483 return false; 3484 3485 if (response.IsUnsupportedResponse()) 3486 m_supports_QSaveRegisterState = eLazyBoolNo; 3487 3488 const uint32_t response_save_id = response.GetU32(0); 3489 if (response_save_id == 0) 3490 return false; 3491 3492 save_id = response_save_id; 3493 return true; 3494 } 3495 3496 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid, 3497 uint32_t save_id) { 3498 // We use the "m_supports_QSaveRegisterState" variable here because the 3499 // QSaveRegisterState and QRestoreRegisterState packets must both be 3500 // supported in order to be useful 3501 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3502 return false; 3503 3504 StreamString payload; 3505 payload.Printf("QRestoreRegisterState:%u", save_id); 3506 StringExtractorGDBRemote response; 3507 if (SendThreadSpecificPacketAndWaitForResponse( 3508 tid, std::move(payload), response) != PacketResult::Success) 3509 return false; 3510 3511 if (response.IsOKResponse()) 3512 return true; 3513 3514 if (response.IsUnsupportedResponse()) 3515 m_supports_QSaveRegisterState = eLazyBoolNo; 3516 return false; 3517 } 3518 3519 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) { 3520 if (!GetSyncThreadStateSupported()) 3521 return false; 3522 3523 StreamString packet; 3524 StringExtractorGDBRemote response; 3525 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid); 3526 return SendPacketAndWaitForResponse(packet.GetString(), response) == 3527 GDBRemoteCommunication::PacketResult::Success && 3528 response.IsOKResponse(); 3529 } 3530 3531 llvm::Expected<TraceSupportedResponse> 3532 GDBRemoteCommunicationClient::SendTraceSupported(std::chrono::seconds timeout) { 3533 Log *log = GetLog(GDBRLog::Process); 3534 3535 StreamGDBRemote escaped_packet; 3536 escaped_packet.PutCString("jLLDBTraceSupported"); 3537 3538 StringExtractorGDBRemote response; 3539 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3540 timeout) == 3541 GDBRemoteCommunication::PacketResult::Success) { 3542 if (response.IsErrorResponse()) 3543 return response.GetStatus().ToError(); 3544 if (response.IsUnsupportedResponse()) 3545 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3546 "jLLDBTraceSupported is unsupported"); 3547 3548 return llvm::json::parse<TraceSupportedResponse>(response.Peek(), 3549 "TraceSupportedResponse"); 3550 } 3551 LLDB_LOG(log, "failed to send packet: jLLDBTraceSupported"); 3552 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3553 "failed to send packet: jLLDBTraceSupported"); 3554 } 3555 3556 llvm::Error 3557 GDBRemoteCommunicationClient::SendTraceStop(const TraceStopRequest &request, 3558 std::chrono::seconds timeout) { 3559 Log *log = GetLog(GDBRLog::Process); 3560 3561 StreamGDBRemote escaped_packet; 3562 escaped_packet.PutCString("jLLDBTraceStop:"); 3563 3564 std::string json_string; 3565 llvm::raw_string_ostream os(json_string); 3566 os << toJSON(request); 3567 os.flush(); 3568 3569 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3570 3571 StringExtractorGDBRemote response; 3572 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3573 timeout) == 3574 GDBRemoteCommunication::PacketResult::Success) { 3575 if (response.IsErrorResponse()) 3576 return response.GetStatus().ToError(); 3577 if (response.IsUnsupportedResponse()) 3578 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3579 "jLLDBTraceStop is unsupported"); 3580 if (response.IsOKResponse()) 3581 return llvm::Error::success(); 3582 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3583 "Invalid jLLDBTraceStart response"); 3584 } 3585 LLDB_LOG(log, "failed to send packet: jLLDBTraceStop"); 3586 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3587 "failed to send packet: jLLDBTraceStop '%s'", 3588 escaped_packet.GetData()); 3589 } 3590 3591 llvm::Error 3592 GDBRemoteCommunicationClient::SendTraceStart(const llvm::json::Value ¶ms, 3593 std::chrono::seconds timeout) { 3594 Log *log = GetLog(GDBRLog::Process); 3595 3596 StreamGDBRemote escaped_packet; 3597 escaped_packet.PutCString("jLLDBTraceStart:"); 3598 3599 std::string json_string; 3600 llvm::raw_string_ostream os(json_string); 3601 os << params; 3602 os.flush(); 3603 3604 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3605 3606 StringExtractorGDBRemote response; 3607 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3608 timeout) == 3609 GDBRemoteCommunication::PacketResult::Success) { 3610 if (response.IsErrorResponse()) 3611 return response.GetStatus().ToError(); 3612 if (response.IsUnsupportedResponse()) 3613 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3614 "jLLDBTraceStart is unsupported"); 3615 if (response.IsOKResponse()) 3616 return llvm::Error::success(); 3617 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3618 "Invalid jLLDBTraceStart response"); 3619 } 3620 LLDB_LOG(log, "failed to send packet: jLLDBTraceStart"); 3621 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3622 "failed to send packet: jLLDBTraceStart '%s'", 3623 escaped_packet.GetData()); 3624 } 3625 3626 llvm::Expected<std::string> 3627 GDBRemoteCommunicationClient::SendTraceGetState(llvm::StringRef type, 3628 std::chrono::seconds timeout) { 3629 Log *log = GetLog(GDBRLog::Process); 3630 3631 StreamGDBRemote escaped_packet; 3632 escaped_packet.PutCString("jLLDBTraceGetState:"); 3633 3634 std::string json_string; 3635 llvm::raw_string_ostream os(json_string); 3636 os << toJSON(TraceGetStateRequest{type.str()}); 3637 os.flush(); 3638 3639 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3640 3641 StringExtractorGDBRemote response; 3642 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3643 timeout) == 3644 GDBRemoteCommunication::PacketResult::Success) { 3645 if (response.IsErrorResponse()) 3646 return response.GetStatus().ToError(); 3647 if (response.IsUnsupportedResponse()) 3648 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3649 "jLLDBTraceGetState is unsupported"); 3650 return std::string(response.Peek()); 3651 } 3652 3653 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetState"); 3654 return llvm::createStringError( 3655 llvm::inconvertibleErrorCode(), 3656 "failed to send packet: jLLDBTraceGetState '%s'", 3657 escaped_packet.GetData()); 3658 } 3659 3660 llvm::Expected<std::vector<uint8_t>> 3661 GDBRemoteCommunicationClient::SendTraceGetBinaryData( 3662 const TraceGetBinaryDataRequest &request, std::chrono::seconds timeout) { 3663 Log *log = GetLog(GDBRLog::Process); 3664 3665 StreamGDBRemote escaped_packet; 3666 escaped_packet.PutCString("jLLDBTraceGetBinaryData:"); 3667 3668 std::string json_string; 3669 llvm::raw_string_ostream os(json_string); 3670 os << toJSON(request); 3671 os.flush(); 3672 3673 escaped_packet.PutEscapedBytes(json_string.c_str(), json_string.size()); 3674 3675 StringExtractorGDBRemote response; 3676 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3677 timeout) == 3678 GDBRemoteCommunication::PacketResult::Success) { 3679 if (response.IsErrorResponse()) 3680 return response.GetStatus().ToError(); 3681 std::string data; 3682 response.GetEscapedBinaryData(data); 3683 return std::vector<uint8_t>(data.begin(), data.end()); 3684 } 3685 LLDB_LOG(log, "failed to send packet: jLLDBTraceGetBinaryData"); 3686 return llvm::createStringError( 3687 llvm::inconvertibleErrorCode(), 3688 "failed to send packet: jLLDBTraceGetBinaryData '%s'", 3689 escaped_packet.GetData()); 3690 } 3691 3692 std::optional<QOffsets> GDBRemoteCommunicationClient::GetQOffsets() { 3693 StringExtractorGDBRemote response; 3694 if (SendPacketAndWaitForResponse("qOffsets", response) != 3695 PacketResult::Success) 3696 return std::nullopt; 3697 if (!response.IsNormalResponse()) 3698 return std::nullopt; 3699 3700 QOffsets result; 3701 llvm::StringRef ref = response.GetStringRef(); 3702 const auto &GetOffset = [&] { 3703 addr_t offset; 3704 if (ref.consumeInteger(16, offset)) 3705 return false; 3706 result.offsets.push_back(offset); 3707 return true; 3708 }; 3709 3710 if (ref.consume_front("Text=")) { 3711 result.segments = false; 3712 if (!GetOffset()) 3713 return std::nullopt; 3714 if (!ref.consume_front(";Data=") || !GetOffset()) 3715 return std::nullopt; 3716 if (ref.empty()) 3717 return result; 3718 if (ref.consume_front(";Bss=") && GetOffset() && ref.empty()) 3719 return result; 3720 } else if (ref.consume_front("TextSeg=")) { 3721 result.segments = true; 3722 if (!GetOffset()) 3723 return std::nullopt; 3724 if (ref.empty()) 3725 return result; 3726 if (ref.consume_front(";DataSeg=") && GetOffset() && ref.empty()) 3727 return result; 3728 } 3729 return std::nullopt; 3730 } 3731 3732 bool GDBRemoteCommunicationClient::GetModuleInfo( 3733 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec, 3734 ModuleSpec &module_spec) { 3735 if (!m_supports_qModuleInfo) 3736 return false; 3737 3738 std::string module_path = module_file_spec.GetPath(false); 3739 if (module_path.empty()) 3740 return false; 3741 3742 StreamString packet; 3743 packet.PutCString("qModuleInfo:"); 3744 packet.PutStringAsRawHex8(module_path); 3745 packet.PutCString(";"); 3746 const auto &triple = arch_spec.GetTriple().getTriple(); 3747 packet.PutStringAsRawHex8(triple); 3748 3749 StringExtractorGDBRemote response; 3750 if (SendPacketAndWaitForResponse(packet.GetString(), response) != 3751 PacketResult::Success) 3752 return false; 3753 3754 if (response.IsErrorResponse()) 3755 return false; 3756 3757 if (response.IsUnsupportedResponse()) { 3758 m_supports_qModuleInfo = false; 3759 return false; 3760 } 3761 3762 llvm::StringRef name; 3763 llvm::StringRef value; 3764 3765 module_spec.Clear(); 3766 module_spec.GetFileSpec() = module_file_spec; 3767 3768 while (response.GetNameColonValue(name, value)) { 3769 if (name == "uuid" || name == "md5") { 3770 StringExtractor extractor(value); 3771 std::string uuid; 3772 extractor.GetHexByteString(uuid); 3773 module_spec.GetUUID().SetFromStringRef(uuid); 3774 } else if (name == "triple") { 3775 StringExtractor extractor(value); 3776 std::string triple; 3777 extractor.GetHexByteString(triple); 3778 module_spec.GetArchitecture().SetTriple(triple.c_str()); 3779 } else if (name == "file_offset") { 3780 uint64_t ival = 0; 3781 if (!value.getAsInteger(16, ival)) 3782 module_spec.SetObjectOffset(ival); 3783 } else if (name == "file_size") { 3784 uint64_t ival = 0; 3785 if (!value.getAsInteger(16, ival)) 3786 module_spec.SetObjectSize(ival); 3787 } else if (name == "file_path") { 3788 StringExtractor extractor(value); 3789 std::string path; 3790 extractor.GetHexByteString(path); 3791 module_spec.GetFileSpec() = FileSpec(path, arch_spec.GetTriple()); 3792 } 3793 } 3794 3795 return true; 3796 } 3797 3798 static std::optional<ModuleSpec> 3799 ParseModuleSpec(StructuredData::Dictionary *dict) { 3800 ModuleSpec result; 3801 if (!dict) 3802 return std::nullopt; 3803 3804 llvm::StringRef string; 3805 uint64_t integer; 3806 3807 if (!dict->GetValueForKeyAsString("uuid", string)) 3808 return std::nullopt; 3809 if (!result.GetUUID().SetFromStringRef(string)) 3810 return std::nullopt; 3811 3812 if (!dict->GetValueForKeyAsInteger("file_offset", integer)) 3813 return std::nullopt; 3814 result.SetObjectOffset(integer); 3815 3816 if (!dict->GetValueForKeyAsInteger("file_size", integer)) 3817 return std::nullopt; 3818 result.SetObjectSize(integer); 3819 3820 if (!dict->GetValueForKeyAsString("triple", string)) 3821 return std::nullopt; 3822 result.GetArchitecture().SetTriple(string); 3823 3824 if (!dict->GetValueForKeyAsString("file_path", string)) 3825 return std::nullopt; 3826 result.GetFileSpec() = FileSpec(string, result.GetArchitecture().GetTriple()); 3827 3828 return result; 3829 } 3830 3831 std::optional<std::vector<ModuleSpec>> 3832 GDBRemoteCommunicationClient::GetModulesInfo( 3833 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 3834 namespace json = llvm::json; 3835 3836 if (!m_supports_jModulesInfo) 3837 return std::nullopt; 3838 3839 json::Array module_array; 3840 for (const FileSpec &module_file_spec : module_file_specs) { 3841 module_array.push_back( 3842 json::Object{{"file", module_file_spec.GetPath(false)}, 3843 {"triple", triple.getTriple()}}); 3844 } 3845 StreamString unescaped_payload; 3846 unescaped_payload.PutCString("jModulesInfo:"); 3847 unescaped_payload.AsRawOstream() << std::move(module_array); 3848 3849 StreamGDBRemote payload; 3850 payload.PutEscapedBytes(unescaped_payload.GetString().data(), 3851 unescaped_payload.GetSize()); 3852 3853 // Increase the timeout for jModulesInfo since this packet can take longer. 3854 ScopedTimeout timeout(*this, std::chrono::seconds(10)); 3855 3856 StringExtractorGDBRemote response; 3857 if (SendPacketAndWaitForResponse(payload.GetString(), response) != 3858 PacketResult::Success || 3859 response.IsErrorResponse()) 3860 return std::nullopt; 3861 3862 if (response.IsUnsupportedResponse()) { 3863 m_supports_jModulesInfo = false; 3864 return std::nullopt; 3865 } 3866 3867 StructuredData::ObjectSP response_object_sp = 3868 StructuredData::ParseJSON(response.GetStringRef()); 3869 if (!response_object_sp) 3870 return std::nullopt; 3871 3872 StructuredData::Array *response_array = response_object_sp->GetAsArray(); 3873 if (!response_array) 3874 return std::nullopt; 3875 3876 std::vector<ModuleSpec> result; 3877 for (size_t i = 0; i < response_array->GetSize(); ++i) { 3878 if (std::optional<ModuleSpec> module_spec = ParseModuleSpec( 3879 response_array->GetItemAtIndex(i)->GetAsDictionary())) 3880 result.push_back(*module_spec); 3881 } 3882 3883 return result; 3884 } 3885 3886 // query the target remote for extended information using the qXfer packet 3887 // 3888 // example: object='features', annex='target.xml' 3889 // return: <xml output> or error 3890 llvm::Expected<std::string> 3891 GDBRemoteCommunicationClient::ReadExtFeature(llvm::StringRef object, 3892 llvm::StringRef annex) { 3893 3894 std::string output; 3895 llvm::raw_string_ostream output_stream(output); 3896 StringExtractorGDBRemote chunk; 3897 3898 uint64_t size = GetRemoteMaxPacketSize(); 3899 if (size == 0) 3900 size = 0x1000; 3901 size = size - 1; // Leave space for the 'm' or 'l' character in the response 3902 int offset = 0; 3903 bool active = true; 3904 3905 // loop until all data has been read 3906 while (active) { 3907 3908 // send query extended feature packet 3909 std::string packet = 3910 ("qXfer:" + object + ":read:" + annex + ":" + 3911 llvm::Twine::utohexstr(offset) + "," + llvm::Twine::utohexstr(size)) 3912 .str(); 3913 3914 GDBRemoteCommunication::PacketResult res = 3915 SendPacketAndWaitForResponse(packet, chunk); 3916 3917 if (res != GDBRemoteCommunication::PacketResult::Success || 3918 chunk.GetStringRef().empty()) { 3919 return llvm::createStringError(llvm::inconvertibleErrorCode(), 3920 "Error sending $qXfer packet"); 3921 } 3922 3923 // check packet code 3924 switch (chunk.GetStringRef()[0]) { 3925 // last chunk 3926 case ('l'): 3927 active = false; 3928 [[fallthrough]]; 3929 3930 // more chunks 3931 case ('m'): 3932 output_stream << chunk.GetStringRef().drop_front(); 3933 offset += chunk.GetStringRef().size() - 1; 3934 break; 3935 3936 // unknown chunk 3937 default: 3938 return llvm::createStringError( 3939 llvm::inconvertibleErrorCode(), 3940 "Invalid continuation code from $qXfer packet"); 3941 } 3942 } 3943 3944 return output_stream.str(); 3945 } 3946 3947 // Notify the target that gdb is prepared to serve symbol lookup requests. 3948 // packet: "qSymbol::" 3949 // reply: 3950 // OK The target does not need to look up any (more) symbols. 3951 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex 3952 // encoded). 3953 // LLDB may provide the value by sending another qSymbol 3954 // packet 3955 // in the form of"qSymbol:<sym_value>:<sym_name>". 3956 // 3957 // Three examples: 3958 // 3959 // lldb sends: qSymbol:: 3960 // lldb receives: OK 3961 // Remote gdb stub does not need to know the addresses of any symbols, lldb 3962 // does not 3963 // need to ask again in this session. 3964 // 3965 // lldb sends: qSymbol:: 3966 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3967 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473 3968 // lldb receives: OK 3969 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does 3970 // not know 3971 // the address at this time. lldb needs to send qSymbol:: again when it has 3972 // more 3973 // solibs loaded. 3974 // 3975 // lldb sends: qSymbol:: 3976 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3977 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473 3978 // lldb receives: OK 3979 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says 3980 // that it 3981 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it 3982 // does not 3983 // need any more symbols. lldb does not need to ask again in this session. 3984 3985 void GDBRemoteCommunicationClient::ServeSymbolLookups( 3986 lldb_private::Process *process) { 3987 // Set to true once we've resolved a symbol to an address for the remote 3988 // stub. If we get an 'OK' response after this, the remote stub doesn't need 3989 // any more symbols and we can stop asking. 3990 bool symbol_response_provided = false; 3991 3992 // Is this the initial qSymbol:: packet? 3993 bool first_qsymbol_query = true; 3994 3995 if (m_supports_qSymbol && !m_qSymbol_requests_done) { 3996 Lock lock(*this); 3997 if (lock) { 3998 StreamString packet; 3999 packet.PutCString("qSymbol::"); 4000 StringExtractorGDBRemote response; 4001 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) == 4002 PacketResult::Success) { 4003 if (response.IsOKResponse()) { 4004 if (symbol_response_provided || first_qsymbol_query) { 4005 m_qSymbol_requests_done = true; 4006 } 4007 4008 // We are done serving symbols requests 4009 return; 4010 } 4011 first_qsymbol_query = false; 4012 4013 if (response.IsUnsupportedResponse()) { 4014 // qSymbol is not supported by the current GDB server we are 4015 // connected to 4016 m_supports_qSymbol = false; 4017 return; 4018 } else { 4019 llvm::StringRef response_str(response.GetStringRef()); 4020 if (response_str.startswith("qSymbol:")) { 4021 response.SetFilePos(strlen("qSymbol:")); 4022 std::string symbol_name; 4023 if (response.GetHexByteString(symbol_name)) { 4024 if (symbol_name.empty()) 4025 return; 4026 4027 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS; 4028 lldb_private::SymbolContextList sc_list; 4029 process->GetTarget().GetImages().FindSymbolsWithNameAndType( 4030 ConstString(symbol_name), eSymbolTypeAny, sc_list); 4031 for (const SymbolContext &sc : sc_list) { 4032 if (symbol_load_addr != LLDB_INVALID_ADDRESS) 4033 break; 4034 if (sc.symbol) { 4035 switch (sc.symbol->GetType()) { 4036 case eSymbolTypeInvalid: 4037 case eSymbolTypeAbsolute: 4038 case eSymbolTypeUndefined: 4039 case eSymbolTypeSourceFile: 4040 case eSymbolTypeHeaderFile: 4041 case eSymbolTypeObjectFile: 4042 case eSymbolTypeCommonBlock: 4043 case eSymbolTypeBlock: 4044 case eSymbolTypeLocal: 4045 case eSymbolTypeParam: 4046 case eSymbolTypeVariable: 4047 case eSymbolTypeVariableType: 4048 case eSymbolTypeLineEntry: 4049 case eSymbolTypeLineHeader: 4050 case eSymbolTypeScopeBegin: 4051 case eSymbolTypeScopeEnd: 4052 case eSymbolTypeAdditional: 4053 case eSymbolTypeCompiler: 4054 case eSymbolTypeInstrumentation: 4055 case eSymbolTypeTrampoline: 4056 break; 4057 4058 case eSymbolTypeCode: 4059 case eSymbolTypeResolver: 4060 case eSymbolTypeData: 4061 case eSymbolTypeRuntime: 4062 case eSymbolTypeException: 4063 case eSymbolTypeObjCClass: 4064 case eSymbolTypeObjCMetaClass: 4065 case eSymbolTypeObjCIVar: 4066 case eSymbolTypeReExported: 4067 symbol_load_addr = 4068 sc.symbol->GetLoadAddress(&process->GetTarget()); 4069 break; 4070 } 4071 } 4072 } 4073 // This is the normal path where our symbol lookup was successful 4074 // and we want to send a packet with the new symbol value and see 4075 // if another lookup needs to be done. 4076 4077 // Change "packet" to contain the requested symbol value and name 4078 packet.Clear(); 4079 packet.PutCString("qSymbol:"); 4080 if (symbol_load_addr != LLDB_INVALID_ADDRESS) { 4081 packet.Printf("%" PRIx64, symbol_load_addr); 4082 symbol_response_provided = true; 4083 } else { 4084 symbol_response_provided = false; 4085 } 4086 packet.PutCString(":"); 4087 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size()); 4088 continue; // go back to the while loop and send "packet" and wait 4089 // for another response 4090 } 4091 } 4092 } 4093 } 4094 // If we make it here, the symbol request packet response wasn't valid or 4095 // our symbol lookup failed so we must abort 4096 return; 4097 4098 } else if (Log *log = GetLog(GDBRLog::Process | GDBRLog::Packets)) { 4099 LLDB_LOGF(log, 4100 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", 4101 __FUNCTION__); 4102 } 4103 } 4104 } 4105 4106 StructuredData::Array * 4107 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() { 4108 if (!m_supported_async_json_packets_is_valid) { 4109 // Query the server for the array of supported asynchronous JSON packets. 4110 m_supported_async_json_packets_is_valid = true; 4111 4112 Log *log = GetLog(GDBRLog::Process); 4113 4114 // Poll it now. 4115 StringExtractorGDBRemote response; 4116 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response) == 4117 PacketResult::Success) { 4118 m_supported_async_json_packets_sp = 4119 StructuredData::ParseJSON(response.GetStringRef()); 4120 if (m_supported_async_json_packets_sp && 4121 !m_supported_async_json_packets_sp->GetAsArray()) { 4122 // We were returned something other than a JSON array. This is 4123 // invalid. Clear it out. 4124 LLDB_LOGF(log, 4125 "GDBRemoteCommunicationClient::%s(): " 4126 "QSupportedAsyncJSONPackets returned invalid " 4127 "result: %s", 4128 __FUNCTION__, response.GetStringRef().data()); 4129 m_supported_async_json_packets_sp.reset(); 4130 } 4131 } else { 4132 LLDB_LOGF(log, 4133 "GDBRemoteCommunicationClient::%s(): " 4134 "QSupportedAsyncJSONPackets unsupported", 4135 __FUNCTION__); 4136 } 4137 4138 if (log && m_supported_async_json_packets_sp) { 4139 StreamString stream; 4140 m_supported_async_json_packets_sp->Dump(stream); 4141 LLDB_LOGF(log, 4142 "GDBRemoteCommunicationClient::%s(): supported async " 4143 "JSON packets: %s", 4144 __FUNCTION__, stream.GetData()); 4145 } 4146 } 4147 4148 return m_supported_async_json_packets_sp 4149 ? m_supported_async_json_packets_sp->GetAsArray() 4150 : nullptr; 4151 } 4152 4153 Status GDBRemoteCommunicationClient::SendSignalsToIgnore( 4154 llvm::ArrayRef<int32_t> signals) { 4155 // Format packet: 4156 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN> 4157 auto range = llvm::make_range(signals.begin(), signals.end()); 4158 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str(); 4159 4160 StringExtractorGDBRemote response; 4161 auto send_status = SendPacketAndWaitForResponse(packet, response); 4162 4163 if (send_status != GDBRemoteCommunication::PacketResult::Success) 4164 return Status("Sending QPassSignals packet failed"); 4165 4166 if (response.IsOKResponse()) { 4167 return Status(); 4168 } else { 4169 return Status("Unknown error happened during sending QPassSignals packet."); 4170 } 4171 } 4172 4173 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( 4174 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) { 4175 Status error; 4176 4177 if (type_name.empty()) { 4178 error.SetErrorString("invalid type_name argument"); 4179 return error; 4180 } 4181 4182 // Build command: Configure{type_name}: serialized config data. 4183 StreamGDBRemote stream; 4184 stream.PutCString("QConfigure"); 4185 stream.PutCString(type_name); 4186 stream.PutChar(':'); 4187 if (config_sp) { 4188 // Gather the plain-text version of the configuration data. 4189 StreamString unescaped_stream; 4190 config_sp->Dump(unescaped_stream); 4191 unescaped_stream.Flush(); 4192 4193 // Add it to the stream in escaped fashion. 4194 stream.PutEscapedBytes(unescaped_stream.GetString().data(), 4195 unescaped_stream.GetSize()); 4196 } 4197 stream.Flush(); 4198 4199 // Send the packet. 4200 StringExtractorGDBRemote response; 4201 auto result = SendPacketAndWaitForResponse(stream.GetString(), response); 4202 if (result == PacketResult::Success) { 4203 // We failed if the config result comes back other than OK. 4204 if (response.GetStringRef() == "OK") { 4205 // Okay! 4206 error.Clear(); 4207 } else { 4208 error.SetErrorStringWithFormatv( 4209 "configuring StructuredData feature {0} failed with error {1}", 4210 type_name, response.GetStringRef()); 4211 } 4212 } else { 4213 // Can we get more data here on the failure? 4214 error.SetErrorStringWithFormatv( 4215 "configuring StructuredData feature {0} failed when sending packet: " 4216 "PacketResult={1}", 4217 type_name, (int)result); 4218 } 4219 return error; 4220 } 4221 4222 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) { 4223 GDBRemoteClientBase::OnRunPacketSent(first); 4224 m_curr_tid = LLDB_INVALID_THREAD_ID; 4225 } 4226 4227 bool GDBRemoteCommunicationClient::UsesNativeSignals() { 4228 if (m_uses_native_signals == eLazyBoolCalculate) 4229 GetRemoteQSupported(); 4230 if (m_uses_native_signals == eLazyBoolYes) 4231 return true; 4232 4233 // If the remote didn't indicate native-signal support explicitly, 4234 // check whether it is an old version of lldb-server. 4235 return GetThreadSuffixSupported(); 4236 } 4237 4238 llvm::Expected<int> GDBRemoteCommunicationClient::KillProcess(lldb::pid_t pid) { 4239 StringExtractorGDBRemote response; 4240 GDBRemoteCommunication::ScopedTimeout(*this, seconds(3)); 4241 4242 if (SendPacketAndWaitForResponse("k", response, GetPacketTimeout()) != 4243 PacketResult::Success) 4244 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4245 "failed to send k packet"); 4246 4247 char packet_cmd = response.GetChar(0); 4248 if (packet_cmd == 'W' || packet_cmd == 'X') 4249 return response.GetHexU8(); 4250 4251 return llvm::createStringError(llvm::inconvertibleErrorCode(), 4252 "unexpected response to k packet: %s", 4253 response.GetStringRef().str().c_str()); 4254 } 4255