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