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