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