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