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