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