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