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