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 { 2069 Args::StringToVersion (value.c_str(), 2070 m_os_version_major, 2071 m_os_version_minor, 2072 m_os_version_update); 2073 if (m_os_version_major != UINT32_MAX) 2074 ++num_keys_decoded; 2075 } 2076 else if (name.compare("watchpoint_exceptions_received") == 0) 2077 { 2078 ++num_keys_decoded; 2079 if (strcmp(value.c_str(),"before") == 0) 2080 m_watchpoints_trigger_after_instruction = eLazyBoolNo; 2081 else if (strcmp(value.c_str(),"after") == 0) 2082 m_watchpoints_trigger_after_instruction = eLazyBoolYes; 2083 else 2084 --num_keys_decoded; 2085 } 2086 else if (name.compare("default_packet_timeout") == 0) 2087 { 2088 m_default_packet_timeout = StringConvert::ToUInt32(value.c_str(), 0); 2089 if (m_default_packet_timeout > 0) 2090 { 2091 SetPacketTimeout(m_default_packet_timeout); 2092 ++num_keys_decoded; 2093 } 2094 } 2095 2096 } 2097 2098 if (num_keys_decoded > 0) 2099 m_qHostInfo_is_valid = eLazyBoolYes; 2100 2101 if (triple.empty()) 2102 { 2103 if (arch_name.empty()) 2104 { 2105 if (cpu != LLDB_INVALID_CPUTYPE) 2106 { 2107 m_host_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 2108 if (pointer_byte_size) 2109 { 2110 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 2111 } 2112 if (byte_order != eByteOrderInvalid) 2113 { 2114 assert (byte_order == m_host_arch.GetByteOrder()); 2115 } 2116 2117 if (!os_name.empty() && vendor_name.compare("apple") == 0 && os_name.find("darwin") == 0) 2118 { 2119 switch (m_host_arch.GetMachine()) 2120 { 2121 case llvm::Triple::aarch64: 2122 case llvm::Triple::arm: 2123 case llvm::Triple::thumb: 2124 os_name = "ios"; 2125 break; 2126 default: 2127 os_name = "macosx"; 2128 break; 2129 } 2130 } 2131 if (!vendor_name.empty()) 2132 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 2133 if (!os_name.empty()) 2134 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 2135 2136 } 2137 } 2138 else 2139 { 2140 std::string triple; 2141 triple += arch_name; 2142 if (!vendor_name.empty() || !os_name.empty()) 2143 { 2144 triple += '-'; 2145 if (vendor_name.empty()) 2146 triple += "unknown"; 2147 else 2148 triple += vendor_name; 2149 triple += '-'; 2150 if (os_name.empty()) 2151 triple += "unknown"; 2152 else 2153 triple += os_name; 2154 } 2155 m_host_arch.SetTriple (triple.c_str()); 2156 2157 llvm::Triple &host_triple = m_host_arch.GetTriple(); 2158 if (host_triple.getVendor() == llvm::Triple::Apple && host_triple.getOS() == llvm::Triple::Darwin) 2159 { 2160 switch (m_host_arch.GetMachine()) 2161 { 2162 case llvm::Triple::aarch64: 2163 case llvm::Triple::arm: 2164 case llvm::Triple::thumb: 2165 host_triple.setOS(llvm::Triple::IOS); 2166 break; 2167 default: 2168 host_triple.setOS(llvm::Triple::MacOSX); 2169 break; 2170 } 2171 } 2172 if (pointer_byte_size) 2173 { 2174 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 2175 } 2176 if (byte_order != eByteOrderInvalid) 2177 { 2178 assert (byte_order == m_host_arch.GetByteOrder()); 2179 } 2180 2181 } 2182 } 2183 else 2184 { 2185 m_host_arch.SetTriple (triple.c_str()); 2186 if (pointer_byte_size) 2187 { 2188 assert (pointer_byte_size == m_host_arch.GetAddressByteSize()); 2189 } 2190 if (byte_order != eByteOrderInvalid) 2191 { 2192 assert (byte_order == m_host_arch.GetByteOrder()); 2193 } 2194 2195 if (log) 2196 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 ()); 2197 } 2198 if (!distribution_id.empty ()) 2199 m_host_arch.SetDistributionId (distribution_id.c_str ()); 2200 } 2201 } 2202 } 2203 return m_qHostInfo_is_valid == eLazyBoolYes; 2204 } 2205 2206 int 2207 GDBRemoteCommunicationClient::SendAttach 2208 ( 2209 lldb::pid_t pid, 2210 StringExtractorGDBRemote& response 2211 ) 2212 { 2213 if (pid != LLDB_INVALID_PROCESS_ID) 2214 { 2215 char packet[64]; 2216 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, pid); 2217 assert (packet_len < (int)sizeof(packet)); 2218 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2219 { 2220 if (response.IsErrorResponse()) 2221 return response.GetError(); 2222 return 0; 2223 } 2224 } 2225 return -1; 2226 } 2227 2228 int 2229 GDBRemoteCommunicationClient::SendStdinNotification (const char* data, size_t data_len) 2230 { 2231 StreamString packet; 2232 packet.PutCString("I"); 2233 packet.PutBytesAsRawHex8(data, data_len); 2234 StringExtractorGDBRemote response; 2235 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2236 { 2237 return 0; 2238 } 2239 return response.GetError(); 2240 2241 } 2242 2243 const lldb_private::ArchSpec & 2244 GDBRemoteCommunicationClient::GetHostArchitecture () 2245 { 2246 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 2247 GetHostInfo (); 2248 return m_host_arch; 2249 } 2250 2251 uint32_t 2252 GDBRemoteCommunicationClient::GetHostDefaultPacketTimeout () 2253 { 2254 if (m_qHostInfo_is_valid == eLazyBoolCalculate) 2255 GetHostInfo (); 2256 return m_default_packet_timeout; 2257 } 2258 2259 addr_t 2260 GDBRemoteCommunicationClient::AllocateMemory (size_t size, uint32_t permissions) 2261 { 2262 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 2263 { 2264 m_supports_alloc_dealloc_memory = eLazyBoolYes; 2265 char packet[64]; 2266 const int packet_len = ::snprintf (packet, sizeof(packet), "_M%" PRIx64 ",%s%s%s", 2267 (uint64_t)size, 2268 permissions & lldb::ePermissionsReadable ? "r" : "", 2269 permissions & lldb::ePermissionsWritable ? "w" : "", 2270 permissions & lldb::ePermissionsExecutable ? "x" : ""); 2271 assert (packet_len < (int)sizeof(packet)); 2272 StringExtractorGDBRemote response; 2273 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2274 { 2275 if (response.IsUnsupportedResponse()) 2276 m_supports_alloc_dealloc_memory = eLazyBoolNo; 2277 else if (!response.IsErrorResponse()) 2278 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 2279 } 2280 else 2281 { 2282 m_supports_alloc_dealloc_memory = eLazyBoolNo; 2283 } 2284 } 2285 return LLDB_INVALID_ADDRESS; 2286 } 2287 2288 bool 2289 GDBRemoteCommunicationClient::DeallocateMemory (addr_t addr) 2290 { 2291 if (m_supports_alloc_dealloc_memory != eLazyBoolNo) 2292 { 2293 m_supports_alloc_dealloc_memory = eLazyBoolYes; 2294 char packet[64]; 2295 const int packet_len = ::snprintf(packet, sizeof(packet), "_m%" PRIx64, (uint64_t)addr); 2296 assert (packet_len < (int)sizeof(packet)); 2297 StringExtractorGDBRemote response; 2298 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2299 { 2300 if (response.IsUnsupportedResponse()) 2301 m_supports_alloc_dealloc_memory = eLazyBoolNo; 2302 else if (response.IsOKResponse()) 2303 return true; 2304 } 2305 else 2306 { 2307 m_supports_alloc_dealloc_memory = eLazyBoolNo; 2308 } 2309 } 2310 return false; 2311 } 2312 2313 Error 2314 GDBRemoteCommunicationClient::Detach (bool keep_stopped) 2315 { 2316 Error error; 2317 2318 if (keep_stopped) 2319 { 2320 if (m_supports_detach_stay_stopped == eLazyBoolCalculate) 2321 { 2322 char packet[64]; 2323 const int packet_len = ::snprintf(packet, sizeof(packet), "qSupportsDetachAndStayStopped:"); 2324 assert (packet_len < (int)sizeof(packet)); 2325 StringExtractorGDBRemote response; 2326 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success 2327 && response.IsOKResponse()) 2328 { 2329 m_supports_detach_stay_stopped = eLazyBoolYes; 2330 } 2331 else 2332 { 2333 m_supports_detach_stay_stopped = eLazyBoolNo; 2334 } 2335 } 2336 2337 if (m_supports_detach_stay_stopped == eLazyBoolNo) 2338 { 2339 error.SetErrorString("Stays stopped not supported by this target."); 2340 return error; 2341 } 2342 else 2343 { 2344 StringExtractorGDBRemote response; 2345 PacketResult packet_result = SendPacketAndWaitForResponse ("D1", 2, response, false); 2346 if (packet_result != PacketResult::Success) 2347 error.SetErrorString ("Sending extended disconnect packet failed."); 2348 } 2349 } 2350 else 2351 { 2352 StringExtractorGDBRemote response; 2353 PacketResult packet_result = SendPacketAndWaitForResponse ("D", 1, response, false); 2354 if (packet_result != PacketResult::Success) 2355 error.SetErrorString ("Sending disconnect packet failed."); 2356 } 2357 return error; 2358 } 2359 2360 Error 2361 GDBRemoteCommunicationClient::GetMemoryRegionInfo (lldb::addr_t addr, 2362 lldb_private::MemoryRegionInfo ®ion_info) 2363 { 2364 Error error; 2365 region_info.Clear(); 2366 2367 if (m_supports_memory_region_info != eLazyBoolNo) 2368 { 2369 m_supports_memory_region_info = eLazyBoolYes; 2370 char packet[64]; 2371 const int packet_len = ::snprintf(packet, sizeof(packet), "qMemoryRegionInfo:%" PRIx64, (uint64_t)addr); 2372 assert (packet_len < (int)sizeof(packet)); 2373 StringExtractorGDBRemote response; 2374 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2375 { 2376 std::string name; 2377 std::string value; 2378 addr_t addr_value; 2379 bool success = true; 2380 bool saw_permissions = false; 2381 while (success && response.GetNameColonValue(name, value)) 2382 { 2383 if (name.compare ("start") == 0) 2384 { 2385 addr_value = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16, &success); 2386 if (success) 2387 region_info.GetRange().SetRangeBase(addr_value); 2388 } 2389 else if (name.compare ("size") == 0) 2390 { 2391 addr_value = StringConvert::ToUInt64(value.c_str(), 0, 16, &success); 2392 if (success) 2393 region_info.GetRange().SetByteSize (addr_value); 2394 } 2395 else if (name.compare ("permissions") == 0 && region_info.GetRange().IsValid()) 2396 { 2397 saw_permissions = true; 2398 if (region_info.GetRange().Contains (addr)) 2399 { 2400 if (value.find('r') != std::string::npos) 2401 region_info.SetReadable (MemoryRegionInfo::eYes); 2402 else 2403 region_info.SetReadable (MemoryRegionInfo::eNo); 2404 2405 if (value.find('w') != std::string::npos) 2406 region_info.SetWritable (MemoryRegionInfo::eYes); 2407 else 2408 region_info.SetWritable (MemoryRegionInfo::eNo); 2409 2410 if (value.find('x') != std::string::npos) 2411 region_info.SetExecutable (MemoryRegionInfo::eYes); 2412 else 2413 region_info.SetExecutable (MemoryRegionInfo::eNo); 2414 } 2415 else 2416 { 2417 // The reported region does not contain this address -- we're looking at an unmapped page 2418 region_info.SetReadable (MemoryRegionInfo::eNo); 2419 region_info.SetWritable (MemoryRegionInfo::eNo); 2420 region_info.SetExecutable (MemoryRegionInfo::eNo); 2421 } 2422 } 2423 else if (name.compare ("error") == 0) 2424 { 2425 StringExtractorGDBRemote name_extractor; 2426 // Swap "value" over into "name_extractor" 2427 name_extractor.GetStringRef().swap(value); 2428 // Now convert the HEX bytes into a string value 2429 name_extractor.GetHexByteString (value); 2430 error.SetErrorString(value.c_str()); 2431 } 2432 } 2433 2434 // We got a valid address range back but no permissions -- which means this is an unmapped page 2435 if (region_info.GetRange().IsValid() && saw_permissions == false) 2436 { 2437 region_info.SetReadable (MemoryRegionInfo::eNo); 2438 region_info.SetWritable (MemoryRegionInfo::eNo); 2439 region_info.SetExecutable (MemoryRegionInfo::eNo); 2440 } 2441 } 2442 else 2443 { 2444 m_supports_memory_region_info = eLazyBoolNo; 2445 } 2446 } 2447 2448 if (m_supports_memory_region_info == eLazyBoolNo) 2449 { 2450 error.SetErrorString("qMemoryRegionInfo is not supported"); 2451 } 2452 if (error.Fail()) 2453 region_info.Clear(); 2454 return error; 2455 2456 } 2457 2458 Error 2459 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num) 2460 { 2461 Error error; 2462 2463 if (m_supports_watchpoint_support_info == eLazyBoolYes) 2464 { 2465 num = m_num_supported_hardware_watchpoints; 2466 return error; 2467 } 2468 2469 // Set num to 0 first. 2470 num = 0; 2471 if (m_supports_watchpoint_support_info != eLazyBoolNo) 2472 { 2473 char packet[64]; 2474 const int packet_len = ::snprintf(packet, sizeof(packet), "qWatchpointSupportInfo:"); 2475 assert (packet_len < (int)sizeof(packet)); 2476 StringExtractorGDBRemote response; 2477 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2478 { 2479 m_supports_watchpoint_support_info = eLazyBoolYes; 2480 std::string name; 2481 std::string value; 2482 while (response.GetNameColonValue(name, value)) 2483 { 2484 if (name.compare ("num") == 0) 2485 { 2486 num = StringConvert::ToUInt32(value.c_str(), 0, 0); 2487 m_num_supported_hardware_watchpoints = num; 2488 } 2489 } 2490 } 2491 else 2492 { 2493 m_supports_watchpoint_support_info = eLazyBoolNo; 2494 } 2495 } 2496 2497 if (m_supports_watchpoint_support_info == eLazyBoolNo) 2498 { 2499 error.SetErrorString("qWatchpointSupportInfo is not supported"); 2500 } 2501 return error; 2502 2503 } 2504 2505 lldb_private::Error 2506 GDBRemoteCommunicationClient::GetWatchpointSupportInfo (uint32_t &num, bool& after, const ArchSpec &arch) 2507 { 2508 Error error(GetWatchpointSupportInfo(num)); 2509 if (error.Success()) 2510 error = GetWatchpointsTriggerAfterInstruction(after, arch); 2511 return error; 2512 } 2513 2514 lldb_private::Error 2515 GDBRemoteCommunicationClient::GetWatchpointsTriggerAfterInstruction (bool &after, const ArchSpec &arch) 2516 { 2517 Error error; 2518 llvm::Triple::ArchType atype = arch.GetMachine(); 2519 2520 // we assume watchpoints will happen after running the relevant opcode 2521 // and we only want to override this behavior if we have explicitly 2522 // received a qHostInfo telling us otherwise 2523 if (m_qHostInfo_is_valid != eLazyBoolYes) 2524 { 2525 // On targets like MIPS, watchpoint exceptions are always generated 2526 // before the instruction is executed. The connected target may not 2527 // support qHostInfo or qWatchpointSupportInfo packets. 2528 if (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel 2529 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el) 2530 after = false; 2531 else 2532 after = true; 2533 } 2534 else 2535 { 2536 // For MIPS, set m_watchpoints_trigger_after_instruction to eLazyBoolNo 2537 // if it is not calculated before. 2538 if (m_watchpoints_trigger_after_instruction == eLazyBoolCalculate && 2539 (atype == llvm::Triple::mips || atype == llvm::Triple::mipsel 2540 || atype == llvm::Triple::mips64 || atype == llvm::Triple::mips64el)) 2541 m_watchpoints_trigger_after_instruction = eLazyBoolNo; 2542 2543 after = (m_watchpoints_trigger_after_instruction != eLazyBoolNo); 2544 } 2545 return error; 2546 } 2547 2548 int 2549 GDBRemoteCommunicationClient::SetSTDIN(const FileSpec &file_spec) 2550 { 2551 if (file_spec) 2552 { 2553 std::string path{file_spec.GetPath(false)}; 2554 StreamString packet; 2555 packet.PutCString("QSetSTDIN:"); 2556 packet.PutCStringAsRawHex8(path.c_str()); 2557 2558 StringExtractorGDBRemote response; 2559 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2560 { 2561 if (response.IsOKResponse()) 2562 return 0; 2563 uint8_t error = response.GetError(); 2564 if (error) 2565 return error; 2566 } 2567 } 2568 return -1; 2569 } 2570 2571 int 2572 GDBRemoteCommunicationClient::SetSTDOUT(const FileSpec &file_spec) 2573 { 2574 if (file_spec) 2575 { 2576 std::string path{file_spec.GetPath(false)}; 2577 StreamString packet; 2578 packet.PutCString("QSetSTDOUT:"); 2579 packet.PutCStringAsRawHex8(path.c_str()); 2580 2581 StringExtractorGDBRemote response; 2582 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2583 { 2584 if (response.IsOKResponse()) 2585 return 0; 2586 uint8_t error = response.GetError(); 2587 if (error) 2588 return error; 2589 } 2590 } 2591 return -1; 2592 } 2593 2594 int 2595 GDBRemoteCommunicationClient::SetSTDERR(const FileSpec &file_spec) 2596 { 2597 if (file_spec) 2598 { 2599 std::string path{file_spec.GetPath(false)}; 2600 StreamString packet; 2601 packet.PutCString("QSetSTDERR:"); 2602 packet.PutCStringAsRawHex8(path.c_str()); 2603 2604 StringExtractorGDBRemote response; 2605 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2606 { 2607 if (response.IsOKResponse()) 2608 return 0; 2609 uint8_t error = response.GetError(); 2610 if (error) 2611 return error; 2612 } 2613 } 2614 return -1; 2615 } 2616 2617 bool 2618 GDBRemoteCommunicationClient::GetWorkingDir(FileSpec &working_dir) 2619 { 2620 StringExtractorGDBRemote response; 2621 if (SendPacketAndWaitForResponse ("qGetWorkingDir", response, false) == PacketResult::Success) 2622 { 2623 if (response.IsUnsupportedResponse()) 2624 return false; 2625 if (response.IsErrorResponse()) 2626 return false; 2627 std::string cwd; 2628 response.GetHexByteString(cwd); 2629 working_dir.SetFile(cwd, false, GetHostArchitecture()); 2630 return !cwd.empty(); 2631 } 2632 return false; 2633 } 2634 2635 int 2636 GDBRemoteCommunicationClient::SetWorkingDir(const FileSpec &working_dir) 2637 { 2638 if (working_dir) 2639 { 2640 std::string path{working_dir.GetPath(false)}; 2641 StreamString packet; 2642 packet.PutCString("QSetWorkingDir:"); 2643 packet.PutCStringAsRawHex8(path.c_str()); 2644 2645 StringExtractorGDBRemote response; 2646 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 2647 { 2648 if (response.IsOKResponse()) 2649 return 0; 2650 uint8_t error = response.GetError(); 2651 if (error) 2652 return error; 2653 } 2654 } 2655 return -1; 2656 } 2657 2658 int 2659 GDBRemoteCommunicationClient::SetDisableASLR (bool enable) 2660 { 2661 char packet[32]; 2662 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDisableASLR:%i", enable ? 1 : 0); 2663 assert (packet_len < (int)sizeof(packet)); 2664 StringExtractorGDBRemote response; 2665 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2666 { 2667 if (response.IsOKResponse()) 2668 return 0; 2669 uint8_t error = response.GetError(); 2670 if (error) 2671 return error; 2672 } 2673 return -1; 2674 } 2675 2676 int 2677 GDBRemoteCommunicationClient::SetDetachOnError (bool enable) 2678 { 2679 char packet[32]; 2680 const int packet_len = ::snprintf (packet, sizeof (packet), "QSetDetachOnError:%i", enable ? 1 : 0); 2681 assert (packet_len < (int)sizeof(packet)); 2682 StringExtractorGDBRemote response; 2683 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2684 { 2685 if (response.IsOKResponse()) 2686 return 0; 2687 uint8_t error = response.GetError(); 2688 if (error) 2689 return error; 2690 } 2691 return -1; 2692 } 2693 2694 2695 bool 2696 GDBRemoteCommunicationClient::DecodeProcessInfoResponse (StringExtractorGDBRemote &response, ProcessInstanceInfo &process_info) 2697 { 2698 if (response.IsNormalResponse()) 2699 { 2700 std::string name; 2701 std::string value; 2702 StringExtractor extractor; 2703 2704 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2705 uint32_t sub = 0; 2706 std::string vendor; 2707 std::string os_type; 2708 2709 while (response.GetNameColonValue(name, value)) 2710 { 2711 if (name.compare("pid") == 0) 2712 { 2713 process_info.SetProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 2714 } 2715 else if (name.compare("ppid") == 0) 2716 { 2717 process_info.SetParentProcessID (StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_PROCESS_ID, 0)); 2718 } 2719 else if (name.compare("uid") == 0) 2720 { 2721 process_info.SetUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0)); 2722 } 2723 else if (name.compare("euid") == 0) 2724 { 2725 process_info.SetEffectiveUserID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0)); 2726 } 2727 else if (name.compare("gid") == 0) 2728 { 2729 process_info.SetGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0)); 2730 } 2731 else if (name.compare("egid") == 0) 2732 { 2733 process_info.SetEffectiveGroupID (StringConvert::ToUInt32 (value.c_str(), UINT32_MAX, 0)); 2734 } 2735 else if (name.compare("triple") == 0) 2736 { 2737 StringExtractor extractor; 2738 extractor.GetStringRef().swap(value); 2739 extractor.SetFilePos(0); 2740 extractor.GetHexByteString (value); 2741 process_info.GetArchitecture ().SetTriple (value.c_str()); 2742 } 2743 else if (name.compare("name") == 0) 2744 { 2745 StringExtractor extractor; 2746 // The process name from ASCII hex bytes since we can't 2747 // control the characters in a process name 2748 extractor.GetStringRef().swap(value); 2749 extractor.SetFilePos(0); 2750 extractor.GetHexByteString (value); 2751 process_info.GetExecutableFile().SetFile (value.c_str(), false); 2752 } 2753 else if (name.compare("cputype") == 0) 2754 { 2755 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16); 2756 } 2757 else if (name.compare("cpusubtype") == 0) 2758 { 2759 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16); 2760 } 2761 else if (name.compare("vendor") == 0) 2762 { 2763 vendor = value; 2764 } 2765 else if (name.compare("ostype") == 0) 2766 { 2767 os_type = value; 2768 } 2769 } 2770 2771 if (cpu != LLDB_INVALID_CPUTYPE && !vendor.empty() && !os_type.empty()) 2772 { 2773 if (vendor == "apple") 2774 { 2775 process_info.GetArchitecture().SetArchitecture (eArchTypeMachO, cpu, sub); 2776 process_info.GetArchitecture().GetTriple().setVendorName (llvm::StringRef (vendor)); 2777 process_info.GetArchitecture().GetTriple().setOSName (llvm::StringRef (os_type)); 2778 } 2779 } 2780 2781 if (process_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) 2782 return true; 2783 } 2784 return false; 2785 } 2786 2787 bool 2788 GDBRemoteCommunicationClient::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info) 2789 { 2790 process_info.Clear(); 2791 2792 if (m_supports_qProcessInfoPID) 2793 { 2794 char packet[32]; 2795 const int packet_len = ::snprintf (packet, sizeof (packet), "qProcessInfoPID:%" PRIu64, pid); 2796 assert (packet_len < (int)sizeof(packet)); 2797 StringExtractorGDBRemote response; 2798 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 2799 { 2800 return DecodeProcessInfoResponse (response, process_info); 2801 } 2802 else 2803 { 2804 m_supports_qProcessInfoPID = false; 2805 return false; 2806 } 2807 } 2808 return false; 2809 } 2810 2811 bool 2812 GDBRemoteCommunicationClient::GetCurrentProcessInfo (bool allow_lazy) 2813 { 2814 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 2815 2816 if (allow_lazy) 2817 { 2818 if (m_qProcessInfo_is_valid == eLazyBoolYes) 2819 return true; 2820 if (m_qProcessInfo_is_valid == eLazyBoolNo) 2821 return false; 2822 } 2823 2824 GetHostInfo (); 2825 2826 StringExtractorGDBRemote response; 2827 if (SendPacketAndWaitForResponse ("qProcessInfo", response, false) == PacketResult::Success) 2828 { 2829 if (response.IsNormalResponse()) 2830 { 2831 std::string name; 2832 std::string value; 2833 uint32_t cpu = LLDB_INVALID_CPUTYPE; 2834 uint32_t sub = 0; 2835 std::string arch_name; 2836 std::string os_name; 2837 std::string vendor_name; 2838 std::string triple; 2839 uint32_t pointer_byte_size = 0; 2840 StringExtractor extractor; 2841 ByteOrder byte_order = eByteOrderInvalid; 2842 uint32_t num_keys_decoded = 0; 2843 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID; 2844 while (response.GetNameColonValue(name, value)) 2845 { 2846 if (name.compare("cputype") == 0) 2847 { 2848 cpu = StringConvert::ToUInt32 (value.c_str(), LLDB_INVALID_CPUTYPE, 16); 2849 if (cpu != LLDB_INVALID_CPUTYPE) 2850 ++num_keys_decoded; 2851 } 2852 else if (name.compare("cpusubtype") == 0) 2853 { 2854 sub = StringConvert::ToUInt32 (value.c_str(), 0, 16); 2855 if (sub != 0) 2856 ++num_keys_decoded; 2857 } 2858 else if (name.compare("triple") == 0) 2859 { 2860 StringExtractor extractor; 2861 extractor.GetStringRef().swap(value); 2862 extractor.SetFilePos(0); 2863 extractor.GetHexByteString (triple); 2864 ++num_keys_decoded; 2865 } 2866 else if (name.compare("ostype") == 0) 2867 { 2868 os_name.swap (value); 2869 ++num_keys_decoded; 2870 } 2871 else if (name.compare("vendor") == 0) 2872 { 2873 vendor_name.swap(value); 2874 ++num_keys_decoded; 2875 } 2876 else if (name.compare("endian") == 0) 2877 { 2878 ++num_keys_decoded; 2879 if (value.compare("little") == 0) 2880 byte_order = eByteOrderLittle; 2881 else if (value.compare("big") == 0) 2882 byte_order = eByteOrderBig; 2883 else if (value.compare("pdp") == 0) 2884 byte_order = eByteOrderPDP; 2885 else 2886 --num_keys_decoded; 2887 } 2888 else if (name.compare("ptrsize") == 0) 2889 { 2890 pointer_byte_size = StringConvert::ToUInt32 (value.c_str(), 0, 16); 2891 if (pointer_byte_size != 0) 2892 ++num_keys_decoded; 2893 } 2894 else if (name.compare("pid") == 0) 2895 { 2896 pid = StringConvert::ToUInt64(value.c_str(), 0, 16); 2897 if (pid != LLDB_INVALID_PROCESS_ID) 2898 ++num_keys_decoded; 2899 } 2900 } 2901 if (num_keys_decoded > 0) 2902 m_qProcessInfo_is_valid = eLazyBoolYes; 2903 if (pid != LLDB_INVALID_PROCESS_ID) 2904 { 2905 m_curr_pid_is_valid = eLazyBoolYes; 2906 m_curr_pid = pid; 2907 } 2908 2909 // Set the ArchSpec from the triple if we have it. 2910 if (!triple.empty ()) 2911 { 2912 m_process_arch.SetTriple (triple.c_str ()); 2913 if (pointer_byte_size) 2914 { 2915 assert (pointer_byte_size == m_process_arch.GetAddressByteSize()); 2916 } 2917 } 2918 else if (cpu != LLDB_INVALID_CPUTYPE && !os_name.empty() && !vendor_name.empty()) 2919 { 2920 llvm::Triple triple(llvm::Twine("-") + vendor_name + "-" + os_name); 2921 2922 assert(triple.getObjectFormat() != llvm::Triple::UnknownObjectFormat); 2923 switch (triple.getObjectFormat()) { 2924 case llvm::Triple::MachO: 2925 m_process_arch.SetArchitecture (eArchTypeMachO, cpu, sub); 2926 break; 2927 case llvm::Triple::ELF: 2928 m_process_arch.SetArchitecture (eArchTypeELF, cpu, sub); 2929 break; 2930 case llvm::Triple::COFF: 2931 m_process_arch.SetArchitecture (eArchTypeCOFF, cpu, sub); 2932 break; 2933 case llvm::Triple::UnknownObjectFormat: 2934 if (log) 2935 log->Printf("error: failed to determine target architecture"); 2936 return false; 2937 } 2938 2939 if (pointer_byte_size) 2940 { 2941 assert (pointer_byte_size == m_process_arch.GetAddressByteSize()); 2942 } 2943 if (byte_order != eByteOrderInvalid) 2944 { 2945 assert (byte_order == m_process_arch.GetByteOrder()); 2946 } 2947 m_process_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 2948 m_process_arch.GetTriple().setOSName(llvm::StringRef (os_name)); 2949 m_host_arch.GetTriple().setVendorName (llvm::StringRef (vendor_name)); 2950 m_host_arch.GetTriple().setOSName (llvm::StringRef (os_name)); 2951 } 2952 return true; 2953 } 2954 } 2955 else 2956 { 2957 m_qProcessInfo_is_valid = eLazyBoolNo; 2958 } 2959 2960 return false; 2961 } 2962 2963 2964 uint32_t 2965 GDBRemoteCommunicationClient::FindProcesses (const ProcessInstanceInfoMatch &match_info, 2966 ProcessInstanceInfoList &process_infos) 2967 { 2968 process_infos.Clear(); 2969 2970 if (m_supports_qfProcessInfo) 2971 { 2972 StreamString packet; 2973 packet.PutCString ("qfProcessInfo"); 2974 if (!match_info.MatchAllProcesses()) 2975 { 2976 packet.PutChar (':'); 2977 const char *name = match_info.GetProcessInfo().GetName(); 2978 bool has_name_match = false; 2979 if (name && name[0]) 2980 { 2981 has_name_match = true; 2982 NameMatchType name_match_type = match_info.GetNameMatchType(); 2983 switch (name_match_type) 2984 { 2985 case eNameMatchIgnore: 2986 has_name_match = false; 2987 break; 2988 2989 case eNameMatchEquals: 2990 packet.PutCString ("name_match:equals;"); 2991 break; 2992 2993 case eNameMatchContains: 2994 packet.PutCString ("name_match:contains;"); 2995 break; 2996 2997 case eNameMatchStartsWith: 2998 packet.PutCString ("name_match:starts_with;"); 2999 break; 3000 3001 case eNameMatchEndsWith: 3002 packet.PutCString ("name_match:ends_with;"); 3003 break; 3004 3005 case eNameMatchRegularExpression: 3006 packet.PutCString ("name_match:regex;"); 3007 break; 3008 } 3009 if (has_name_match) 3010 { 3011 packet.PutCString ("name:"); 3012 packet.PutBytesAsRawHex8(name, ::strlen(name)); 3013 packet.PutChar (';'); 3014 } 3015 } 3016 3017 if (match_info.GetProcessInfo().ProcessIDIsValid()) 3018 packet.Printf("pid:%" PRIu64 ";",match_info.GetProcessInfo().GetProcessID()); 3019 if (match_info.GetProcessInfo().ParentProcessIDIsValid()) 3020 packet.Printf("parent_pid:%" PRIu64 ";",match_info.GetProcessInfo().GetParentProcessID()); 3021 if (match_info.GetProcessInfo().UserIDIsValid()) 3022 packet.Printf("uid:%u;",match_info.GetProcessInfo().GetUserID()); 3023 if (match_info.GetProcessInfo().GroupIDIsValid()) 3024 packet.Printf("gid:%u;",match_info.GetProcessInfo().GetGroupID()); 3025 if (match_info.GetProcessInfo().EffectiveUserIDIsValid()) 3026 packet.Printf("euid:%u;",match_info.GetProcessInfo().GetEffectiveUserID()); 3027 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 3028 packet.Printf("egid:%u;",match_info.GetProcessInfo().GetEffectiveGroupID()); 3029 if (match_info.GetProcessInfo().EffectiveGroupIDIsValid()) 3030 packet.Printf("all_users:%u;",match_info.GetMatchAllUsers() ? 1 : 0); 3031 if (match_info.GetProcessInfo().GetArchitecture().IsValid()) 3032 { 3033 const ArchSpec &match_arch = match_info.GetProcessInfo().GetArchitecture(); 3034 const llvm::Triple &triple = match_arch.GetTriple(); 3035 packet.PutCString("triple:"); 3036 packet.PutCString(triple.getTriple().c_str()); 3037 packet.PutChar (';'); 3038 } 3039 } 3040 StringExtractorGDBRemote response; 3041 // Increase timeout as the first qfProcessInfo packet takes a long time 3042 // on Android. The value of 1min was arrived at empirically. 3043 GDBRemoteCommunication::ScopedTimeout timeout (*this, 60); 3044 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success) 3045 { 3046 do 3047 { 3048 ProcessInstanceInfo process_info; 3049 if (!DecodeProcessInfoResponse (response, process_info)) 3050 break; 3051 process_infos.Append(process_info); 3052 response.GetStringRef().clear(); 3053 response.SetFilePos(0); 3054 } while (SendPacketAndWaitForResponse ("qsProcessInfo", strlen ("qsProcessInfo"), response, false) == PacketResult::Success); 3055 } 3056 else 3057 { 3058 m_supports_qfProcessInfo = false; 3059 return 0; 3060 } 3061 } 3062 return process_infos.GetSize(); 3063 3064 } 3065 3066 bool 3067 GDBRemoteCommunicationClient::GetUserName (uint32_t uid, std::string &name) 3068 { 3069 if (m_supports_qUserName) 3070 { 3071 char packet[32]; 3072 const int packet_len = ::snprintf (packet, sizeof (packet), "qUserName:%i", uid); 3073 assert (packet_len < (int)sizeof(packet)); 3074 StringExtractorGDBRemote response; 3075 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 3076 { 3077 if (response.IsNormalResponse()) 3078 { 3079 // Make sure we parsed the right number of characters. The response is 3080 // the hex encoded user name and should make up the entire packet. 3081 // If there are any non-hex ASCII bytes, the length won't match below.. 3082 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 3083 return true; 3084 } 3085 } 3086 else 3087 { 3088 m_supports_qUserName = false; 3089 return false; 3090 } 3091 } 3092 return false; 3093 3094 } 3095 3096 bool 3097 GDBRemoteCommunicationClient::GetGroupName (uint32_t gid, std::string &name) 3098 { 3099 if (m_supports_qGroupName) 3100 { 3101 char packet[32]; 3102 const int packet_len = ::snprintf (packet, sizeof (packet), "qGroupName:%i", gid); 3103 assert (packet_len < (int)sizeof(packet)); 3104 StringExtractorGDBRemote response; 3105 if (SendPacketAndWaitForResponse (packet, packet_len, response, false) == PacketResult::Success) 3106 { 3107 if (response.IsNormalResponse()) 3108 { 3109 // Make sure we parsed the right number of characters. The response is 3110 // the hex encoded group name and should make up the entire packet. 3111 // If there are any non-hex ASCII bytes, the length won't match below.. 3112 if (response.GetHexByteString (name) * 2 == response.GetStringRef().size()) 3113 return true; 3114 } 3115 } 3116 else 3117 { 3118 m_supports_qGroupName = false; 3119 return false; 3120 } 3121 } 3122 return false; 3123 } 3124 3125 bool 3126 GDBRemoteCommunicationClient::SetNonStopMode (const bool enable) 3127 { 3128 // Form non-stop packet request 3129 char packet[32]; 3130 const int packet_len = ::snprintf(packet, sizeof(packet), "QNonStop:%1d", (int)enable); 3131 assert(packet_len < (int)sizeof(packet)); 3132 3133 StringExtractorGDBRemote response; 3134 // Send to target 3135 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3136 if (response.IsOKResponse()) 3137 return true; 3138 3139 // Failed or not supported 3140 return false; 3141 3142 } 3143 3144 static void 3145 MakeSpeedTestPacket(StreamString &packet, uint32_t send_size, uint32_t recv_size) 3146 { 3147 packet.Clear(); 3148 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 3149 uint32_t bytes_left = send_size; 3150 while (bytes_left > 0) 3151 { 3152 if (bytes_left >= 26) 3153 { 3154 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 3155 bytes_left -= 26; 3156 } 3157 else 3158 { 3159 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 3160 bytes_left = 0; 3161 } 3162 } 3163 } 3164 3165 template<typename T> 3166 T calculate_standard_deviation(const std::vector<T> &v) 3167 { 3168 T sum = std::accumulate(std::begin(v), std::end(v), T(0)); 3169 T mean = sum / (T)v.size(); 3170 T accum = T(0); 3171 std::for_each (std::begin(v), std::end(v), [&](const T d) { 3172 T delta = d - mean; 3173 accum += delta * delta; 3174 }); 3175 3176 T stdev = sqrt(accum / (v.size()-1)); 3177 return stdev; 3178 } 3179 3180 void 3181 GDBRemoteCommunicationClient::TestPacketSpeed (const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, bool json, Stream &strm) 3182 { 3183 uint32_t i; 3184 TimeValue start_time, end_time; 3185 uint64_t total_time_nsec; 3186 if (SendSpeedTestPacket (0, 0)) 3187 { 3188 StreamString packet; 3189 if (json) 3190 strm.Printf("{ \"packet_speeds\" : {\n \"num_packets\" : %u,\n \"results\" : [", num_packets); 3191 else 3192 strm.Printf("Testing sending %u packets of various sizes:\n", num_packets); 3193 strm.Flush(); 3194 3195 uint32_t result_idx = 0; 3196 uint32_t send_size; 3197 std::vector<float> packet_times; 3198 3199 for (send_size = 0; send_size <= max_send; send_size ? send_size *= 2 : send_size = 4) 3200 { 3201 for (uint32_t recv_size = 0; recv_size <= max_recv; recv_size ? recv_size *= 2 : recv_size = 4) 3202 { 3203 MakeSpeedTestPacket (packet, send_size, recv_size); 3204 3205 packet_times.clear(); 3206 // Test how long it takes to send 'num_packets' packets 3207 start_time = TimeValue::Now(); 3208 for (i=0; i<num_packets; ++i) 3209 { 3210 TimeValue packet_start_time = TimeValue::Now(); 3211 StringExtractorGDBRemote response; 3212 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false); 3213 TimeValue packet_end_time = TimeValue::Now(); 3214 uint64_t packet_time_nsec = packet_end_time.GetAsNanoSecondsSinceJan1_1970() - packet_start_time.GetAsNanoSecondsSinceJan1_1970(); 3215 packet_times.push_back((float)packet_time_nsec); 3216 } 3217 end_time = TimeValue::Now(); 3218 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 3219 3220 float packets_per_second = (((float)num_packets)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 3221 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec; 3222 float average_ms_per_packet = total_ms / num_packets; 3223 const float standard_deviation = calculate_standard_deviation<float>(packet_times); 3224 if (json) 3225 { 3226 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); 3227 ++result_idx; 3228 } 3229 else 3230 { 3231 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", 3232 send_size, 3233 recv_size, 3234 total_time_nsec / TimeValue::NanoSecPerSec, 3235 total_time_nsec % TimeValue::NanoSecPerSec, 3236 packets_per_second, 3237 average_ms_per_packet, 3238 standard_deviation/(float)TimeValue::NanoSecPerMilliSec); 3239 } 3240 strm.Flush(); 3241 } 3242 } 3243 3244 const uint64_t k_recv_amount = 4*1024*1024; // Receive amount in bytes 3245 3246 const float k_recv_amount_mb = (float)k_recv_amount/(1024.0f*1024.0f); 3247 if (json) 3248 strm.Printf("\n ]\n },\n \"download_speed\" : {\n \"byte_size\" : %" PRIu64 ",\n \"results\" : [", k_recv_amount); 3249 else 3250 strm.Printf("Testing receiving %2.1fMB of data using varying receive packet sizes:\n", k_recv_amount_mb); 3251 strm.Flush(); 3252 send_size = 0; 3253 result_idx = 0; 3254 for (uint32_t recv_size = 32; recv_size <= max_recv; recv_size *= 2) 3255 { 3256 MakeSpeedTestPacket (packet, send_size, recv_size); 3257 3258 // If we have a receive size, test how long it takes to receive 4MB of data 3259 if (recv_size > 0) 3260 { 3261 start_time = TimeValue::Now(); 3262 uint32_t bytes_read = 0; 3263 uint32_t packet_count = 0; 3264 while (bytes_read < k_recv_amount) 3265 { 3266 StringExtractorGDBRemote response; 3267 SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false); 3268 bytes_read += recv_size; 3269 ++packet_count; 3270 } 3271 end_time = TimeValue::Now(); 3272 total_time_nsec = end_time.GetAsNanoSecondsSinceJan1_1970() - start_time.GetAsNanoSecondsSinceJan1_1970(); 3273 float mb_second = ((((float)k_recv_amount)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec) / (1024.0*1024.0); 3274 float packets_per_second = (((float)packet_count)/(float)total_time_nsec) * (float)TimeValue::NanoSecPerSec; 3275 float total_ms = (float)total_time_nsec/(float)TimeValue::NanoSecPerMilliSec; 3276 float average_ms_per_packet = total_ms / packet_count; 3277 3278 if (json) 3279 { 3280 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); 3281 ++result_idx; 3282 } 3283 else 3284 { 3285 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", 3286 send_size, 3287 recv_size, 3288 packet_count, 3289 k_recv_amount_mb, 3290 total_time_nsec / TimeValue::NanoSecPerSec, 3291 total_time_nsec % TimeValue::NanoSecPerSec, 3292 mb_second, 3293 packets_per_second, 3294 average_ms_per_packet); 3295 } 3296 strm.Flush(); 3297 } 3298 } 3299 if (json) 3300 strm.Printf("\n ]\n }\n}\n"); 3301 else 3302 strm.EOL(); 3303 } 3304 } 3305 3306 bool 3307 GDBRemoteCommunicationClient::SendSpeedTestPacket (uint32_t send_size, uint32_t recv_size) 3308 { 3309 StreamString packet; 3310 packet.Printf ("qSpeedTest:response_size:%i;data:", recv_size); 3311 uint32_t bytes_left = send_size; 3312 while (bytes_left > 0) 3313 { 3314 if (bytes_left >= 26) 3315 { 3316 packet.PutCString("abcdefghijklmnopqrstuvwxyz"); 3317 bytes_left -= 26; 3318 } 3319 else 3320 { 3321 packet.Printf ("%*.*s;", bytes_left, bytes_left, "abcdefghijklmnopqrstuvwxyz"); 3322 bytes_left = 0; 3323 } 3324 } 3325 3326 StringExtractorGDBRemote response; 3327 return SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) == PacketResult::Success; 3328 } 3329 3330 bool 3331 GDBRemoteCommunicationClient::LaunchGDBServer (const char *remote_accept_hostname, 3332 lldb::pid_t &pid, 3333 uint16_t &port, 3334 std::string &socket_name) 3335 { 3336 pid = LLDB_INVALID_PROCESS_ID; 3337 port = 0; 3338 socket_name.clear(); 3339 3340 StringExtractorGDBRemote response; 3341 StreamString stream; 3342 stream.PutCString("qLaunchGDBServer;"); 3343 std::string hostname; 3344 if (remote_accept_hostname && remote_accept_hostname[0]) 3345 hostname = remote_accept_hostname; 3346 else 3347 { 3348 if (HostInfo::GetHostname(hostname)) 3349 { 3350 // Make the GDB server we launch only accept connections from this host 3351 stream.Printf("host:%s;", hostname.c_str()); 3352 } 3353 else 3354 { 3355 // Make the GDB server we launch accept connections from any host since we can't figure out the hostname 3356 stream.Printf("host:*;"); 3357 } 3358 } 3359 const char *packet = stream.GetData(); 3360 int packet_len = stream.GetSize(); 3361 3362 // give the process a few seconds to startup 3363 GDBRemoteCommunication::ScopedTimeout timeout (*this, 10); 3364 3365 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3366 { 3367 std::string name; 3368 std::string value; 3369 StringExtractor extractor; 3370 while (response.GetNameColonValue(name, value)) 3371 { 3372 if (name.compare("port") == 0) 3373 port = StringConvert::ToUInt32(value.c_str(), 0, 0); 3374 else if (name.compare("pid") == 0) 3375 pid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_PROCESS_ID, 0); 3376 else if (name.compare("socket_name") == 0) 3377 { 3378 extractor.GetStringRef().swap(value); 3379 extractor.SetFilePos(0); 3380 extractor.GetHexByteString(value); 3381 3382 socket_name = value; 3383 } 3384 } 3385 return true; 3386 } 3387 return false; 3388 } 3389 3390 size_t 3391 GDBRemoteCommunicationClient::QueryGDBServer (std::vector<std::pair<uint16_t, std::string>>& connection_urls) 3392 { 3393 connection_urls.clear(); 3394 3395 StringExtractorGDBRemote response; 3396 if (SendPacketAndWaitForResponse("qQueryGDBServer", response, false) != PacketResult::Success) 3397 return 0; 3398 3399 StructuredData::ObjectSP data = StructuredData::ParseJSON(response.GetStringRef()); 3400 if (!data) 3401 return 0; 3402 3403 StructuredData::Array* array = data->GetAsArray(); 3404 if (!array) 3405 return 0; 3406 3407 for (size_t i = 0, count = array->GetSize(); i < count; ++i) 3408 { 3409 StructuredData::Dictionary* element = nullptr; 3410 if (!array->GetItemAtIndexAsDictionary(i, element)) 3411 continue; 3412 3413 uint16_t port = 0; 3414 if (StructuredData::ObjectSP port_osp = element->GetValueForKey(llvm::StringRef("port"))) 3415 port = port_osp->GetIntegerValue(0); 3416 3417 std::string socket_name; 3418 if (StructuredData::ObjectSP socket_name_osp = element->GetValueForKey(llvm::StringRef("socket_name"))) 3419 socket_name = socket_name_osp->GetStringValue(); 3420 3421 if (port != 0 || !socket_name.empty()) 3422 connection_urls.emplace_back(port, socket_name); 3423 } 3424 return connection_urls.size(); 3425 } 3426 3427 bool 3428 GDBRemoteCommunicationClient::KillSpawnedProcess (lldb::pid_t pid) 3429 { 3430 StreamString stream; 3431 stream.Printf ("qKillSpawnedProcess:%" PRId64 , pid); 3432 const char *packet = stream.GetData(); 3433 int packet_len = stream.GetSize(); 3434 3435 StringExtractorGDBRemote response; 3436 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3437 { 3438 if (response.IsOKResponse()) 3439 return true; 3440 } 3441 return false; 3442 } 3443 3444 bool 3445 GDBRemoteCommunicationClient::SetCurrentThread (uint64_t tid) 3446 { 3447 if (m_curr_tid == tid) 3448 return true; 3449 3450 char packet[32]; 3451 int packet_len; 3452 if (tid == UINT64_MAX) 3453 packet_len = ::snprintf (packet, sizeof(packet), "Hg-1"); 3454 else 3455 packet_len = ::snprintf (packet, sizeof(packet), "Hg%" PRIx64, tid); 3456 assert (packet_len + 1 < (int)sizeof(packet)); 3457 StringExtractorGDBRemote response; 3458 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3459 { 3460 if (response.IsOKResponse()) 3461 { 3462 m_curr_tid = tid; 3463 return true; 3464 } 3465 3466 /* 3467 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hg packet. 3468 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can 3469 * give us pid and/or tid. Assume pid=tid=1 in such cases. 3470 */ 3471 if (response.IsUnsupportedResponse() && IsConnected()) 3472 { 3473 m_curr_tid = 1; 3474 return true; 3475 } 3476 } 3477 return false; 3478 } 3479 3480 bool 3481 GDBRemoteCommunicationClient::SetCurrentThreadForRun (uint64_t tid) 3482 { 3483 if (m_curr_tid_run == tid) 3484 return true; 3485 3486 char packet[32]; 3487 int packet_len; 3488 if (tid == UINT64_MAX) 3489 packet_len = ::snprintf (packet, sizeof(packet), "Hc-1"); 3490 else 3491 packet_len = ::snprintf (packet, sizeof(packet), "Hc%" PRIx64, tid); 3492 3493 assert (packet_len + 1 < (int)sizeof(packet)); 3494 StringExtractorGDBRemote response; 3495 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3496 { 3497 if (response.IsOKResponse()) 3498 { 3499 m_curr_tid_run = tid; 3500 return true; 3501 } 3502 3503 /* 3504 * Connected bare-iron target (like YAMON gdb-stub) may not have support for Hc packet. 3505 * The reply from '?' packet could be as simple as 'S05'. There is no packet which can 3506 * give us pid and/or tid. Assume pid=tid=1 in such cases. 3507 */ 3508 if (response.IsUnsupportedResponse() && IsConnected()) 3509 { 3510 m_curr_tid_run = 1; 3511 return true; 3512 } 3513 } 3514 return false; 3515 } 3516 3517 bool 3518 GDBRemoteCommunicationClient::GetStopReply (StringExtractorGDBRemote &response) 3519 { 3520 if (SendPacketAndWaitForResponse("?", 1, response, false) == PacketResult::Success) 3521 return response.IsNormalResponse(); 3522 return false; 3523 } 3524 3525 bool 3526 GDBRemoteCommunicationClient::GetThreadStopInfo (lldb::tid_t tid, StringExtractorGDBRemote &response) 3527 { 3528 if (m_supports_qThreadStopInfo) 3529 { 3530 char packet[256]; 3531 int packet_len = ::snprintf(packet, sizeof(packet), "qThreadStopInfo%" PRIx64, tid); 3532 assert (packet_len < (int)sizeof(packet)); 3533 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3534 { 3535 if (response.IsUnsupportedResponse()) 3536 m_supports_qThreadStopInfo = false; 3537 else if (response.IsNormalResponse()) 3538 return true; 3539 else 3540 return false; 3541 } 3542 else 3543 { 3544 m_supports_qThreadStopInfo = false; 3545 } 3546 } 3547 return false; 3548 } 3549 3550 3551 uint8_t 3552 GDBRemoteCommunicationClient::SendGDBStoppointTypePacket (GDBStoppointType type, bool insert, addr_t addr, uint32_t length) 3553 { 3554 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_BREAKPOINTS)); 3555 if (log) 3556 log->Printf ("GDBRemoteCommunicationClient::%s() %s at addr = 0x%" PRIx64, 3557 __FUNCTION__, insert ? "add" : "remove", addr); 3558 3559 // Check if the stub is known not to support this breakpoint type 3560 if (!SupportsGDBStoppointPacket(type)) 3561 return UINT8_MAX; 3562 // Construct the breakpoint packet 3563 char packet[64]; 3564 const int packet_len = ::snprintf (packet, 3565 sizeof(packet), 3566 "%c%i,%" PRIx64 ",%x", 3567 insert ? 'Z' : 'z', 3568 type, 3569 addr, 3570 length); 3571 // Check we haven't overwritten the end of the packet buffer 3572 assert (packet_len + 1 < (int)sizeof(packet)); 3573 StringExtractorGDBRemote response; 3574 // Try to send the breakpoint packet, and check that it was correctly sent 3575 if (SendPacketAndWaitForResponse(packet, packet_len, response, true) == PacketResult::Success) 3576 { 3577 // Receive and OK packet when the breakpoint successfully placed 3578 if (response.IsOKResponse()) 3579 return 0; 3580 3581 // Error while setting breakpoint, send back specific error 3582 if (response.IsErrorResponse()) 3583 return response.GetError(); 3584 3585 // Empty packet informs us that breakpoint is not supported 3586 if (response.IsUnsupportedResponse()) 3587 { 3588 // Disable this breakpoint type since it is unsupported 3589 switch (type) 3590 { 3591 case eBreakpointSoftware: m_supports_z0 = false; break; 3592 case eBreakpointHardware: m_supports_z1 = false; break; 3593 case eWatchpointWrite: m_supports_z2 = false; break; 3594 case eWatchpointRead: m_supports_z3 = false; break; 3595 case eWatchpointReadWrite: m_supports_z4 = false; break; 3596 case eStoppointInvalid: return UINT8_MAX; 3597 } 3598 } 3599 } 3600 // Signal generic failure 3601 return UINT8_MAX; 3602 } 3603 3604 size_t 3605 GDBRemoteCommunicationClient::GetCurrentThreadIDs (std::vector<lldb::tid_t> &thread_ids, 3606 bool &sequence_mutex_unavailable) 3607 { 3608 Mutex::Locker locker; 3609 thread_ids.clear(); 3610 3611 if (GetSequenceMutex (locker, "ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex")) 3612 { 3613 sequence_mutex_unavailable = false; 3614 StringExtractorGDBRemote response; 3615 3616 PacketResult packet_result; 3617 for (packet_result = SendPacketAndWaitForResponseNoLock ("qfThreadInfo", strlen("qfThreadInfo"), response); 3618 packet_result == PacketResult::Success && response.IsNormalResponse(); 3619 packet_result = SendPacketAndWaitForResponseNoLock ("qsThreadInfo", strlen("qsThreadInfo"), response)) 3620 { 3621 char ch = response.GetChar(); 3622 if (ch == 'l') 3623 break; 3624 if (ch == 'm') 3625 { 3626 do 3627 { 3628 tid_t tid = response.GetHexMaxU64(false, LLDB_INVALID_THREAD_ID); 3629 3630 if (tid != LLDB_INVALID_THREAD_ID) 3631 { 3632 thread_ids.push_back (tid); 3633 } 3634 ch = response.GetChar(); // Skip the command separator 3635 } while (ch == ','); // Make sure we got a comma separator 3636 } 3637 } 3638 3639 /* 3640 * Connected bare-iron target (like YAMON gdb-stub) may not have support for 3641 * qProcessInfo, qC and qfThreadInfo packets. The reply from '?' packet could 3642 * be as simple as 'S05'. There is no packet which can give us pid and/or tid. 3643 * Assume pid=tid=1 in such cases. 3644 */ 3645 if (response.IsUnsupportedResponse() && thread_ids.size() == 0 && IsConnected()) 3646 { 3647 thread_ids.push_back (1); 3648 } 3649 } 3650 else 3651 { 3652 #if defined (LLDB_CONFIGURATION_DEBUG) 3653 // assert(!"ProcessGDBRemote::UpdateThreadList() failed due to not getting the sequence mutex"); 3654 #else 3655 Log *log (ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet (GDBR_LOG_PROCESS | GDBR_LOG_PACKETS)); 3656 if (log) 3657 log->Printf("error: failed to get packet sequence mutex, not sending packet 'qfThreadInfo'"); 3658 #endif 3659 sequence_mutex_unavailable = true; 3660 } 3661 return thread_ids.size(); 3662 } 3663 3664 lldb::addr_t 3665 GDBRemoteCommunicationClient::GetShlibInfoAddr() 3666 { 3667 if (!IsRunning()) 3668 { 3669 StringExtractorGDBRemote response; 3670 if (SendPacketAndWaitForResponse("qShlibInfoAddr", ::strlen ("qShlibInfoAddr"), response, false) == PacketResult::Success) 3671 { 3672 if (response.IsNormalResponse()) 3673 return response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 3674 } 3675 } 3676 return LLDB_INVALID_ADDRESS; 3677 } 3678 3679 lldb_private::Error 3680 GDBRemoteCommunicationClient::RunShellCommand(const char *command, // Shouldn't be NULL 3681 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory 3682 int *status_ptr, // Pass NULL if you don't want the process exit status 3683 int *signo_ptr, // Pass NULL if you don't want the signal that caused the process to exit 3684 std::string *command_output, // Pass NULL if you don't want the command output 3685 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish 3686 { 3687 lldb_private::StreamString stream; 3688 stream.PutCString("qPlatform_shell:"); 3689 stream.PutBytesAsRawHex8(command, strlen(command)); 3690 stream.PutChar(','); 3691 stream.PutHex32(timeout_sec); 3692 if (working_dir) 3693 { 3694 std::string path{working_dir.GetPath(false)}; 3695 stream.PutChar(','); 3696 stream.PutCStringAsRawHex8(path.c_str()); 3697 } 3698 const char *packet = stream.GetData(); 3699 int packet_len = stream.GetSize(); 3700 StringExtractorGDBRemote response; 3701 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3702 { 3703 if (response.GetChar() != 'F') 3704 return Error("malformed reply"); 3705 if (response.GetChar() != ',') 3706 return Error("malformed reply"); 3707 uint32_t exitcode = response.GetHexMaxU32(false, UINT32_MAX); 3708 if (exitcode == UINT32_MAX) 3709 return Error("unable to run remote process"); 3710 else if (status_ptr) 3711 *status_ptr = exitcode; 3712 if (response.GetChar() != ',') 3713 return Error("malformed reply"); 3714 uint32_t signo = response.GetHexMaxU32(false, UINT32_MAX); 3715 if (signo_ptr) 3716 *signo_ptr = signo; 3717 if (response.GetChar() != ',') 3718 return Error("malformed reply"); 3719 std::string output; 3720 response.GetEscapedBinaryData(output); 3721 if (command_output) 3722 command_output->assign(output); 3723 return Error(); 3724 } 3725 return Error("unable to send packet"); 3726 } 3727 3728 Error 3729 GDBRemoteCommunicationClient::MakeDirectory(const FileSpec &file_spec, 3730 uint32_t file_permissions) 3731 { 3732 std::string path{file_spec.GetPath(false)}; 3733 lldb_private::StreamString stream; 3734 stream.PutCString("qPlatform_mkdir:"); 3735 stream.PutHex32(file_permissions); 3736 stream.PutChar(','); 3737 stream.PutCStringAsRawHex8(path.c_str()); 3738 const char *packet = stream.GetData(); 3739 int packet_len = stream.GetSize(); 3740 StringExtractorGDBRemote response; 3741 3742 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success) 3743 return Error("failed to send '%s' packet", packet); 3744 3745 if (response.GetChar() != 'F') 3746 return Error("invalid response to '%s' packet", packet); 3747 3748 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 3749 } 3750 3751 Error 3752 GDBRemoteCommunicationClient::SetFilePermissions(const FileSpec &file_spec, 3753 uint32_t file_permissions) 3754 { 3755 std::string path{file_spec.GetPath(false)}; 3756 lldb_private::StreamString stream; 3757 stream.PutCString("qPlatform_chmod:"); 3758 stream.PutHex32(file_permissions); 3759 stream.PutChar(','); 3760 stream.PutCStringAsRawHex8(path.c_str()); 3761 const char *packet = stream.GetData(); 3762 int packet_len = stream.GetSize(); 3763 StringExtractorGDBRemote response; 3764 3765 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) != PacketResult::Success) 3766 return Error("failed to send '%s' packet", packet); 3767 3768 if (response.GetChar() != 'F') 3769 return Error("invalid response to '%s' packet", packet); 3770 3771 return Error(response.GetU32(UINT32_MAX), eErrorTypePOSIX); 3772 } 3773 3774 static uint64_t 3775 ParseHostIOPacketResponse (StringExtractorGDBRemote &response, 3776 uint64_t fail_result, 3777 Error &error) 3778 { 3779 response.SetFilePos(0); 3780 if (response.GetChar() != 'F') 3781 return fail_result; 3782 int32_t result = response.GetS32 (-2); 3783 if (result == -2) 3784 return fail_result; 3785 if (response.GetChar() == ',') 3786 { 3787 int result_errno = response.GetS32 (-2); 3788 if (result_errno != -2) 3789 error.SetError(result_errno, eErrorTypePOSIX); 3790 else 3791 error.SetError(-1, eErrorTypeGeneric); 3792 } 3793 else 3794 error.Clear(); 3795 return result; 3796 } 3797 lldb::user_id_t 3798 GDBRemoteCommunicationClient::OpenFile (const lldb_private::FileSpec& file_spec, 3799 uint32_t flags, 3800 mode_t mode, 3801 Error &error) 3802 { 3803 std::string path(file_spec.GetPath(false)); 3804 lldb_private::StreamString stream; 3805 stream.PutCString("vFile:open:"); 3806 if (path.empty()) 3807 return UINT64_MAX; 3808 stream.PutCStringAsRawHex8(path.c_str()); 3809 stream.PutChar(','); 3810 stream.PutHex32(flags); 3811 stream.PutChar(','); 3812 stream.PutHex32(mode); 3813 const char* packet = stream.GetData(); 3814 int packet_len = stream.GetSize(); 3815 StringExtractorGDBRemote response; 3816 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3817 { 3818 return ParseHostIOPacketResponse (response, UINT64_MAX, error); 3819 } 3820 return UINT64_MAX; 3821 } 3822 3823 bool 3824 GDBRemoteCommunicationClient::CloseFile (lldb::user_id_t fd, 3825 Error &error) 3826 { 3827 lldb_private::StreamString stream; 3828 stream.Printf("vFile:close:%i", (int)fd); 3829 const char* packet = stream.GetData(); 3830 int packet_len = stream.GetSize(); 3831 StringExtractorGDBRemote response; 3832 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3833 { 3834 return ParseHostIOPacketResponse (response, -1, error) == 0; 3835 } 3836 return false; 3837 } 3838 3839 // Extension of host I/O packets to get the file size. 3840 lldb::user_id_t 3841 GDBRemoteCommunicationClient::GetFileSize (const lldb_private::FileSpec& file_spec) 3842 { 3843 std::string path(file_spec.GetPath(false)); 3844 lldb_private::StreamString stream; 3845 stream.PutCString("vFile:size:"); 3846 stream.PutCStringAsRawHex8(path.c_str()); 3847 const char* packet = stream.GetData(); 3848 int packet_len = stream.GetSize(); 3849 StringExtractorGDBRemote response; 3850 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3851 { 3852 if (response.GetChar() != 'F') 3853 return UINT64_MAX; 3854 uint32_t retcode = response.GetHexMaxU64(false, UINT64_MAX); 3855 return retcode; 3856 } 3857 return UINT64_MAX; 3858 } 3859 3860 Error 3861 GDBRemoteCommunicationClient::GetFilePermissions(const FileSpec &file_spec, 3862 uint32_t &file_permissions) 3863 { 3864 std::string path{file_spec.GetPath(false)}; 3865 Error error; 3866 lldb_private::StreamString stream; 3867 stream.PutCString("vFile:mode:"); 3868 stream.PutCStringAsRawHex8(path.c_str()); 3869 const char* packet = stream.GetData(); 3870 int packet_len = stream.GetSize(); 3871 StringExtractorGDBRemote response; 3872 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3873 { 3874 if (response.GetChar() != 'F') 3875 { 3876 error.SetErrorStringWithFormat ("invalid response to '%s' packet", packet); 3877 } 3878 else 3879 { 3880 const uint32_t mode = response.GetS32(-1); 3881 if (static_cast<int32_t>(mode) == -1) 3882 { 3883 if (response.GetChar() == ',') 3884 { 3885 int response_errno = response.GetS32(-1); 3886 if (response_errno > 0) 3887 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3888 else 3889 error.SetErrorToGenericError(); 3890 } 3891 else 3892 error.SetErrorToGenericError(); 3893 } 3894 else 3895 { 3896 file_permissions = mode & (S_IRWXU|S_IRWXG|S_IRWXO); 3897 } 3898 } 3899 } 3900 else 3901 { 3902 error.SetErrorStringWithFormat ("failed to send '%s' packet", packet); 3903 } 3904 return error; 3905 } 3906 3907 uint64_t 3908 GDBRemoteCommunicationClient::ReadFile (lldb::user_id_t fd, 3909 uint64_t offset, 3910 void *dst, 3911 uint64_t dst_len, 3912 Error &error) 3913 { 3914 lldb_private::StreamString stream; 3915 stream.Printf("vFile:pread:%i,%" PRId64 ",%" PRId64, (int)fd, dst_len, offset); 3916 const char* packet = stream.GetData(); 3917 int packet_len = stream.GetSize(); 3918 StringExtractorGDBRemote response; 3919 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3920 { 3921 if (response.GetChar() != 'F') 3922 return 0; 3923 uint32_t retcode = response.GetHexMaxU32(false, UINT32_MAX); 3924 if (retcode == UINT32_MAX) 3925 return retcode; 3926 const char next = (response.Peek() ? *response.Peek() : 0); 3927 if (next == ',') 3928 return 0; 3929 if (next == ';') 3930 { 3931 response.GetChar(); // skip the semicolon 3932 std::string buffer; 3933 if (response.GetEscapedBinaryData(buffer)) 3934 { 3935 const uint64_t data_to_write = std::min<uint64_t>(dst_len, buffer.size()); 3936 if (data_to_write > 0) 3937 memcpy(dst, &buffer[0], data_to_write); 3938 return data_to_write; 3939 } 3940 } 3941 } 3942 return 0; 3943 } 3944 3945 uint64_t 3946 GDBRemoteCommunicationClient::WriteFile (lldb::user_id_t fd, 3947 uint64_t offset, 3948 const void* src, 3949 uint64_t src_len, 3950 Error &error) 3951 { 3952 lldb_private::StreamGDBRemote stream; 3953 stream.Printf("vFile:pwrite:%i,%" PRId64 ",", (int)fd, offset); 3954 stream.PutEscapedBytes(src, src_len); 3955 const char* packet = stream.GetData(); 3956 int packet_len = stream.GetSize(); 3957 StringExtractorGDBRemote response; 3958 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 3959 { 3960 if (response.GetChar() != 'F') 3961 { 3962 error.SetErrorStringWithFormat("write file failed"); 3963 return 0; 3964 } 3965 uint64_t bytes_written = response.GetU64(UINT64_MAX); 3966 if (bytes_written == UINT64_MAX) 3967 { 3968 error.SetErrorToGenericError(); 3969 if (response.GetChar() == ',') 3970 { 3971 int response_errno = response.GetS32(-1); 3972 if (response_errno > 0) 3973 error.SetError(response_errno, lldb::eErrorTypePOSIX); 3974 } 3975 return 0; 3976 } 3977 return bytes_written; 3978 } 3979 else 3980 { 3981 error.SetErrorString ("failed to send vFile:pwrite packet"); 3982 } 3983 return 0; 3984 } 3985 3986 Error 3987 GDBRemoteCommunicationClient::CreateSymlink(const FileSpec &src, const FileSpec &dst) 3988 { 3989 std::string src_path{src.GetPath(false)}, 3990 dst_path{dst.GetPath(false)}; 3991 Error error; 3992 lldb_private::StreamGDBRemote stream; 3993 stream.PutCString("vFile:symlink:"); 3994 // the unix symlink() command reverses its parameters where the dst if first, 3995 // so we follow suit here 3996 stream.PutCStringAsRawHex8(dst_path.c_str()); 3997 stream.PutChar(','); 3998 stream.PutCStringAsRawHex8(src_path.c_str()); 3999 const char* packet = stream.GetData(); 4000 int packet_len = stream.GetSize(); 4001 StringExtractorGDBRemote response; 4002 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 4003 { 4004 if (response.GetChar() == 'F') 4005 { 4006 uint32_t result = response.GetU32(UINT32_MAX); 4007 if (result != 0) 4008 { 4009 error.SetErrorToGenericError(); 4010 if (response.GetChar() == ',') 4011 { 4012 int response_errno = response.GetS32(-1); 4013 if (response_errno > 0) 4014 error.SetError(response_errno, lldb::eErrorTypePOSIX); 4015 } 4016 } 4017 } 4018 else 4019 { 4020 // Should have returned with 'F<result>[,<errno>]' 4021 error.SetErrorStringWithFormat("symlink failed"); 4022 } 4023 } 4024 else 4025 { 4026 error.SetErrorString ("failed to send vFile:symlink packet"); 4027 } 4028 return error; 4029 } 4030 4031 Error 4032 GDBRemoteCommunicationClient::Unlink(const FileSpec &file_spec) 4033 { 4034 std::string path{file_spec.GetPath(false)}; 4035 Error error; 4036 lldb_private::StreamGDBRemote stream; 4037 stream.PutCString("vFile:unlink:"); 4038 // the unix symlink() command reverses its parameters where the dst if first, 4039 // so we follow suit here 4040 stream.PutCStringAsRawHex8(path.c_str()); 4041 const char* packet = stream.GetData(); 4042 int packet_len = stream.GetSize(); 4043 StringExtractorGDBRemote response; 4044 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 4045 { 4046 if (response.GetChar() == 'F') 4047 { 4048 uint32_t result = response.GetU32(UINT32_MAX); 4049 if (result != 0) 4050 { 4051 error.SetErrorToGenericError(); 4052 if (response.GetChar() == ',') 4053 { 4054 int response_errno = response.GetS32(-1); 4055 if (response_errno > 0) 4056 error.SetError(response_errno, lldb::eErrorTypePOSIX); 4057 } 4058 } 4059 } 4060 else 4061 { 4062 // Should have returned with 'F<result>[,<errno>]' 4063 error.SetErrorStringWithFormat("unlink failed"); 4064 } 4065 } 4066 else 4067 { 4068 error.SetErrorString ("failed to send vFile:unlink packet"); 4069 } 4070 return error; 4071 } 4072 4073 // Extension of host I/O packets to get whether a file exists. 4074 bool 4075 GDBRemoteCommunicationClient::GetFileExists (const lldb_private::FileSpec& file_spec) 4076 { 4077 std::string path(file_spec.GetPath(false)); 4078 lldb_private::StreamString stream; 4079 stream.PutCString("vFile:exists:"); 4080 stream.PutCStringAsRawHex8(path.c_str()); 4081 const char* packet = stream.GetData(); 4082 int packet_len = stream.GetSize(); 4083 StringExtractorGDBRemote response; 4084 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 4085 { 4086 if (response.GetChar() != 'F') 4087 return false; 4088 if (response.GetChar() != ',') 4089 return false; 4090 bool retcode = (response.GetChar() != '0'); 4091 return retcode; 4092 } 4093 return false; 4094 } 4095 4096 bool 4097 GDBRemoteCommunicationClient::CalculateMD5 (const lldb_private::FileSpec& file_spec, 4098 uint64_t &high, 4099 uint64_t &low) 4100 { 4101 std::string path(file_spec.GetPath(false)); 4102 lldb_private::StreamString stream; 4103 stream.PutCString("vFile:MD5:"); 4104 stream.PutCStringAsRawHex8(path.c_str()); 4105 const char* packet = stream.GetData(); 4106 int packet_len = stream.GetSize(); 4107 StringExtractorGDBRemote response; 4108 if (SendPacketAndWaitForResponse(packet, packet_len, response, false) == PacketResult::Success) 4109 { 4110 if (response.GetChar() != 'F') 4111 return false; 4112 if (response.GetChar() != ',') 4113 return false; 4114 if (response.Peek() && *response.Peek() == 'x') 4115 return false; 4116 low = response.GetHexMaxU64(false, UINT64_MAX); 4117 high = response.GetHexMaxU64(false, UINT64_MAX); 4118 return true; 4119 } 4120 return false; 4121 } 4122 4123 bool 4124 GDBRemoteCommunicationClient::AvoidGPackets (ProcessGDBRemote *process) 4125 { 4126 // Some targets have issues with g/G packets and we need to avoid using them 4127 if (m_avoid_g_packets == eLazyBoolCalculate) 4128 { 4129 if (process) 4130 { 4131 m_avoid_g_packets = eLazyBoolNo; 4132 const ArchSpec &arch = process->GetTarget().GetArchitecture(); 4133 if (arch.IsValid() 4134 && arch.GetTriple().getVendor() == llvm::Triple::Apple 4135 && arch.GetTriple().getOS() == llvm::Triple::IOS 4136 && arch.GetTriple().getArch() == llvm::Triple::aarch64) 4137 { 4138 m_avoid_g_packets = eLazyBoolYes; 4139 uint32_t gdb_server_version = GetGDBServerProgramVersion(); 4140 if (gdb_server_version != 0) 4141 { 4142 const char *gdb_server_name = GetGDBServerProgramName(); 4143 if (gdb_server_name && strcmp(gdb_server_name, "debugserver") == 0) 4144 { 4145 if (gdb_server_version >= 310) 4146 m_avoid_g_packets = eLazyBoolNo; 4147 } 4148 } 4149 } 4150 } 4151 } 4152 return m_avoid_g_packets == eLazyBoolYes; 4153 } 4154 4155 bool 4156 GDBRemoteCommunicationClient::ReadRegister(lldb::tid_t tid, uint32_t reg, StringExtractorGDBRemote &response) 4157 { 4158 Mutex::Locker locker; 4159 if (GetSequenceMutex (locker, "Didn't get sequence mutex for p packet.")) 4160 { 4161 const bool thread_suffix_supported = GetThreadSuffixSupported(); 4162 4163 if (thread_suffix_supported || SetCurrentThread(tid)) 4164 { 4165 char packet[64]; 4166 int packet_len = 0; 4167 if (thread_suffix_supported) 4168 packet_len = ::snprintf (packet, sizeof(packet), "p%x;thread:%4.4" PRIx64 ";", reg, tid); 4169 else 4170 packet_len = ::snprintf (packet, sizeof(packet), "p%x", reg); 4171 assert (packet_len < ((int)sizeof(packet) - 1)); 4172 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 4173 } 4174 } 4175 return false; 4176 4177 } 4178 4179 4180 bool 4181 GDBRemoteCommunicationClient::ReadAllRegisters (lldb::tid_t tid, StringExtractorGDBRemote &response) 4182 { 4183 Mutex::Locker locker; 4184 if (GetSequenceMutex (locker, "Didn't get sequence mutex for g packet.")) 4185 { 4186 const bool thread_suffix_supported = GetThreadSuffixSupported(); 4187 4188 if (thread_suffix_supported || SetCurrentThread(tid)) 4189 { 4190 char packet[64]; 4191 int packet_len = 0; 4192 // Get all registers in one packet 4193 if (thread_suffix_supported) 4194 packet_len = ::snprintf (packet, sizeof(packet), "g;thread:%4.4" PRIx64 ";", tid); 4195 else 4196 packet_len = ::snprintf (packet, sizeof(packet), "g"); 4197 assert (packet_len < ((int)sizeof(packet) - 1)); 4198 return SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success; 4199 } 4200 } 4201 return false; 4202 } 4203 bool 4204 GDBRemoteCommunicationClient::SaveRegisterState (lldb::tid_t tid, uint32_t &save_id) 4205 { 4206 save_id = 0; // Set to invalid save ID 4207 if (m_supports_QSaveRegisterState == eLazyBoolNo) 4208 return false; 4209 4210 m_supports_QSaveRegisterState = eLazyBoolYes; 4211 Mutex::Locker locker; 4212 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QSaveRegisterState.")) 4213 { 4214 const bool thread_suffix_supported = GetThreadSuffixSupported(); 4215 if (thread_suffix_supported || SetCurrentThread(tid)) 4216 { 4217 char packet[256]; 4218 if (thread_suffix_supported) 4219 ::snprintf (packet, sizeof(packet), "QSaveRegisterState;thread:%4.4" PRIx64 ";", tid); 4220 else 4221 ::snprintf(packet, sizeof(packet), "QSaveRegisterState"); 4222 4223 StringExtractorGDBRemote response; 4224 4225 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 4226 { 4227 if (response.IsUnsupportedResponse()) 4228 { 4229 // This packet isn't supported, don't try calling it again 4230 m_supports_QSaveRegisterState = eLazyBoolNo; 4231 } 4232 4233 const uint32_t response_save_id = response.GetU32(0); 4234 if (response_save_id != 0) 4235 { 4236 save_id = response_save_id; 4237 return true; 4238 } 4239 } 4240 } 4241 } 4242 return false; 4243 } 4244 4245 bool 4246 GDBRemoteCommunicationClient::RestoreRegisterState (lldb::tid_t tid, uint32_t save_id) 4247 { 4248 // We use the "m_supports_QSaveRegisterState" variable here because the 4249 // QSaveRegisterState and QRestoreRegisterState packets must both be supported in 4250 // order to be useful 4251 if (m_supports_QSaveRegisterState == eLazyBoolNo) 4252 return false; 4253 4254 Mutex::Locker locker; 4255 if (GetSequenceMutex (locker, "Didn't get sequence mutex for QRestoreRegisterState.")) 4256 { 4257 const bool thread_suffix_supported = GetThreadSuffixSupported(); 4258 if (thread_suffix_supported || SetCurrentThread(tid)) 4259 { 4260 char packet[256]; 4261 if (thread_suffix_supported) 4262 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u;thread:%4.4" PRIx64 ";", save_id, tid); 4263 else 4264 ::snprintf (packet, sizeof(packet), "QRestoreRegisterState:%u" PRIx64 ";", save_id); 4265 4266 StringExtractorGDBRemote response; 4267 4268 if (SendPacketAndWaitForResponse(packet, response, false) == PacketResult::Success) 4269 { 4270 if (response.IsOKResponse()) 4271 { 4272 return true; 4273 } 4274 else if (response.IsUnsupportedResponse()) 4275 { 4276 // This packet isn't supported, don't try calling this packet or 4277 // QSaveRegisterState again... 4278 m_supports_QSaveRegisterState = eLazyBoolNo; 4279 } 4280 } 4281 } 4282 } 4283 return false; 4284 } 4285 4286 bool 4287 GDBRemoteCommunicationClient::GetModuleInfo (const FileSpec& module_file_spec, 4288 const lldb_private::ArchSpec& arch_spec, 4289 ModuleSpec &module_spec) 4290 { 4291 if (!m_supports_qModuleInfo) 4292 return false; 4293 4294 std::string module_path = module_file_spec.GetPath (false); 4295 if (module_path.empty ()) 4296 return false; 4297 4298 StreamString packet; 4299 packet.PutCString("qModuleInfo:"); 4300 packet.PutCStringAsRawHex8(module_path.c_str()); 4301 packet.PutCString(";"); 4302 const auto& triple = arch_spec.GetTriple().getTriple(); 4303 packet.PutCStringAsRawHex8(triple.c_str()); 4304 4305 StringExtractorGDBRemote response; 4306 if (SendPacketAndWaitForResponse (packet.GetData(), packet.GetSize(), response, false) != PacketResult::Success) 4307 return false; 4308 4309 if (response.IsErrorResponse ()) 4310 return false; 4311 4312 if (response.IsUnsupportedResponse ()) 4313 { 4314 m_supports_qModuleInfo = false; 4315 return false; 4316 } 4317 4318 std::string name; 4319 std::string value; 4320 bool success; 4321 StringExtractor extractor; 4322 4323 module_spec.Clear (); 4324 module_spec.GetFileSpec () = module_file_spec; 4325 4326 while (response.GetNameColonValue (name, value)) 4327 { 4328 if (name == "uuid" || name == "md5") 4329 { 4330 extractor.GetStringRef ().swap (value); 4331 extractor.SetFilePos (0); 4332 extractor.GetHexByteString (value); 4333 module_spec.GetUUID().SetFromCString (value.c_str(), value.size() / 2); 4334 } 4335 else if (name == "triple") 4336 { 4337 extractor.GetStringRef ().swap (value); 4338 extractor.SetFilePos (0); 4339 extractor.GetHexByteString (value); 4340 module_spec.GetArchitecture().SetTriple (value.c_str ()); 4341 } 4342 else if (name == "file_offset") 4343 { 4344 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success); 4345 if (success) 4346 module_spec.SetObjectOffset (ival); 4347 } 4348 else if (name == "file_size") 4349 { 4350 const auto ival = StringConvert::ToUInt64 (value.c_str (), 0, 16, &success); 4351 if (success) 4352 module_spec.SetObjectSize (ival); 4353 } 4354 else if (name == "file_path") 4355 { 4356 extractor.GetStringRef ().swap (value); 4357 extractor.SetFilePos (0); 4358 extractor.GetHexByteString (value); 4359 module_spec.GetFileSpec() = FileSpec(value.c_str(), false, arch_spec); 4360 } 4361 } 4362 4363 return true; 4364 } 4365 4366 // query the target remote for extended information using the qXfer packet 4367 // 4368 // example: object='features', annex='target.xml', out=<xml output> 4369 // return: 'true' on success 4370 // 'false' on failure (err set) 4371 bool 4372 GDBRemoteCommunicationClient::ReadExtFeature (const lldb_private::ConstString object, 4373 const lldb_private::ConstString annex, 4374 std::string & out, 4375 lldb_private::Error & err) { 4376 4377 std::stringstream output; 4378 StringExtractorGDBRemote chunk; 4379 4380 uint64_t size = GetRemoteMaxPacketSize(); 4381 if (size == 0) 4382 size = 0x1000; 4383 size = size - 1; // Leave space for the 'm' or 'l' character in the response 4384 int offset = 0; 4385 bool active = true; 4386 4387 // loop until all data has been read 4388 while ( active ) { 4389 4390 // send query extended feature packet 4391 std::stringstream packet; 4392 packet << "qXfer:" 4393 << object.AsCString("") << ":read:" 4394 << annex.AsCString("") << ":" 4395 << std::hex << offset << "," 4396 << std::hex << size; 4397 4398 GDBRemoteCommunication::PacketResult res = 4399 SendPacketAndWaitForResponse( packet.str().c_str(), 4400 chunk, 4401 false ); 4402 4403 if ( res != GDBRemoteCommunication::PacketResult::Success ) { 4404 err.SetErrorString( "Error sending $qXfer packet" ); 4405 return false; 4406 } 4407 4408 const std::string & str = chunk.GetStringRef( ); 4409 if ( str.length() == 0 ) { 4410 // should have some data in chunk 4411 err.SetErrorString( "Empty response from $qXfer packet" ); 4412 return false; 4413 } 4414 4415 // check packet code 4416 switch ( str[0] ) { 4417 // last chunk 4418 case ( 'l' ): 4419 active = false; 4420 // fall through intentional 4421 4422 // more chunks 4423 case ( 'm' ) : 4424 if ( str.length() > 1 ) 4425 output << &str[1]; 4426 offset += size; 4427 break; 4428 4429 // unknown chunk 4430 default: 4431 err.SetErrorString( "Invalid continuation code from $qXfer packet" ); 4432 return false; 4433 } 4434 } 4435 4436 out = output.str( ); 4437 err.Success( ); 4438 return true; 4439 } 4440 4441 // Notify the target that gdb is prepared to serve symbol lookup requests. 4442 // packet: "qSymbol::" 4443 // reply: 4444 // OK The target does not need to look up any (more) symbols. 4445 // qSymbol:<sym_name> The target requests the value of symbol sym_name (hex encoded). 4446 // LLDB may provide the value by sending another qSymbol packet 4447 // in the form of"qSymbol:<sym_value>:<sym_name>". 4448 // 4449 // Three examples: 4450 // 4451 // lldb sends: qSymbol:: 4452 // lldb receives: OK 4453 // Remote gdb stub does not need to know the addresses of any symbols, lldb does not 4454 // need to ask again in this session. 4455 // 4456 // lldb sends: qSymbol:: 4457 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 4458 // lldb sends: qSymbol::64697370617463685f71756575655f6f666673657473 4459 // lldb receives: OK 4460 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb does not know 4461 // the address at this time. lldb needs to send qSymbol:: again when it has more 4462 // solibs loaded. 4463 // 4464 // lldb sends: qSymbol:: 4465 // lldb receives: qSymbol:64697370617463685f71756575655f6f666673657473 4466 // lldb sends: qSymbol:2bc97554:64697370617463685f71756575655f6f666673657473 4467 // lldb receives: OK 4468 // Remote gdb stub asks for address of 'dispatch_queue_offsets'. lldb says that it 4469 // is at address 0x2bc97554. Remote gdb stub sends 'OK' indicating that it does not 4470 // need any more symbols. lldb does not need to ask again in this session. 4471 4472 void 4473 GDBRemoteCommunicationClient::ServeSymbolLookups(lldb_private::Process *process) 4474 { 4475 // Set to true once we've resolved a symbol to an address for the remote stub. 4476 // If we get an 'OK' response after this, the remote stub doesn't need any more 4477 // symbols and we can stop asking. 4478 bool symbol_response_provided = false; 4479 4480 // Is this the inital qSymbol:: packet? 4481 bool first_qsymbol_query = true; 4482 4483 if (m_supports_qSymbol && m_qSymbol_requests_done == false) 4484 { 4485 Mutex::Locker locker; 4486 if (GetSequenceMutex(locker, "GDBRemoteCommunicationClient::ServeSymbolLookups() failed due to not getting the sequence mutex")) 4487 { 4488 StreamString packet; 4489 packet.PutCString ("qSymbol::"); 4490 StringExtractorGDBRemote response; 4491 while (SendPacketAndWaitForResponseNoLock(packet.GetData(), packet.GetSize(), response) == PacketResult::Success) 4492 { 4493 if (response.IsOKResponse()) 4494 { 4495 if (symbol_response_provided || first_qsymbol_query) 4496 { 4497 m_qSymbol_requests_done = true; 4498 } 4499 4500 // We are done serving symbols requests 4501 return; 4502 } 4503 first_qsymbol_query = false; 4504 4505 if (response.IsUnsupportedResponse()) 4506 { 4507 // qSymbol is not supported by the current GDB server we are connected to 4508 m_supports_qSymbol = false; 4509 return; 4510 } 4511 else 4512 { 4513 llvm::StringRef response_str(response.GetStringRef()); 4514 if (response_str.startswith("qSymbol:")) 4515 { 4516 response.SetFilePos(strlen("qSymbol:")); 4517 std::string symbol_name; 4518 if (response.GetHexByteString(symbol_name)) 4519 { 4520 if (symbol_name.empty()) 4521 return; 4522 4523 addr_t symbol_load_addr = LLDB_INVALID_ADDRESS; 4524 lldb_private::SymbolContextList sc_list; 4525 if (process->GetTarget().GetImages().FindSymbolsWithNameAndType(ConstString(symbol_name), eSymbolTypeAny, sc_list)) 4526 { 4527 const size_t num_scs = sc_list.GetSize(); 4528 for (size_t sc_idx=0; sc_idx<num_scs && symbol_load_addr == LLDB_INVALID_ADDRESS; ++sc_idx) 4529 { 4530 SymbolContext sc; 4531 if (sc_list.GetContextAtIndex(sc_idx, sc)) 4532 { 4533 if (sc.symbol) 4534 { 4535 switch (sc.symbol->GetType()) 4536 { 4537 case eSymbolTypeInvalid: 4538 case eSymbolTypeAbsolute: 4539 case eSymbolTypeUndefined: 4540 case eSymbolTypeSourceFile: 4541 case eSymbolTypeHeaderFile: 4542 case eSymbolTypeObjectFile: 4543 case eSymbolTypeCommonBlock: 4544 case eSymbolTypeBlock: 4545 case eSymbolTypeLocal: 4546 case eSymbolTypeParam: 4547 case eSymbolTypeVariable: 4548 case eSymbolTypeVariableType: 4549 case eSymbolTypeLineEntry: 4550 case eSymbolTypeLineHeader: 4551 case eSymbolTypeScopeBegin: 4552 case eSymbolTypeScopeEnd: 4553 case eSymbolTypeAdditional: 4554 case eSymbolTypeCompiler: 4555 case eSymbolTypeInstrumentation: 4556 case eSymbolTypeTrampoline: 4557 break; 4558 4559 case eSymbolTypeCode: 4560 case eSymbolTypeResolver: 4561 case eSymbolTypeData: 4562 case eSymbolTypeRuntime: 4563 case eSymbolTypeException: 4564 case eSymbolTypeObjCClass: 4565 case eSymbolTypeObjCMetaClass: 4566 case eSymbolTypeObjCIVar: 4567 case eSymbolTypeReExported: 4568 symbol_load_addr = sc.symbol->GetLoadAddress(&process->GetTarget()); 4569 break; 4570 } 4571 } 4572 } 4573 } 4574 } 4575 // This is the normal path where our symbol lookup was successful and we want 4576 // to send a packet with the new symbol value and see if another lookup needs to be 4577 // done. 4578 4579 // Change "packet" to contain the requested symbol value and name 4580 packet.Clear(); 4581 packet.PutCString("qSymbol:"); 4582 if (symbol_load_addr != LLDB_INVALID_ADDRESS) 4583 { 4584 packet.Printf("%" PRIx64, symbol_load_addr); 4585 symbol_response_provided = true; 4586 } 4587 else 4588 { 4589 symbol_response_provided = false; 4590 } 4591 packet.PutCString(":"); 4592 packet.PutBytesAsRawHex8(symbol_name.data(), symbol_name.size()); 4593 continue; // go back to the while loop and send "packet" and wait for another response 4594 } 4595 } 4596 } 4597 } 4598 // If we make it here, the symbol request packet response wasn't valid or 4599 // our symbol lookup failed so we must abort 4600 return; 4601 4602 } 4603 } 4604 } 4605 4606