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