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