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