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