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 if (avail_type == CompressionType::None) { 1026 for (auto compression : supported_compressions) { 1027 if (compression == "lzfse") { 1028 avail_type = CompressionType::LZFSE; 1029 avail_name = compression; 1030 break; 1031 } 1032 } 1033 } 1034 #endif 1035 1036 #if defined(HAVE_LIBCOMPRESSION) 1037 if (avail_type == CompressionType::None) { 1038 for (auto compression : supported_compressions) { 1039 if (compression == "zlib-deflate") { 1040 avail_type = CompressionType::ZlibDeflate; 1041 avail_name = compression; 1042 break; 1043 } 1044 } 1045 } 1046 #endif 1047 1048 #if defined(HAVE_LIBZ) 1049 if (avail_type == CompressionType::None) { 1050 for (auto compression : supported_compressions) { 1051 if (compression == "zlib-deflate") { 1052 avail_type = CompressionType::ZlibDeflate; 1053 avail_name = compression; 1054 break; 1055 } 1056 } 1057 } 1058 #endif 1059 1060 #if defined(HAVE_LIBCOMPRESSION) 1061 if (avail_type == CompressionType::None) { 1062 for (auto compression : supported_compressions) { 1063 if (compression == "lz4") { 1064 avail_type = CompressionType::LZ4; 1065 avail_name = compression; 1066 break; 1067 } 1068 } 1069 } 1070 #endif 1071 1072 #if defined(HAVE_LIBCOMPRESSION) 1073 if (avail_type == CompressionType::None) { 1074 for (auto compression : supported_compressions) { 1075 if (compression == "lzma") { 1076 avail_type = CompressionType::LZMA; 1077 avail_name = compression; 1078 break; 1079 } 1080 } 1081 } 1082 #endif 1083 1084 if (avail_type != CompressionType::None) { 1085 StringExtractorGDBRemote response; 1086 std::string packet = "QEnableCompression:type:" + avail_name + ";"; 1087 if (SendPacketAndWaitForResponse(packet, response, false) != 1088 PacketResult::Success) 1089 return; 1090 1091 if (response.IsOKResponse()) { 1092 m_compression_type = avail_type; 1093 } 1094 } 1095 } 1096 1097 const char *GDBRemoteCommunicationClient::GetGDBServerProgramName() { 1098 if (GetGDBServerVersion()) { 1099 if (!m_gdb_server_name.empty()) 1100 return m_gdb_server_name.c_str(); 1101 } 1102 return NULL; 1103 } 1104 1105 uint32_t GDBRemoteCommunicationClient::GetGDBServerProgramVersion() { 1106 if (GetGDBServerVersion()) 1107 return m_gdb_server_version; 1108 return 0; 1109 } 1110 1111 bool GDBRemoteCommunicationClient::GetDefaultThreadId(lldb::tid_t &tid) { 1112 StringExtractorGDBRemote response; 1113 if (SendPacketAndWaitForResponse("qC", response, false) != 1114 PacketResult::Success) 1115 return false; 1116 1117 if (!response.IsNormalResponse()) 1118 return false; 1119 1120 if (response.GetChar() == 'Q' && response.GetChar() == 'C') 1121 tid = response.GetHexMaxU32(true, -1); 1122 1123 return true; 1124 } 1125 1126 bool GDBRemoteCommunicationClient::GetHostInfo(bool force) { 1127 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS)); 1128 1129 if (force || m_qHostInfo_is_valid == eLazyBoolCalculate) { 1130 m_qHostInfo_is_valid = eLazyBoolNo; 1131 StringExtractorGDBRemote response; 1132 if (SendPacketAndWaitForResponse("qHostInfo", response, false) == 1133 PacketResult::Success) { 1134 if (response.IsNormalResponse()) { 1135 llvm::StringRef name; 1136 llvm::StringRef value; 1137 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1138 uint32_t sub = 0; 1139 std::string arch_name; 1140 std::string os_name; 1141 std::string vendor_name; 1142 std::string triple; 1143 std::string distribution_id; 1144 uint32_t pointer_byte_size = 0; 1145 ByteOrder byte_order = eByteOrderInvalid; 1146 uint32_t num_keys_decoded = 0; 1147 while (response.GetNameColonValue(name, value)) { 1148 if (name.equals("cputype")) { 1149 // exception type in big endian hex 1150 if (!value.getAsInteger(0, cpu)) 1151 ++num_keys_decoded; 1152 } else if (name.equals("cpusubtype")) { 1153 // exception count in big endian hex 1154 if (!value.getAsInteger(0, sub)) 1155 ++num_keys_decoded; 1156 } else if (name.equals("arch")) { 1157 arch_name = value; 1158 ++num_keys_decoded; 1159 } else if (name.equals("triple")) { 1160 StringExtractor extractor(value); 1161 extractor.GetHexByteString(triple); 1162 ++num_keys_decoded; 1163 } else if (name.equals("distribution_id")) { 1164 StringExtractor extractor(value); 1165 extractor.GetHexByteString(distribution_id); 1166 ++num_keys_decoded; 1167 } else if (name.equals("os_build")) { 1168 StringExtractor extractor(value); 1169 extractor.GetHexByteString(m_os_build); 1170 ++num_keys_decoded; 1171 } else if (name.equals("hostname")) { 1172 StringExtractor extractor(value); 1173 extractor.GetHexByteString(m_hostname); 1174 ++num_keys_decoded; 1175 } else if (name.equals("os_kernel")) { 1176 StringExtractor extractor(value); 1177 extractor.GetHexByteString(m_os_kernel); 1178 ++num_keys_decoded; 1179 } else if (name.equals("ostype")) { 1180 os_name = value; 1181 ++num_keys_decoded; 1182 } else if (name.equals("vendor")) { 1183 vendor_name = value; 1184 ++num_keys_decoded; 1185 } else if (name.equals("endian")) { 1186 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value) 1187 .Case("little", eByteOrderLittle) 1188 .Case("big", eByteOrderBig) 1189 .Case("pdp", eByteOrderPDP) 1190 .Default(eByteOrderInvalid); 1191 if (byte_order != eByteOrderInvalid) 1192 ++num_keys_decoded; 1193 } else if (name.equals("ptrsize")) { 1194 if (!value.getAsInteger(0, pointer_byte_size)) 1195 ++num_keys_decoded; 1196 } else if (name.equals("os_version") || 1197 name.equals( 1198 "version")) // Older debugserver binaries used the 1199 // "version" key instead of 1200 // "os_version"... 1201 { 1202 Args::StringToVersion(value, m_os_version_major, m_os_version_minor, 1203 m_os_version_update); 1204 if (m_os_version_major != UINT32_MAX) 1205 ++num_keys_decoded; 1206 } else if (name.equals("watchpoint_exceptions_received")) { 1207 m_watchpoints_trigger_after_instruction = 1208 llvm::StringSwitch<LazyBool>(value) 1209 .Case("before", eLazyBoolNo) 1210 .Case("after", eLazyBoolYes) 1211 .Default(eLazyBoolCalculate); 1212 if (m_watchpoints_trigger_after_instruction != eLazyBoolCalculate) 1213 ++num_keys_decoded; 1214 } else if (name.equals("default_packet_timeout")) { 1215 uint32_t timeout_seconds; 1216 if (!value.getAsInteger(0, timeout_seconds)) { 1217 m_default_packet_timeout = seconds(timeout_seconds); 1218 SetPacketTimeout(m_default_packet_timeout); 1219 ++num_keys_decoded; 1220 } 1221 } 1222 } 1223 1224 if (num_keys_decoded > 0) 1225 m_qHostInfo_is_valid = eLazyBoolYes; 1226 1227 if (triple.empty()) { 1228 if (arch_name.empty()) { 1229 if (cpu != LLDB_INVALID_CPUTYPE) { 1230 m_host_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 1231 if (pointer_byte_size) { 1232 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1233 } 1234 if (byte_order != eByteOrderInvalid) { 1235 assert(byte_order == m_host_arch.GetByteOrder()); 1236 } 1237 1238 if (!vendor_name.empty()) 1239 m_host_arch.GetTriple().setVendorName( 1240 llvm::StringRef(vendor_name)); 1241 if (!os_name.empty()) 1242 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 1243 } 1244 } else { 1245 std::string triple; 1246 triple += arch_name; 1247 if (!vendor_name.empty() || !os_name.empty()) { 1248 triple += '-'; 1249 if (vendor_name.empty()) 1250 triple += "unknown"; 1251 else 1252 triple += vendor_name; 1253 triple += '-'; 1254 if (os_name.empty()) 1255 triple += "unknown"; 1256 else 1257 triple += os_name; 1258 } 1259 m_host_arch.SetTriple(triple.c_str()); 1260 1261 llvm::Triple &host_triple = m_host_arch.GetTriple(); 1262 if (host_triple.getVendor() == llvm::Triple::Apple && 1263 host_triple.getOS() == llvm::Triple::Darwin) { 1264 switch (m_host_arch.GetMachine()) { 1265 case llvm::Triple::aarch64: 1266 case llvm::Triple::arm: 1267 case llvm::Triple::thumb: 1268 host_triple.setOS(llvm::Triple::IOS); 1269 break; 1270 default: 1271 host_triple.setOS(llvm::Triple::MacOSX); 1272 break; 1273 } 1274 } 1275 if (pointer_byte_size) { 1276 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1277 } 1278 if (byte_order != eByteOrderInvalid) { 1279 assert(byte_order == m_host_arch.GetByteOrder()); 1280 } 1281 } 1282 } else { 1283 m_host_arch.SetTriple(triple.c_str()); 1284 if (pointer_byte_size) { 1285 assert(pointer_byte_size == m_host_arch.GetAddressByteSize()); 1286 } 1287 if (byte_order != eByteOrderInvalid) { 1288 assert(byte_order == m_host_arch.GetByteOrder()); 1289 } 1290 1291 if (log) 1292 log->Printf("GDBRemoteCommunicationClient::%s parsed host " 1293 "architecture as %s, triple as %s from triple text %s", 1294 __FUNCTION__, m_host_arch.GetArchitectureName() 1295 ? m_host_arch.GetArchitectureName() 1296 : "<null-arch-name>", 1297 m_host_arch.GetTriple().getTriple().c_str(), 1298 triple.c_str()); 1299 } 1300 if (!distribution_id.empty()) 1301 m_host_arch.SetDistributionId(distribution_id.c_str()); 1302 } 1303 } 1304 } 1305 return m_qHostInfo_is_valid == eLazyBoolYes; 1306 } 1307 1308 int GDBRemoteCommunicationClient::SendAttach( 1309 lldb::pid_t pid, StringExtractorGDBRemote &response) { 1310 if (pid != LLDB_INVALID_PROCESS_ID) { 1311 char packet[64]; 1312 const int packet_len = 1313 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, pid); 1314 UNUSED_IF_ASSERT_DISABLED(packet_len); 1315 assert(packet_len < (int)sizeof(packet)); 1316 if (SendPacketAndWaitForResponse(packet, response, false) == 1317 PacketResult::Success) { 1318 if (response.IsErrorResponse()) 1319 return response.GetError(); 1320 return 0; 1321 } 1322 } 1323 return -1; 1324 } 1325 1326 int GDBRemoteCommunicationClient::SendStdinNotification(const char *data, 1327 size_t data_len) { 1328 StreamString packet; 1329 packet.PutCString("I"); 1330 packet.PutBytesAsRawHex8(data, data_len); 1331 StringExtractorGDBRemote response; 1332 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1333 PacketResult::Success) { 1334 return 0; 1335 } 1336 return response.GetError(); 1337 } 1338 1339 const lldb_private::ArchSpec & 1340 GDBRemoteCommunicationClient::GetHostArchitecture() { 1341 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1342 GetHostInfo(); 1343 return m_host_arch; 1344 } 1345 1346 seconds GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout() { 1347 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 1348 GetHostInfo(); 1349 return m_default_packet_timeout; 1350 } 1351 1352 addr_t GDBRemoteCommunicationClient::AllocateMemory(size_t size, 1353 uint32_t permissions) { 1354 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) { 1355 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1356 char packet[64]; 1357 const int packet_len = ::snprintf( 1358 packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", (uint64_t)size, 1359 permissions & lldb::ePermissionsReadable ? "r" : "", 1360 permissions & lldb::ePermissionsWritable ? "w" : "", 1361 permissions & lldb::ePermissionsExecutable ? "x" : ""); 1362 assert(packet_len < (int)sizeof(packet)); 1363 UNUSED_IF_ASSERT_DISABLED(packet_len); 1364 StringExtractorGDBRemote response; 1365 if (SendPacketAndWaitForResponse(packet, response, false) == 1366 PacketResult::Success) { 1367 if (response.IsUnsupportedResponse()) 1368 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1369 else if (!response.IsErrorResponse()) 1370 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 1371 } else { 1372 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1373 } 1374 } 1375 return LLDB_INVALID_ADDRESS; 1376 } 1377 1378 bool GDBRemoteCommunicationClient::DeallocateMemory(addr_t addr) { 1379 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) { 1380 m_supports_alloc_dealloc_memory = eLazyBoolYes; 1381 char packet[64]; 1382 const int packet_len = 1383 ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 1384 assert(packet_len < (int)sizeof(packet)); 1385 UNUSED_IF_ASSERT_DISABLED(packet_len); 1386 StringExtractorGDBRemote response; 1387 if (SendPacketAndWaitForResponse(packet, response, false) == 1388 PacketResult::Success) { 1389 if (response.IsUnsupportedResponse()) 1390 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1391 else if (response.IsOKResponse()) 1392 return true; 1393 } else { 1394 m_supports_alloc_dealloc_memory = eLazyBoolNo; 1395 } 1396 } 1397 return false; 1398 } 1399 1400 Status GDBRemoteCommunicationClient::Detach(bool keep_stopped) { 1401 Status error; 1402 1403 if (keep_stopped) { 1404 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) { 1405 char packet[64]; 1406 const int packet_len = 1407 ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:"); 1408 assert(packet_len < (int)sizeof(packet)); 1409 UNUSED_IF_ASSERT_DISABLED(packet_len); 1410 StringExtractorGDBRemote response; 1411 if (SendPacketAndWaitForResponse(packet, response, false) == 1412 PacketResult::Success && 1413 response.IsOKResponse()) { 1414 m_supports_detach_stay_stopped = eLazyBoolYes; 1415 } else { 1416 m_supports_detach_stay_stopped = eLazyBoolNo; 1417 } 1418 } 1419 1420 if (m_supports_detach_stay_stopped == eLazyBoolNo) { 1421 error.SetErrorString("Stays stopped not supported by this target."); 1422 return error; 1423 } else { 1424 StringExtractorGDBRemote response; 1425 PacketResult packet_result = 1426 SendPacketAndWaitForResponse("D1", response, false); 1427 if (packet_result != PacketResult::Success) 1428 error.SetErrorString("Sending extended disconnect packet failed."); 1429 } 1430 } else { 1431 StringExtractorGDBRemote response; 1432 PacketResult packet_result = 1433 SendPacketAndWaitForResponse("D", response, false); 1434 if (packet_result != PacketResult::Success) 1435 error.SetErrorString("Sending disconnect packet failed."); 1436 } 1437 return error; 1438 } 1439 1440 Status GDBRemoteCommunicationClient::GetMemoryRegionInfo( 1441 lldb::addr_t addr, lldb_private::MemoryRegionInfo ®ion_info) { 1442 Status error; 1443 region_info.Clear(); 1444 1445 if (m_supports_memory_region_info != eLazyBoolNo) { 1446 m_supports_memory_region_info = eLazyBoolYes; 1447 char packet[64]; 1448 const int packet_len = ::snprintf( 1449 packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 1450 assert(packet_len < (int)sizeof(packet)); 1451 UNUSED_IF_ASSERT_DISABLED(packet_len); 1452 StringExtractorGDBRemote response; 1453 if (SendPacketAndWaitForResponse(packet, response, false) == 1454 PacketResult::Success) { 1455 llvm::StringRef name; 1456 llvm::StringRef value; 1457 addr_t addr_value = LLDB_INVALID_ADDRESS; 1458 bool success = true; 1459 bool saw_permissions = false; 1460 while (success && response.GetNameColonValue(name, value)) { 1461 if (name.equals("start")) { 1462 if (!value.getAsInteger(16, addr_value)) 1463 region_info.GetRange().SetRangeBase(addr_value); 1464 } else if (name.equals("size")) { 1465 if (!value.getAsInteger(16, addr_value)) 1466 region_info.GetRange().SetByteSize(addr_value); 1467 } else if (name.equals("permissions") && 1468 region_info.GetRange().IsValid()) { 1469 saw_permissions = true; 1470 if (region_info.GetRange().Contains(addr)) { 1471 if (value.find('r') != llvm::StringRef::npos) 1472 region_info.SetReadable(MemoryRegionInfo::eYes); 1473 else 1474 region_info.SetReadable(MemoryRegionInfo::eNo); 1475 1476 if (value.find('w') != llvm::StringRef::npos) 1477 region_info.SetWritable(MemoryRegionInfo::eYes); 1478 else 1479 region_info.SetWritable(MemoryRegionInfo::eNo); 1480 1481 if (value.find('x') != llvm::StringRef::npos) 1482 region_info.SetExecutable(MemoryRegionInfo::eYes); 1483 else 1484 region_info.SetExecutable(MemoryRegionInfo::eNo); 1485 1486 region_info.SetMapped(MemoryRegionInfo::eYes); 1487 } else { 1488 // The reported region does not contain this address -- we're 1489 // looking at an unmapped page 1490 region_info.SetReadable(MemoryRegionInfo::eNo); 1491 region_info.SetWritable(MemoryRegionInfo::eNo); 1492 region_info.SetExecutable(MemoryRegionInfo::eNo); 1493 region_info.SetMapped(MemoryRegionInfo::eNo); 1494 } 1495 } else if (name.equals("name")) { 1496 StringExtractorGDBRemote name_extractor(value); 1497 std::string name; 1498 name_extractor.GetHexByteString(name); 1499 region_info.SetName(name.c_str()); 1500 } else if (name.equals("error")) { 1501 StringExtractorGDBRemote error_extractor(value); 1502 std::string error_string; 1503 // Now convert the HEX bytes into a string value 1504 error_extractor.GetHexByteString(error_string); 1505 error.SetErrorString(error_string.c_str()); 1506 } 1507 } 1508 1509 if (region_info.GetRange().IsValid()) { 1510 // We got a valid address range back but no permissions -- which means 1511 // this is an unmapped page 1512 if (!saw_permissions) { 1513 region_info.SetReadable(MemoryRegionInfo::eNo); 1514 region_info.SetWritable(MemoryRegionInfo::eNo); 1515 region_info.SetExecutable(MemoryRegionInfo::eNo); 1516 region_info.SetMapped(MemoryRegionInfo::eNo); 1517 } 1518 } else { 1519 // We got an invalid address range back 1520 error.SetErrorString("Server returned invalid range"); 1521 } 1522 } else { 1523 m_supports_memory_region_info = eLazyBoolNo; 1524 } 1525 } 1526 1527 if (m_supports_memory_region_info == eLazyBoolNo) { 1528 error.SetErrorString("qMemoryRegionInfo is not supported"); 1529 } 1530 if (error.Fail()) 1531 region_info.Clear(); 1532 return error; 1533 } 1534 1535 Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo(uint32_t &num) { 1536 Status error; 1537 1538 if (m_supports_watchpoint_support_info == eLazyBoolYes) { 1539 num = m_num_supported_hardware_watchpoints; 1540 return error; 1541 } 1542 1543 // Set num to 0 first. 1544 num = 0; 1545 if (m_supports_watchpoint_support_info != eLazyBoolNo) { 1546 char packet[64]; 1547 const int packet_len = 1548 ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 1549 assert(packet_len < (int)sizeof(packet)); 1550 UNUSED_IF_ASSERT_DISABLED(packet_len); 1551 StringExtractorGDBRemote response; 1552 if (SendPacketAndWaitForResponse(packet, response, false) == 1553 PacketResult::Success) { 1554 m_supports_watchpoint_support_info = eLazyBoolYes; 1555 llvm::StringRef name; 1556 llvm::StringRef value; 1557 while (response.GetNameColonValue(name, value)) { 1558 if (name.equals("num")) { 1559 value.getAsInteger(0, m_num_supported_hardware_watchpoints); 1560 num = m_num_supported_hardware_watchpoints; 1561 } 1562 } 1563 } else { 1564 m_supports_watchpoint_support_info = eLazyBoolNo; 1565 } 1566 } 1567 1568 if (m_supports_watchpoint_support_info == eLazyBoolNo) { 1569 error.SetErrorString("qWatchpointSupportInfo is not supported"); 1570 } 1571 return error; 1572 } 1573 1574 lldb_private::Status GDBRemoteCommunicationClient::GetWatchpointSupportInfo( 1575 uint32_t &num, bool &after, const ArchSpec &arch) { 1576 Status error(GetWatchpointSupportInfo(num)); 1577 if (error.Success()) 1578 error = GetWatchpointsTriggerAfterInstruction(after, arch); 1579 return error; 1580 } 1581 1582 lldb_private::Status 1583 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction( 1584 bool &after, const ArchSpec &arch) { 1585 Status error; 1586 llvm::Triple::ArchType atype = arch.GetMachine(); 1587 1588 // we assume watchpoints will happen after running the relevant opcode 1589 // and we only want to override this behavior if we have explicitly 1590 // received a qHostInfo telling us otherwise 1591 if (m_qHostInfo_is_valid != eLazyBoolYes) { 1592 // On targets like MIPS and ppc64le, watchpoint exceptions are always 1593 // generated before the instruction is executed. The connected target 1594 // may not support qHostInfo or qWatchpointSupportInfo packets. 1595 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel || 1596 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el || 1597 atype == llvm::Triple::ppc64le) 1598 after = false; 1599 else 1600 after = true; 1601 } else { 1602 // For MIPS and ppc64le, set m_watchpoints_trigger_after_instruction to 1603 // eLazyBoolNo if it is not calculated before. 1604 if ((m_watchpoints_trigger_after_instruction == eLazyBoolCalculate && 1605 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel || 1606 atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) || 1607 atype == llvm::Triple::ppc64le) { 1608 m_watchpoints_trigger_after_instruction = eLazyBoolNo; 1609 } 1610 1611 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 1612 } 1613 return error; 1614 } 1615 1616 int GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) { 1617 if (file_spec) { 1618 std::string path{file_spec.GetPath(false)}; 1619 StreamString packet; 1620 packet.PutCString("QSetSTDIN:"); 1621 packet.PutCStringAsRawHex8(path.c_str()); 1622 1623 StringExtractorGDBRemote response; 1624 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1625 PacketResult::Success) { 1626 if (response.IsOKResponse()) 1627 return 0; 1628 uint8_t error = response.GetError(); 1629 if (error) 1630 return error; 1631 } 1632 } 1633 return -1; 1634 } 1635 1636 int GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) { 1637 if (file_spec) { 1638 std::string path{file_spec.GetPath(false)}; 1639 StreamString packet; 1640 packet.PutCString("QSetSTDOUT:"); 1641 packet.PutCStringAsRawHex8(path.c_str()); 1642 1643 StringExtractorGDBRemote response; 1644 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1645 PacketResult::Success) { 1646 if (response.IsOKResponse()) 1647 return 0; 1648 uint8_t error = response.GetError(); 1649 if (error) 1650 return error; 1651 } 1652 } 1653 return -1; 1654 } 1655 1656 int GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) { 1657 if (file_spec) { 1658 std::string path{file_spec.GetPath(false)}; 1659 StreamString packet; 1660 packet.PutCString("QSetSTDERR:"); 1661 packet.PutCStringAsRawHex8(path.c_str()); 1662 1663 StringExtractorGDBRemote response; 1664 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1665 PacketResult::Success) { 1666 if (response.IsOKResponse()) 1667 return 0; 1668 uint8_t error = response.GetError(); 1669 if (error) 1670 return error; 1671 } 1672 } 1673 return -1; 1674 } 1675 1676 bool GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) { 1677 StringExtractorGDBRemote response; 1678 if (SendPacketAndWaitForResponse("qGetWorkingDir", response, false) == 1679 PacketResult::Success) { 1680 if (response.IsUnsupportedResponse()) 1681 return false; 1682 if (response.IsErrorResponse()) 1683 return false; 1684 std::string cwd; 1685 response.GetHexByteString(cwd); 1686 working_dir.SetFile(cwd, false, GetHostArchitecture().GetTriple()); 1687 return !cwd.empty(); 1688 } 1689 return false; 1690 } 1691 1692 int GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) { 1693 if (working_dir) { 1694 std::string path{working_dir.GetPath(false)}; 1695 StreamString packet; 1696 packet.PutCString("QSetWorkingDir:"); 1697 packet.PutCStringAsRawHex8(path.c_str()); 1698 1699 StringExtractorGDBRemote response; 1700 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 1701 PacketResult::Success) { 1702 if (response.IsOKResponse()) 1703 return 0; 1704 uint8_t error = response.GetError(); 1705 if (error) 1706 return error; 1707 } 1708 } 1709 return -1; 1710 } 1711 1712 int GDBRemoteCommunicationClient::SetDisableASLR(bool enable) { 1713 char packet[32]; 1714 const int packet_len = 1715 ::snprintf(packet, sizeof(packet), "QSetDisableASLR:%i", enable ? 1 : 0); 1716 assert(packet_len < (int)sizeof(packet)); 1717 UNUSED_IF_ASSERT_DISABLED(packet_len); 1718 StringExtractorGDBRemote response; 1719 if (SendPacketAndWaitForResponse(packet, response, false) == 1720 PacketResult::Success) { 1721 if (response.IsOKResponse()) 1722 return 0; 1723 uint8_t error = response.GetError(); 1724 if (error) 1725 return error; 1726 } 1727 return -1; 1728 } 1729 1730 int GDBRemoteCommunicationClient::SetDetachOnError(bool enable) { 1731 char packet[32]; 1732 const int packet_len = ::snprintf(packet, sizeof(packet), 1733 "QSetDetachOnError:%i", enable ? 1 : 0); 1734 assert(packet_len < (int)sizeof(packet)); 1735 UNUSED_IF_ASSERT_DISABLED(packet_len); 1736 StringExtractorGDBRemote response; 1737 if (SendPacketAndWaitForResponse(packet, response, false) == 1738 PacketResult::Success) { 1739 if (response.IsOKResponse()) 1740 return 0; 1741 uint8_t error = response.GetError(); 1742 if (error) 1743 return error; 1744 } 1745 return -1; 1746 } 1747 1748 bool GDBRemoteCommunicationClient::DecodeProcessInfoResponse( 1749 StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) { 1750 if (response.IsNormalResponse()) { 1751 llvm::StringRef name; 1752 llvm::StringRef value; 1753 StringExtractor extractor; 1754 1755 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1756 uint32_t sub = 0; 1757 std::string vendor; 1758 std::string os_type; 1759 1760 while (response.GetNameColonValue(name, value)) { 1761 if (name.equals("pid")) { 1762 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 1763 value.getAsInteger(0, pid); 1764 process_info.SetProcessID(pid); 1765 } else if (name.equals("ppid")) { 1766 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 1767 value.getAsInteger(0, pid); 1768 process_info.SetParentProcessID(pid); 1769 } else if (name.equals("uid")) { 1770 uint32_t uid = UINT32_MAX; 1771 value.getAsInteger(0, uid); 1772 process_info.SetUserID(uid); 1773 } else if (name.equals("euid")) { 1774 uint32_t uid = UINT32_MAX; 1775 value.getAsInteger(0, uid); 1776 process_info.SetEffectiveGroupID(uid); 1777 } else if (name.equals("gid")) { 1778 uint32_t gid = UINT32_MAX; 1779 value.getAsInteger(0, gid); 1780 process_info.SetGroupID(gid); 1781 } else if (name.equals("egid")) { 1782 uint32_t gid = UINT32_MAX; 1783 value.getAsInteger(0, gid); 1784 process_info.SetEffectiveGroupID(gid); 1785 } else if (name.equals("triple")) { 1786 StringExtractor extractor(value); 1787 std::string triple; 1788 extractor.GetHexByteString(triple); 1789 process_info.GetArchitecture().SetTriple(triple.c_str()); 1790 } else if (name.equals("name")) { 1791 StringExtractor extractor(value); 1792 // The process name from ASCII hex bytes since we can't 1793 // control the characters in a process name 1794 std::string name; 1795 extractor.GetHexByteString(name); 1796 process_info.GetExecutableFile().SetFile(name, false); 1797 } else if (name.equals("cputype")) { 1798 value.getAsInteger(0, cpu); 1799 } else if (name.equals("cpusubtype")) { 1800 value.getAsInteger(0, sub); 1801 } else if (name.equals("vendor")) { 1802 vendor = value; 1803 } else if (name.equals("ostype")) { 1804 os_type = value; 1805 } 1806 } 1807 1808 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) { 1809 if (vendor == "apple") { 1810 process_info.GetArchitecture().SetArchitecture(eArchTypeMachO, cpu, 1811 sub); 1812 process_info.GetArchitecture().GetTriple().setVendorName( 1813 llvm::StringRef(vendor)); 1814 process_info.GetArchitecture().GetTriple().setOSName( 1815 llvm::StringRef(os_type)); 1816 } 1817 } 1818 1819 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 1820 return true; 1821 } 1822 return false; 1823 } 1824 1825 bool GDBRemoteCommunicationClient::GetProcessInfo( 1826 lldb::pid_t pid, ProcessInstanceInfo &process_info) { 1827 process_info.Clear(); 1828 1829 if (m_supports_qProcessInfoPID) { 1830 char packet[32]; 1831 const int packet_len = 1832 ::snprintf(packet, sizeof(packet), "qProcessInfoPID:%" PRIu64, pid); 1833 assert(packet_len < (int)sizeof(packet)); 1834 UNUSED_IF_ASSERT_DISABLED(packet_len); 1835 StringExtractorGDBRemote response; 1836 if (SendPacketAndWaitForResponse(packet, response, false) == 1837 PacketResult::Success) { 1838 return DecodeProcessInfoResponse(response, process_info); 1839 } else { 1840 m_supports_qProcessInfoPID = false; 1841 return false; 1842 } 1843 } 1844 return false; 1845 } 1846 1847 bool GDBRemoteCommunicationClient::GetCurrentProcessInfo(bool allow_lazy) { 1848 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | 1849 GDBR_LOG_PACKETS)); 1850 1851 if (allow_lazy) { 1852 if (m_qProcessInfo_is_valid == eLazyBoolYes) 1853 return true; 1854 if (m_qProcessInfo_is_valid == eLazyBoolNo) 1855 return false; 1856 } 1857 1858 GetHostInfo(); 1859 1860 StringExtractorGDBRemote response; 1861 if (SendPacketAndWaitForResponse("qProcessInfo", response, false) == 1862 PacketResult::Success) { 1863 if (response.IsNormalResponse()) { 1864 llvm::StringRef name; 1865 llvm::StringRef value; 1866 uint32_t cpu = LLDB_INVALID_CPUTYPE; 1867 uint32_t sub = 0; 1868 std::string arch_name; 1869 std::string os_name; 1870 std::string vendor_name; 1871 std::string triple; 1872 std::string elf_abi; 1873 uint32_t pointer_byte_size = 0; 1874 StringExtractor extractor; 1875 ByteOrder byte_order = eByteOrderInvalid; 1876 uint32_t num_keys_decoded = 0; 1877 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 1878 while (response.GetNameColonValue(name, value)) { 1879 if (name.equals("cputype")) { 1880 if (!value.getAsInteger(16, cpu)) 1881 ++num_keys_decoded; 1882 } else if (name.equals("cpusubtype")) { 1883 if (!value.getAsInteger(16, sub)) 1884 ++num_keys_decoded; 1885 } else if (name.equals("triple")) { 1886 StringExtractor extractor(value); 1887 extractor.GetHexByteString(triple); 1888 ++num_keys_decoded; 1889 } else if (name.equals("ostype")) { 1890 os_name = value; 1891 ++num_keys_decoded; 1892 } else if (name.equals("vendor")) { 1893 vendor_name = value; 1894 ++num_keys_decoded; 1895 } else if (name.equals("endian")) { 1896 byte_order = llvm::StringSwitch<lldb::ByteOrder>(value) 1897 .Case("little", eByteOrderLittle) 1898 .Case("big", eByteOrderBig) 1899 .Case("pdp", eByteOrderPDP) 1900 .Default(eByteOrderInvalid); 1901 if (byte_order != eByteOrderInvalid) 1902 ++num_keys_decoded; 1903 } else if (name.equals("ptrsize")) { 1904 if (!value.getAsInteger(16, pointer_byte_size)) 1905 ++num_keys_decoded; 1906 } else if (name.equals("pid")) { 1907 if (!value.getAsInteger(16, pid)) 1908 ++num_keys_decoded; 1909 } else if (name.equals("elf_abi")) { 1910 elf_abi = value; 1911 ++num_keys_decoded; 1912 } 1913 } 1914 if (num_keys_decoded > 0) 1915 m_qProcessInfo_is_valid = eLazyBoolYes; 1916 if (pid != LLDB_INVALID_PROCESS_ID) { 1917 m_curr_pid_is_valid = eLazyBoolYes; 1918 m_curr_pid = pid; 1919 } 1920 1921 // Set the ArchSpec from the triple if we have it. 1922 if (!triple.empty()) { 1923 m_process_arch.SetTriple(triple.c_str()); 1924 m_process_arch.SetFlags(elf_abi); 1925 if (pointer_byte_size) { 1926 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 1927 } 1928 } else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && 1929 !vendor_name.empty()) { 1930 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name); 1931 1932 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat); 1933 assert(triple.getObjectFormat() != llvm::Triple::Wasm); 1934 switch (triple.getObjectFormat()) { 1935 case llvm::Triple::MachO: 1936 m_process_arch.SetArchitecture(eArchTypeMachO, cpu, sub); 1937 break; 1938 case llvm::Triple::ELF: 1939 m_process_arch.SetArchitecture(eArchTypeELF, cpu, sub); 1940 break; 1941 case llvm::Triple::COFF: 1942 m_process_arch.SetArchitecture(eArchTypeCOFF, cpu, sub); 1943 break; 1944 case llvm::Triple::Wasm: 1945 if (log) 1946 log->Printf("error: not supported target architecture"); 1947 return false; 1948 case llvm::Triple::UnknownObjectFormat: 1949 if (log) 1950 log->Printf("error: failed to determine target architecture"); 1951 return false; 1952 } 1953 1954 if (pointer_byte_size) { 1955 assert(pointer_byte_size == m_process_arch.GetAddressByteSize()); 1956 } 1957 if (byte_order != eByteOrderInvalid) { 1958 assert(byte_order == m_process_arch.GetByteOrder()); 1959 } 1960 m_process_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name)); 1961 m_process_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 1962 m_host_arch.GetTriple().setVendorName(llvm::StringRef(vendor_name)); 1963 m_host_arch.GetTriple().setOSName(llvm::StringRef(os_name)); 1964 } 1965 return true; 1966 } 1967 } else { 1968 m_qProcessInfo_is_valid = eLazyBoolNo; 1969 } 1970 1971 return false; 1972 } 1973 1974 uint32_t GDBRemoteCommunicationClient::FindProcesses( 1975 const ProcessInstanceInfoMatch &match_info, 1976 ProcessInstanceInfoList &process_infos) { 1977 process_infos.Clear(); 1978 1979 if (m_supports_qfProcessInfo) { 1980 StreamString packet; 1981 packet.PutCString("qfProcessInfo"); 1982 if (!match_info.MatchAllProcesses()) { 1983 packet.PutChar(':'); 1984 const char *name = match_info.GetProcessInfo().GetName(); 1985 bool has_name_match = false; 1986 if (name && name[0]) { 1987 has_name_match = true; 1988 NameMatch name_match_type = match_info.GetNameMatchType(); 1989 switch (name_match_type) { 1990 case NameMatch::Ignore: 1991 has_name_match = false; 1992 break; 1993 1994 case NameMatch::Equals: 1995 packet.PutCString("name_match:equals;"); 1996 break; 1997 1998 case NameMatch::Contains: 1999 packet.PutCString("name_match:contains;"); 2000 break; 2001 2002 case NameMatch::StartsWith: 2003 packet.PutCString("name_match:starts_with;"); 2004 break; 2005 2006 case NameMatch::EndsWith: 2007 packet.PutCString("name_match:ends_with;"); 2008 break; 2009 2010 case NameMatch::RegularExpression: 2011 packet.PutCString("name_match:regex;"); 2012 break; 2013 } 2014 if (has_name_match) { 2015 packet.PutCString("name:"); 2016 packet.PutBytesAsRawHex8(name, ::strlen(name)); 2017 packet.PutChar(';'); 2018 } 2019 } 2020 2021 if (match_info.GetProcessInfo().ProcessIDIsValid()) 2022 packet.Printf("pid:%" PRIu64 ";", 2023 match_info.GetProcessInfo().GetProcessID()); 2024 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 2025 packet.Printf("parent_pid:%" PRIu64 ";", 2026 match_info.GetProcessInfo().GetParentProcessID()); 2027 if (match_info.GetProcessInfo().UserIDIsValid()) 2028 packet.Printf("uid:%u;", match_info.GetProcessInfo().GetUserID()); 2029 if (match_info.GetProcessInfo().GroupIDIsValid()) 2030 packet.Printf("gid:%u;", match_info.GetProcessInfo().GetGroupID()); 2031 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 2032 packet.Printf("euid:%u;", 2033 match_info.GetProcessInfo().GetEffectiveUserID()); 2034 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2035 packet.Printf("egid:%u;", 2036 match_info.GetProcessInfo().GetEffectiveGroupID()); 2037 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 2038 packet.Printf("all_users:%u;", match_info.GetMatchAllUsers() ? 1 : 0); 2039 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) { 2040 const ArchSpec &match_arch = 2041 match_info.GetProcessInfo().GetArchitecture(); 2042 const llvm::Triple &triple = match_arch.GetTriple(); 2043 packet.PutCString("triple:"); 2044 packet.PutCString(triple.getTriple()); 2045 packet.PutChar(';'); 2046 } 2047 } 2048 StringExtractorGDBRemote response; 2049 // Increase timeout as the first qfProcessInfo packet takes a long time 2050 // on Android. The value of 1min was arrived at empirically. 2051 ScopedTimeout timeout(*this, minutes(1)); 2052 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) == 2053 PacketResult::Success) { 2054 do { 2055 ProcessInstanceInfo process_info; 2056 if (!DecodeProcessInfoResponse(response, process_info)) 2057 break; 2058 process_infos.Append(process_info); 2059 response.GetStringRef().clear(); 2060 response.SetFilePos(0); 2061 } while (SendPacketAndWaitForResponse("qsProcessInfo", response, false) == 2062 PacketResult::Success); 2063 } else { 2064 m_supports_qfProcessInfo = false; 2065 return 0; 2066 } 2067 } 2068 return process_infos.GetSize(); 2069 } 2070 2071 bool GDBRemoteCommunicationClient::GetUserName(uint32_t uid, 2072 std::string &name) { 2073 if (m_supports_qUserName) { 2074 char packet[32]; 2075 const int packet_len = 2076 ::snprintf(packet, sizeof(packet), "qUserName:%i", uid); 2077 assert(packet_len < (int)sizeof(packet)); 2078 UNUSED_IF_ASSERT_DISABLED(packet_len); 2079 StringExtractorGDBRemote response; 2080 if (SendPacketAndWaitForResponse(packet, response, false) == 2081 PacketResult::Success) { 2082 if (response.IsNormalResponse()) { 2083 // Make sure we parsed the right number of characters. The response is 2084 // the hex encoded user name and should make up the entire packet. 2085 // If there are any non-hex ASCII bytes, the length won't match below.. 2086 if (response.GetHexByteString(name) * 2 == 2087 response.GetStringRef().size()) 2088 return true; 2089 } 2090 } else { 2091 m_supports_qUserName = false; 2092 return false; 2093 } 2094 } 2095 return false; 2096 } 2097 2098 bool GDBRemoteCommunicationClient::GetGroupName(uint32_t gid, 2099 std::string &name) { 2100 if (m_supports_qGroupName) { 2101 char packet[32]; 2102 const int packet_len = 2103 ::snprintf(packet, sizeof(packet), "qGroupName:%i", gid); 2104 assert(packet_len < (int)sizeof(packet)); 2105 UNUSED_IF_ASSERT_DISABLED(packet_len); 2106 StringExtractorGDBRemote response; 2107 if (SendPacketAndWaitForResponse(packet, response, false) == 2108 PacketResult::Success) { 2109 if (response.IsNormalResponse()) { 2110 // Make sure we parsed the right number of characters. The response is 2111 // the hex encoded group name and should make up the entire packet. 2112 // If there are any non-hex ASCII bytes, the length won't match below.. 2113 if (response.GetHexByteString(name) * 2 == 2114 response.GetStringRef().size()) 2115 return true; 2116 } 2117 } else { 2118 m_supports_qGroupName = false; 2119 return false; 2120 } 2121 } 2122 return false; 2123 } 2124 2125 bool GDBRemoteCommunicationClient::SetNonStopMode(const bool enable) { 2126 // Form non-stop packet request 2127 char packet[32]; 2128 const int packet_len = 2129 ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable); 2130 assert(packet_len < (int)sizeof(packet)); 2131 UNUSED_IF_ASSERT_DISABLED(packet_len); 2132 2133 StringExtractorGDBRemote response; 2134 // Send to target 2135 if (SendPacketAndWaitForResponse(packet, response, false) == 2136 PacketResult::Success) 2137 if (response.IsOKResponse()) 2138 return true; 2139 2140 // Failed or not supported 2141 return false; 2142 } 2143 2144 static void MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, 2145 uint32_t recv_size) { 2146 packet.Clear(); 2147 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2148 uint32_t bytes_left = send_size; 2149 while (bytes_left > 0) { 2150 if (bytes_left >= 26) { 2151 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2152 bytes_left -= 26; 2153 } else { 2154 packet.Printf("%*.*s;", bytes_left, bytes_left, 2155 "abcdefghijklmnopqrstuvwxyz"); 2156 bytes_left = 0; 2157 } 2158 } 2159 } 2160 2161 duration<float> 2162 calculate_standard_deviation(const std::vector<duration<float>> &v) { 2163 using Dur = duration<float>; 2164 Dur sum = std::accumulate(std::begin(v), std::end(v), Dur()); 2165 Dur mean = sum / v.size(); 2166 float accum = 0; 2167 for (auto d : v) { 2168 float delta = (d - mean).count(); 2169 accum += delta * delta; 2170 }; 2171 2172 return Dur(sqrtf(accum / (v.size() - 1))); 2173 } 2174 2175 void GDBRemoteCommunicationClient::TestPacketSpeed(const uint32_t num_packets, 2176 uint32_t max_send, 2177 uint32_t max_recv, 2178 uint64_t recv_amount, 2179 bool json, Stream &strm) { 2180 uint32_t i; 2181 if (SendSpeedTestPacket(0, 0)) { 2182 StreamString packet; 2183 if (json) 2184 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n " 2185 "\"results\" : [", 2186 num_packets); 2187 else 2188 strm.Printf("Testing sending %u packets of various sizes:\n", 2189 num_packets); 2190 strm.Flush(); 2191 2192 uint32_t result_idx = 0; 2193 uint32_t send_size; 2194 std::vector<duration<float>> packet_times; 2195 2196 for (send_size = 0; send_size <= max_send; 2197 send_size ? send_size *= 2 : send_size = 4) { 2198 for (uint32_t recv_size = 0; recv_size <= max_recv; 2199 recv_size ? recv_size *= 2 : recv_size = 4) { 2200 MakeSpeedTestPacket(packet, send_size, recv_size); 2201 2202 packet_times.clear(); 2203 // Test how long it takes to send 'num_packets' packets 2204 const auto start_time = steady_clock::now(); 2205 for (i = 0; i < num_packets; ++i) { 2206 const auto packet_start_time = steady_clock::now(); 2207 StringExtractorGDBRemote response; 2208 SendPacketAndWaitForResponse(packet.GetString(), response, false); 2209 const auto packet_end_time = steady_clock::now(); 2210 packet_times.push_back(packet_end_time - packet_start_time); 2211 } 2212 const auto end_time = steady_clock::now(); 2213 const auto total_time = end_time - start_time; 2214 2215 float packets_per_second = 2216 ((float)num_packets) / duration<float>(total_time).count(); 2217 auto average_per_packet = total_time / num_packets; 2218 const duration<float> standard_deviation = 2219 calculate_standard_deviation(packet_times); 2220 if (json) { 2221 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2222 "{2,6}, \"total_time_nsec\" : {3,12:ns-}, " 2223 "\"standard_deviation_nsec\" : {4,9:ns-f0}}", 2224 result_idx > 0 ? "," : "", send_size, recv_size, 2225 total_time, standard_deviation); 2226 ++result_idx; 2227 } else { 2228 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) in {2:s+f9} for " 2229 "{3,9:f2} packets/s ({4,10:ms+f6} per packet) with " 2230 "standard deviation of {5,10:ms+f6}\n", 2231 send_size, recv_size, duration<float>(total_time), 2232 packets_per_second, duration<float>(average_per_packet), 2233 standard_deviation); 2234 } 2235 strm.Flush(); 2236 } 2237 } 2238 2239 const float k_recv_amount_mb = (float)recv_amount / (1024.0f * 1024.0f); 2240 if (json) 2241 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" " 2242 ": %" PRIu64 ",\n \"results\" : [", 2243 recv_amount); 2244 else 2245 strm.Printf("Testing receiving %2.1fMB of data using varying receive " 2246 "packet sizes:\n", 2247 k_recv_amount_mb); 2248 strm.Flush(); 2249 send_size = 0; 2250 result_idx = 0; 2251 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) { 2252 MakeSpeedTestPacket(packet, send_size, recv_size); 2253 2254 // If we have a receive size, test how long it takes to receive 4MB of 2255 // data 2256 if (recv_size > 0) { 2257 const auto start_time = steady_clock::now(); 2258 uint32_t bytes_read = 0; 2259 uint32_t packet_count = 0; 2260 while (bytes_read < recv_amount) { 2261 StringExtractorGDBRemote response; 2262 SendPacketAndWaitForResponse(packet.GetString(), response, false); 2263 bytes_read += recv_size; 2264 ++packet_count; 2265 } 2266 const auto end_time = steady_clock::now(); 2267 const auto total_time = end_time - start_time; 2268 float mb_second = ((float)recv_amount) / 2269 duration<float>(total_time).count() / 2270 (1024.0 * 1024.0); 2271 float packets_per_second = 2272 ((float)packet_count) / duration<float>(total_time).count(); 2273 const auto average_per_packet = total_time / packet_count; 2274 2275 if (json) { 2276 strm.Format("{0}\n {{\"send_size\" : {1,6}, \"recv_size\" : " 2277 "{2,6}, \"total_time_nsec\" : {3,12:ns-}}", 2278 result_idx > 0 ? "," : "", send_size, recv_size, 2279 total_time); 2280 ++result_idx; 2281 } else { 2282 strm.Format("qSpeedTest(send={0,7}, recv={1,7}) {2,6} packets needed " 2283 "to receive {3:f1}MB in {4:s+f9} for {5} MB/sec for " 2284 "{6,9:f2} packets/sec ({7,10:ms+f6} per packet)\n", 2285 send_size, recv_size, packet_count, k_recv_amount_mb, 2286 duration<float>(total_time), mb_second, 2287 packets_per_second, duration<float>(average_per_packet)); 2288 } 2289 strm.Flush(); 2290 } 2291 } 2292 if (json) 2293 strm.Printf("\n ]\n }\n}\n"); 2294 else 2295 strm.EOL(); 2296 } 2297 } 2298 2299 bool GDBRemoteCommunicationClient::SendSpeedTestPacket(uint32_t send_size, 2300 uint32_t recv_size) { 2301 StreamString packet; 2302 packet.Printf("qSpeedTest:response_size:%i;data:", recv_size); 2303 uint32_t bytes_left = send_size; 2304 while (bytes_left > 0) { 2305 if (bytes_left >= 26) { 2306 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 2307 bytes_left -= 26; 2308 } else { 2309 packet.Printf("%*.*s;", bytes_left, bytes_left, 2310 "abcdefghijklmnopqrstuvwxyz"); 2311 bytes_left = 0; 2312 } 2313 } 2314 2315 StringExtractorGDBRemote response; 2316 return SendPacketAndWaitForResponse(packet.GetString(), response, false) == 2317 PacketResult::Success; 2318 } 2319 2320 bool GDBRemoteCommunicationClient::LaunchGDBServer( 2321 const char *remote_accept_hostname, lldb::pid_t &pid, uint16_t &port, 2322 std::string &socket_name) { 2323 pid = LLDB_INVALID_PROCESS_ID; 2324 port = 0; 2325 socket_name.clear(); 2326 2327 StringExtractorGDBRemote response; 2328 StreamString stream; 2329 stream.PutCString("qLaunchGDBServer;"); 2330 std::string hostname; 2331 if (remote_accept_hostname && remote_accept_hostname[0]) 2332 hostname = remote_accept_hostname; 2333 else { 2334 if (HostInfo::GetHostname(hostname)) { 2335 // Make the GDB server we launch only accept connections from this host 2336 stream.Printf("host:%s;", hostname.c_str()); 2337 } else { 2338 // Make the GDB server we launch accept connections from any host since we 2339 // can't figure out the hostname 2340 stream.Printf("host:*;"); 2341 } 2342 } 2343 // give the process a few seconds to startup 2344 ScopedTimeout timeout(*this, seconds(10)); 2345 2346 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2347 PacketResult::Success) { 2348 llvm::StringRef name; 2349 llvm::StringRef value; 2350 while (response.GetNameColonValue(name, value)) { 2351 if (name.equals("port")) 2352 value.getAsInteger(0, port); 2353 else if (name.equals("pid")) 2354 value.getAsInteger(0, pid); 2355 else if (name.compare("socket_name") == 0) { 2356 StringExtractor extractor(value); 2357 extractor.GetHexByteString(socket_name); 2358 } 2359 } 2360 return true; 2361 } 2362 return false; 2363 } 2364 2365 size_t GDBRemoteCommunicationClient::QueryGDBServer( 2366 std::vector<std::pair<uint16_t, std::string>> &connection_urls) { 2367 connection_urls.clear(); 2368 2369 StringExtractorGDBRemote response; 2370 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != 2371 PacketResult::Success) 2372 return 0; 2373 2374 StructuredData::ObjectSP data = 2375 StructuredData::ParseJSON(response.GetStringRef()); 2376 if (!data) 2377 return 0; 2378 2379 StructuredData::Array *array = data->GetAsArray(); 2380 if (!array) 2381 return 0; 2382 2383 for (size_t i = 0, count = array->GetSize(); i < count; ++i) { 2384 StructuredData::Dictionary *element = nullptr; 2385 if (!array->GetItemAtIndexAsDictionary(i, element)) 2386 continue; 2387 2388 uint16_t port = 0; 2389 if (StructuredData::ObjectSP port_osp = 2390 element->GetValueForKey(llvm::StringRef("port"))) 2391 port = port_osp->GetIntegerValue(0); 2392 2393 std::string socket_name; 2394 if (StructuredData::ObjectSP socket_name_osp = 2395 element->GetValueForKey(llvm::StringRef("socket_name"))) 2396 socket_name = socket_name_osp->GetStringValue(); 2397 2398 if (port != 0 || !socket_name.empty()) 2399 connection_urls.emplace_back(port, socket_name); 2400 } 2401 return connection_urls.size(); 2402 } 2403 2404 bool GDBRemoteCommunicationClient::KillSpawnedProcess(lldb::pid_t pid) { 2405 StreamString stream; 2406 stream.Printf("qKillSpawnedProcess:%" PRId64, pid); 2407 2408 StringExtractorGDBRemote response; 2409 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2410 PacketResult::Success) { 2411 if (response.IsOKResponse()) 2412 return true; 2413 } 2414 return false; 2415 } 2416 2417 bool GDBRemoteCommunicationClient::SetCurrentThread(uint64_t tid) { 2418 if (m_curr_tid == tid) 2419 return true; 2420 2421 char packet[32]; 2422 int packet_len; 2423 if (tid == UINT64_MAX) 2424 packet_len = ::snprintf(packet, sizeof(packet), "Hg-1"); 2425 else 2426 packet_len = ::snprintf(packet, sizeof(packet), "Hg%" PRIx64, tid); 2427 assert(packet_len + 1 < (int)sizeof(packet)); 2428 UNUSED_IF_ASSERT_DISABLED(packet_len); 2429 StringExtractorGDBRemote response; 2430 if (SendPacketAndWaitForResponse(packet, response, false) == 2431 PacketResult::Success) { 2432 if (response.IsOKResponse()) { 2433 m_curr_tid = tid; 2434 return true; 2435 } 2436 2437 /* 2438 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2439 * Hg packet. 2440 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2441 * which can 2442 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2443 */ 2444 if (response.IsUnsupportedResponse() && IsConnected()) { 2445 m_curr_tid = 1; 2446 return true; 2447 } 2448 } 2449 return false; 2450 } 2451 2452 bool GDBRemoteCommunicationClient::SetCurrentThreadForRun(uint64_t tid) { 2453 if (m_curr_tid_run == tid) 2454 return true; 2455 2456 char packet[32]; 2457 int packet_len; 2458 if (tid == UINT64_MAX) 2459 packet_len = ::snprintf(packet, sizeof(packet), "Hc-1"); 2460 else 2461 packet_len = ::snprintf(packet, sizeof(packet), "Hc%" PRIx64, tid); 2462 2463 assert(packet_len + 1 < (int)sizeof(packet)); 2464 UNUSED_IF_ASSERT_DISABLED(packet_len); 2465 StringExtractorGDBRemote response; 2466 if (SendPacketAndWaitForResponse(packet, response, false) == 2467 PacketResult::Success) { 2468 if (response.IsOKResponse()) { 2469 m_curr_tid_run = tid; 2470 return true; 2471 } 2472 2473 /* 2474 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2475 * Hc packet. 2476 * The reply from '?' packet could be as simple as 'S05'. There is no packet 2477 * which can 2478 * give us pid and/or tid. Assume pid=tid=1 in such cases. 2479 */ 2480 if (response.IsUnsupportedResponse() && IsConnected()) { 2481 m_curr_tid_run = 1; 2482 return true; 2483 } 2484 } 2485 return false; 2486 } 2487 2488 bool GDBRemoteCommunicationClient::GetStopReply( 2489 StringExtractorGDBRemote &response) { 2490 if (SendPacketAndWaitForResponse("?", response, false) == 2491 PacketResult::Success) 2492 return response.IsNormalResponse(); 2493 return false; 2494 } 2495 2496 bool GDBRemoteCommunicationClient::GetThreadStopInfo( 2497 lldb::tid_t tid, StringExtractorGDBRemote &response) { 2498 if (m_supports_qThreadStopInfo) { 2499 char packet[256]; 2500 int packet_len = 2501 ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 2502 assert(packet_len < (int)sizeof(packet)); 2503 UNUSED_IF_ASSERT_DISABLED(packet_len); 2504 if (SendPacketAndWaitForResponse(packet, response, false) == 2505 PacketResult::Success) { 2506 if (response.IsUnsupportedResponse()) 2507 m_supports_qThreadStopInfo = false; 2508 else if (response.IsNormalResponse()) 2509 return true; 2510 else 2511 return false; 2512 } else { 2513 m_supports_qThreadStopInfo = false; 2514 } 2515 } 2516 return false; 2517 } 2518 2519 uint8_t GDBRemoteCommunicationClient::SendGDBStoppointTypePacket( 2520 GDBStoppointType type, bool insert, addr_t addr, uint32_t length) { 2521 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_BREAKPOINTS)); 2522 if (log) 2523 log->Printf("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64, 2524 __FUNCTION__, insert ? "add" : "remove", addr); 2525 2526 // Check if the stub is known not to support this breakpoint type 2527 if (!SupportsGDBStoppointPacket(type)) 2528 return UINT8_MAX; 2529 // Construct the breakpoint packet 2530 char packet[64]; 2531 const int packet_len = 2532 ::snprintf(packet, sizeof(packet), "%c%i,%" PRIx64 ",%x", 2533 insert ? 'Z' : 'z', type, addr, length); 2534 // Check we haven't overwritten the end of the packet buffer 2535 assert(packet_len + 1 < (int)sizeof(packet)); 2536 UNUSED_IF_ASSERT_DISABLED(packet_len); 2537 StringExtractorGDBRemote response; 2538 // Make sure the response is either "OK", "EXX" where XX are two hex digits, 2539 // or "" (unsupported) 2540 response.SetResponseValidatorToOKErrorNotSupported(); 2541 // Try to send the breakpoint packet, and check that it was correctly sent 2542 if (SendPacketAndWaitForResponse(packet, response, true) == 2543 PacketResult::Success) { 2544 // Receive and OK packet when the breakpoint successfully placed 2545 if (response.IsOKResponse()) 2546 return 0; 2547 2548 // Status while setting breakpoint, send back specific error 2549 if (response.IsErrorResponse()) 2550 return response.GetError(); 2551 2552 // Empty packet informs us that breakpoint is not supported 2553 if (response.IsUnsupportedResponse()) { 2554 // Disable this breakpoint type since it is unsupported 2555 switch (type) { 2556 case eBreakpointSoftware: 2557 m_supports_z0 = false; 2558 break; 2559 case eBreakpointHardware: 2560 m_supports_z1 = false; 2561 break; 2562 case eWatchpointWrite: 2563 m_supports_z2 = false; 2564 break; 2565 case eWatchpointRead: 2566 m_supports_z3 = false; 2567 break; 2568 case eWatchpointReadWrite: 2569 m_supports_z4 = false; 2570 break; 2571 case eStoppointInvalid: 2572 return UINT8_MAX; 2573 } 2574 } 2575 } 2576 // Signal generic failure 2577 return UINT8_MAX; 2578 } 2579 2580 size_t GDBRemoteCommunicationClient::GetCurrentThreadIDs( 2581 std::vector<lldb::tid_t> &thread_ids, bool &sequence_mutex_unavailable) { 2582 thread_ids.clear(); 2583 2584 Lock lock(*this, false); 2585 if (lock) { 2586 sequence_mutex_unavailable = false; 2587 StringExtractorGDBRemote response; 2588 2589 PacketResult packet_result; 2590 for (packet_result = 2591 SendPacketAndWaitForResponseNoLock("qfThreadInfo", response); 2592 packet_result == PacketResult::Success && response.IsNormalResponse(); 2593 packet_result = 2594 SendPacketAndWaitForResponseNoLock("qsThreadInfo", response)) { 2595 char ch = response.GetChar(); 2596 if (ch == 'l') 2597 break; 2598 if (ch == 'm') { 2599 do { 2600 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 2601 2602 if (tid != LLDB_INVALID_THREAD_ID) { 2603 thread_ids.push_back(tid); 2604 } 2605 ch = response.GetChar(); // Skip the command separator 2606 } while (ch == ','); // Make sure we got a comma separator 2607 } 2608 } 2609 2610 /* 2611 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 2612 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet 2613 * could 2614 * be as simple as 'S05'. There is no packet which can give us pid and/or 2615 * tid. 2616 * Assume pid=tid=1 in such cases. 2617 */ 2618 if ((response.IsUnsupportedResponse() || response.IsNormalResponse()) && 2619 thread_ids.size() == 0 && IsConnected()) { 2620 thread_ids.push_back(1); 2621 } 2622 } else { 2623 #if !defined(LLDB_CONFIGURATION_DEBUG) 2624 Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet(GDBR_LOG_PROCESS | 2625 GDBR_LOG_PACKETS)); 2626 if (log) 2627 log->Printf("error: failed to get packet sequence mutex, not sending " 2628 "packet 'qfThreadInfo'"); 2629 #endif 2630 sequence_mutex_unavailable = true; 2631 } 2632 return thread_ids.size(); 2633 } 2634 2635 lldb::addr_t GDBRemoteCommunicationClient::GetShlibInfoAddr() { 2636 StringExtractorGDBRemote response; 2637 if (SendPacketAndWaitForResponse("qShlibInfoAddr", response, false) != 2638 PacketResult::Success || 2639 !response.IsNormalResponse()) 2640 return LLDB_INVALID_ADDRESS; 2641 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2642 } 2643 2644 lldb_private::Status GDBRemoteCommunicationClient::RunShellCommand( 2645 const char *command, // Shouldn't be NULL 2646 const FileSpec & 2647 working_dir, // Pass empty FileSpec to use the current working directory 2648 int *status_ptr, // Pass NULL if you don't want the process exit status 2649 int *signo_ptr, // Pass NULL if you don't want the signal that caused the 2650 // process to exit 2651 std::string 2652 *command_output, // Pass NULL if you don't want the command output 2653 uint32_t 2654 timeout_sec) // Timeout in seconds to wait for shell program to finish 2655 { 2656 lldb_private::StreamString stream; 2657 stream.PutCString("qPlatform_shell:"); 2658 stream.PutBytesAsRawHex8(command, strlen(command)); 2659 stream.PutChar(','); 2660 stream.PutHex32(timeout_sec); 2661 if (working_dir) { 2662 std::string path{working_dir.GetPath(false)}; 2663 stream.PutChar(','); 2664 stream.PutCStringAsRawHex8(path.c_str()); 2665 } 2666 StringExtractorGDBRemote response; 2667 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2668 PacketResult::Success) { 2669 if (response.GetChar() != 'F') 2670 return Status("malformed reply"); 2671 if (response.GetChar() != ',') 2672 return Status("malformed reply"); 2673 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 2674 if (exitcode == UINT32_MAX) 2675 return Status("unable to run remote process"); 2676 else if (status_ptr) 2677 *status_ptr = exitcode; 2678 if (response.GetChar() != ',') 2679 return Status("malformed reply"); 2680 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 2681 if (signo_ptr) 2682 *signo_ptr = signo; 2683 if (response.GetChar() != ',') 2684 return Status("malformed reply"); 2685 std::string output; 2686 response.GetEscapedBinaryData(output); 2687 if (command_output) 2688 command_output->assign(output); 2689 return Status(); 2690 } 2691 return Status("unable to send packet"); 2692 } 2693 2694 Status GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, 2695 uint32_t file_permissions) { 2696 std::string path{file_spec.GetPath(false)}; 2697 lldb_private::StreamString stream; 2698 stream.PutCString("qPlatform_mkdir:"); 2699 stream.PutHex32(file_permissions); 2700 stream.PutChar(','); 2701 stream.PutCStringAsRawHex8(path.c_str()); 2702 llvm::StringRef packet = stream.GetString(); 2703 StringExtractorGDBRemote response; 2704 2705 if (SendPacketAndWaitForResponse(packet, response, false) != 2706 PacketResult::Success) 2707 return Status("failed to send '%s' packet", packet.str().c_str()); 2708 2709 if (response.GetChar() != 'F') 2710 return Status("invalid response to '%s' packet", packet.str().c_str()); 2711 2712 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 2713 } 2714 2715 Status 2716 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec, 2717 uint32_t file_permissions) { 2718 std::string path{file_spec.GetPath(false)}; 2719 lldb_private::StreamString stream; 2720 stream.PutCString("qPlatform_chmod:"); 2721 stream.PutHex32(file_permissions); 2722 stream.PutChar(','); 2723 stream.PutCStringAsRawHex8(path.c_str()); 2724 llvm::StringRef packet = stream.GetString(); 2725 StringExtractorGDBRemote response; 2726 2727 if (SendPacketAndWaitForResponse(packet, response, false) != 2728 PacketResult::Success) 2729 return Status("failed to send '%s' packet", stream.GetData()); 2730 2731 if (response.GetChar() != 'F') 2732 return Status("invalid response to '%s' packet", stream.GetData()); 2733 2734 return Status(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 2735 } 2736 2737 static uint64_t ParseHostIOPacketResponse(StringExtractorGDBRemote &response, 2738 uint64_t fail_result, Status &error) { 2739 response.SetFilePos(0); 2740 if (response.GetChar() != 'F') 2741 return fail_result; 2742 int32_t result = response.GetS32(-2); 2743 if (result == -2) 2744 return fail_result; 2745 if (response.GetChar() == ',') { 2746 int result_errno = response.GetS32(-2); 2747 if (result_errno != -2) 2748 error.SetError(result_errno, eErrorTypePOSIX); 2749 else 2750 error.SetError(-1, eErrorTypeGeneric); 2751 } else 2752 error.Clear(); 2753 return result; 2754 } 2755 lldb::user_id_t 2756 GDBRemoteCommunicationClient::OpenFile(const lldb_private::FileSpec &file_spec, 2757 uint32_t flags, mode_t mode, 2758 Status &error) { 2759 std::string path(file_spec.GetPath(false)); 2760 lldb_private::StreamString stream; 2761 stream.PutCString("vFile:open:"); 2762 if (path.empty()) 2763 return UINT64_MAX; 2764 stream.PutCStringAsRawHex8(path.c_str()); 2765 stream.PutChar(','); 2766 stream.PutHex32(flags); 2767 stream.PutChar(','); 2768 stream.PutHex32(mode); 2769 StringExtractorGDBRemote response; 2770 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2771 PacketResult::Success) { 2772 return ParseHostIOPacketResponse(response, UINT64_MAX, error); 2773 } 2774 return UINT64_MAX; 2775 } 2776 2777 bool GDBRemoteCommunicationClient::CloseFile(lldb::user_id_t fd, 2778 Status &error) { 2779 lldb_private::StreamString stream; 2780 stream.Printf("vFile:close:%i", (int)fd); 2781 StringExtractorGDBRemote response; 2782 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2783 PacketResult::Success) { 2784 return ParseHostIOPacketResponse(response, -1, error) == 0; 2785 } 2786 return false; 2787 } 2788 2789 // Extension of host I/O packets to get the file size. 2790 lldb::user_id_t GDBRemoteCommunicationClient::GetFileSize( 2791 const lldb_private::FileSpec &file_spec) { 2792 std::string path(file_spec.GetPath(false)); 2793 lldb_private::StreamString stream; 2794 stream.PutCString("vFile:size:"); 2795 stream.PutCStringAsRawHex8(path.c_str()); 2796 StringExtractorGDBRemote response; 2797 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2798 PacketResult::Success) { 2799 if (response.GetChar() != 'F') 2800 return UINT64_MAX; 2801 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 2802 return retcode; 2803 } 2804 return UINT64_MAX; 2805 } 2806 2807 Status 2808 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec, 2809 uint32_t &file_permissions) { 2810 std::string path{file_spec.GetPath(false)}; 2811 Status error; 2812 lldb_private::StreamString stream; 2813 stream.PutCString("vFile:mode:"); 2814 stream.PutCStringAsRawHex8(path.c_str()); 2815 StringExtractorGDBRemote response; 2816 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2817 PacketResult::Success) { 2818 if (response.GetChar() != 'F') { 2819 error.SetErrorStringWithFormat("invalid response to '%s' packet", 2820 stream.GetData()); 2821 } else { 2822 const uint32_t mode = response.GetS32(-1); 2823 if (static_cast<int32_t>(mode) == -1) { 2824 if (response.GetChar() == ',') { 2825 int response_errno = response.GetS32(-1); 2826 if (response_errno > 0) 2827 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2828 else 2829 error.SetErrorToGenericError(); 2830 } else 2831 error.SetErrorToGenericError(); 2832 } else { 2833 file_permissions = mode & (S_IRWXU | S_IRWXG | S_IRWXO); 2834 } 2835 } 2836 } else { 2837 error.SetErrorStringWithFormat("failed to send '%s' packet", 2838 stream.GetData()); 2839 } 2840 return error; 2841 } 2842 2843 uint64_t GDBRemoteCommunicationClient::ReadFile(lldb::user_id_t fd, 2844 uint64_t offset, void *dst, 2845 uint64_t dst_len, 2846 Status &error) { 2847 lldb_private::StreamString stream; 2848 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, 2849 offset); 2850 StringExtractorGDBRemote response; 2851 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2852 PacketResult::Success) { 2853 if (response.GetChar() != 'F') 2854 return 0; 2855 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX); 2856 if (retcode == UINT32_MAX) 2857 return retcode; 2858 const char next = (response.Peek() ? *response.Peek() : 0); 2859 if (next == ',') 2860 return 0; 2861 if (next == ';') { 2862 response.GetChar(); // skip the semicolon 2863 std::string buffer; 2864 if (response.GetEscapedBinaryData(buffer)) { 2865 const uint64_t data_to_write = 2866 std::min<uint64_t>(dst_len, buffer.size()); 2867 if (data_to_write > 0) 2868 memcpy(dst, &buffer[0], data_to_write); 2869 return data_to_write; 2870 } 2871 } 2872 } 2873 return 0; 2874 } 2875 2876 uint64_t GDBRemoteCommunicationClient::WriteFile(lldb::user_id_t fd, 2877 uint64_t offset, 2878 const void *src, 2879 uint64_t src_len, 2880 Status &error) { 2881 lldb_private::StreamGDBRemote stream; 2882 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); 2883 stream.PutEscapedBytes(src, src_len); 2884 StringExtractorGDBRemote response; 2885 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2886 PacketResult::Success) { 2887 if (response.GetChar() != 'F') { 2888 error.SetErrorStringWithFormat("write file failed"); 2889 return 0; 2890 } 2891 uint64_t bytes_written = response.GetU64(UINT64_MAX); 2892 if (bytes_written == UINT64_MAX) { 2893 error.SetErrorToGenericError(); 2894 if (response.GetChar() == ',') { 2895 int response_errno = response.GetS32(-1); 2896 if (response_errno > 0) 2897 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2898 } 2899 return 0; 2900 } 2901 return bytes_written; 2902 } else { 2903 error.SetErrorString("failed to send vFile:pwrite packet"); 2904 } 2905 return 0; 2906 } 2907 2908 Status GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, 2909 const FileSpec &dst) { 2910 std::string src_path{src.GetPath(false)}, dst_path{dst.GetPath(false)}; 2911 Status error; 2912 lldb_private::StreamGDBRemote stream; 2913 stream.PutCString("vFile:symlink:"); 2914 // the unix symlink() command reverses its parameters where the dst if first, 2915 // so we follow suit here 2916 stream.PutCStringAsRawHex8(dst_path.c_str()); 2917 stream.PutChar(','); 2918 stream.PutCStringAsRawHex8(src_path.c_str()); 2919 StringExtractorGDBRemote response; 2920 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2921 PacketResult::Success) { 2922 if (response.GetChar() == 'F') { 2923 uint32_t result = response.GetU32(UINT32_MAX); 2924 if (result != 0) { 2925 error.SetErrorToGenericError(); 2926 if (response.GetChar() == ',') { 2927 int response_errno = response.GetS32(-1); 2928 if (response_errno > 0) 2929 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2930 } 2931 } 2932 } else { 2933 // Should have returned with 'F<result>[,<errno>]' 2934 error.SetErrorStringWithFormat("symlink failed"); 2935 } 2936 } else { 2937 error.SetErrorString("failed to send vFile:symlink packet"); 2938 } 2939 return error; 2940 } 2941 2942 Status GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) { 2943 std::string path{file_spec.GetPath(false)}; 2944 Status error; 2945 lldb_private::StreamGDBRemote stream; 2946 stream.PutCString("vFile:unlink:"); 2947 // the unix symlink() command reverses its parameters where the dst if first, 2948 // so we follow suit here 2949 stream.PutCStringAsRawHex8(path.c_str()); 2950 StringExtractorGDBRemote response; 2951 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2952 PacketResult::Success) { 2953 if (response.GetChar() == 'F') { 2954 uint32_t result = response.GetU32(UINT32_MAX); 2955 if (result != 0) { 2956 error.SetErrorToGenericError(); 2957 if (response.GetChar() == ',') { 2958 int response_errno = response.GetS32(-1); 2959 if (response_errno > 0) 2960 error.SetError(response_errno, lldb::eErrorTypePOSIX); 2961 } 2962 } 2963 } else { 2964 // Should have returned with 'F<result>[,<errno>]' 2965 error.SetErrorStringWithFormat("unlink failed"); 2966 } 2967 } else { 2968 error.SetErrorString("failed to send vFile:unlink packet"); 2969 } 2970 return error; 2971 } 2972 2973 // Extension of host I/O packets to get whether a file exists. 2974 bool GDBRemoteCommunicationClient::GetFileExists( 2975 const lldb_private::FileSpec &file_spec) { 2976 std::string path(file_spec.GetPath(false)); 2977 lldb_private::StreamString stream; 2978 stream.PutCString("vFile:exists:"); 2979 stream.PutCStringAsRawHex8(path.c_str()); 2980 StringExtractorGDBRemote response; 2981 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 2982 PacketResult::Success) { 2983 if (response.GetChar() != 'F') 2984 return false; 2985 if (response.GetChar() != ',') 2986 return false; 2987 bool retcode = (response.GetChar() != '0'); 2988 return retcode; 2989 } 2990 return false; 2991 } 2992 2993 bool GDBRemoteCommunicationClient::CalculateMD5( 2994 const lldb_private::FileSpec &file_spec, uint64_t &high, uint64_t &low) { 2995 std::string path(file_spec.GetPath(false)); 2996 lldb_private::StreamString stream; 2997 stream.PutCString("vFile:MD5:"); 2998 stream.PutCStringAsRawHex8(path.c_str()); 2999 StringExtractorGDBRemote response; 3000 if (SendPacketAndWaitForResponse(stream.GetString(), response, false) == 3001 PacketResult::Success) { 3002 if (response.GetChar() != 'F') 3003 return false; 3004 if (response.GetChar() != ',') 3005 return false; 3006 if (response.Peek() && *response.Peek() == 'x') 3007 return false; 3008 low = response.GetHexMaxU64(false, UINT64_MAX); 3009 high = response.GetHexMaxU64(false, UINT64_MAX); 3010 return true; 3011 } 3012 return false; 3013 } 3014 3015 bool GDBRemoteCommunicationClient::AvoidGPackets(ProcessGDBRemote *process) { 3016 // Some targets have issues with g/G packets and we need to avoid using them 3017 if (m_avoid_g_packets == eLazyBoolCalculate) { 3018 if (process) { 3019 m_avoid_g_packets = eLazyBoolNo; 3020 const ArchSpec &arch = process->GetTarget().GetArchitecture(); 3021 if (arch.IsValid() && 3022 arch.GetTriple().getVendor() == llvm::Triple::Apple && 3023 arch.GetTriple().getOS() == llvm::Triple::IOS && 3024 arch.GetTriple().getArch() == llvm::Triple::aarch64) { 3025 m_avoid_g_packets = eLazyBoolYes; 3026 uint32_t gdb_server_version = GetGDBServerProgramVersion(); 3027 if (gdb_server_version != 0) { 3028 const char *gdb_server_name = GetGDBServerProgramName(); 3029 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) { 3030 if (gdb_server_version >= 310) 3031 m_avoid_g_packets = eLazyBoolNo; 3032 } 3033 } 3034 } 3035 } 3036 } 3037 return m_avoid_g_packets == eLazyBoolYes; 3038 } 3039 3040 DataBufferSP GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, 3041 uint32_t reg) { 3042 StreamString payload; 3043 payload.Printf("p%x", reg); 3044 StringExtractorGDBRemote response; 3045 if (SendThreadSpecificPacketAndWaitForResponse( 3046 tid, std::move(payload), response, false) != PacketResult::Success || 3047 !response.IsNormalResponse()) 3048 return nullptr; 3049 3050 DataBufferSP buffer_sp( 3051 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3052 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3053 return buffer_sp; 3054 } 3055 3056 DataBufferSP GDBRemoteCommunicationClient::ReadAllRegisters(lldb::tid_t tid) { 3057 StreamString payload; 3058 payload.PutChar('g'); 3059 StringExtractorGDBRemote response; 3060 if (SendThreadSpecificPacketAndWaitForResponse( 3061 tid, std::move(payload), response, false) != PacketResult::Success || 3062 !response.IsNormalResponse()) 3063 return nullptr; 3064 3065 DataBufferSP buffer_sp( 3066 new DataBufferHeap(response.GetStringRef().size() / 2, 0)); 3067 response.GetHexBytes(buffer_sp->GetData(), '\xcc'); 3068 return buffer_sp; 3069 } 3070 3071 bool GDBRemoteCommunicationClient::WriteRegister(lldb::tid_t tid, 3072 uint32_t reg_num, 3073 llvm::ArrayRef<uint8_t> data) { 3074 StreamString payload; 3075 payload.Printf("P%x=", reg_num); 3076 payload.PutBytesAsRawHex8(data.data(), data.size(), 3077 endian::InlHostByteOrder(), 3078 endian::InlHostByteOrder()); 3079 StringExtractorGDBRemote response; 3080 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), 3081 response, false) == 3082 PacketResult::Success && 3083 response.IsOKResponse(); 3084 } 3085 3086 bool GDBRemoteCommunicationClient::WriteAllRegisters( 3087 lldb::tid_t tid, llvm::ArrayRef<uint8_t> data) { 3088 StreamString payload; 3089 payload.PutChar('G'); 3090 payload.PutBytesAsRawHex8(data.data(), data.size(), 3091 endian::InlHostByteOrder(), 3092 endian::InlHostByteOrder()); 3093 StringExtractorGDBRemote response; 3094 return SendThreadSpecificPacketAndWaitForResponse(tid, std::move(payload), 3095 response, false) == 3096 PacketResult::Success && 3097 response.IsOKResponse(); 3098 } 3099 3100 bool GDBRemoteCommunicationClient::SaveRegisterState(lldb::tid_t tid, 3101 uint32_t &save_id) { 3102 save_id = 0; // Set to invalid save ID 3103 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3104 return false; 3105 3106 m_supports_QSaveRegisterState = eLazyBoolYes; 3107 StreamString payload; 3108 payload.PutCString("QSaveRegisterState"); 3109 StringExtractorGDBRemote response; 3110 if (SendThreadSpecificPacketAndWaitForResponse( 3111 tid, std::move(payload), response, false) != PacketResult::Success) 3112 return false; 3113 3114 if (response.IsUnsupportedResponse()) 3115 m_supports_QSaveRegisterState = eLazyBoolNo; 3116 3117 const uint32_t response_save_id = response.GetU32(0); 3118 if (response_save_id == 0) 3119 return false; 3120 3121 save_id = response_save_id; 3122 return true; 3123 } 3124 3125 bool GDBRemoteCommunicationClient::RestoreRegisterState(lldb::tid_t tid, 3126 uint32_t save_id) { 3127 // We use the "m_supports_QSaveRegisterState" variable here because the 3128 // QSaveRegisterState and QRestoreRegisterState packets must both be supported 3129 // in 3130 // order to be useful 3131 if (m_supports_QSaveRegisterState == eLazyBoolNo) 3132 return false; 3133 3134 StreamString payload; 3135 payload.Printf("QRestoreRegisterState:%u", save_id); 3136 StringExtractorGDBRemote response; 3137 if (SendThreadSpecificPacketAndWaitForResponse( 3138 tid, std::move(payload), response, false) != PacketResult::Success) 3139 return false; 3140 3141 if (response.IsOKResponse()) 3142 return true; 3143 3144 if (response.IsUnsupportedResponse()) 3145 m_supports_QSaveRegisterState = eLazyBoolNo; 3146 return false; 3147 } 3148 3149 bool GDBRemoteCommunicationClient::SyncThreadState(lldb::tid_t tid) { 3150 if (!GetSyncThreadStateSupported()) 3151 return false; 3152 3153 StreamString packet; 3154 StringExtractorGDBRemote response; 3155 packet.Printf("QSyncThreadState:%4.4" PRIx64 ";", tid); 3156 return SendPacketAndWaitForResponse(packet.GetString(), response, false) == 3157 GDBRemoteCommunication::PacketResult::Success && 3158 response.IsOKResponse(); 3159 } 3160 3161 lldb::user_id_t 3162 GDBRemoteCommunicationClient::SendStartTracePacket(const TraceOptions &options, 3163 Status &error) { 3164 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3165 lldb::user_id_t ret_uid = LLDB_INVALID_UID; 3166 3167 StreamGDBRemote escaped_packet; 3168 escaped_packet.PutCString("jTraceStart:"); 3169 3170 StructuredData::Dictionary json_packet; 3171 json_packet.AddIntegerItem("type", options.getType()); 3172 json_packet.AddIntegerItem("buffersize", options.getTraceBufferSize()); 3173 json_packet.AddIntegerItem("metabuffersize", options.getMetaDataBufferSize()); 3174 3175 if (options.getThreadID() != LLDB_INVALID_THREAD_ID) 3176 json_packet.AddIntegerItem("threadid", options.getThreadID()); 3177 3178 StructuredData::DictionarySP custom_params = options.getTraceParams(); 3179 if (custom_params) 3180 json_packet.AddItem("params", custom_params); 3181 3182 StreamString json_string; 3183 json_packet.Dump(json_string, false); 3184 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3185 3186 StringExtractorGDBRemote response; 3187 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3188 true) == 3189 GDBRemoteCommunication::PacketResult::Success) { 3190 if (!response.IsNormalResponse()) { 3191 error = response.GetStatus(); 3192 LLDB_LOG(log, "Target does not support Tracing , error {0}", error); 3193 } else { 3194 ret_uid = response.GetHexMaxU64(false, LLDB_INVALID_UID); 3195 } 3196 } else { 3197 LLDB_LOG(log, "failed to send packet"); 3198 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3199 escaped_packet.GetData()); 3200 } 3201 return ret_uid; 3202 } 3203 3204 Status 3205 GDBRemoteCommunicationClient::SendStopTracePacket(lldb::user_id_t uid, 3206 lldb::tid_t thread_id) { 3207 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3208 StringExtractorGDBRemote response; 3209 Status error; 3210 3211 StructuredData::Dictionary json_packet; 3212 StreamGDBRemote escaped_packet; 3213 StreamString json_string; 3214 escaped_packet.PutCString("jTraceStop:"); 3215 3216 json_packet.AddIntegerItem("traceid", uid); 3217 3218 if (thread_id != LLDB_INVALID_THREAD_ID) 3219 json_packet.AddIntegerItem("threadid", thread_id); 3220 3221 json_packet.Dump(json_string, false); 3222 3223 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3224 3225 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3226 true) == 3227 GDBRemoteCommunication::PacketResult::Success) { 3228 if (!response.IsOKResponse()) { 3229 error = response.GetStatus(); 3230 LLDB_LOG(log, "stop tracing failed"); 3231 } 3232 } else { 3233 LLDB_LOG(log, "failed to send packet"); 3234 error.SetErrorStringWithFormat( 3235 "failed to send packet: '%s' with error '%d'", escaped_packet.GetData(), 3236 response.GetError()); 3237 } 3238 return error; 3239 } 3240 3241 Status GDBRemoteCommunicationClient::SendGetDataPacket( 3242 lldb::user_id_t uid, lldb::tid_t thread_id, 3243 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3244 3245 StreamGDBRemote escaped_packet; 3246 escaped_packet.PutCString("jTraceBufferRead:"); 3247 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset); 3248 } 3249 3250 Status GDBRemoteCommunicationClient::SendGetMetaDataPacket( 3251 lldb::user_id_t uid, lldb::tid_t thread_id, 3252 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3253 3254 StreamGDBRemote escaped_packet; 3255 escaped_packet.PutCString("jTraceMetaRead:"); 3256 return SendGetTraceDataPacket(escaped_packet, uid, thread_id, buffer, offset); 3257 } 3258 3259 Status 3260 GDBRemoteCommunicationClient::SendGetTraceConfigPacket(lldb::user_id_t uid, 3261 TraceOptions &options) { 3262 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3263 StringExtractorGDBRemote response; 3264 Status error; 3265 3266 StreamString json_string; 3267 StreamGDBRemote escaped_packet; 3268 escaped_packet.PutCString("jTraceConfigRead:"); 3269 3270 StructuredData::Dictionary json_packet; 3271 json_packet.AddIntegerItem("traceid", uid); 3272 3273 if (options.getThreadID() != LLDB_INVALID_THREAD_ID) 3274 json_packet.AddIntegerItem("threadid", options.getThreadID()); 3275 3276 json_packet.Dump(json_string, false); 3277 escaped_packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3278 3279 if (SendPacketAndWaitForResponse(escaped_packet.GetString(), response, 3280 true) == 3281 GDBRemoteCommunication::PacketResult::Success) { 3282 if (response.IsNormalResponse()) { 3283 uint64_t type = std::numeric_limits<uint64_t>::max(); 3284 uint64_t buffersize = std::numeric_limits<uint64_t>::max(); 3285 uint64_t metabuffersize = std::numeric_limits<uint64_t>::max(); 3286 3287 auto json_object = StructuredData::ParseJSON(response.Peek()); 3288 3289 if (!json_object || 3290 json_object->GetType() != lldb::eStructuredDataTypeDictionary) { 3291 error.SetErrorString("Invalid Configuration obtained"); 3292 return error; 3293 } 3294 3295 auto json_dict = json_object->GetAsDictionary(); 3296 3297 json_dict->GetValueForKeyAsInteger<uint64_t>("metabuffersize", 3298 metabuffersize); 3299 options.setMetaDataBufferSize(metabuffersize); 3300 3301 json_dict->GetValueForKeyAsInteger<uint64_t>("buffersize", buffersize); 3302 options.setTraceBufferSize(buffersize); 3303 3304 json_dict->GetValueForKeyAsInteger<uint64_t>("type", type); 3305 options.setType(static_cast<lldb::TraceType>(type)); 3306 3307 StructuredData::ObjectSP custom_params_sp = 3308 json_dict->GetValueForKey("params"); 3309 if (custom_params_sp) { 3310 if (custom_params_sp->GetType() != 3311 lldb::eStructuredDataTypeDictionary) { 3312 error.SetErrorString("Invalid Configuration obtained"); 3313 return error; 3314 } else 3315 options.setTraceParams( 3316 static_pointer_cast<StructuredData::Dictionary>( 3317 custom_params_sp)); 3318 } 3319 } else { 3320 error = response.GetStatus(); 3321 } 3322 } else { 3323 LLDB_LOG(log, "failed to send packet"); 3324 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3325 escaped_packet.GetData()); 3326 } 3327 return error; 3328 } 3329 3330 Status GDBRemoteCommunicationClient::SendGetTraceDataPacket( 3331 StreamGDBRemote &packet, lldb::user_id_t uid, lldb::tid_t thread_id, 3332 llvm::MutableArrayRef<uint8_t> &buffer, size_t offset) { 3333 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3334 Status error; 3335 3336 StructuredData::Dictionary json_packet; 3337 3338 json_packet.AddIntegerItem("traceid", uid); 3339 json_packet.AddIntegerItem("offset", offset); 3340 json_packet.AddIntegerItem("buffersize", buffer.size()); 3341 3342 if (thread_id != LLDB_INVALID_THREAD_ID) 3343 json_packet.AddIntegerItem("threadid", thread_id); 3344 3345 StreamString json_string; 3346 json_packet.Dump(json_string, false); 3347 3348 packet.PutEscapedBytes(json_string.GetData(), json_string.GetSize()); 3349 StringExtractorGDBRemote response; 3350 if (SendPacketAndWaitForResponse(packet.GetString(), response, true) == 3351 GDBRemoteCommunication::PacketResult::Success) { 3352 if (response.IsNormalResponse()) { 3353 size_t filled_size = response.GetHexBytesAvail(buffer); 3354 buffer = llvm::MutableArrayRef<uint8_t>(buffer.data(), filled_size); 3355 } else { 3356 error = response.GetStatus(); 3357 buffer = buffer.slice(buffer.size()); 3358 } 3359 } else { 3360 LLDB_LOG(log, "failed to send packet"); 3361 error.SetErrorStringWithFormat("failed to send packet: '%s'", 3362 packet.GetData()); 3363 buffer = buffer.slice(buffer.size()); 3364 } 3365 return error; 3366 } 3367 3368 bool GDBRemoteCommunicationClient::GetModuleInfo( 3369 const FileSpec &module_file_spec, const lldb_private::ArchSpec &arch_spec, 3370 ModuleSpec &module_spec) { 3371 if (!m_supports_qModuleInfo) 3372 return false; 3373 3374 std::string module_path = module_file_spec.GetPath(false); 3375 if (module_path.empty()) 3376 return false; 3377 3378 StreamString packet; 3379 packet.PutCString("qModuleInfo:"); 3380 packet.PutCStringAsRawHex8(module_path.c_str()); 3381 packet.PutCString(";"); 3382 const auto &triple = arch_spec.GetTriple().getTriple(); 3383 packet.PutCStringAsRawHex8(triple.c_str()); 3384 3385 StringExtractorGDBRemote response; 3386 if (SendPacketAndWaitForResponse(packet.GetString(), response, false) != 3387 PacketResult::Success) 3388 return false; 3389 3390 if (response.IsErrorResponse()) 3391 return false; 3392 3393 if (response.IsUnsupportedResponse()) { 3394 m_supports_qModuleInfo = false; 3395 return false; 3396 } 3397 3398 llvm::StringRef name; 3399 llvm::StringRef value; 3400 3401 module_spec.Clear(); 3402 module_spec.GetFileSpec() = module_file_spec; 3403 3404 while (response.GetNameColonValue(name, value)) { 3405 if (name == "uuid" || name == "md5") { 3406 StringExtractor extractor(value); 3407 std::string uuid; 3408 extractor.GetHexByteString(uuid); 3409 module_spec.GetUUID().SetFromCString(uuid.c_str(), uuid.size() / 2); 3410 } else if (name == "triple") { 3411 StringExtractor extractor(value); 3412 std::string triple; 3413 extractor.GetHexByteString(triple); 3414 module_spec.GetArchitecture().SetTriple(triple.c_str()); 3415 } else if (name == "file_offset") { 3416 uint64_t ival = 0; 3417 if (!value.getAsInteger(16, ival)) 3418 module_spec.SetObjectOffset(ival); 3419 } else if (name == "file_size") { 3420 uint64_t ival = 0; 3421 if (!value.getAsInteger(16, ival)) 3422 module_spec.SetObjectSize(ival); 3423 } else if (name == "file_path") { 3424 StringExtractor extractor(value); 3425 std::string path; 3426 extractor.GetHexByteString(path); 3427 module_spec.GetFileSpec() = FileSpec(path, false, arch_spec.GetTriple()); 3428 } 3429 } 3430 3431 return true; 3432 } 3433 3434 static llvm::Optional<ModuleSpec> 3435 ParseModuleSpec(StructuredData::Dictionary *dict) { 3436 ModuleSpec result; 3437 if (!dict) 3438 return llvm::None; 3439 3440 llvm::StringRef string; 3441 uint64_t integer; 3442 3443 if (!dict->GetValueForKeyAsString("uuid", string)) 3444 return llvm::None; 3445 result.GetUUID().SetFromStringRef(string, string.size()); 3446 3447 if (!dict->GetValueForKeyAsInteger("file_offset", integer)) 3448 return llvm::None; 3449 result.SetObjectOffset(integer); 3450 3451 if (!dict->GetValueForKeyAsInteger("file_size", integer)) 3452 return llvm::None; 3453 result.SetObjectSize(integer); 3454 3455 if (!dict->GetValueForKeyAsString("triple", string)) 3456 return llvm::None; 3457 result.GetArchitecture().SetTriple(string); 3458 3459 if (!dict->GetValueForKeyAsString("file_path", string)) 3460 return llvm::None; 3461 result.GetFileSpec() = 3462 FileSpec(string, false, result.GetArchitecture().GetTriple()); 3463 3464 return result; 3465 } 3466 3467 llvm::Optional<std::vector<ModuleSpec>> 3468 GDBRemoteCommunicationClient::GetModulesInfo( 3469 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) { 3470 if (!m_supports_jModulesInfo) 3471 return llvm::None; 3472 3473 JSONArray::SP module_array_sp = std::make_shared<JSONArray>(); 3474 for (const FileSpec &module_file_spec : module_file_specs) { 3475 JSONObject::SP module_sp = std::make_shared<JSONObject>(); 3476 module_array_sp->AppendObject(module_sp); 3477 module_sp->SetObject( 3478 "file", std::make_shared<JSONString>(module_file_spec.GetPath(false))); 3479 module_sp->SetObject("triple", 3480 std::make_shared<JSONString>(triple.getTriple())); 3481 } 3482 StreamString unescaped_payload; 3483 unescaped_payload.PutCString("jModulesInfo:"); 3484 module_array_sp->Write(unescaped_payload); 3485 StreamGDBRemote payload; 3486 payload.PutEscapedBytes(unescaped_payload.GetString().data(), 3487 unescaped_payload.GetSize()); 3488 3489 // Increase the timeout for jModulesInfo since this packet can take longer. 3490 ScopedTimeout timeout(*this, std::chrono::seconds(10)); 3491 3492 StringExtractorGDBRemote response; 3493 if (SendPacketAndWaitForResponse(payload.GetString(), response, false) != 3494 PacketResult::Success || 3495 response.IsErrorResponse()) 3496 return llvm::None; 3497 3498 if (response.IsUnsupportedResponse()) { 3499 m_supports_jModulesInfo = false; 3500 return llvm::None; 3501 } 3502 3503 StructuredData::ObjectSP response_object_sp = 3504 StructuredData::ParseJSON(response.GetStringRef()); 3505 if (!response_object_sp) 3506 return llvm::None; 3507 3508 StructuredData::Array *response_array = response_object_sp->GetAsArray(); 3509 if (!response_array) 3510 return llvm::None; 3511 3512 std::vector<ModuleSpec> result; 3513 for (size_t i = 0; i < response_array->GetSize(); ++i) { 3514 if (llvm::Optional<ModuleSpec> module_spec = ParseModuleSpec( 3515 response_array->GetItemAtIndex(i)->GetAsDictionary())) 3516 result.push_back(*module_spec); 3517 } 3518 3519 return result; 3520 } 3521 3522 // query the target remote for extended information using the qXfer packet 3523 // 3524 // example: object='features', annex='target.xml', out=<xml output> 3525 // return: 'true' on success 3526 // 'false' on failure (err set) 3527 bool GDBRemoteCommunicationClient::ReadExtFeature( 3528 const lldb_private::ConstString object, 3529 const lldb_private::ConstString annex, std::string &out, 3530 lldb_private::Status &err) { 3531 3532 std::stringstream output; 3533 StringExtractorGDBRemote chunk; 3534 3535 uint64_t size = GetRemoteMaxPacketSize(); 3536 if (size == 0) 3537 size = 0x1000; 3538 size = size - 1; // Leave space for the 'm' or 'l' character in the response 3539 int offset = 0; 3540 bool active = true; 3541 3542 // loop until all data has been read 3543 while (active) { 3544 3545 // send query extended feature packet 3546 std::stringstream packet; 3547 packet << "qXfer:" << object.AsCString("") 3548 << ":read:" << annex.AsCString("") << ":" << std::hex << offset 3549 << "," << std::hex << size; 3550 3551 GDBRemoteCommunication::PacketResult res = 3552 SendPacketAndWaitForResponse(packet.str(), chunk, false); 3553 3554 if (res != GDBRemoteCommunication::PacketResult::Success) { 3555 err.SetErrorString("Error sending $qXfer packet"); 3556 return false; 3557 } 3558 3559 const std::string &str = chunk.GetStringRef(); 3560 if (str.length() == 0) { 3561 // should have some data in chunk 3562 err.SetErrorString("Empty response from $qXfer packet"); 3563 return false; 3564 } 3565 3566 // check packet code 3567 switch (str[0]) { 3568 // last chunk 3569 case ('l'): 3570 active = false; 3571 LLVM_FALLTHROUGH; 3572 3573 // more chunks 3574 case ('m'): 3575 if (str.length() > 1) 3576 output << &str[1]; 3577 offset += size; 3578 break; 3579 3580 // unknown chunk 3581 default: 3582 err.SetErrorString("Invalid continuation code from $qXfer packet"); 3583 return false; 3584 } 3585 } 3586 3587 out = output.str(); 3588 err.Success(); 3589 return true; 3590 } 3591 3592 // Notify the target that gdb is prepared to serve symbol lookup requests. 3593 // packet: "qSymbol::" 3594 // reply: 3595 // OK The target does not need to look up any (more) symbols. 3596 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex 3597 // encoded). 3598 // LLDB may provide the value by sending another qSymbol 3599 // packet 3600 // in the form of"qSymbol:<sym_value>:<sym_name>". 3601 // 3602 // Three examples: 3603 // 3604 // lldb sends: qSymbol:: 3605 // lldb receives: OK 3606 // Remote gdb stub does not need to know the addresses of any symbols, lldb 3607 // does not 3608 // need to ask again in this session. 3609 // 3610 // lldb sends: qSymbol:: 3611 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3612 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473 3613 // lldb receives: OK 3614 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does 3615 // not know 3616 // the address at this time. lldb needs to send qSymbol:: again when it has 3617 // more 3618 // solibs loaded. 3619 // 3620 // lldb sends: qSymbol:: 3621 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 3622 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473 3623 // lldb receives: OK 3624 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says 3625 // that it 3626 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it 3627 // does not 3628 // need any more symbols. lldb does not need to ask again in this session. 3629 3630 void GDBRemoteCommunicationClient::ServeSymbolLookups( 3631 lldb_private::Process *process) { 3632 // Set to true once we've resolved a symbol to an address for the remote stub. 3633 // If we get an 'OK' response after this, the remote stub doesn't need any 3634 // more 3635 // symbols and we can stop asking. 3636 bool symbol_response_provided = false; 3637 3638 // Is this the initial qSymbol:: packet? 3639 bool first_qsymbol_query = true; 3640 3641 if (m_supports_qSymbol && m_qSymbol_requests_done == false) { 3642 Lock lock(*this, false); 3643 if (lock) { 3644 StreamString packet; 3645 packet.PutCString("qSymbol::"); 3646 StringExtractorGDBRemote response; 3647 while (SendPacketAndWaitForResponseNoLock(packet.GetString(), response) == 3648 PacketResult::Success) { 3649 if (response.IsOKResponse()) { 3650 if (symbol_response_provided || first_qsymbol_query) { 3651 m_qSymbol_requests_done = true; 3652 } 3653 3654 // We are done serving symbols requests 3655 return; 3656 } 3657 first_qsymbol_query = false; 3658 3659 if (response.IsUnsupportedResponse()) { 3660 // qSymbol is not supported by the current GDB server we are connected 3661 // to 3662 m_supports_qSymbol = false; 3663 return; 3664 } else { 3665 llvm::StringRef response_str(response.GetStringRef()); 3666 if (response_str.startswith("qSymbol:")) { 3667 response.SetFilePos(strlen("qSymbol:")); 3668 std::string symbol_name; 3669 if (response.GetHexByteString(symbol_name)) { 3670 if (symbol_name.empty()) 3671 return; 3672 3673 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS; 3674 lldb_private::SymbolContextList sc_list; 3675 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType( 3676 ConstString(symbol_name), eSymbolTypeAny, sc_list)) { 3677 const size_t num_scs = sc_list.GetSize(); 3678 for (size_t sc_idx = 0; 3679 sc_idx < num_scs && 3680 symbol_load_addr == LLDB_INVALID_ADDRESS; 3681 ++sc_idx) { 3682 SymbolContext sc; 3683 if (sc_list.GetContextAtIndex(sc_idx, sc)) { 3684 if (sc.symbol) { 3685 switch (sc.symbol->GetType()) { 3686 case eSymbolTypeInvalid: 3687 case eSymbolTypeAbsolute: 3688 case eSymbolTypeUndefined: 3689 case eSymbolTypeSourceFile: 3690 case eSymbolTypeHeaderFile: 3691 case eSymbolTypeObjectFile: 3692 case eSymbolTypeCommonBlock: 3693 case eSymbolTypeBlock: 3694 case eSymbolTypeLocal: 3695 case eSymbolTypeParam: 3696 case eSymbolTypeVariable: 3697 case eSymbolTypeVariableType: 3698 case eSymbolTypeLineEntry: 3699 case eSymbolTypeLineHeader: 3700 case eSymbolTypeScopeBegin: 3701 case eSymbolTypeScopeEnd: 3702 case eSymbolTypeAdditional: 3703 case eSymbolTypeCompiler: 3704 case eSymbolTypeInstrumentation: 3705 case eSymbolTypeTrampoline: 3706 break; 3707 3708 case eSymbolTypeCode: 3709 case eSymbolTypeResolver: 3710 case eSymbolTypeData: 3711 case eSymbolTypeRuntime: 3712 case eSymbolTypeException: 3713 case eSymbolTypeObjCClass: 3714 case eSymbolTypeObjCMetaClass: 3715 case eSymbolTypeObjCIVar: 3716 case eSymbolTypeReExported: 3717 symbol_load_addr = 3718 sc.symbol->GetLoadAddress(&process->GetTarget()); 3719 break; 3720 } 3721 } 3722 } 3723 } 3724 } 3725 // This is the normal path where our symbol lookup was successful 3726 // and we want 3727 // to send a packet with the new symbol value and see if another 3728 // lookup needs to be 3729 // done. 3730 3731 // Change "packet" to contain the requested symbol value and name 3732 packet.Clear(); 3733 packet.PutCString("qSymbol:"); 3734 if (symbol_load_addr != LLDB_INVALID_ADDRESS) { 3735 packet.Printf("%" PRIx64, symbol_load_addr); 3736 symbol_response_provided = true; 3737 } else { 3738 symbol_response_provided = false; 3739 } 3740 packet.PutCString(":"); 3741 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size()); 3742 continue; // go back to the while loop and send "packet" and wait 3743 // for another response 3744 } 3745 } 3746 } 3747 } 3748 // If we make it here, the symbol request packet response wasn't valid or 3749 // our symbol lookup failed so we must abort 3750 return; 3751 3752 } else if (Log *log = ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( 3753 GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)) { 3754 log->Printf( 3755 "GDBRemoteCommunicationClient::%s: Didn't get sequence mutex.", 3756 __FUNCTION__); 3757 } 3758 } 3759 } 3760 3761 StructuredData::Array * 3762 GDBRemoteCommunicationClient::GetSupportedStructuredDataPlugins() { 3763 if (!m_supported_async_json_packets_is_valid) { 3764 // Query the server for the array of supported asynchronous JSON 3765 // packets. 3766 m_supported_async_json_packets_is_valid = true; 3767 3768 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3769 3770 // Poll it now. 3771 StringExtractorGDBRemote response; 3772 const bool send_async = false; 3773 if (SendPacketAndWaitForResponse("qStructuredDataPlugins", response, 3774 send_async) == PacketResult::Success) { 3775 m_supported_async_json_packets_sp = 3776 StructuredData::ParseJSON(response.GetStringRef()); 3777 if (m_supported_async_json_packets_sp && 3778 !m_supported_async_json_packets_sp->GetAsArray()) { 3779 // We were returned something other than a JSON array. This 3780 // is invalid. Clear it out. 3781 if (log) 3782 log->Printf("GDBRemoteCommunicationClient::%s(): " 3783 "QSupportedAsyncJSONPackets returned invalid " 3784 "result: %s", 3785 __FUNCTION__, response.GetStringRef().c_str()); 3786 m_supported_async_json_packets_sp.reset(); 3787 } 3788 } else { 3789 if (log) 3790 log->Printf("GDBRemoteCommunicationClient::%s(): " 3791 "QSupportedAsyncJSONPackets unsupported", 3792 __FUNCTION__); 3793 } 3794 3795 if (log && m_supported_async_json_packets_sp) { 3796 StreamString stream; 3797 m_supported_async_json_packets_sp->Dump(stream); 3798 log->Printf("GDBRemoteCommunicationClient::%s(): supported async " 3799 "JSON packets: %s", 3800 __FUNCTION__, stream.GetData()); 3801 } 3802 } 3803 3804 return m_supported_async_json_packets_sp 3805 ? m_supported_async_json_packets_sp->GetAsArray() 3806 : nullptr; 3807 } 3808 3809 Status GDBRemoteCommunicationClient::SendSignalsToIgnore( 3810 llvm::ArrayRef<int32_t> signals) { 3811 // Format packet: 3812 // QPassSignals:<hex_sig1>;<hex_sig2>...;<hex_sigN> 3813 auto range = llvm::make_range(signals.begin(), signals.end()); 3814 std::string packet = formatv("QPassSignals:{0:$[;]@(x-2)}", range).str(); 3815 3816 StringExtractorGDBRemote response; 3817 auto send_status = SendPacketAndWaitForResponse(packet, response, false); 3818 3819 if (send_status != GDBRemoteCommunication::PacketResult::Success) 3820 return Status("Sending QPassSignals packet failed"); 3821 3822 if (response.IsOKResponse()) { 3823 return Status(); 3824 } else { 3825 return Status("Unknown error happened during sending QPassSignals packet."); 3826 } 3827 } 3828 3829 Status GDBRemoteCommunicationClient::ConfigureRemoteStructuredData( 3830 const ConstString &type_name, const StructuredData::ObjectSP &config_sp) { 3831 Status error; 3832 3833 if (type_name.GetLength() == 0) { 3834 error.SetErrorString("invalid type_name argument"); 3835 return error; 3836 } 3837 3838 // Build command: Configure{type_name}: serialized config 3839 // data. 3840 StreamGDBRemote stream; 3841 stream.PutCString("QConfigure"); 3842 stream.PutCString(type_name.AsCString()); 3843 stream.PutChar(':'); 3844 if (config_sp) { 3845 // Gather the plain-text version of the configuration data. 3846 StreamString unescaped_stream; 3847 config_sp->Dump(unescaped_stream); 3848 unescaped_stream.Flush(); 3849 3850 // Add it to the stream in escaped fashion. 3851 stream.PutEscapedBytes(unescaped_stream.GetString().data(), 3852 unescaped_stream.GetSize()); 3853 } 3854 stream.Flush(); 3855 3856 // Send the packet. 3857 const bool send_async = false; 3858 StringExtractorGDBRemote response; 3859 auto result = 3860 SendPacketAndWaitForResponse(stream.GetString(), response, send_async); 3861 if (result == PacketResult::Success) { 3862 // We failed if the config result comes back other than OK. 3863 if (strcmp(response.GetStringRef().c_str(), "OK") == 0) { 3864 // Okay! 3865 error.Clear(); 3866 } else { 3867 error.SetErrorStringWithFormat("configuring StructuredData feature " 3868 "%s failed with error %s", 3869 type_name.AsCString(), 3870 response.GetStringRef().c_str()); 3871 } 3872 } else { 3873 // Can we get more data here on the failure? 3874 error.SetErrorStringWithFormat("configuring StructuredData feature %s " 3875 "failed when sending packet: " 3876 "PacketResult=%d", 3877 type_name.AsCString(), (int)result); 3878 } 3879 return error; 3880 } 3881 3882 void GDBRemoteCommunicationClient::OnRunPacketSent(bool first) { 3883 GDBRemoteClientBase::OnRunPacketSent(first); 3884 m_curr_tid = LLDB_INVALID_THREAD_ID; 3885 } 3886