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