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