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