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