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