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