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