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