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