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