ProcessGDBRemote.cpp revision 288943
1//===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9 10#include "lldb/Host/Config.h" 11 12// C Includes 13#include <errno.h> 14#include <stdlib.h> 15#ifndef LLDB_DISABLE_POSIX 16#include <netinet/in.h> 17#include <sys/mman.h> // for mmap 18#endif 19#include <sys/stat.h> 20#include <sys/types.h> 21#include <time.h> 22 23// C++ Includes 24#include <algorithm> 25#include <map> 26#include <mutex> 27 28#include "lldb/Breakpoint/Watchpoint.h" 29#include "lldb/Interpreter/Args.h" 30#include "lldb/Core/ArchSpec.h" 31#include "lldb/Core/Debugger.h" 32#include "lldb/Host/ConnectionFileDescriptor.h" 33#include "lldb/Host/FileSpec.h" 34#include "lldb/Core/Module.h" 35#include "lldb/Core/ModuleSpec.h" 36#include "lldb/Core/PluginManager.h" 37#include "lldb/Core/State.h" 38#include "lldb/Core/StreamFile.h" 39#include "lldb/Core/StreamString.h" 40#include "lldb/Core/Timer.h" 41#include "lldb/Core/Value.h" 42#include "lldb/DataFormatters/FormatManager.h" 43#include "lldb/Host/HostThread.h" 44#include "lldb/Host/StringConvert.h" 45#include "lldb/Host/Symbols.h" 46#include "lldb/Host/ThreadLauncher.h" 47#include "lldb/Host/TimeValue.h" 48#include "lldb/Host/XML.h" 49#include "lldb/Interpreter/CommandInterpreter.h" 50#include "lldb/Interpreter/CommandObject.h" 51#include "lldb/Interpreter/CommandObjectMultiword.h" 52#include "lldb/Interpreter/CommandReturnObject.h" 53#include "lldb/Interpreter/OptionValueProperties.h" 54#include "lldb/Interpreter/Options.h" 55#include "lldb/Interpreter/OptionGroupBoolean.h" 56#include "lldb/Interpreter/OptionGroupUInt64.h" 57#include "lldb/Interpreter/Property.h" 58#include "lldb/Symbol/ObjectFile.h" 59#include "lldb/Target/DynamicLoader.h" 60#include "lldb/Target/Target.h" 61#include "lldb/Target/TargetList.h" 62#include "lldb/Target/ThreadPlanCallFunction.h" 63#include "lldb/Target/SystemRuntime.h" 64#include "lldb/Utility/PseudoTerminal.h" 65 66// Project includes 67#include "lldb/Host/Host.h" 68#include "Plugins/Process/Utility/GDBRemoteSignals.h" 69#include "Plugins/Process/Utility/InferiorCallPOSIX.h" 70#include "Plugins/Process/Utility/StopInfoMachException.h" 71#include "Utility/StringExtractorGDBRemote.h" 72#include "GDBRemoteRegisterContext.h" 73#include "ProcessGDBRemote.h" 74#include "ProcessGDBRemoteLog.h" 75#include "ThreadGDBRemote.h" 76 77#define DEBUGSERVER_BASENAME "debugserver" 78using namespace lldb; 79using namespace lldb_private; 80using namespace lldb_private::process_gdb_remote; 81 82namespace lldb 83{ 84 // Provide a function that can easily dump the packet history if we know a 85 // ProcessGDBRemote * value (which we can get from logs or from debugging). 86 // We need the function in the lldb namespace so it makes it into the final 87 // executable since the LLDB shared library only exports stuff in the lldb 88 // namespace. This allows you to attach with a debugger and call this 89 // function and get the packet history dumped to a file. 90 void 91 DumpProcessGDBRemotePacketHistory (void *p, const char *path) 92 { 93 StreamFile strm; 94 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate)); 95 if (error.Success()) 96 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm); 97 } 98} 99 100namespace { 101 102 static PropertyDefinition 103 g_properties[] = 104 { 105 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." }, 106 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." }, 107 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL } 108 }; 109 110 enum 111 { 112 ePropertyPacketTimeout, 113 ePropertyTargetDefinitionFile 114 }; 115 116 class PluginProperties : public Properties 117 { 118 public: 119 120 static ConstString 121 GetSettingName () 122 { 123 return ProcessGDBRemote::GetPluginNameStatic(); 124 } 125 126 PluginProperties() : 127 Properties () 128 { 129 m_collection_sp.reset (new OptionValueProperties(GetSettingName())); 130 m_collection_sp->Initialize(g_properties); 131 } 132 133 virtual 134 ~PluginProperties() 135 { 136 } 137 138 uint64_t 139 GetPacketTimeout() 140 { 141 const uint32_t idx = ePropertyPacketTimeout; 142 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value); 143 } 144 145 bool 146 SetPacketTimeout(uint64_t timeout) 147 { 148 const uint32_t idx = ePropertyPacketTimeout; 149 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout); 150 } 151 152 FileSpec 153 GetTargetDefinitionFile () const 154 { 155 const uint32_t idx = ePropertyTargetDefinitionFile; 156 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx); 157 } 158 }; 159 160 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP; 161 162 static const ProcessKDPPropertiesSP & 163 GetGlobalPluginProperties() 164 { 165 static ProcessKDPPropertiesSP g_settings_sp; 166 if (!g_settings_sp) 167 g_settings_sp.reset (new PluginProperties ()); 168 return g_settings_sp; 169 } 170 171} // anonymous namespace end 172 173class ProcessGDBRemote::GDBLoadedModuleInfoList 174{ 175public: 176 177 class LoadedModuleInfo 178 { 179 public: 180 181 enum e_data_point 182 { 183 e_has_name = 0, 184 e_has_base , 185 e_has_dynamic , 186 e_has_link_map , 187 e_num 188 }; 189 190 LoadedModuleInfo () 191 { 192 for (uint32_t i = 0; i < e_num; ++i) 193 m_has[i] = false; 194 }; 195 196 void set_name (const std::string & name) 197 { 198 m_name = name; 199 m_has[e_has_name] = true; 200 } 201 bool get_name (std::string & out) const 202 { 203 out = m_name; 204 return m_has[e_has_name]; 205 } 206 207 void set_base (const lldb::addr_t base) 208 { 209 m_base = base; 210 m_has[e_has_base] = true; 211 } 212 bool get_base (lldb::addr_t & out) const 213 { 214 out = m_base; 215 return m_has[e_has_base]; 216 } 217 218 void set_link_map (const lldb::addr_t addr) 219 { 220 m_link_map = addr; 221 m_has[e_has_link_map] = true; 222 } 223 bool get_link_map (lldb::addr_t & out) const 224 { 225 out = m_link_map; 226 return m_has[e_has_link_map]; 227 } 228 229 void set_dynamic (const lldb::addr_t addr) 230 { 231 m_dynamic = addr; 232 m_has[e_has_dynamic] = true; 233 } 234 bool get_dynamic (lldb::addr_t & out) const 235 { 236 out = m_dynamic; 237 return m_has[e_has_dynamic]; 238 } 239 240 bool has_info (e_data_point datum) 241 { 242 assert (datum < e_num); 243 return m_has[datum]; 244 } 245 246 protected: 247 248 bool m_has[e_num]; 249 std::string m_name; 250 lldb::addr_t m_link_map; 251 lldb::addr_t m_base; 252 lldb::addr_t m_dynamic; 253 }; 254 255 GDBLoadedModuleInfoList () 256 : m_list () 257 , m_link_map (LLDB_INVALID_ADDRESS) 258 {} 259 260 void add (const LoadedModuleInfo & mod) 261 { 262 m_list.push_back (mod); 263 } 264 265 void clear () 266 { 267 m_list.clear (); 268 } 269 270 std::vector<LoadedModuleInfo> m_list; 271 lldb::addr_t m_link_map; 272}; 273 274// TODO Randomly assigning a port is unsafe. We should get an unused 275// ephemeral port from the kernel and make sure we reserve it before passing 276// it to debugserver. 277 278#if defined (__APPLE__) 279#define LOW_PORT (IPPORT_RESERVED) 280#define HIGH_PORT (IPPORT_HIFIRSTAUTO) 281#else 282#define LOW_PORT (1024u) 283#define HIGH_PORT (49151u) 284#endif 285 286#if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__)) 287static bool rand_initialized = false; 288 289static inline uint16_t 290get_random_port () 291{ 292 if (!rand_initialized) 293 { 294 time_t seed = time(NULL); 295 296 rand_initialized = true; 297 srand(seed); 298 } 299 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT; 300} 301#endif 302 303ConstString 304ProcessGDBRemote::GetPluginNameStatic() 305{ 306 static ConstString g_name("gdb-remote"); 307 return g_name; 308} 309 310const char * 311ProcessGDBRemote::GetPluginDescriptionStatic() 312{ 313 return "GDB Remote protocol based debugging plug-in."; 314} 315 316void 317ProcessGDBRemote::Terminate() 318{ 319 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance); 320} 321 322 323lldb::ProcessSP 324ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path) 325{ 326 lldb::ProcessSP process_sp; 327 if (crash_file_path == NULL) 328 process_sp.reset (new ProcessGDBRemote (target, listener)); 329 return process_sp; 330} 331 332bool 333ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name) 334{ 335 if (plugin_specified_by_name) 336 return true; 337 338 // For now we are just making sure the file exists for a given module 339 Module *exe_module = target.GetExecutableModulePointer(); 340 if (exe_module) 341 { 342 ObjectFile *exe_objfile = exe_module->GetObjectFile(); 343 // We can't debug core files... 344 switch (exe_objfile->GetType()) 345 { 346 case ObjectFile::eTypeInvalid: 347 case ObjectFile::eTypeCoreFile: 348 case ObjectFile::eTypeDebugInfo: 349 case ObjectFile::eTypeObjectFile: 350 case ObjectFile::eTypeSharedLibrary: 351 case ObjectFile::eTypeStubLibrary: 352 case ObjectFile::eTypeJIT: 353 return false; 354 case ObjectFile::eTypeExecutable: 355 case ObjectFile::eTypeDynamicLinker: 356 case ObjectFile::eTypeUnknown: 357 break; 358 } 359 return exe_module->GetFileSpec().Exists(); 360 } 361 // However, if there is no executable module, we return true since we might be preparing to attach. 362 return true; 363} 364 365//---------------------------------------------------------------------- 366// ProcessGDBRemote constructor 367//---------------------------------------------------------------------- 368ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) : 369 Process (target, listener), 370 m_flags (0), 371 m_gdb_comm (), 372 m_debugserver_pid (LLDB_INVALID_PROCESS_ID), 373 m_last_stop_packet_mutex (Mutex::eMutexTypeRecursive), 374 m_register_info (), 375 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"), 376 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive), 377 m_thread_ids (), 378 m_threads_info_sp (), 379 m_continue_c_tids (), 380 m_continue_C_tids (), 381 m_continue_s_tids (), 382 m_continue_S_tids (), 383 m_max_memory_size (0), 384 m_remote_stub_max_memory_size (0), 385 m_addr_to_mmap_size (), 386 m_thread_create_bp_sp (), 387 m_waiting_for_attach (false), 388 m_destroy_tried_resuming (false), 389 m_command_sp (), 390 m_breakpoint_pc_offset (0), 391 m_initial_tid (LLDB_INVALID_THREAD_ID) 392{ 393 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit"); 394 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue"); 395 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit"); 396 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout(); 397 if (timeout_seconds > 0) 398 m_gdb_comm.SetPacketTimeout(timeout_seconds); 399} 400 401//---------------------------------------------------------------------- 402// Destructor 403//---------------------------------------------------------------------- 404ProcessGDBRemote::~ProcessGDBRemote() 405{ 406 // m_mach_process.UnregisterNotificationCallbacks (this); 407 Clear(); 408 // We need to call finalize on the process before destroying ourselves 409 // to make sure all of the broadcaster cleanup goes as planned. If we 410 // destruct this class, then Process::~Process() might have problems 411 // trying to fully destroy the broadcaster. 412 Finalize(); 413 414 // The general Finalize is going to try to destroy the process and that SHOULD 415 // shut down the async thread. However, if we don't kill it it will get stranded and 416 // its connection will go away so when it wakes up it will crash. So kill it for sure here. 417 StopAsyncThread(); 418 KillDebugserverProcess(); 419} 420 421//---------------------------------------------------------------------- 422// PluginInterface 423//---------------------------------------------------------------------- 424ConstString 425ProcessGDBRemote::GetPluginName() 426{ 427 return GetPluginNameStatic(); 428} 429 430uint32_t 431ProcessGDBRemote::GetPluginVersion() 432{ 433 return 1; 434} 435 436bool 437ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec) 438{ 439 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); 440 Error error; 441 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error)); 442 if (module_object_sp) 443 { 444 StructuredData::DictionarySP target_definition_sp( 445 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error)); 446 447 if (target_definition_sp) 448 { 449 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info")); 450 if (target_object) 451 { 452 if (auto host_info_dict = target_object->GetAsDictionary()) 453 { 454 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple"); 455 if (auto triple_string_value = triple_value->GetAsString()) 456 { 457 std::string triple_string = triple_string_value->GetValue(); 458 ArchSpec host_arch(triple_string.c_str()); 459 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) 460 { 461 GetTarget().SetArchitecture(host_arch); 462 } 463 } 464 } 465 } 466 m_breakpoint_pc_offset = 0; 467 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset"); 468 if (breakpoint_pc_offset_value) 469 { 470 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger()) 471 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue(); 472 } 473 474 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0) 475 { 476 return true; 477 } 478 } 479 } 480 return false; 481} 482 483static size_t 484SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> ®nums, int base) 485{ 486 regnums.clear(); 487 std::pair<llvm::StringRef, llvm::StringRef> value_pair; 488 value_pair.second = comma_separated_regiter_numbers; 489 do 490 { 491 value_pair = value_pair.second.split(','); 492 if (!value_pair.first.empty()) 493 { 494 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base); 495 if (reg != LLDB_INVALID_REGNUM) 496 regnums.push_back (reg); 497 } 498 } while (!value_pair.second.empty()); 499 return regnums.size(); 500} 501 502 503void 504ProcessGDBRemote::BuildDynamicRegisterInfo (bool force) 505{ 506 if (!force && m_register_info.GetNumRegisters() > 0) 507 return; 508 509 m_register_info.Clear(); 510 511 // Check if qHostInfo specified a specific packet timeout for this connection. 512 // If so then lets update our setting so the user knows what the timeout is 513 // and can see it. 514 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout(); 515 if (host_packet_timeout) 516 { 517 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout); 518 } 519 520 // Register info search order: 521 // 1 - Use the target definition python file if one is specified. 522 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml. 523 // 3 - Fall back on the qRegisterInfo packets. 524 525 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile (); 526 if (target_definition_fspec) 527 { 528 // See if we can get register definitions from a python file 529 if (ParsePythonTargetDefinition (target_definition_fspec)) 530 return; 531 } 532 533 if (GetGDBServerRegisterInfo ()) 534 return; 535 536 char packet[128]; 537 uint32_t reg_offset = 0; 538 uint32_t reg_num = 0; 539 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse; 540 response_type == StringExtractorGDBRemote::eResponse; 541 ++reg_num) 542 { 543 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num); 544 assert (packet_len < (int)sizeof(packet)); 545 StringExtractorGDBRemote response; 546 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success) 547 { 548 response_type = response.GetResponseType(); 549 if (response_type == StringExtractorGDBRemote::eResponse) 550 { 551 std::string name; 552 std::string value; 553 ConstString reg_name; 554 ConstString alt_name; 555 ConstString set_name; 556 std::vector<uint32_t> value_regs; 557 std::vector<uint32_t> invalidate_regs; 558 RegisterInfo reg_info = { NULL, // Name 559 NULL, // Alt name 560 0, // byte size 561 reg_offset, // offset 562 eEncodingUint, // encoding 563 eFormatHex, // formate 564 { 565 LLDB_INVALID_REGNUM, // GCC reg num 566 LLDB_INVALID_REGNUM, // DWARF reg num 567 LLDB_INVALID_REGNUM, // generic reg num 568 reg_num, // GDB reg num 569 reg_num // native register number 570 }, 571 NULL, 572 NULL 573 }; 574 575 while (response.GetNameColonValue(name, value)) 576 { 577 if (name.compare("name") == 0) 578 { 579 reg_name.SetCString(value.c_str()); 580 } 581 else if (name.compare("alt-name") == 0) 582 { 583 alt_name.SetCString(value.c_str()); 584 } 585 else if (name.compare("bitsize") == 0) 586 { 587 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT; 588 } 589 else if (name.compare("offset") == 0) 590 { 591 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0); 592 if (reg_offset != offset) 593 { 594 reg_offset = offset; 595 } 596 } 597 else if (name.compare("encoding") == 0) 598 { 599 const Encoding encoding = Args::StringToEncoding (value.c_str()); 600 if (encoding != eEncodingInvalid) 601 reg_info.encoding = encoding; 602 } 603 else if (name.compare("format") == 0) 604 { 605 Format format = eFormatInvalid; 606 if (Args::StringToFormat (value.c_str(), format, NULL).Success()) 607 reg_info.format = format; 608 else if (value.compare("binary") == 0) 609 reg_info.format = eFormatBinary; 610 else if (value.compare("decimal") == 0) 611 reg_info.format = eFormatDecimal; 612 else if (value.compare("hex") == 0) 613 reg_info.format = eFormatHex; 614 else if (value.compare("float") == 0) 615 reg_info.format = eFormatFloat; 616 else if (value.compare("vector-sint8") == 0) 617 reg_info.format = eFormatVectorOfSInt8; 618 else if (value.compare("vector-uint8") == 0) 619 reg_info.format = eFormatVectorOfUInt8; 620 else if (value.compare("vector-sint16") == 0) 621 reg_info.format = eFormatVectorOfSInt16; 622 else if (value.compare("vector-uint16") == 0) 623 reg_info.format = eFormatVectorOfUInt16; 624 else if (value.compare("vector-sint32") == 0) 625 reg_info.format = eFormatVectorOfSInt32; 626 else if (value.compare("vector-uint32") == 0) 627 reg_info.format = eFormatVectorOfUInt32; 628 else if (value.compare("vector-float32") == 0) 629 reg_info.format = eFormatVectorOfFloat32; 630 else if (value.compare("vector-uint128") == 0) 631 reg_info.format = eFormatVectorOfUInt128; 632 } 633 else if (name.compare("set") == 0) 634 { 635 set_name.SetCString(value.c_str()); 636 } 637 else if (name.compare("gcc") == 0) 638 { 639 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 640 } 641 else if (name.compare("dwarf") == 0) 642 { 643 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 644 } 645 else if (name.compare("generic") == 0) 646 { 647 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str()); 648 } 649 else if (name.compare("container-regs") == 0) 650 { 651 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16); 652 } 653 else if (name.compare("invalidate-regs") == 0) 654 { 655 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16); 656 } 657 } 658 659 reg_info.byte_offset = reg_offset; 660 assert (reg_info.byte_size != 0); 661 reg_offset += reg_info.byte_size; 662 if (!value_regs.empty()) 663 { 664 value_regs.push_back(LLDB_INVALID_REGNUM); 665 reg_info.value_regs = value_regs.data(); 666 } 667 if (!invalidate_regs.empty()) 668 { 669 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 670 reg_info.invalidate_regs = invalidate_regs.data(); 671 } 672 673 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); 674 } 675 else 676 { 677 break; // ensure exit before reg_num is incremented 678 } 679 } 680 else 681 { 682 break; 683 } 684 } 685 686 if (m_register_info.GetNumRegisters() > 0) 687 { 688 m_register_info.Finalize(GetTarget().GetArchitecture()); 689 return; 690 } 691 692 // We didn't get anything if the accumulated reg_num is zero. See if we are 693 // debugging ARM and fill with a hard coded register set until we can get an 694 // updated debugserver down on the devices. 695 // On the other hand, if the accumulated reg_num is positive, see if we can 696 // add composite registers to the existing primordial ones. 697 bool from_scratch = (m_register_info.GetNumRegisters() == 0); 698 699 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 700 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture(); 701 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); 702 703 // Use the process' architecture instead of the host arch, if available 704 ArchSpec remote_arch; 705 if (remote_process_arch.IsValid ()) 706 remote_arch = remote_process_arch; 707 else 708 remote_arch = remote_host_arch; 709 710 if (!target_arch.IsValid()) 711 { 712 if (remote_arch.IsValid() 713 && remote_arch.GetMachine() == llvm::Triple::arm 714 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple) 715 m_register_info.HardcodeARMRegisters(from_scratch); 716 } 717 else if (target_arch.GetMachine() == llvm::Triple::arm) 718 { 719 m_register_info.HardcodeARMRegisters(from_scratch); 720 } 721 722 // At this point, we can finalize our register info. 723 m_register_info.Finalize (GetTarget().GetArchitecture()); 724} 725 726Error 727ProcessGDBRemote::WillLaunch (Module* module) 728{ 729 return WillLaunchOrAttach (); 730} 731 732Error 733ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid) 734{ 735 return WillLaunchOrAttach (); 736} 737 738Error 739ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) 740{ 741 return WillLaunchOrAttach (); 742} 743 744Error 745ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url) 746{ 747 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 748 Error error (WillLaunchOrAttach ()); 749 750 if (error.Fail()) 751 return error; 752 753 error = ConnectToDebugserver (remote_url); 754 755 if (error.Fail()) 756 return error; 757 StartAsyncThread (); 758 759 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 760 if (pid == LLDB_INVALID_PROCESS_ID) 761 { 762 // We don't have a valid process ID, so note that we are connected 763 // and could now request to launch or attach, or get remote process 764 // listings... 765 SetPrivateState (eStateConnected); 766 } 767 else 768 { 769 // We have a valid process 770 SetID (pid); 771 GetThreadList(); 772 StringExtractorGDBRemote response; 773 if (m_gdb_comm.GetStopReply(response)) 774 { 775 SetLastStopPacket(response); 776 777 // '?' Packets must be handled differently in non-stop mode 778 if (GetTarget().GetNonStopModeEnabled()) 779 HandleStopReplySequence(); 780 781 if (!m_target.GetArchitecture().IsValid()) 782 { 783 if (m_gdb_comm.GetProcessArchitecture().IsValid()) 784 { 785 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture()); 786 } 787 else 788 { 789 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture()); 790 } 791 } 792 793 const StateType state = SetThreadStopInfo (response); 794 if (state == eStateStopped) 795 { 796 SetPrivateState (state); 797 } 798 else 799 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state)); 800 } 801 else 802 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url); 803 } 804 805 if (log) 806 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalizing target architecture initial triple: %s (GetTarget().GetArchitecture().IsValid() %s, m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str (), GetTarget ().GetArchitecture ().IsValid () ? "true" : "false", m_gdb_comm.GetHostArchitecture ().IsValid () ? "true" : "false"); 807 808 809 if (error.Success() 810 && !GetTarget().GetArchitecture().IsValid() 811 && m_gdb_comm.GetHostArchitecture().IsValid()) 812 { 813 // Prefer the *process'* architecture over that of the *host*, if available. 814 if (m_gdb_comm.GetProcessArchitecture().IsValid()) 815 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture()); 816 else 817 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture()); 818 } 819 820 if (log) 821 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ()); 822 823 if (error.Success()) 824 { 825 PlatformSP platform_sp = GetTarget().GetPlatform(); 826 if (platform_sp && platform_sp->IsConnected()) 827 SetUnixSignals(platform_sp->GetUnixSignals()); 828 else 829 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture())); 830 } 831 832 return error; 833} 834 835Error 836ProcessGDBRemote::WillLaunchOrAttach () 837{ 838 Error error; 839 m_stdio_communication.Clear (); 840 return error; 841} 842 843//---------------------------------------------------------------------- 844// Process Control 845//---------------------------------------------------------------------- 846Error 847ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info) 848{ 849 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 850 Error error; 851 852 if (log) 853 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__); 854 855 uint32_t launch_flags = launch_info.GetFlags().Get(); 856 FileSpec stdin_file_spec{}; 857 FileSpec stdout_file_spec{}; 858 FileSpec stderr_file_spec{}; 859 FileSpec working_dir = launch_info.GetWorkingDirectory(); 860 861 const FileAction *file_action; 862 file_action = launch_info.GetFileActionForFD (STDIN_FILENO); 863 if (file_action) 864 { 865 if (file_action->GetAction() == FileAction::eFileActionOpen) 866 stdin_file_spec = file_action->GetFileSpec(); 867 } 868 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO); 869 if (file_action) 870 { 871 if (file_action->GetAction() == FileAction::eFileActionOpen) 872 stdout_file_spec = file_action->GetFileSpec(); 873 } 874 file_action = launch_info.GetFileActionForFD (STDERR_FILENO); 875 if (file_action) 876 { 877 if (file_action->GetAction() == FileAction::eFileActionOpen) 878 stderr_file_spec = file_action->GetFileSpec(); 879 } 880 881 if (log) 882 { 883 if (stdin_file_spec || stdout_file_spec || stderr_file_spec) 884 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s", 885 __FUNCTION__, 886 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>", 887 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>", 888 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>"); 889 else 890 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__); 891 } 892 893 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 894 if (stdin_file_spec || disable_stdio) 895 { 896 // the inferior will be reading stdin from the specified file 897 // or stdio is completely disabled 898 m_stdin_forward = false; 899 } 900 else 901 { 902 m_stdin_forward = true; 903 } 904 905 // ::LogSetBitMask (GDBR_LOG_DEFAULT); 906 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); 907 // ::LogSetLogFile ("/dev/stdout"); 908 909 ObjectFile * object_file = exe_module->GetObjectFile(); 910 if (object_file) 911 { 912 // Make sure we aren't already connected? 913 if (!m_gdb_comm.IsConnected()) 914 { 915 error = LaunchAndConnectToDebugserver (launch_info); 916 } 917 918 if (error.Success()) 919 { 920 lldb_utility::PseudoTerminal pty; 921 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 922 923 PlatformSP platform_sp (m_target.GetPlatform()); 924 if (disable_stdio) 925 { 926 // set to /dev/null unless redirected to a file above 927 if (!stdin_file_spec) 928 stdin_file_spec.SetFile("/dev/null", false); 929 if (!stdout_file_spec) 930 stdout_file_spec.SetFile("/dev/null", false); 931 if (!stderr_file_spec) 932 stderr_file_spec.SetFile("/dev/null", false); 933 } 934 else if (platform_sp && platform_sp->IsHost()) 935 { 936 // If the debugserver is local and we aren't disabling STDIO, lets use 937 // a pseudo terminal to instead of relying on the 'O' packets for stdio 938 // since 'O' packets can really slow down debugging if the inferior 939 // does a lot of output. 940 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) && 941 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0)) 942 { 943 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false}; 944 945 if (!stdin_file_spec) 946 stdin_file_spec = slave_name; 947 948 if (!stdout_file_spec) 949 stdout_file_spec = slave_name; 950 951 if (!stderr_file_spec) 952 stderr_file_spec = slave_name; 953 } 954 if (log) 955 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s", 956 __FUNCTION__, 957 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>", 958 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>", 959 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>"); 960 } 961 962 if (log) 963 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s", 964 __FUNCTION__, 965 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>", 966 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>", 967 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>"); 968 969 if (stdin_file_spec) 970 m_gdb_comm.SetSTDIN(stdin_file_spec); 971 if (stdout_file_spec) 972 m_gdb_comm.SetSTDOUT(stdout_file_spec); 973 if (stderr_file_spec) 974 m_gdb_comm.SetSTDERR(stderr_file_spec); 975 976 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR); 977 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError); 978 979 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName()); 980 981 const char * launch_event_data = launch_info.GetLaunchEventData(); 982 if (launch_event_data != NULL && *launch_event_data != '\0') 983 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data); 984 985 if (working_dir) 986 { 987 m_gdb_comm.SetWorkingDir (working_dir); 988 } 989 990 // Send the environment and the program + arguments after we connect 991 const Args &environment = launch_info.GetEnvironmentEntries(); 992 if (environment.GetArgumentCount()) 993 { 994 size_t num_environment_entries = environment.GetArgumentCount(); 995 for (size_t i=0; i<num_environment_entries; ++i) 996 { 997 const char *env_entry = environment.GetArgumentAtIndex(i); 998 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0) 999 break; 1000 } 1001 } 1002 1003 { 1004 // Scope for the scoped timeout object 1005 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10); 1006 1007 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info); 1008 if (arg_packet_err == 0) 1009 { 1010 std::string error_str; 1011 if (m_gdb_comm.GetLaunchSuccess (error_str)) 1012 { 1013 SetID (m_gdb_comm.GetCurrentProcessID ()); 1014 } 1015 else 1016 { 1017 error.SetErrorString (error_str.c_str()); 1018 } 1019 } 1020 else 1021 { 1022 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err); 1023 } 1024 } 1025 1026 if (GetID() == LLDB_INVALID_PROCESS_ID) 1027 { 1028 if (log) 1029 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 1030 KillDebugserverProcess (); 1031 return error; 1032 } 1033 1034 StringExtractorGDBRemote response; 1035 if (m_gdb_comm.GetStopReply(response)) 1036 { 1037 SetLastStopPacket(response); 1038 // '?' Packets must be handled differently in non-stop mode 1039 if (GetTarget().GetNonStopModeEnabled()) 1040 HandleStopReplySequence(); 1041 1042 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture(); 1043 1044 if (process_arch.IsValid()) 1045 { 1046 m_target.MergeArchitecture(process_arch); 1047 } 1048 else 1049 { 1050 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture(); 1051 if (host_arch.IsValid()) 1052 m_target.MergeArchitecture(host_arch); 1053 } 1054 1055 SetPrivateState (SetThreadStopInfo (response)); 1056 1057 if (!disable_stdio) 1058 { 1059 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd) 1060 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor()); 1061 } 1062 } 1063 } 1064 else 1065 { 1066 if (log) 1067 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 1068 } 1069 } 1070 else 1071 { 1072 // Set our user ID to an invalid process ID. 1073 SetID(LLDB_INVALID_PROCESS_ID); 1074 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s", 1075 exe_module->GetFileSpec().GetFilename().AsCString(), 1076 exe_module->GetArchitecture().GetArchitectureName()); 1077 } 1078 return error; 1079 1080} 1081 1082 1083Error 1084ProcessGDBRemote::ConnectToDebugserver (const char *connect_url) 1085{ 1086 Error error; 1087 // Only connect if we have a valid connect URL 1088 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1089 1090 if (connect_url && connect_url[0]) 1091 { 1092 if (log) 1093 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url); 1094 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor()); 1095 if (conn_ap.get()) 1096 { 1097 const uint32_t max_retry_count = 50; 1098 uint32_t retry_count = 0; 1099 while (!m_gdb_comm.IsConnected()) 1100 { 1101 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) 1102 { 1103 m_gdb_comm.SetConnection (conn_ap.release()); 1104 break; 1105 } 1106 else if (error.WasInterrupted()) 1107 { 1108 // If we were interrupted, don't keep retrying. 1109 break; 1110 } 1111 1112 retry_count++; 1113 1114 if (retry_count >= max_retry_count) 1115 break; 1116 1117 usleep (100000); 1118 } 1119 } 1120 } 1121 1122 if (!m_gdb_comm.IsConnected()) 1123 { 1124 if (error.Success()) 1125 error.SetErrorString("not connected to remote gdb server"); 1126 return error; 1127 } 1128 1129 1130 // Start the communications read thread so all incoming data can be 1131 // parsed into packets and queued as they arrive. 1132 if (GetTarget().GetNonStopModeEnabled()) 1133 m_gdb_comm.StartReadThread(); 1134 1135 // We always seem to be able to open a connection to a local port 1136 // so we need to make sure we can then send data to it. If we can't 1137 // then we aren't actually connected to anything, so try and do the 1138 // handshake with the remote GDB server and make sure that goes 1139 // alright. 1140 if (!m_gdb_comm.HandshakeWithServer (&error)) 1141 { 1142 m_gdb_comm.Disconnect(); 1143 if (error.Success()) 1144 error.SetErrorString("not connected to remote gdb server"); 1145 return error; 1146 } 1147 1148 // Send $QNonStop:1 packet on startup if required 1149 if (GetTarget().GetNonStopModeEnabled()) 1150 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true)); 1151 1152 m_gdb_comm.GetEchoSupported (); 1153 m_gdb_comm.GetThreadSuffixSupported (); 1154 m_gdb_comm.GetListThreadsInStopReplySupported (); 1155 m_gdb_comm.GetHostInfo (); 1156 m_gdb_comm.GetVContSupported ('c'); 1157 m_gdb_comm.GetVAttachOrWaitSupported(); 1158 1159 // Ask the remote server for the default thread id 1160 if (GetTarget().GetNonStopModeEnabled()) 1161 m_gdb_comm.GetDefaultThreadId(m_initial_tid); 1162 1163 1164 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount(); 1165 for (size_t idx = 0; idx < num_cmds; idx++) 1166 { 1167 StringExtractorGDBRemote response; 1168 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false); 1169 } 1170 return error; 1171} 1172 1173void 1174ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch) 1175{ 1176 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1177 if (log) 1178 log->Printf ("ProcessGDBRemote::DidLaunch()"); 1179 if (GetID() != LLDB_INVALID_PROCESS_ID) 1180 { 1181 BuildDynamicRegisterInfo (false); 1182 1183 // See if the GDB server supports the qHostInfo information 1184 1185 1186 // See if the GDB server supports the qProcessInfo packet, if so 1187 // prefer that over the Host information as it will be more specific 1188 // to our process. 1189 1190 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); 1191 if (remote_process_arch.IsValid()) 1192 { 1193 process_arch = remote_process_arch; 1194 if (log) 1195 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s", 1196 __FUNCTION__, 1197 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>", 1198 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>"); 1199 } 1200 else 1201 { 1202 process_arch = m_gdb_comm.GetHostArchitecture(); 1203 if (log) 1204 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s", 1205 __FUNCTION__, 1206 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>", 1207 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>"); 1208 } 1209 1210 if (process_arch.IsValid()) 1211 { 1212 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 1213 if (target_arch.IsValid()) 1214 { 1215 if (log) 1216 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s", 1217 __FUNCTION__, 1218 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>", 1219 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>"); 1220 1221 // If the remote host is ARM and we have apple as the vendor, then 1222 // ARM executables and shared libraries can have mixed ARM architectures. 1223 // You can have an armv6 executable, and if the host is armv7, then the 1224 // system will load the best possible architecture for all shared libraries 1225 // it has, so we really need to take the remote host architecture as our 1226 // defacto architecture in this case. 1227 1228 if (process_arch.GetMachine() == llvm::Triple::arm && 1229 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) 1230 { 1231 GetTarget().SetArchitecture (process_arch); 1232 if (log) 1233 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s", 1234 __FUNCTION__, 1235 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>", 1236 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>"); 1237 } 1238 else 1239 { 1240 // Fill in what is missing in the triple 1241 const llvm::Triple &remote_triple = process_arch.GetTriple(); 1242 llvm::Triple new_target_triple = target_arch.GetTriple(); 1243 if (new_target_triple.getVendorName().size() == 0) 1244 { 1245 new_target_triple.setVendor (remote_triple.getVendor()); 1246 1247 if (new_target_triple.getOSName().size() == 0) 1248 { 1249 new_target_triple.setOS (remote_triple.getOS()); 1250 1251 if (new_target_triple.getEnvironmentName().size() == 0) 1252 new_target_triple.setEnvironment (remote_triple.getEnvironment()); 1253 } 1254 1255 ArchSpec new_target_arch = target_arch; 1256 new_target_arch.SetTriple(new_target_triple); 1257 GetTarget().SetArchitecture(new_target_arch); 1258 } 1259 } 1260 1261 if (log) 1262 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s", 1263 __FUNCTION__, 1264 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>", 1265 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>"); 1266 } 1267 else 1268 { 1269 // The target doesn't have a valid architecture yet, set it from 1270 // the architecture we got from the remote GDB server 1271 GetTarget().SetArchitecture (process_arch); 1272 } 1273 } 1274 } 1275} 1276 1277void 1278ProcessGDBRemote::DidLaunch () 1279{ 1280 ArchSpec process_arch; 1281 DidLaunchOrAttach (process_arch); 1282} 1283 1284Error 1285ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) 1286{ 1287 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1288 Error error; 1289 1290 if (log) 1291 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__); 1292 1293 // Clear out and clean up from any current state 1294 Clear(); 1295 if (attach_pid != LLDB_INVALID_PROCESS_ID) 1296 { 1297 // Make sure we aren't already connected? 1298 if (!m_gdb_comm.IsConnected()) 1299 { 1300 error = LaunchAndConnectToDebugserver (attach_info); 1301 1302 if (error.Fail()) 1303 { 1304 const char *error_string = error.AsCString(); 1305 if (error_string == NULL) 1306 error_string = "unable to launch " DEBUGSERVER_BASENAME; 1307 1308 SetExitStatus (-1, error_string); 1309 } 1310 } 1311 1312 if (error.Success()) 1313 { 1314 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); 1315 1316 char packet[64]; 1317 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid); 1318 SetID (attach_pid); 1319 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len)); 1320 } 1321 } 1322 1323 return error; 1324} 1325 1326Error 1327ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info) 1328{ 1329 Error error; 1330 // Clear out and clean up from any current state 1331 Clear(); 1332 1333 if (process_name && process_name[0]) 1334 { 1335 // Make sure we aren't already connected? 1336 if (!m_gdb_comm.IsConnected()) 1337 { 1338 error = LaunchAndConnectToDebugserver (attach_info); 1339 1340 if (error.Fail()) 1341 { 1342 const char *error_string = error.AsCString(); 1343 if (error_string == NULL) 1344 error_string = "unable to launch " DEBUGSERVER_BASENAME; 1345 1346 SetExitStatus (-1, error_string); 1347 } 1348 } 1349 1350 if (error.Success()) 1351 { 1352 StreamString packet; 1353 1354 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); 1355 1356 if (attach_info.GetWaitForLaunch()) 1357 { 1358 if (!m_gdb_comm.GetVAttachOrWaitSupported()) 1359 { 1360 packet.PutCString ("vAttachWait"); 1361 } 1362 else 1363 { 1364 if (attach_info.GetIgnoreExisting()) 1365 packet.PutCString("vAttachWait"); 1366 else 1367 packet.PutCString ("vAttachOrWait"); 1368 } 1369 } 1370 else 1371 packet.PutCString("vAttachName"); 1372 packet.PutChar(';'); 1373 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 1374 1375 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize())); 1376 1377 } 1378 } 1379 return error; 1380} 1381 1382void 1383ProcessGDBRemote::DidExit () 1384{ 1385 // When we exit, disconnect from the GDB server communications 1386 m_gdb_comm.Disconnect(); 1387} 1388 1389void 1390ProcessGDBRemote::DidAttach (ArchSpec &process_arch) 1391{ 1392 // If you can figure out what the architecture is, fill it in here. 1393 process_arch.Clear(); 1394 DidLaunchOrAttach (process_arch); 1395} 1396 1397 1398Error 1399ProcessGDBRemote::WillResume () 1400{ 1401 m_continue_c_tids.clear(); 1402 m_continue_C_tids.clear(); 1403 m_continue_s_tids.clear(); 1404 m_continue_S_tids.clear(); 1405 return Error(); 1406} 1407 1408Error 1409ProcessGDBRemote::DoResume () 1410{ 1411 Error error; 1412 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1413 if (log) 1414 log->Printf ("ProcessGDBRemote::Resume()"); 1415 1416 Listener listener ("gdb-remote.resume-packet-sent"); 1417 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) 1418 { 1419 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); 1420 1421 const size_t num_threads = GetThreadList().GetSize(); 1422 1423 StreamString continue_packet; 1424 bool continue_packet_error = false; 1425 if (m_gdb_comm.HasAnyVContSupport ()) 1426 { 1427 if (!GetTarget().GetNonStopModeEnabled() && 1428 (m_continue_c_tids.size() == num_threads || 1429 (m_continue_c_tids.empty() && 1430 m_continue_C_tids.empty() && 1431 m_continue_s_tids.empty() && 1432 m_continue_S_tids.empty()))) 1433 { 1434 // All threads are continuing, just send a "c" packet 1435 continue_packet.PutCString ("c"); 1436 } 1437 else 1438 { 1439 continue_packet.PutCString ("vCont"); 1440 1441 if (!m_continue_c_tids.empty()) 1442 { 1443 if (m_gdb_comm.GetVContSupported ('c')) 1444 { 1445 for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos) 1446 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos); 1447 } 1448 else 1449 continue_packet_error = true; 1450 } 1451 1452 if (!continue_packet_error && !m_continue_C_tids.empty()) 1453 { 1454 if (m_gdb_comm.GetVContSupported ('C')) 1455 { 1456 for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos) 1457 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); 1458 } 1459 else 1460 continue_packet_error = true; 1461 } 1462 1463 if (!continue_packet_error && !m_continue_s_tids.empty()) 1464 { 1465 if (m_gdb_comm.GetVContSupported ('s')) 1466 { 1467 for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos) 1468 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos); 1469 } 1470 else 1471 continue_packet_error = true; 1472 } 1473 1474 if (!continue_packet_error && !m_continue_S_tids.empty()) 1475 { 1476 if (m_gdb_comm.GetVContSupported ('S')) 1477 { 1478 for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos) 1479 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); 1480 } 1481 else 1482 continue_packet_error = true; 1483 } 1484 1485 if (continue_packet_error) 1486 continue_packet.GetString().clear(); 1487 } 1488 } 1489 else 1490 continue_packet_error = true; 1491 1492 if (continue_packet_error) 1493 { 1494 // Either no vCont support, or we tried to use part of the vCont 1495 // packet that wasn't supported by the remote GDB server. 1496 // We need to try and make a simple packet that can do our continue 1497 const size_t num_continue_c_tids = m_continue_c_tids.size(); 1498 const size_t num_continue_C_tids = m_continue_C_tids.size(); 1499 const size_t num_continue_s_tids = m_continue_s_tids.size(); 1500 const size_t num_continue_S_tids = m_continue_S_tids.size(); 1501 if (num_continue_c_tids > 0) 1502 { 1503 if (num_continue_c_tids == num_threads) 1504 { 1505 // All threads are resuming... 1506 m_gdb_comm.SetCurrentThreadForRun (-1); 1507 continue_packet.PutChar ('c'); 1508 continue_packet_error = false; 1509 } 1510 else if (num_continue_c_tids == 1 && 1511 num_continue_C_tids == 0 && 1512 num_continue_s_tids == 0 && 1513 num_continue_S_tids == 0 ) 1514 { 1515 // Only one thread is continuing 1516 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front()); 1517 continue_packet.PutChar ('c'); 1518 continue_packet_error = false; 1519 } 1520 } 1521 1522 if (continue_packet_error && num_continue_C_tids > 0) 1523 { 1524 if ((num_continue_C_tids + num_continue_c_tids) == num_threads && 1525 num_continue_C_tids > 0 && 1526 num_continue_s_tids == 0 && 1527 num_continue_S_tids == 0 ) 1528 { 1529 const int continue_signo = m_continue_C_tids.front().second; 1530 // Only one thread is continuing 1531 if (num_continue_C_tids > 1) 1532 { 1533 // More that one thread with a signal, yet we don't have 1534 // vCont support and we are being asked to resume each 1535 // thread with a signal, we need to make sure they are 1536 // all the same signal, or we can't issue the continue 1537 // accurately with the current support... 1538 if (num_continue_C_tids > 1) 1539 { 1540 continue_packet_error = false; 1541 for (size_t i=1; i<m_continue_C_tids.size(); ++i) 1542 { 1543 if (m_continue_C_tids[i].second != continue_signo) 1544 continue_packet_error = true; 1545 } 1546 } 1547 if (!continue_packet_error) 1548 m_gdb_comm.SetCurrentThreadForRun (-1); 1549 } 1550 else 1551 { 1552 // Set the continue thread ID 1553 continue_packet_error = false; 1554 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first); 1555 } 1556 if (!continue_packet_error) 1557 { 1558 // Add threads continuing with the same signo... 1559 continue_packet.Printf("C%2.2x", continue_signo); 1560 } 1561 } 1562 } 1563 1564 if (continue_packet_error && num_continue_s_tids > 0) 1565 { 1566 if (num_continue_s_tids == num_threads) 1567 { 1568 // All threads are resuming... 1569 m_gdb_comm.SetCurrentThreadForRun (-1); 1570 1571 // If in Non-Stop-Mode use vCont when stepping 1572 if (GetTarget().GetNonStopModeEnabled()) 1573 { 1574 if (m_gdb_comm.GetVContSupported('s')) 1575 continue_packet.PutCString("vCont;s"); 1576 else 1577 continue_packet.PutChar('s'); 1578 } 1579 else 1580 continue_packet.PutChar('s'); 1581 1582 continue_packet_error = false; 1583 } 1584 else if (num_continue_c_tids == 0 && 1585 num_continue_C_tids == 0 && 1586 num_continue_s_tids == 1 && 1587 num_continue_S_tids == 0 ) 1588 { 1589 // Only one thread is stepping 1590 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front()); 1591 continue_packet.PutChar ('s'); 1592 continue_packet_error = false; 1593 } 1594 } 1595 1596 if (!continue_packet_error && num_continue_S_tids > 0) 1597 { 1598 if (num_continue_S_tids == num_threads) 1599 { 1600 const int step_signo = m_continue_S_tids.front().second; 1601 // Are all threads trying to step with the same signal? 1602 continue_packet_error = false; 1603 if (num_continue_S_tids > 1) 1604 { 1605 for (size_t i=1; i<num_threads; ++i) 1606 { 1607 if (m_continue_S_tids[i].second != step_signo) 1608 continue_packet_error = true; 1609 } 1610 } 1611 if (!continue_packet_error) 1612 { 1613 // Add threads stepping with the same signo... 1614 m_gdb_comm.SetCurrentThreadForRun (-1); 1615 continue_packet.Printf("S%2.2x", step_signo); 1616 } 1617 } 1618 else if (num_continue_c_tids == 0 && 1619 num_continue_C_tids == 0 && 1620 num_continue_s_tids == 0 && 1621 num_continue_S_tids == 1 ) 1622 { 1623 // Only one thread is stepping with signal 1624 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first); 1625 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); 1626 continue_packet_error = false; 1627 } 1628 } 1629 } 1630 1631 if (continue_packet_error) 1632 { 1633 error.SetErrorString ("can't make continue packet for this resume"); 1634 } 1635 else 1636 { 1637 EventSP event_sp; 1638 TimeValue timeout; 1639 timeout = TimeValue::Now(); 1640 timeout.OffsetWithSeconds (5); 1641 if (!m_async_thread.IsJoinable()) 1642 { 1643 error.SetErrorString ("Trying to resume but the async thread is dead."); 1644 if (log) 1645 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead."); 1646 return error; 1647 } 1648 1649 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize())); 1650 1651 if (listener.WaitForEvent (&timeout, event_sp) == false) 1652 { 1653 error.SetErrorString("Resume timed out."); 1654 if (log) 1655 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out."); 1656 } 1657 else if (event_sp->BroadcasterIs (&m_async_broadcaster)) 1658 { 1659 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back."); 1660 if (log) 1661 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back."); 1662 return error; 1663 } 1664 } 1665 } 1666 1667 return error; 1668} 1669 1670void 1671ProcessGDBRemote::HandleStopReplySequence () 1672{ 1673 while(true) 1674 { 1675 // Send vStopped 1676 StringExtractorGDBRemote response; 1677 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false); 1678 1679 // OK represents end of signal list 1680 if (response.IsOKResponse()) 1681 break; 1682 1683 // If not OK or a normal packet we have a problem 1684 if (!response.IsNormalResponse()) 1685 break; 1686 1687 SetLastStopPacket(response); 1688 } 1689} 1690 1691void 1692ProcessGDBRemote::ClearThreadIDList () 1693{ 1694 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1695 m_thread_ids.clear(); 1696} 1697 1698size_t 1699ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value) 1700{ 1701 m_thread_ids.clear(); 1702 size_t comma_pos; 1703 lldb::tid_t tid; 1704 while ((comma_pos = value.find(',')) != std::string::npos) 1705 { 1706 value[comma_pos] = '\0'; 1707 // thread in big endian hex 1708 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1709 if (tid != LLDB_INVALID_THREAD_ID) 1710 m_thread_ids.push_back (tid); 1711 value.erase(0, comma_pos + 1); 1712 } 1713 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1714 if (tid != LLDB_INVALID_THREAD_ID) 1715 m_thread_ids.push_back (tid); 1716 return m_thread_ids.size(); 1717} 1718 1719bool 1720ProcessGDBRemote::UpdateThreadIDList () 1721{ 1722 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1723 1724 if (m_threads_info_sp) 1725 { 1726 // If we have the JSON threads info, we can get the thread list from that 1727 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray(); 1728 if (thread_infos && thread_infos->GetSize() > 0) 1729 { 1730 m_thread_ids.clear(); 1731 thread_infos->ForEach([this](StructuredData::Object* object) -> bool { 1732 StructuredData::Dictionary *thread_dict = object->GetAsDictionary(); 1733 if (thread_dict) 1734 { 1735 // Set the thread stop info from the JSON dictionary 1736 SetThreadStopInfo (thread_dict); 1737 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 1738 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid)) 1739 m_thread_ids.push_back(tid); 1740 } 1741 return true; // Keep iterating through all thread_info objects 1742 }); 1743 } 1744 if (!m_thread_ids.empty()) 1745 return true; 1746 } 1747 else 1748 { 1749 // See if we can get the thread IDs from the current stop reply packets 1750 // that might contain a "threads" key/value pair 1751 1752 // Lock the thread stack while we access it 1753 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex); 1754 // Get the number of stop packets on the stack 1755 int nItems = m_stop_packet_stack.size(); 1756 // Iterate over them 1757 for (int i = 0; i < nItems; i++) 1758 { 1759 // Get the thread stop info 1760 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i]; 1761 const std::string &stop_info_str = stop_info.GetStringRef(); 1762 const size_t threads_pos = stop_info_str.find(";threads:"); 1763 if (threads_pos != std::string::npos) 1764 { 1765 const size_t start = threads_pos + strlen(";threads:"); 1766 const size_t end = stop_info_str.find(';', start); 1767 if (end != std::string::npos) 1768 { 1769 std::string value = stop_info_str.substr(start, end - start); 1770 if (UpdateThreadIDsFromStopReplyThreadsValue(value)) 1771 return true; 1772 } 1773 } 1774 } 1775 } 1776 1777 bool sequence_mutex_unavailable = false; 1778 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable); 1779 if (sequence_mutex_unavailable) 1780 { 1781 return false; // We just didn't get the list 1782 } 1783 return true; 1784} 1785 1786bool 1787ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 1788{ 1789 // locker will keep a mutex locked until it goes out of scope 1790 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1791 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1792 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID()); 1793 1794 size_t num_thread_ids = m_thread_ids.size(); 1795 // The "m_thread_ids" thread ID list should always be updated after each stop 1796 // reply packet, but in case it isn't, update it here. 1797 if (num_thread_ids == 0) 1798 { 1799 if (!UpdateThreadIDList ()) 1800 return false; 1801 num_thread_ids = m_thread_ids.size(); 1802 } 1803 1804 ThreadList old_thread_list_copy(old_thread_list); 1805 if (num_thread_ids > 0) 1806 { 1807 for (size_t i=0; i<num_thread_ids; ++i) 1808 { 1809 tid_t tid = m_thread_ids[i]; 1810 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false)); 1811 if (!thread_sp) 1812 { 1813 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1814 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1815 log->Printf( 1816 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n", 1817 __FUNCTION__, static_cast<void*>(thread_sp.get()), 1818 thread_sp->GetID()); 1819 } 1820 else 1821 { 1822 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1823 log->Printf( 1824 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n", 1825 __FUNCTION__, static_cast<void*>(thread_sp.get()), 1826 thread_sp->GetID()); 1827 } 1828 new_thread_list.AddThread(thread_sp); 1829 } 1830 } 1831 1832 // Whatever that is left in old_thread_list_copy are not 1833 // present in new_thread_list. Remove non-existent threads from internal id table. 1834 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false); 1835 for (size_t i=0; i<old_num_thread_ids; i++) 1836 { 1837 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false)); 1838 if (old_thread_sp) 1839 { 1840 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID(); 1841 m_thread_id_to_index_id_map.erase(old_thread_id); 1842 } 1843 } 1844 1845 return true; 1846} 1847 1848bool 1849ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread) 1850{ 1851 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet 1852 if (m_threads_info_sp) 1853 { 1854 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray(); 1855 if (thread_infos) 1856 { 1857 lldb::tid_t tid; 1858 const size_t n = thread_infos->GetSize(); 1859 for (size_t i=0; i<n; ++i) 1860 { 1861 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 1862 if (thread_dict) 1863 { 1864 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID)) 1865 { 1866 if (tid == thread->GetID()) 1867 return SetThreadStopInfo(thread_dict); 1868 } 1869 } 1870 } 1871 } 1872 } 1873 1874 // Fall back to using the qThreadStopInfo packet 1875 StringExtractorGDBRemote stop_packet; 1876 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet)) 1877 return SetThreadStopInfo (stop_packet) == eStateStopped; 1878 return false; 1879} 1880 1881 1882ThreadSP 1883ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid, 1884 ExpeditedRegisterMap &expedited_register_map, 1885 uint8_t signo, 1886 const std::string &thread_name, 1887 const std::string &reason, 1888 const std::string &description, 1889 uint32_t exc_type, 1890 const std::vector<addr_t> &exc_data, 1891 addr_t thread_dispatch_qaddr, 1892 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid 1893 std::string &queue_name, 1894 QueueKind queue_kind, 1895 uint64_t queue_serial) 1896{ 1897 ThreadSP thread_sp; 1898 if (tid != LLDB_INVALID_THREAD_ID) 1899 { 1900 // Scope for "locker" below 1901 { 1902 // m_thread_list_real does have its own mutex, but we need to 1903 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...) 1904 // and the m_thread_list_real.AddThread(...) so it doesn't change on us 1905 Mutex::Locker locker (m_thread_list_real.GetMutex ()); 1906 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false); 1907 1908 if (!thread_sp) 1909 { 1910 // Create the thread if we need to 1911 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1912 m_thread_list_real.AddThread(thread_sp); 1913 } 1914 } 1915 1916 if (thread_sp) 1917 { 1918 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1919 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true); 1920 1921 for (const auto &pair : expedited_register_map) 1922 { 1923 StringExtractor reg_value_extractor; 1924 reg_value_extractor.GetStringRef() = pair.second; 1925 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor); 1926 } 1927 1928 // Clear the stop info just in case we don't set it to anything 1929 thread_sp->SetStopInfo (StopInfoSP()); 1930 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str()); 1931 1932 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1933 // Check if the GDB server was able to provide the queue name, kind and serial number 1934 if (queue_vars_valid) 1935 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial); 1936 else 1937 gdb_thread->ClearQueueInfo(); 1938 1939 1940 if (exc_type != 0) 1941 { 1942 const size_t exc_data_size = exc_data.size(); 1943 1944 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp, 1945 exc_type, 1946 exc_data_size, 1947 exc_data_size >= 1 ? exc_data[0] : 0, 1948 exc_data_size >= 2 ? exc_data[1] : 0, 1949 exc_data_size >= 3 ? exc_data[2] : 0)); 1950 } 1951 else 1952 { 1953 bool handled = false; 1954 bool did_exec = false; 1955 if (!reason.empty()) 1956 { 1957 if (reason.compare("trace") == 0) 1958 { 1959 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1960 handled = true; 1961 } 1962 else if (reason.compare("breakpoint") == 0) 1963 { 1964 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1965 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1966 if (bp_site_sp) 1967 { 1968 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1969 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1970 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1971 handled = true; 1972 if (bp_site_sp->ValidForThisThread (thread_sp.get())) 1973 { 1974 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1975 } 1976 else 1977 { 1978 StopInfoSP invalid_stop_info_sp; 1979 thread_sp->SetStopInfo (invalid_stop_info_sp); 1980 } 1981 } 1982 } 1983 else if (reason.compare("trap") == 0) 1984 { 1985 // Let the trap just use the standard signal stop reason below... 1986 } 1987 else if (reason.compare("watchpoint") == 0) 1988 { 1989 StringExtractor desc_extractor(description.c_str()); 1990 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); 1991 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32); 1992 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); 1993 watch_id_t watch_id = LLDB_INVALID_WATCH_ID; 1994 if (wp_addr != LLDB_INVALID_ADDRESS) 1995 { 1996 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr); 1997 if (wp_sp) 1998 { 1999 wp_sp->SetHardwareIndex(wp_index); 2000 watch_id = wp_sp->GetID(); 2001 } 2002 } 2003 if (watch_id == LLDB_INVALID_WATCH_ID) 2004 { 2005 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS)); 2006 if (log) log->Printf ("failed to find watchpoint"); 2007 } 2008 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr)); 2009 handled = true; 2010 } 2011 else if (reason.compare("exception") == 0) 2012 { 2013 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str())); 2014 handled = true; 2015 } 2016 else if (reason.compare("exec") == 0) 2017 { 2018 did_exec = true; 2019 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp)); 2020 handled = true; 2021 } 2022 } 2023 2024 if (!handled && signo && did_exec == false) 2025 { 2026 if (signo == SIGTRAP) 2027 { 2028 // Currently we are going to assume SIGTRAP means we are either 2029 // hitting a breakpoint or hardware single stepping. 2030 handled = true; 2031 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset; 2032 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 2033 2034 if (bp_site_sp) 2035 { 2036 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 2037 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 2038 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 2039 if (bp_site_sp->ValidForThisThread (thread_sp.get())) 2040 { 2041 if(m_breakpoint_pc_offset != 0) 2042 thread_sp->GetRegisterContext()->SetPC(pc); 2043 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 2044 } 2045 else 2046 { 2047 StopInfoSP invalid_stop_info_sp; 2048 thread_sp->SetStopInfo (invalid_stop_info_sp); 2049 } 2050 } 2051 else 2052 { 2053 // If we were stepping then assume the stop was the result of the trace. If we were 2054 // not stepping then report the SIGTRAP. 2055 // FIXME: We are still missing the case where we single step over a trap instruction. 2056 if (thread_sp->GetTemporaryResumeState() == eStateStepping) 2057 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 2058 else 2059 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str())); 2060 } 2061 } 2062 if (!handled) 2063 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str())); 2064 } 2065 2066 if (!description.empty()) 2067 { 2068 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ()); 2069 if (stop_info_sp) 2070 { 2071 const char *stop_info_desc = stop_info_sp->GetDescription(); 2072 if (!stop_info_desc || !stop_info_desc[0]) 2073 stop_info_sp->SetDescription (description.c_str()); 2074 } 2075 else 2076 { 2077 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str())); 2078 } 2079 } 2080 } 2081 } 2082 } 2083 return thread_sp; 2084} 2085 2086StateType 2087ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict) 2088{ 2089 static ConstString g_key_tid("tid"); 2090 static ConstString g_key_name("name"); 2091 static ConstString g_key_reason("reason"); 2092 static ConstString g_key_metype("metype"); 2093 static ConstString g_key_medata("medata"); 2094 static ConstString g_key_qaddr("qaddr"); 2095 static ConstString g_key_queue_name("qname"); 2096 static ConstString g_key_queue_kind("qkind"); 2097 static ConstString g_key_queue_serial("qserial"); 2098 static ConstString g_key_registers("registers"); 2099 static ConstString g_key_memory("memory"); 2100 static ConstString g_key_address("address"); 2101 static ConstString g_key_bytes("bytes"); 2102 static ConstString g_key_description("description"); 2103 2104 // Stop with signal and thread info 2105 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2106 uint8_t signo = 0; 2107 std::string value; 2108 std::string thread_name; 2109 std::string reason; 2110 std::string description; 2111 uint32_t exc_type = 0; 2112 std::vector<addr_t> exc_data; 2113 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2114 ExpeditedRegisterMap expedited_register_map; 2115 bool queue_vars_valid = false; 2116 std::string queue_name; 2117 QueueKind queue_kind = eQueueKindUnknown; 2118 uint64_t queue_serial = 0; 2119 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary 2120 2121 thread_dict->ForEach([this, 2122 &tid, 2123 &expedited_register_map, 2124 &thread_name, 2125 &signo, 2126 &reason, 2127 &description, 2128 &exc_type, 2129 &exc_data, 2130 &thread_dispatch_qaddr, 2131 &queue_vars_valid, 2132 &queue_name, 2133 &queue_kind, 2134 &queue_serial] 2135 (ConstString key, StructuredData::Object* object) -> bool 2136 { 2137 if (key == g_key_tid) 2138 { 2139 // thread in big endian hex 2140 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID); 2141 } 2142 else if (key == g_key_metype) 2143 { 2144 // exception type in big endian hex 2145 exc_type = object->GetIntegerValue(0); 2146 } 2147 else if (key == g_key_medata) 2148 { 2149 // exception data in big endian hex 2150 StructuredData::Array *array = object->GetAsArray(); 2151 if (array) 2152 { 2153 array->ForEach([&exc_data](StructuredData::Object* object) -> bool { 2154 exc_data.push_back(object->GetIntegerValue()); 2155 return true; // Keep iterating through all array items 2156 }); 2157 } 2158 } 2159 else if (key == g_key_name) 2160 { 2161 thread_name = std::move(object->GetStringValue()); 2162 } 2163 else if (key == g_key_qaddr) 2164 { 2165 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS); 2166 } 2167 else if (key == g_key_queue_name) 2168 { 2169 queue_vars_valid = true; 2170 queue_name = std::move(object->GetStringValue()); 2171 } 2172 else if (key == g_key_queue_kind) 2173 { 2174 std::string queue_kind_str = object->GetStringValue(); 2175 if (queue_kind_str == "serial") 2176 { 2177 queue_vars_valid = true; 2178 queue_kind = eQueueKindSerial; 2179 } 2180 else if (queue_kind_str == "concurrent") 2181 { 2182 queue_vars_valid = true; 2183 queue_kind = eQueueKindConcurrent; 2184 } 2185 } 2186 else if (key == g_key_queue_serial) 2187 { 2188 queue_serial = object->GetIntegerValue(0); 2189 if (queue_serial != 0) 2190 queue_vars_valid = true; 2191 } 2192 else if (key == g_key_reason) 2193 { 2194 reason = std::move(object->GetStringValue()); 2195 } 2196 else if (key == g_key_description) 2197 { 2198 description = std::move(object->GetStringValue()); 2199 } 2200 else if (key == g_key_registers) 2201 { 2202 StructuredData::Dictionary *registers_dict = object->GetAsDictionary(); 2203 2204 if (registers_dict) 2205 { 2206 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool { 2207 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10); 2208 if (reg != UINT32_MAX) 2209 expedited_register_map[reg] = std::move(object->GetStringValue()); 2210 return true; // Keep iterating through all array items 2211 }); 2212 } 2213 } 2214 else if (key == g_key_memory) 2215 { 2216 StructuredData::Array *array = object->GetAsArray(); 2217 if (array) 2218 { 2219 array->ForEach([this](StructuredData::Object* object) -> bool { 2220 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary(); 2221 if (mem_cache_dict) 2222 { 2223 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; 2224 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr)) 2225 { 2226 if (mem_cache_addr != LLDB_INVALID_ADDRESS) 2227 { 2228 StringExtractor bytes; 2229 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef())) 2230 { 2231 bytes.SetFilePos(0); 2232 2233 const size_t byte_size = bytes.GetStringRef().size()/2; 2234 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0)); 2235 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0); 2236 if (bytes_copied == byte_size) 2237 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp); 2238 } 2239 } 2240 } 2241 } 2242 return true; // Keep iterating through all array items 2243 }); 2244 } 2245 2246 } 2247 return true; // Keep iterating through all dictionary key/value pairs 2248 }); 2249 2250 SetThreadStopInfo (tid, 2251 expedited_register_map, 2252 signo, 2253 thread_name, 2254 reason, 2255 description, 2256 exc_type, 2257 exc_data, 2258 thread_dispatch_qaddr, 2259 queue_vars_valid, 2260 queue_name, 2261 queue_kind, 2262 queue_serial); 2263 2264 return eStateExited; 2265} 2266 2267StateType 2268ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 2269{ 2270 stop_packet.SetFilePos (0); 2271 const char stop_type = stop_packet.GetChar(); 2272 switch (stop_type) 2273 { 2274 case 'T': 2275 case 'S': 2276 { 2277 // This is a bit of a hack, but is is required. If we did exec, we 2278 // need to clear our thread lists and also know to rebuild our dynamic 2279 // register info before we lookup and threads and populate the expedited 2280 // register values so we need to know this right away so we can cleanup 2281 // and update our registers. 2282 const uint32_t stop_id = GetStopID(); 2283 if (stop_id == 0) 2284 { 2285 // Our first stop, make sure we have a process ID, and also make 2286 // sure we know about our registers 2287 if (GetID() == LLDB_INVALID_PROCESS_ID) 2288 { 2289 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 2290 if (pid != LLDB_INVALID_PROCESS_ID) 2291 SetID (pid); 2292 } 2293 BuildDynamicRegisterInfo (true); 2294 } 2295 // Stop with signal and thread info 2296 lldb::tid_t tid = LLDB_INVALID_THREAD_ID; 2297 const uint8_t signo = stop_packet.GetHexU8(); 2298 std::string key; 2299 std::string value; 2300 std::string thread_name; 2301 std::string reason; 2302 std::string description; 2303 uint32_t exc_type = 0; 2304 std::vector<addr_t> exc_data; 2305 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 2306 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid 2307 std::string queue_name; 2308 QueueKind queue_kind = eQueueKindUnknown; 2309 uint64_t queue_serial = 0; 2310 ExpeditedRegisterMap expedited_register_map; 2311 while (stop_packet.GetNameColonValue(key, value)) 2312 { 2313 if (key.compare("metype") == 0) 2314 { 2315 // exception type in big endian hex 2316 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16); 2317 } 2318 else if (key.compare("medata") == 0) 2319 { 2320 // exception data in big endian hex 2321 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16)); 2322 } 2323 else if (key.compare("thread") == 0) 2324 { 2325 // thread in big endian hex 2326 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 2327 } 2328 else if (key.compare("threads") == 0) 2329 { 2330 Mutex::Locker locker(m_thread_list_real.GetMutex()); 2331 m_thread_ids.clear(); 2332 // A comma separated list of all threads in the current 2333 // process that includes the thread for this stop reply 2334 // packet 2335 size_t comma_pos; 2336 lldb::tid_t tid; 2337 while ((comma_pos = value.find(',')) != std::string::npos) 2338 { 2339 value[comma_pos] = '\0'; 2340 // thread in big endian hex 2341 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 2342 if (tid != LLDB_INVALID_THREAD_ID) 2343 m_thread_ids.push_back (tid); 2344 value.erase(0, comma_pos + 1); 2345 } 2346 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 2347 if (tid != LLDB_INVALID_THREAD_ID) 2348 m_thread_ids.push_back (tid); 2349 } 2350 else if (key.compare("hexname") == 0) 2351 { 2352 StringExtractor name_extractor; 2353 // Swap "value" over into "name_extractor" 2354 name_extractor.GetStringRef().swap(value); 2355 // Now convert the HEX bytes into a string value 2356 name_extractor.GetHexByteString (value); 2357 thread_name.swap (value); 2358 } 2359 else if (key.compare("name") == 0) 2360 { 2361 thread_name.swap (value); 2362 } 2363 else if (key.compare("qaddr") == 0) 2364 { 2365 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16); 2366 } 2367 else if (key.compare("qname") == 0) 2368 { 2369 queue_vars_valid = true; 2370 StringExtractor name_extractor; 2371 // Swap "value" over into "name_extractor" 2372 name_extractor.GetStringRef().swap(value); 2373 // Now convert the HEX bytes into a string value 2374 name_extractor.GetHexByteString (value); 2375 queue_name.swap (value); 2376 } 2377 else if (key.compare("qkind") == 0) 2378 { 2379 if (value == "serial") 2380 { 2381 queue_vars_valid = true; 2382 queue_kind = eQueueKindSerial; 2383 } 2384 else if (value == "concurrent") 2385 { 2386 queue_vars_valid = true; 2387 queue_kind = eQueueKindConcurrent; 2388 } 2389 } 2390 else if (key.compare("qserial") == 0) 2391 { 2392 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0); 2393 if (queue_serial != 0) 2394 queue_vars_valid = true; 2395 } 2396 else if (key.compare("reason") == 0) 2397 { 2398 reason.swap(value); 2399 } 2400 else if (key.compare("description") == 0) 2401 { 2402 StringExtractor desc_extractor; 2403 // Swap "value" over into "name_extractor" 2404 desc_extractor.GetStringRef().swap(value); 2405 // Now convert the HEX bytes into a string value 2406 desc_extractor.GetHexByteString (value); 2407 description.swap(value); 2408 } 2409 else if (key.compare("memory") == 0) 2410 { 2411 // Expedited memory. GDB servers can choose to send back expedited memory 2412 // that can populate the L1 memory cache in the process so that things like 2413 // the frame pointer backchain can be expedited. This will help stack 2414 // backtracing be more efficient by not having to send as many memory read 2415 // requests down the remote GDB server. 2416 2417 // Key/value pair format: memory:<addr>=<bytes>; 2418 // <addr> is a number whose base will be interpreted by the prefix: 2419 // "0x[0-9a-fA-F]+" for hex 2420 // "0[0-7]+" for octal 2421 // "[1-9]+" for decimal 2422 // <bytes> is native endian ASCII hex bytes just like the register values 2423 llvm::StringRef value_ref(value); 2424 std::pair<llvm::StringRef, llvm::StringRef> pair; 2425 pair = value_ref.split('='); 2426 if (!pair.first.empty() && !pair.second.empty()) 2427 { 2428 std::string addr_str(pair.first.str()); 2429 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0); 2430 if (mem_cache_addr != LLDB_INVALID_ADDRESS) 2431 { 2432 StringExtractor bytes; 2433 bytes.GetStringRef() = std::move(pair.second.str()); 2434 const size_t byte_size = bytes.GetStringRef().size()/2; 2435 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0)); 2436 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0); 2437 if (bytes_copied == byte_size) 2438 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp); 2439 } 2440 } 2441 } 2442 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0) 2443 { 2444 // Support standard GDB remote stop reply packet 'TAAwatch:addr' 2445 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16); 2446 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr); 2447 uint32_t wp_index = LLDB_INVALID_INDEX32; 2448 2449 if (wp_sp) 2450 wp_index = wp_sp->GetHardwareIndex(); 2451 2452 reason = "watchpoint"; 2453 StreamString ostr; 2454 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index); 2455 description = ostr.GetString().c_str(); 2456 } 2457 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) 2458 { 2459 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16); 2460 if (reg != UINT32_MAX) 2461 expedited_register_map[reg] = std::move(value); 2462 } 2463 } 2464 2465 if (tid == LLDB_INVALID_THREAD_ID) 2466 { 2467 // A thread id may be invalid if the response is old style 'S' packet which does not provide the 2468 // thread information. So update the thread list and choose the first one. 2469 UpdateThreadIDList (); 2470 2471 if (!m_thread_ids.empty ()) 2472 { 2473 tid = m_thread_ids.front (); 2474 } 2475 } 2476 2477 ThreadSP thread_sp = SetThreadStopInfo (tid, 2478 expedited_register_map, 2479 signo, 2480 thread_name, 2481 reason, 2482 description, 2483 exc_type, 2484 exc_data, 2485 thread_dispatch_qaddr, 2486 queue_vars_valid, 2487 queue_name, 2488 queue_kind, 2489 queue_serial); 2490 2491 return eStateStopped; 2492 } 2493 break; 2494 2495 case 'W': 2496 case 'X': 2497 // process exited 2498 return eStateExited; 2499 2500 default: 2501 break; 2502 } 2503 return eStateInvalid; 2504} 2505 2506void 2507ProcessGDBRemote::RefreshStateAfterStop () 2508{ 2509 Mutex::Locker locker(m_thread_list_real.GetMutex()); 2510 m_thread_ids.clear(); 2511 // Set the thread stop info. It might have a "threads" key whose value is 2512 // a list of all thread IDs in the current process, so m_thread_ids might 2513 // get set. 2514 2515 // Scope for the lock 2516 { 2517 // Lock the thread stack while we access it 2518 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex); 2519 // Get the number of stop packets on the stack 2520 int nItems = m_stop_packet_stack.size(); 2521 // Iterate over them 2522 for (int i = 0; i < nItems; i++) 2523 { 2524 // Get the thread stop info 2525 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i]; 2526 // Process thread stop info 2527 SetThreadStopInfo(stop_info); 2528 } 2529 // Clear the thread stop stack 2530 m_stop_packet_stack.clear(); 2531 } 2532 2533 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 2534 if (m_thread_ids.empty()) 2535 { 2536 // No, we need to fetch the thread list manually 2537 UpdateThreadIDList(); 2538 } 2539 2540 // If we have queried for a default thread id 2541 if (m_initial_tid != LLDB_INVALID_THREAD_ID) 2542 { 2543 m_thread_list.SetSelectedThreadByID(m_initial_tid); 2544 m_initial_tid = LLDB_INVALID_THREAD_ID; 2545 } 2546 2547 // Fetch the threads via an efficient packet that gets stop infos for all threads 2548 // only if we have more than one thread 2549 if (m_thread_ids.size() > 1) 2550 m_threads_info_sp = m_gdb_comm.GetThreadsInfo(); 2551 2552 // Let all threads recover from stopping and do any clean up based 2553 // on the previous thread state (if any). 2554 m_thread_list_real.RefreshStateAfterStop(); 2555 2556} 2557 2558Error 2559ProcessGDBRemote::DoHalt (bool &caused_stop) 2560{ 2561 Error error; 2562 2563 bool timed_out = false; 2564 Mutex::Locker locker; 2565 2566 if (m_public_state.GetValue() == eStateAttaching) 2567 { 2568 // We are being asked to halt during an attach. We need to just close 2569 // our file handle and debugserver will go away, and we can be done... 2570 m_gdb_comm.Disconnect(); 2571 } 2572 else 2573 { 2574 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out)) 2575 { 2576 if (timed_out) 2577 error.SetErrorString("timed out sending interrupt packet"); 2578 else 2579 error.SetErrorString("unknown error sending interrupt packet"); 2580 } 2581 2582 caused_stop = m_gdb_comm.GetInterruptWasSent (); 2583 } 2584 return error; 2585} 2586 2587Error 2588ProcessGDBRemote::DoDetach(bool keep_stopped) 2589{ 2590 Error error; 2591 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2592 if (log) 2593 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 2594 2595 error = m_gdb_comm.Detach (keep_stopped); 2596 if (log) 2597 { 2598 if (error.Success()) 2599 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 2600 else 2601 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>"); 2602 } 2603 2604 if (!error.Success()) 2605 return error; 2606 2607 // Sleep for one second to let the process get all detached... 2608 StopAsyncThread (); 2609 2610 SetPrivateState (eStateDetached); 2611 ResumePrivateStateThread(); 2612 2613 //KillDebugserverProcess (); 2614 return error; 2615} 2616 2617 2618Error 2619ProcessGDBRemote::DoDestroy () 2620{ 2621 Error error; 2622 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2623 if (log) 2624 log->Printf ("ProcessGDBRemote::DoDestroy()"); 2625 2626#if 0 // XXX Currently no iOS target support on FreeBSD 2627 // There is a bug in older iOS debugservers where they don't shut down the process 2628 // they are debugging properly. If the process is sitting at a breakpoint or an exception, 2629 // this can cause problems with restarting. So we check to see if any of our threads are stopped 2630 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN 2631 // destroy it again. 2632 // 2633 // Note, we don't have a good way to test the version of debugserver, but I happen to know that 2634 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of 2635 // the debugservers with this bug are equal. There really should be a better way to test this! 2636 // 2637 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and 2638 // get called here to destroy again and we're still at a breakpoint or exception, then we should 2639 // just do the straight-forward kill. 2640 // 2641 // And of course, if we weren't able to stop the process by the time we get here, it isn't 2642 // necessary (or helpful) to do any of this. 2643 2644 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) 2645 { 2646 PlatformSP platform_sp = GetTarget().GetPlatform(); 2647 2648 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 2649 if (platform_sp 2650 && platform_sp->GetName() 2651 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) 2652 { 2653 if (m_destroy_tried_resuming) 2654 { 2655 if (log) 2656 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again."); 2657 } 2658 else 2659 { 2660 // At present, the plans are discarded and the breakpoints disabled Process::Destroy, 2661 // but we really need it to happen here and it doesn't matter if we do it twice. 2662 m_thread_list.DiscardThreadPlans(); 2663 DisableAllBreakpointSites(); 2664 2665 bool stop_looks_like_crash = false; 2666 ThreadList &threads = GetThreadList(); 2667 2668 { 2669 Mutex::Locker locker(threads.GetMutex()); 2670 2671 size_t num_threads = threads.GetSize(); 2672 for (size_t i = 0; i < num_threads; i++) 2673 { 2674 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2675 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2676 StopReason reason = eStopReasonInvalid; 2677 if (stop_info_sp) 2678 reason = stop_info_sp->GetStopReason(); 2679 if (reason == eStopReasonBreakpoint 2680 || reason == eStopReasonException) 2681 { 2682 if (log) 2683 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.", 2684 thread_sp->GetProtocolID(), 2685 stop_info_sp->GetDescription()); 2686 stop_looks_like_crash = true; 2687 break; 2688 } 2689 } 2690 } 2691 2692 if (stop_looks_like_crash) 2693 { 2694 if (log) 2695 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill."); 2696 m_destroy_tried_resuming = true; 2697 2698 // If we are going to run again before killing, it would be good to suspend all the threads 2699 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with 2700 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do 2701 // have to run the risk of letting those threads proceed a bit. 2702 2703 { 2704 Mutex::Locker locker(threads.GetMutex()); 2705 2706 size_t num_threads = threads.GetSize(); 2707 for (size_t i = 0; i < num_threads; i++) 2708 { 2709 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2710 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2711 StopReason reason = eStopReasonInvalid; 2712 if (stop_info_sp) 2713 reason = stop_info_sp->GetStopReason(); 2714 if (reason != eStopReasonBreakpoint 2715 && reason != eStopReasonException) 2716 { 2717 if (log) 2718 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.", 2719 thread_sp->GetProtocolID()); 2720 thread_sp->SetResumeState(eStateSuspended); 2721 } 2722 } 2723 } 2724 Resume (); 2725 return Destroy(false); 2726 } 2727 } 2728 } 2729 } 2730#endif 2731 2732 // Interrupt if our inferior is running... 2733 int exit_status = SIGABRT; 2734 std::string exit_string; 2735 2736 if (m_gdb_comm.IsConnected()) 2737 { 2738 if (m_public_state.GetValue() != eStateAttaching) 2739 { 2740 StringExtractorGDBRemote response; 2741 bool send_async = true; 2742 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3); 2743 2744 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success) 2745 { 2746 char packet_cmd = response.GetChar(0); 2747 2748 if (packet_cmd == 'W' || packet_cmd == 'X') 2749 { 2750#if defined(__APPLE__) 2751 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off 2752 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill 2753 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns 2754 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap 2755 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of 2756 // switching ownership back to lldb which was the original parent, and gets confused in the handoff. 2757 // Anyway, so call waitpid here to finally reap it. 2758 PlatformSP platform_sp(GetTarget().GetPlatform()); 2759 if (platform_sp && platform_sp->IsHost()) 2760 { 2761 int status; 2762 ::pid_t reap_pid; 2763 reap_pid = waitpid (GetID(), &status, WNOHANG); 2764 if (log) 2765 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status); 2766 } 2767#endif 2768 SetLastStopPacket (response); 2769 ClearThreadIDList (); 2770 exit_status = response.GetHexU8(); 2771 } 2772 else 2773 { 2774 if (log) 2775 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str()); 2776 exit_string.assign("got unexpected response to k packet: "); 2777 exit_string.append(response.GetStringRef()); 2778 } 2779 } 2780 else 2781 { 2782 if (log) 2783 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 2784 exit_string.assign("failed to send the k packet"); 2785 } 2786 } 2787 else 2788 { 2789 if (log) 2790 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching"); 2791 exit_string.assign ("killed or interrupted while attaching."); 2792 } 2793 } 2794 else 2795 { 2796 // If we missed setting the exit status on the way out, do it here. 2797 // NB set exit status can be called multiple times, the first one sets the status. 2798 exit_string.assign("destroying when not connected to debugserver"); 2799 } 2800 2801 SetExitStatus(exit_status, exit_string.c_str()); 2802 2803 StopAsyncThread (); 2804 KillDebugserverProcess (); 2805 return error; 2806} 2807 2808void 2809ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response) 2810{ 2811 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos; 2812 if (did_exec) 2813 { 2814 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2815 if (log) 2816 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2817 2818 m_thread_list_real.Clear(); 2819 m_thread_list.Clear(); 2820 BuildDynamicRegisterInfo (true); 2821 m_gdb_comm.ResetDiscoverableSettings (did_exec); 2822 } 2823 2824 // Scope the lock 2825 { 2826 // Lock the thread stack while we access it 2827 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex); 2828 // Add this stop packet to the stop packet stack 2829 // This stack will get popped and examined when we switch to the 2830 // Stopped state 2831 m_stop_packet_stack.push_back(response); 2832 } 2833} 2834 2835 2836//------------------------------------------------------------------ 2837// Process Queries 2838//------------------------------------------------------------------ 2839 2840bool 2841ProcessGDBRemote::IsAlive () 2842{ 2843 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 2844} 2845 2846addr_t 2847ProcessGDBRemote::GetImageInfoAddress() 2848{ 2849 // request the link map address via the $qShlibInfoAddr packet 2850 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); 2851 2852 // the loaded module list can also provides a link map address 2853 if (addr == LLDB_INVALID_ADDRESS) 2854 { 2855 GDBLoadedModuleInfoList list; 2856 if (GetLoadedModuleList (list).Success()) 2857 addr = list.m_link_map; 2858 } 2859 2860 return addr; 2861} 2862 2863//------------------------------------------------------------------ 2864// Process Memory 2865//------------------------------------------------------------------ 2866size_t 2867ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2868{ 2869 GetMaxMemorySize (); 2870 if (size > m_max_memory_size) 2871 { 2872 // Keep memory read sizes down to a sane limit. This function will be 2873 // called multiple times in order to complete the task by 2874 // lldb_private::Process so it is ok to do this. 2875 size = m_max_memory_size; 2876 } 2877 2878 char packet[64]; 2879 int packet_len; 2880 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2881 if (binary_memory_read) 2882 { 2883 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size); 2884 } 2885 else 2886 { 2887 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size); 2888 } 2889 assert (packet_len + 1 < (int)sizeof(packet)); 2890 StringExtractorGDBRemote response; 2891 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success) 2892 { 2893 if (response.IsNormalResponse()) 2894 { 2895 error.Clear(); 2896 if (binary_memory_read) 2897 { 2898 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any 2899 // 0x7d character escaping that was present in the packet 2900 2901 size_t data_received_size = response.GetBytesLeft(); 2902 if (data_received_size > size) 2903 { 2904 // Don't write past the end of BUF if the remote debug server gave us too 2905 // much data for some reason. 2906 data_received_size = size; 2907 } 2908 memcpy (buf, response.GetStringRef().data(), data_received_size); 2909 return data_received_size; 2910 } 2911 else 2912 { 2913 return response.GetHexBytes(buf, size, '\xdd'); 2914 } 2915 } 2916 else if (response.IsErrorResponse()) 2917 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2918 else if (response.IsUnsupportedResponse()) 2919 error.SetErrorStringWithFormat("GDB server does not support reading memory"); 2920 else 2921 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str()); 2922 } 2923 else 2924 { 2925 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2926 } 2927 return 0; 2928} 2929 2930size_t 2931ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2932{ 2933 GetMaxMemorySize (); 2934 if (size > m_max_memory_size) 2935 { 2936 // Keep memory read sizes down to a sane limit. This function will be 2937 // called multiple times in order to complete the task by 2938 // lldb_private::Process so it is ok to do this. 2939 size = m_max_memory_size; 2940 } 2941 2942 StreamString packet; 2943 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2944 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 2945 StringExtractorGDBRemote response; 2946 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success) 2947 { 2948 if (response.IsOKResponse()) 2949 { 2950 error.Clear(); 2951 return size; 2952 } 2953 else if (response.IsErrorResponse()) 2954 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr); 2955 else if (response.IsUnsupportedResponse()) 2956 error.SetErrorStringWithFormat("GDB server does not support writing memory"); 2957 else 2958 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 2959 } 2960 else 2961 { 2962 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str()); 2963 } 2964 return 0; 2965} 2966 2967lldb::addr_t 2968ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 2969{ 2970 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS)); 2971 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2972 2973 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2974 switch (supported) 2975 { 2976 case eLazyBoolCalculate: 2977 case eLazyBoolYes: 2978 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 2979 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 2980 return allocated_addr; 2981 2982 case eLazyBoolNo: 2983 // Call mmap() to create memory in the inferior.. 2984 unsigned prot = 0; 2985 if (permissions & lldb::ePermissionsReadable) 2986 prot |= eMmapProtRead; 2987 if (permissions & lldb::ePermissionsWritable) 2988 prot |= eMmapProtWrite; 2989 if (permissions & lldb::ePermissionsExecutable) 2990 prot |= eMmapProtExec; 2991 2992 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2993 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2994 m_addr_to_mmap_size[allocated_addr] = size; 2995 else 2996 { 2997 allocated_addr = LLDB_INVALID_ADDRESS; 2998 if (log) 2999 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__); 3000 } 3001 break; 3002 } 3003 3004 if (allocated_addr == LLDB_INVALID_ADDRESS) 3005 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions)); 3006 else 3007 error.Clear(); 3008 return allocated_addr; 3009} 3010 3011Error 3012ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr, 3013 MemoryRegionInfo ®ion_info) 3014{ 3015 3016 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info)); 3017 return error; 3018} 3019 3020Error 3021ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num) 3022{ 3023 3024 Error error (m_gdb_comm.GetWatchpointSupportInfo (num)); 3025 return error; 3026} 3027 3028Error 3029ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after) 3030{ 3031 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture())); 3032 return error; 3033} 3034 3035Error 3036ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 3037{ 3038 Error error; 3039 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 3040 3041 switch (supported) 3042 { 3043 case eLazyBoolCalculate: 3044 // We should never be deallocating memory without allocating memory 3045 // first so we should never get eLazyBoolCalculate 3046 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 3047 break; 3048 3049 case eLazyBoolYes: 3050 if (!m_gdb_comm.DeallocateMemory (addr)) 3051 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 3052 break; 3053 3054 case eLazyBoolNo: 3055 // Call munmap() to deallocate memory in the inferior.. 3056 { 3057 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 3058 if (pos != m_addr_to_mmap_size.end() && 3059 InferiorCallMunmap(this, addr, pos->second)) 3060 m_addr_to_mmap_size.erase (pos); 3061 else 3062 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 3063 } 3064 break; 3065 } 3066 3067 return error; 3068} 3069 3070 3071//------------------------------------------------------------------ 3072// Process STDIO 3073//------------------------------------------------------------------ 3074size_t 3075ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 3076{ 3077 if (m_stdio_communication.IsConnected()) 3078 { 3079 ConnectionStatus status; 3080 m_stdio_communication.Write(src, src_len, status, NULL); 3081 } 3082 else if (m_stdin_forward) 3083 { 3084 m_gdb_comm.SendStdinNotification(src, src_len); 3085 } 3086 return 0; 3087} 3088 3089Error 3090ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site) 3091{ 3092 Error error; 3093 assert(bp_site != NULL); 3094 3095 // Get logging info 3096 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3097 user_id_t site_id = bp_site->GetID(); 3098 3099 // Get the breakpoint address 3100 const addr_t addr = bp_site->GetLoadAddress(); 3101 3102 // Log that a breakpoint was requested 3103 if (log) 3104 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr); 3105 3106 // Breakpoint already exists and is enabled 3107 if (bp_site->IsEnabled()) 3108 { 3109 if (log) 3110 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 3111 return error; 3112 } 3113 3114 // Get the software breakpoint trap opcode size 3115 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3116 3117 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type 3118 // is supported by the remote stub. These are set to true by default, and later set to false 3119 // only after we receive an unimplemented response when sending a breakpoint packet. This means 3120 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will 3121 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which 3122 // indicates if the user specifically asked for hardware breakpoints. If true then we will 3123 // skip over software breakpoints. 3124 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired())) 3125 { 3126 // Try to send off a software breakpoint packet ($Z0) 3127 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 3128 { 3129 // The breakpoint was placed successfully 3130 bp_site->SetEnabled(true); 3131 bp_site->SetType(BreakpointSite::eExternal); 3132 return error; 3133 } 3134 3135 // SendGDBStoppointTypePacket() will return an error if it was unable to set this 3136 // breakpoint. We need to differentiate between a error specific to placing this breakpoint 3137 // or if we have learned that this breakpoint type is unsupported. To do this, we 3138 // must test the support boolean for this breakpoint type to see if it now indicates that 3139 // this breakpoint type is unsupported. If they are still supported then we should return 3140 // with the error code. If they are now unsupported, then we would like to fall through 3141 // and try another form of breakpoint. 3142 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 3143 return error; 3144 3145 // We reach here when software breakpoints have been found to be unsupported. For future 3146 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is 3147 // known not to be supported. 3148 if (log) 3149 log->Printf("Software breakpoints are unsupported"); 3150 3151 // So we will fall through and try a hardware breakpoint 3152 } 3153 3154 // The process of setting a hardware breakpoint is much the same as above. We check the 3155 // supported boolean for this breakpoint type, and if it is thought to be supported then we 3156 // will try to set this breakpoint with a hardware breakpoint. 3157 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) 3158 { 3159 // Try to send off a hardware breakpoint packet ($Z1) 3160 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 3161 { 3162 // The breakpoint was placed successfully 3163 bp_site->SetEnabled(true); 3164 bp_site->SetType(BreakpointSite::eHardware); 3165 return error; 3166 } 3167 3168 // Check if the error was something other then an unsupported breakpoint type 3169 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) 3170 { 3171 // Unable to set this hardware breakpoint 3172 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)"); 3173 return error; 3174 } 3175 3176 // We will reach here when the stub gives an unsupported response to a hardware breakpoint 3177 if (log) 3178 log->Printf("Hardware breakpoints are unsupported"); 3179 3180 // Finally we will falling through to a #trap style breakpoint 3181 } 3182 3183 // Don't fall through when hardware breakpoints were specifically requested 3184 if (bp_site->HardwareRequired()) 3185 { 3186 error.SetErrorString("hardware breakpoints are not supported"); 3187 return error; 3188 } 3189 3190 // As a last resort we want to place a manual breakpoint. An instruction 3191 // is placed into the process memory using memory write packets. 3192 return EnableSoftwareBreakpoint(bp_site); 3193} 3194 3195Error 3196ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site) 3197{ 3198 Error error; 3199 assert (bp_site != NULL); 3200 addr_t addr = bp_site->GetLoadAddress(); 3201 user_id_t site_id = bp_site->GetID(); 3202 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3203 if (log) 3204 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr); 3205 3206 if (bp_site->IsEnabled()) 3207 { 3208 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 3209 3210 BreakpointSite::Type bp_type = bp_site->GetType(); 3211 switch (bp_type) 3212 { 3213 case BreakpointSite::eSoftware: 3214 error = DisableSoftwareBreakpoint (bp_site); 3215 break; 3216 3217 case BreakpointSite::eHardware: 3218 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size)) 3219 error.SetErrorToGenericError(); 3220 break; 3221 3222 case BreakpointSite::eExternal: 3223 { 3224 GDBStoppointType stoppoint_type; 3225 if (bp_site->IsHardware()) 3226 stoppoint_type = eBreakpointHardware; 3227 else 3228 stoppoint_type = eBreakpointSoftware; 3229 3230 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size)) 3231 error.SetErrorToGenericError(); 3232 } 3233 break; 3234 } 3235 if (error.Success()) 3236 bp_site->SetEnabled(false); 3237 } 3238 else 3239 { 3240 if (log) 3241 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 3242 return error; 3243 } 3244 3245 if (error.Success()) 3246 error.SetErrorToGenericError(); 3247 return error; 3248} 3249 3250// Pre-requisite: wp != NULL. 3251static GDBStoppointType 3252GetGDBStoppointType (Watchpoint *wp) 3253{ 3254 assert(wp); 3255 bool watch_read = wp->WatchpointRead(); 3256 bool watch_write = wp->WatchpointWrite(); 3257 3258 // watch_read and watch_write cannot both be false. 3259 assert(watch_read || watch_write); 3260 if (watch_read && watch_write) 3261 return eWatchpointReadWrite; 3262 else if (watch_read) 3263 return eWatchpointRead; 3264 else // Must be watch_write, then. 3265 return eWatchpointWrite; 3266} 3267 3268Error 3269ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify) 3270{ 3271 Error error; 3272 if (wp) 3273 { 3274 user_id_t watchID = wp->GetID(); 3275 addr_t addr = wp->GetLoadAddress(); 3276 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3277 if (log) 3278 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID); 3279 if (wp->IsEnabled()) 3280 { 3281 if (log) 3282 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr); 3283 return error; 3284 } 3285 3286 GDBStoppointType type = GetGDBStoppointType(wp); 3287 // Pass down an appropriate z/Z packet... 3288 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 3289 { 3290 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 3291 { 3292 wp->SetEnabled(true, notify); 3293 return error; 3294 } 3295 else 3296 error.SetErrorString("sending gdb watchpoint packet failed"); 3297 } 3298 else 3299 error.SetErrorString("watchpoints not supported"); 3300 } 3301 else 3302 { 3303 error.SetErrorString("Watchpoint argument was NULL."); 3304 } 3305 if (error.Success()) 3306 error.SetErrorToGenericError(); 3307 return error; 3308} 3309 3310Error 3311ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify) 3312{ 3313 Error error; 3314 if (wp) 3315 { 3316 user_id_t watchID = wp->GetID(); 3317 3318 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3319 3320 addr_t addr = wp->GetLoadAddress(); 3321 3322 if (log) 3323 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr); 3324 3325 if (!wp->IsEnabled()) 3326 { 3327 if (log) 3328 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 3329 // See also 'class WatchpointSentry' within StopInfo.cpp. 3330 // This disabling attempt might come from the user-supplied actions, we'll route it in order for 3331 // the watchpoint object to intelligently process this action. 3332 wp->SetEnabled(false, notify); 3333 return error; 3334 } 3335 3336 if (wp->IsHardware()) 3337 { 3338 GDBStoppointType type = GetGDBStoppointType(wp); 3339 // Pass down an appropriate z/Z packet... 3340 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 3341 { 3342 wp->SetEnabled(false, notify); 3343 return error; 3344 } 3345 else 3346 error.SetErrorString("sending gdb watchpoint packet failed"); 3347 } 3348 // TODO: clear software watchpoints if we implement them 3349 } 3350 else 3351 { 3352 error.SetErrorString("Watchpoint argument was NULL."); 3353 } 3354 if (error.Success()) 3355 error.SetErrorToGenericError(); 3356 return error; 3357} 3358 3359void 3360ProcessGDBRemote::Clear() 3361{ 3362 m_flags = 0; 3363 m_thread_list_real.Clear(); 3364 m_thread_list.Clear(); 3365} 3366 3367Error 3368ProcessGDBRemote::DoSignal (int signo) 3369{ 3370 Error error; 3371 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3372 if (log) 3373 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 3374 3375 if (!m_gdb_comm.SendAsyncSignal (signo)) 3376 error.SetErrorStringWithFormat("failed to send signal %i", signo); 3377 return error; 3378} 3379 3380Error 3381ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info) 3382{ 3383 Error error; 3384 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 3385 { 3386 // If we locate debugserver, keep that located version around 3387 static FileSpec g_debugserver_file_spec; 3388 3389 ProcessLaunchInfo debugserver_launch_info; 3390 // Make debugserver run in its own session so signals generated by 3391 // special terminal key sequences (^C) don't affect debugserver. 3392 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); 3393 3394 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false); 3395 debugserver_launch_info.SetUserID(process_info.GetUserID()); 3396 3397#if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__)) 3398 // On iOS, still do a local connection using a random port 3399 const char *hostname = "127.0.0.1"; 3400 uint16_t port = get_random_port (); 3401#else 3402 // Set hostname being NULL to do the reverse connect where debugserver 3403 // will bind to port zero and it will communicate back to us the port 3404 // that we will connect to 3405 const char *hostname = NULL; 3406 uint16_t port = 0; 3407#endif 3408 3409 error = m_gdb_comm.StartDebugserverProcess (hostname, 3410 port, 3411 debugserver_launch_info, 3412 port); 3413 3414 if (error.Success ()) 3415 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 3416 else 3417 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3418 3419 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 3420 StartAsyncThread (); 3421 3422 if (error.Fail()) 3423 { 3424 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 3425 3426 if (log) 3427 log->Printf("failed to start debugserver process: %s", error.AsCString()); 3428 return error; 3429 } 3430 3431 if (m_gdb_comm.IsConnected()) 3432 { 3433 // Finish the connection process by doing the handshake without connecting (send NULL URL) 3434 ConnectToDebugserver (NULL); 3435 } 3436 else 3437 { 3438 StreamString connect_url; 3439 connect_url.Printf("connect://%s:%u", hostname, port); 3440 error = ConnectToDebugserver (connect_url.GetString().c_str()); 3441 } 3442 3443 } 3444 return error; 3445} 3446 3447bool 3448ProcessGDBRemote::MonitorDebugserverProcess 3449( 3450 void *callback_baton, 3451 lldb::pid_t debugserver_pid, 3452 bool exited, // True if the process did exit 3453 int signo, // Zero for no signal 3454 int exit_status // Exit value of process if signal is zero 3455) 3456{ 3457 // The baton is a "ProcessGDBRemote *". Now this class might be gone 3458 // and might not exist anymore, so we need to carefully try to get the 3459 // target for this process first since we have a race condition when 3460 // we are done running between getting the notice that the inferior 3461 // process has died and the debugserver that was debugging this process. 3462 // In our test suite, we are also continually running process after 3463 // process, so we must be very careful to make sure: 3464 // 1 - process object hasn't been deleted already 3465 // 2 - that a new process object hasn't been recreated in its place 3466 3467 // "debugserver_pid" argument passed in is the process ID for 3468 // debugserver that we are tracking... 3469 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3470 3471 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 3472 3473 // Get a shared pointer to the target that has a matching process pointer. 3474 // This target could be gone, or the target could already have a new process 3475 // object inside of it 3476 TargetSP target_sp (Debugger::FindTargetWithProcess(process)); 3477 3478 if (log) 3479 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 3480 3481 if (target_sp) 3482 { 3483 // We found a process in a target that matches, but another thread 3484 // might be in the process of launching a new process that will 3485 // soon replace it, so get a shared pointer to the process so we 3486 // can keep it alive. 3487 ProcessSP process_sp (target_sp->GetProcessSP()); 3488 // Now we have a shared pointer to the process that can't go away on us 3489 // so we now make sure it was the same as the one passed in, and also make 3490 // sure that our previous "process *" didn't get deleted and have a new 3491 // "process *" created in its place with the same pointer. To verify this 3492 // we make sure the process has our debugserver process ID. If we pass all 3493 // of these tests, then we are sure that this process is the one we were 3494 // looking for. 3495 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid) 3496 { 3497 // Sleep for a half a second to make sure our inferior process has 3498 // time to set its exit status before we set it incorrectly when 3499 // both the debugserver and the inferior process shut down. 3500 usleep (500000); 3501 // If our process hasn't yet exited, debugserver might have died. 3502 // If the process did exit, the we are reaping it. 3503 const StateType state = process->GetState(); 3504 3505 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 3506 state != eStateInvalid && 3507 state != eStateUnloaded && 3508 state != eStateExited && 3509 state != eStateDetached) 3510 { 3511 char error_str[1024]; 3512 if (signo) 3513 { 3514 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo); 3515 if (signal_cstr) 3516 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 3517 else 3518 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 3519 } 3520 else 3521 { 3522 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 3523 } 3524 3525 process->SetExitStatus (-1, error_str); 3526 } 3527 // Debugserver has exited we need to let our ProcessGDBRemote 3528 // know that it no longer has a debugserver instance 3529 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3530 } 3531 } 3532 return true; 3533} 3534 3535void 3536ProcessGDBRemote::KillDebugserverProcess () 3537{ 3538 m_gdb_comm.Disconnect(); 3539 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 3540 { 3541 Host::Kill (m_debugserver_pid, SIGINT); 3542 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3543 } 3544} 3545 3546void 3547ProcessGDBRemote::Initialize() 3548{ 3549 static std::once_flag g_once_flag; 3550 3551 std::call_once(g_once_flag, []() 3552 { 3553 PluginManager::RegisterPlugin (GetPluginNameStatic(), 3554 GetPluginDescriptionStatic(), 3555 CreateInstance, 3556 DebuggerInitialize); 3557 }); 3558} 3559 3560void 3561ProcessGDBRemote::DebuggerInitialize (Debugger &debugger) 3562{ 3563 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName())) 3564 { 3565 const bool is_global_setting = true; 3566 PluginManager::CreateSettingForProcessPlugin (debugger, 3567 GetGlobalPluginProperties()->GetValueProperties(), 3568 ConstString ("Properties for the gdb-remote process plug-in."), 3569 is_global_setting); 3570 } 3571} 3572 3573bool 3574ProcessGDBRemote::StartAsyncThread () 3575{ 3576 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3577 3578 if (log) 3579 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 3580 3581 Mutex::Locker start_locker(m_async_thread_state_mutex); 3582 if (!m_async_thread.IsJoinable()) 3583 { 3584 // Create a thread that watches our internal state and controls which 3585 // events make it to clients (into the DCProcess event queue). 3586 3587 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 3588 } 3589 else if (log) 3590 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__); 3591 3592 return m_async_thread.IsJoinable(); 3593} 3594 3595void 3596ProcessGDBRemote::StopAsyncThread () 3597{ 3598 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3599 3600 if (log) 3601 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 3602 3603 Mutex::Locker start_locker(m_async_thread_state_mutex); 3604 if (m_async_thread.IsJoinable()) 3605 { 3606 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 3607 3608 // This will shut down the async thread. 3609 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3610 3611 // Stop the stdio thread 3612 m_async_thread.Join(nullptr); 3613 m_async_thread.Reset(); 3614 } 3615 else if (log) 3616 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__); 3617} 3618 3619bool 3620ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet) 3621{ 3622 // get the packet at a string 3623 const std::string &pkt = packet.GetStringRef(); 3624 // skip %stop: 3625 StringExtractorGDBRemote stop_info(pkt.c_str() + 5); 3626 3627 // pass as a thread stop info packet 3628 SetLastStopPacket(stop_info); 3629 3630 // check for more stop reasons 3631 HandleStopReplySequence(); 3632 3633 // if the process is stopped then we need to fake a resume 3634 // so that we can stop properly with the new break. This 3635 // is possible due to SetPrivateState() broadcasting the 3636 // state change as a side effect. 3637 if (GetPrivateState() == lldb::StateType::eStateStopped) 3638 { 3639 SetPrivateState(lldb::StateType::eStateRunning); 3640 } 3641 3642 // since we have some stopped packets we can halt the process 3643 SetPrivateState(lldb::StateType::eStateStopped); 3644 3645 return true; 3646} 3647 3648thread_result_t 3649ProcessGDBRemote::AsyncThread (void *arg) 3650{ 3651 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 3652 3653 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 3654 if (log) 3655 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID()); 3656 3657 Listener listener ("ProcessGDBRemote::AsyncThread"); 3658 EventSP event_sp; 3659 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 3660 eBroadcastBitAsyncThreadShouldExit; 3661 3662 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 3663 { 3664 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit | 3665 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify); 3666 3667 bool done = false; 3668 while (!done) 3669 { 3670 if (log) 3671 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 3672 if (listener.WaitForEvent (NULL, event_sp)) 3673 { 3674 const uint32_t event_type = event_sp->GetType(); 3675 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 3676 { 3677 if (log) 3678 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 3679 3680 switch (event_type) 3681 { 3682 case eBroadcastBitAsyncContinue: 3683 { 3684 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3685 3686 if (continue_packet) 3687 { 3688 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 3689 const size_t continue_cstr_len = continue_packet->GetByteSize (); 3690 if (log) 3691 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 3692 3693 if (::strstr (continue_cstr, "vAttach") == NULL) 3694 process->SetPrivateState(eStateRunning); 3695 StringExtractorGDBRemote response; 3696 3697 // If in Non-Stop-Mode 3698 if (process->GetTarget().GetNonStopModeEnabled()) 3699 { 3700 // send the vCont packet 3701 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response)) 3702 { 3703 // Something went wrong 3704 done = true; 3705 break; 3706 } 3707 } 3708 // If in All-Stop-Mode 3709 else 3710 { 3711 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 3712 3713 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads. 3714 // The thread ID list might be contained within the "response", or the stop reply packet that 3715 // caused the stop. So clear it now before we give the stop reply packet to the process 3716 // using the process->SetLastStopPacket()... 3717 process->ClearThreadIDList (); 3718 3719 switch (stop_state) 3720 { 3721 case eStateStopped: 3722 case eStateCrashed: 3723 case eStateSuspended: 3724 process->SetLastStopPacket (response); 3725 process->SetPrivateState (stop_state); 3726 break; 3727 3728 case eStateExited: 3729 { 3730 process->SetLastStopPacket (response); 3731 process->ClearThreadIDList(); 3732 response.SetFilePos(1); 3733 3734 int exit_status = response.GetHexU8(); 3735 const char *desc_cstr = NULL; 3736 StringExtractor extractor; 3737 std::string desc_string; 3738 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') 3739 { 3740 std::string desc_token; 3741 while (response.GetNameColonValue (desc_token, desc_string)) 3742 { 3743 if (desc_token == "description") 3744 { 3745 extractor.GetStringRef().swap(desc_string); 3746 extractor.SetFilePos(0); 3747 extractor.GetHexByteString (desc_string); 3748 desc_cstr = desc_string.c_str(); 3749 } 3750 } 3751 } 3752 process->SetExitStatus(exit_status, desc_cstr); 3753 done = true; 3754 break; 3755 } 3756 case eStateInvalid: 3757 process->SetExitStatus(-1, "lost connection"); 3758 break; 3759 3760 default: 3761 process->SetPrivateState (stop_state); 3762 break; 3763 } // switch(stop_state) 3764 } // else // if in All-stop-mode 3765 } // if (continue_packet) 3766 } // case eBroadcastBitAysncContinue 3767 break; 3768 3769 case eBroadcastBitAsyncThreadShouldExit: 3770 if (log) 3771 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 3772 done = true; 3773 break; 3774 3775 default: 3776 if (log) 3777 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 3778 done = true; 3779 break; 3780 } 3781 } 3782 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 3783 { 3784 switch (event_type) 3785 { 3786 case Communication::eBroadcastBitReadThreadDidExit: 3787 process->SetExitStatus (-1, "lost connection"); 3788 done = true; 3789 break; 3790 3791 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: 3792 { 3793 lldb_private::Event *event = event_sp.get(); 3794 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event); 3795 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes()); 3796 // Hand this over to the process to handle 3797 process->HandleNotifyPacket(notify); 3798 break; 3799 } 3800 3801 default: 3802 if (log) 3803 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 3804 done = true; 3805 break; 3806 } 3807 } 3808 } 3809 else 3810 { 3811 if (log) 3812 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 3813 done = true; 3814 } 3815 } 3816 } 3817 3818 if (log) 3819 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID()); 3820 3821 return NULL; 3822} 3823 3824//uint32_t 3825//ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 3826//{ 3827// // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 3828// // process and ask it for the list of processes. But if we are local, we can let the Host do it. 3829// if (m_local_debugserver) 3830// { 3831// return Host::ListProcessesMatchingName (name, matches, pids); 3832// } 3833// else 3834// { 3835// // FIXME: Implement talking to the remote debugserver. 3836// return 0; 3837// } 3838// 3839//} 3840// 3841bool 3842ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 3843 StoppointCallbackContext *context, 3844 lldb::user_id_t break_id, 3845 lldb::user_id_t break_loc_id) 3846{ 3847 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 3848 // run so I can stop it if that's what I want to do. 3849 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3850 if (log) 3851 log->Printf("Hit New Thread Notification breakpoint."); 3852 return false; 3853} 3854 3855 3856bool 3857ProcessGDBRemote::StartNoticingNewThreads() 3858{ 3859 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3860 if (m_thread_create_bp_sp) 3861 { 3862 if (log && log->GetVerbose()) 3863 log->Printf("Enabled noticing new thread breakpoint."); 3864 m_thread_create_bp_sp->SetEnabled(true); 3865 } 3866 else 3867 { 3868 PlatformSP platform_sp (m_target.GetPlatform()); 3869 if (platform_sp) 3870 { 3871 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target); 3872 if (m_thread_create_bp_sp) 3873 { 3874 if (log && log->GetVerbose()) 3875 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); 3876 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3877 } 3878 else 3879 { 3880 if (log) 3881 log->Printf("Failed to create new thread notification breakpoint."); 3882 } 3883 } 3884 } 3885 return m_thread_create_bp_sp.get() != NULL; 3886} 3887 3888bool 3889ProcessGDBRemote::StopNoticingNewThreads() 3890{ 3891 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3892 if (log && log->GetVerbose()) 3893 log->Printf ("Disabling new thread notification breakpoint."); 3894 3895 if (m_thread_create_bp_sp) 3896 m_thread_create_bp_sp->SetEnabled(false); 3897 3898 return true; 3899} 3900 3901DynamicLoader * 3902ProcessGDBRemote::GetDynamicLoader () 3903{ 3904 if (m_dyld_ap.get() == NULL) 3905 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 3906 return m_dyld_ap.get(); 3907} 3908 3909Error 3910ProcessGDBRemote::SendEventData(const char *data) 3911{ 3912 int return_value; 3913 bool was_supported; 3914 3915 Error error; 3916 3917 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported); 3918 if (return_value != 0) 3919 { 3920 if (!was_supported) 3921 error.SetErrorString("Sending events is not supported for this process."); 3922 else 3923 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value); 3924 } 3925 return error; 3926} 3927 3928const DataBufferSP 3929ProcessGDBRemote::GetAuxvData() 3930{ 3931 DataBufferSP buf; 3932 if (m_gdb_comm.GetQXferAuxvReadSupported()) 3933 { 3934 std::string response_string; 3935 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success) 3936 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length())); 3937 } 3938 return buf; 3939} 3940 3941StructuredData::ObjectSP 3942ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid) 3943{ 3944 StructuredData::ObjectSP object_sp; 3945 3946 if (m_gdb_comm.GetThreadExtendedInfoSupported()) 3947 { 3948 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3949 SystemRuntime *runtime = GetSystemRuntime(); 3950 if (runtime) 3951 { 3952 runtime->AddThreadExtendedInfoPacketHints (args_dict); 3953 } 3954 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid); 3955 3956 StreamString packet; 3957 packet << "jThreadExtendedInfo:"; 3958 args_dict->Dump (packet); 3959 3960 // FIXME the final character of a JSON dictionary, '}', is the escape 3961 // character in gdb-remote binary mode. lldb currently doesn't escape 3962 // these characters in its packet output -- so we add the quoted version 3963 // of the } character here manually in case we talk to a debugserver which 3964 // un-escapes the characters at packet read time. 3965 packet << (char) (0x7d ^ 0x20); 3966 3967 StringExtractorGDBRemote response; 3968 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success) 3969 { 3970 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); 3971 if (response_type == StringExtractorGDBRemote::eResponse) 3972 { 3973 if (!response.Empty()) 3974 { 3975 object_sp = StructuredData::ParseJSON (response.GetStringRef()); 3976 } 3977 } 3978 } 3979 } 3980 return object_sp; 3981} 3982 3983StructuredData::ObjectSP 3984ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count) 3985{ 3986 StructuredData::ObjectSP object_sp; 3987 3988 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) 3989 { 3990 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3991 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address); 3992 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count); 3993 3994 StreamString packet; 3995 packet << "jGetLoadedDynamicLibrariesInfos:"; 3996 args_dict->Dump (packet); 3997 3998 // FIXME the final character of a JSON dictionary, '}', is the escape 3999 // character in gdb-remote binary mode. lldb currently doesn't escape 4000 // these characters in its packet output -- so we add the quoted version 4001 // of the } character here manually in case we talk to a debugserver which 4002 // un-escapes the characters at packet read time. 4003 packet << (char) (0x7d ^ 0x20); 4004 4005 StringExtractorGDBRemote response; 4006 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success) 4007 { 4008 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); 4009 if (response_type == StringExtractorGDBRemote::eResponse) 4010 { 4011 if (!response.Empty()) 4012 { 4013 // The packet has already had the 0x7d xor quoting stripped out at the 4014 // GDBRemoteCommunication packet receive level. 4015 object_sp = StructuredData::ParseJSON (response.GetStringRef()); 4016 } 4017 } 4018 } 4019 } 4020 return object_sp; 4021} 4022 4023 4024// Establish the largest memory read/write payloads we should use. 4025// If the remote stub has a max packet size, stay under that size. 4026// 4027// If the remote stub's max packet size is crazy large, use a 4028// reasonable largeish default. 4029// 4030// If the remote stub doesn't advertise a max packet size, use a 4031// conservative default. 4032 4033void 4034ProcessGDBRemote::GetMaxMemorySize() 4035{ 4036 const uint64_t reasonable_largeish_default = 128 * 1024; 4037 const uint64_t conservative_default = 512; 4038 4039 if (m_max_memory_size == 0) 4040 { 4041 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 4042 if (stub_max_size != UINT64_MAX && stub_max_size != 0) 4043 { 4044 // Save the stub's claimed maximum packet size 4045 m_remote_stub_max_memory_size = stub_max_size; 4046 4047 // Even if the stub says it can support ginormous packets, 4048 // don't exceed our reasonable largeish default packet size. 4049 if (stub_max_size > reasonable_largeish_default) 4050 { 4051 stub_max_size = reasonable_largeish_default; 4052 } 4053 4054 m_max_memory_size = stub_max_size; 4055 } 4056 else 4057 { 4058 m_max_memory_size = conservative_default; 4059 } 4060 } 4061} 4062 4063void 4064ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max) 4065{ 4066 if (user_specified_max != 0) 4067 { 4068 GetMaxMemorySize (); 4069 4070 if (m_remote_stub_max_memory_size != 0) 4071 { 4072 if (m_remote_stub_max_memory_size < user_specified_max) 4073 { 4074 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big 4075 // as the remote stub says we can go. 4076 } 4077 else 4078 { 4079 m_max_memory_size = user_specified_max; // user's packet size is good 4080 } 4081 } 4082 else 4083 { 4084 m_max_memory_size = user_specified_max; // user's packet size is probably fine 4085 } 4086 } 4087} 4088 4089bool 4090ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec, 4091 const ArchSpec& arch, 4092 ModuleSpec &module_spec) 4093{ 4094 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM); 4095 4096 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec)) 4097 { 4098 if (log) 4099 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s", 4100 __FUNCTION__, module_file_spec.GetPath ().c_str (), 4101 arch.GetTriple ().getTriple ().c_str ()); 4102 return false; 4103 } 4104 4105 if (log) 4106 { 4107 StreamString stream; 4108 module_spec.Dump (stream); 4109 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4110 __FUNCTION__, module_file_spec.GetPath ().c_str (), 4111 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ()); 4112 } 4113 4114 return true; 4115} 4116 4117namespace { 4118 4119typedef std::vector<std::string> stringVec; 4120 4121typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4122struct RegisterSetInfo 4123{ 4124 ConstString name; 4125}; 4126 4127typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4128 4129struct GdbServerTargetInfo 4130{ 4131 std::string arch; 4132 std::string osabi; 4133 stringVec includes; 4134 RegisterSetMap reg_set_map; 4135 XMLNode feature_node; 4136}; 4137 4138bool 4139ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info) 4140{ 4141 if (!feature_node) 4142 return false; 4143 4144 uint32_t prev_reg_num = 0; 4145 uint32_t reg_offset = 0; 4146 4147 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &prev_reg_num, ®_offset](const XMLNode ®_node) -> bool { 4148 std::string gdb_group; 4149 std::string gdb_type; 4150 ConstString reg_name; 4151 ConstString alt_name; 4152 ConstString set_name; 4153 std::vector<uint32_t> value_regs; 4154 std::vector<uint32_t> invalidate_regs; 4155 bool encoding_set = false; 4156 bool format_set = false; 4157 RegisterInfo reg_info = { NULL, // Name 4158 NULL, // Alt name 4159 0, // byte size 4160 reg_offset, // offset 4161 eEncodingUint, // encoding 4162 eFormatHex, // formate 4163 { 4164 LLDB_INVALID_REGNUM, // GCC reg num 4165 LLDB_INVALID_REGNUM, // DWARF reg num 4166 LLDB_INVALID_REGNUM, // generic reg num 4167 prev_reg_num, // GDB reg num 4168 prev_reg_num // native register number 4169 }, 4170 NULL, 4171 NULL 4172 }; 4173 4174 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, ®_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, ®_info, &prev_reg_num, ®_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool { 4175 if (name == "name") 4176 { 4177 reg_name.SetString(value); 4178 } 4179 else if (name == "bitsize") 4180 { 4181 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT; 4182 } 4183 else if (name == "type") 4184 { 4185 gdb_type = value.str(); 4186 } 4187 else if (name == "group") 4188 { 4189 gdb_group = value.str(); 4190 } 4191 else if (name == "regnum") 4192 { 4193 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4194 if (regnum != LLDB_INVALID_REGNUM) 4195 { 4196 reg_info.kinds[eRegisterKindGDB] = regnum; 4197 reg_info.kinds[eRegisterKindLLDB] = regnum; 4198 prev_reg_num = regnum; 4199 } 4200 } 4201 else if (name == "offset") 4202 { 4203 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4204 } 4205 else if (name == "altname") 4206 { 4207 alt_name.SetString(value); 4208 } 4209 else if (name == "encoding") 4210 { 4211 encoding_set = true; 4212 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint); 4213 } 4214 else if (name == "format") 4215 { 4216 format_set = true; 4217 Format format = eFormatInvalid; 4218 if (Args::StringToFormat (value.data(), format, NULL).Success()) 4219 reg_info.format = format; 4220 else if (value == "vector-sint8") 4221 reg_info.format = eFormatVectorOfSInt8; 4222 else if (value == "vector-uint8") 4223 reg_info.format = eFormatVectorOfUInt8; 4224 else if (value == "vector-sint16") 4225 reg_info.format = eFormatVectorOfSInt16; 4226 else if (value == "vector-uint16") 4227 reg_info.format = eFormatVectorOfUInt16; 4228 else if (value == "vector-sint32") 4229 reg_info.format = eFormatVectorOfSInt32; 4230 else if (value == "vector-uint32") 4231 reg_info.format = eFormatVectorOfUInt32; 4232 else if (value == "vector-float32") 4233 reg_info.format = eFormatVectorOfFloat32; 4234 else if (value == "vector-uint128") 4235 reg_info.format = eFormatVectorOfUInt128; 4236 } 4237 else if (name == "group_id") 4238 { 4239 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4240 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id); 4241 if (pos != target_info.reg_set_map.end()) 4242 set_name = pos->second.name; 4243 } 4244 else if (name == "gcc_regnum") 4245 { 4246 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4247 } 4248 else if (name == "dwarf_regnum") 4249 { 4250 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4251 } 4252 else if (name == "generic") 4253 { 4254 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data()); 4255 } 4256 else if (name == "value_regnums") 4257 { 4258 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0); 4259 } 4260 else if (name == "invalidate_regnums") 4261 { 4262 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0); 4263 } 4264 else 4265 { 4266 printf("unhandled attribute %s = %s\n", name.data(), value.data()); 4267 } 4268 return true; // Keep iterating through all attributes 4269 }); 4270 4271 if (!gdb_type.empty() && !(encoding_set || format_set)) 4272 { 4273 if (gdb_type.find("int") == 0) 4274 { 4275 reg_info.format = eFormatHex; 4276 reg_info.encoding = eEncodingUint; 4277 } 4278 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") 4279 { 4280 reg_info.format = eFormatAddressInfo; 4281 reg_info.encoding = eEncodingUint; 4282 } 4283 else if (gdb_type == "i387_ext" || gdb_type == "float") 4284 { 4285 reg_info.format = eFormatFloat; 4286 reg_info.encoding = eEncodingIEEE754; 4287 } 4288 } 4289 4290 // Only update the register set name if we didn't get a "reg_set" attribute. 4291 // "set_name" will be empty if we didn't have a "reg_set" attribute. 4292 if (!set_name && !gdb_group.empty()) 4293 set_name.SetCString(gdb_group.c_str()); 4294 4295 reg_info.byte_offset = reg_offset; 4296 assert (reg_info.byte_size != 0); 4297 reg_offset += reg_info.byte_size; 4298 if (!value_regs.empty()) 4299 { 4300 value_regs.push_back(LLDB_INVALID_REGNUM); 4301 reg_info.value_regs = value_regs.data(); 4302 } 4303 if (!invalidate_regs.empty()) 4304 { 4305 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 4306 reg_info.invalidate_regs = invalidate_regs.data(); 4307 } 4308 4309 ++prev_reg_num; 4310 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name); 4311 4312 return true; // Keep iterating through all "reg" elements 4313 }); 4314 return true; 4315} 4316 4317} // namespace {} 4318 4319 4320// query the target of gdb-remote for extended target information 4321// return: 'true' on success 4322// 'false' on failure 4323bool 4324ProcessGDBRemote::GetGDBServerRegisterInfo () 4325{ 4326 // Make sure LLDB has an XML parser it can use first 4327 if (!XMLDocument::XMLEnabled()) 4328 return false; 4329 4330 // redirect libxml2's error handler since the default prints to stdout 4331 4332 GDBRemoteCommunicationClient & comm = m_gdb_comm; 4333 4334 // check that we have extended feature read support 4335 if ( !comm.GetQXferFeaturesReadSupported( ) ) 4336 return false; 4337 4338 // request the target xml file 4339 std::string raw; 4340 lldb_private::Error lldberr; 4341 if (!comm.ReadExtFeature(ConstString("features"), 4342 ConstString("target.xml"), 4343 raw, 4344 lldberr)) 4345 { 4346 return false; 4347 } 4348 4349 4350 XMLDocument xml_document; 4351 4352 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) 4353 { 4354 GdbServerTargetInfo target_info; 4355 4356 XMLNode target_node = xml_document.GetRootElement("target"); 4357 if (target_node) 4358 { 4359 XMLNode feature_node; 4360 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool 4361 { 4362 llvm::StringRef name = node.GetName(); 4363 if (name == "architecture") 4364 { 4365 node.GetElementText(target_info.arch); 4366 } 4367 else if (name == "osabi") 4368 { 4369 node.GetElementText(target_info.osabi); 4370 } 4371 else if (name == "xi:include" || name == "include") 4372 { 4373 llvm::StringRef href = node.GetAttributeValue("href"); 4374 if (!href.empty()) 4375 target_info.includes.push_back(href.str()); 4376 } 4377 else if (name == "feature") 4378 { 4379 feature_node = node; 4380 } 4381 else if (name == "groups") 4382 { 4383 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool { 4384 uint32_t set_id = UINT32_MAX; 4385 RegisterSetInfo set_info; 4386 4387 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool { 4388 if (name == "id") 4389 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4390 if (name == "name") 4391 set_info.name = ConstString(value); 4392 return true; // Keep iterating through all attributes 4393 }); 4394 4395 if (set_id != UINT32_MAX) 4396 target_info.reg_set_map[set_id] = set_info; 4397 return true; // Keep iterating through all "group" elements 4398 }); 4399 } 4400 return true; // Keep iterating through all children of the target_node 4401 }); 4402 4403 if (feature_node) 4404 { 4405 ParseRegisters(feature_node, target_info, this->m_register_info); 4406 } 4407 4408 for (const auto &include : target_info.includes) 4409 { 4410 // request register file 4411 std::string xml_data; 4412 if (!comm.ReadExtFeature(ConstString("features"), 4413 ConstString(include), 4414 xml_data, 4415 lldberr)) 4416 continue; 4417 4418 XMLDocument include_xml_document; 4419 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str()); 4420 XMLNode include_feature_node = include_xml_document.GetRootElement("feature"); 4421 if (include_feature_node) 4422 { 4423 ParseRegisters(include_feature_node, target_info, this->m_register_info); 4424 } 4425 } 4426 this->m_register_info.Finalize(GetTarget().GetArchitecture()); 4427 } 4428 } 4429 4430 return m_register_info.GetNumRegisters() > 0; 4431} 4432 4433Error 4434ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list) 4435{ 4436 // Make sure LLDB has an XML parser it can use first 4437 if (!XMLDocument::XMLEnabled()) 4438 return Error (0, ErrorType::eErrorTypeGeneric); 4439 4440 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS); 4441 if (log) 4442 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__); 4443 4444 GDBRemoteCommunicationClient & comm = m_gdb_comm; 4445 4446 // check that we have extended feature read support 4447 if (comm.GetQXferLibrariesSVR4ReadSupported ()) { 4448 list.clear (); 4449 4450 // request the loaded library list 4451 std::string raw; 4452 lldb_private::Error lldberr; 4453 4454 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr)) 4455 return Error (0, ErrorType::eErrorTypeGeneric); 4456 4457 // parse the xml file in memory 4458 if (log) 4459 log->Printf ("parsing: %s", raw.c_str()); 4460 XMLDocument doc; 4461 4462 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4463 return Error (0, ErrorType::eErrorTypeGeneric); 4464 4465 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4466 if (!root_element) 4467 return Error(); 4468 4469 // main link map structure 4470 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm"); 4471 if (!main_lm.empty()) 4472 { 4473 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0); 4474 } 4475 4476 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool { 4477 4478 GDBLoadedModuleInfoList::LoadedModuleInfo module; 4479 4480 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool { 4481 4482 if (name == "name") 4483 module.set_name (value.str()); 4484 else if (name == "lm") 4485 { 4486 // the address of the link_map struct. 4487 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0)); 4488 } 4489 else if (name == "l_addr") 4490 { 4491 // the displacement as read from the field 'l_addr' of the link_map struct. 4492 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0)); 4493 4494 } 4495 else if (name == "l_ld") 4496 { 4497 // the memory address of the libraries PT_DYAMIC section. 4498 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0)); 4499 } 4500 4501 return true; // Keep iterating over all properties of "library" 4502 }); 4503 4504 if (log) 4505 { 4506 std::string name; 4507 lldb::addr_t lm=0, base=0, ld=0; 4508 4509 module.get_name (name); 4510 module.get_link_map (lm); 4511 module.get_base (base); 4512 module.get_dynamic (ld); 4513 4514 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str()); 4515 } 4516 4517 list.add (module); 4518 return true; // Keep iterating over all "library" elements in the root node 4519 }); 4520 4521 if (log) 4522 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size()); 4523 } else if (comm.GetQXferLibrariesReadSupported ()) { 4524 list.clear (); 4525 4526 // request the loaded library list 4527 std::string raw; 4528 lldb_private::Error lldberr; 4529 4530 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr)) 4531 return Error (0, ErrorType::eErrorTypeGeneric); 4532 4533 if (log) 4534 log->Printf ("parsing: %s", raw.c_str()); 4535 XMLDocument doc; 4536 4537 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4538 return Error (0, ErrorType::eErrorTypeGeneric); 4539 4540 XMLNode root_element = doc.GetRootElement("library-list"); 4541 if (!root_element) 4542 return Error(); 4543 4544 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool { 4545 GDBLoadedModuleInfoList::LoadedModuleInfo module; 4546 4547 llvm::StringRef name = library.GetAttributeValue("name"); 4548 module.set_name(name.str()); 4549 4550 // The base address of a given library will be the address of its 4551 // first section. Most remotes send only one section for Windows 4552 // targets for example. 4553 const XMLNode §ion = library.FindFirstChildElementWithName("section"); 4554 llvm::StringRef address = section.GetAttributeValue("address"); 4555 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0)); 4556 4557 if (log) 4558 { 4559 std::string name; 4560 lldb::addr_t base = 0; 4561 module.get_name (name); 4562 module.get_base (base); 4563 4564 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str()); 4565 } 4566 4567 list.add (module); 4568 return true; // Keep iterating over all "library" elements in the root node 4569 }); 4570 4571 if (log) 4572 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size()); 4573 } else { 4574 return Error (0, ErrorType::eErrorTypeGeneric); 4575 } 4576 4577 return Error(); 4578} 4579 4580lldb::ModuleSP 4581ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr) 4582{ 4583 Target &target = m_process->GetTarget(); 4584 ModuleList &modules = target.GetImages(); 4585 ModuleSP module_sp; 4586 4587 bool changed = false; 4588 4589 ModuleSpec module_spec (file, target.GetArchitecture()); 4590 if ((module_sp = modules.FindFirstModule (module_spec))) 4591 { 4592 module_sp->SetLoadAddress (target, base_addr, true, changed); 4593 } 4594 else if ((module_sp = target.GetSharedModule (module_spec))) 4595 { 4596 module_sp->SetLoadAddress (target, base_addr, true, changed); 4597 } 4598 4599 return module_sp; 4600} 4601 4602size_t 4603ProcessGDBRemote::LoadModules () 4604{ 4605 using lldb_private::process_gdb_remote::ProcessGDBRemote; 4606 4607 // request a list of loaded libraries from GDBServer 4608 GDBLoadedModuleInfoList module_list; 4609 if (GetLoadedModuleList (module_list).Fail()) 4610 return 0; 4611 4612 // get a list of all the modules 4613 ModuleList new_modules; 4614 4615 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list) 4616 { 4617 std::string mod_name; 4618 lldb::addr_t mod_base; 4619 4620 bool valid = true; 4621 valid &= modInfo.get_name (mod_name); 4622 valid &= modInfo.get_base (mod_base); 4623 if (!valid) 4624 continue; 4625 4626 // hack (cleaner way to get file name only?) (win/unix compat?) 4627 size_t marker = mod_name.rfind ('/'); 4628 if (marker == std::string::npos) 4629 marker = 0; 4630 else 4631 marker += 1; 4632 4633 FileSpec file (mod_name.c_str()+marker, true); 4634 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base); 4635 4636 if (module_sp.get()) 4637 new_modules.Append (module_sp); 4638 } 4639 4640 if (new_modules.GetSize() > 0) 4641 { 4642 Target & target = m_target; 4643 4644 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool 4645 { 4646 lldb_private::ObjectFile * obj = module_sp->GetObjectFile (); 4647 if (!obj) 4648 return true; 4649 4650 if (obj->GetType () != ObjectFile::Type::eTypeExecutable) 4651 return true; 4652 4653 lldb::ModuleSP module_copy_sp = module_sp; 4654 target.SetExecutableModule (module_copy_sp, false); 4655 return false; 4656 }); 4657 4658 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 4659 loaded_modules.AppendIfNeeded (new_modules); 4660 m_process->GetTarget().ModulesDidLoad (new_modules); 4661 } 4662 4663 return new_modules.GetSize(); 4664} 4665 4666Error 4667ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr) 4668{ 4669 is_loaded = false; 4670 load_addr = LLDB_INVALID_ADDRESS; 4671 4672 std::string file_path = file.GetPath(false); 4673 if (file_path.empty ()) 4674 return Error("Empty file name specified"); 4675 4676 StreamString packet; 4677 packet.PutCString("qFileLoadAddress:"); 4678 packet.PutCStringAsRawHex8(file_path.c_str()); 4679 4680 StringExtractorGDBRemote response; 4681 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success) 4682 return Error("Sending qFileLoadAddress packet failed"); 4683 4684 if (response.IsErrorResponse()) 4685 { 4686 if (response.GetError() == 1) 4687 { 4688 // The file is not loaded into the inferior 4689 is_loaded = false; 4690 load_addr = LLDB_INVALID_ADDRESS; 4691 return Error(); 4692 } 4693 4694 return Error("Fetching file load address from remote server returned an error"); 4695 } 4696 4697 if (response.IsNormalResponse()) 4698 { 4699 is_loaded = true; 4700 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 4701 return Error(); 4702 } 4703 4704 return Error("Unknown error happened during sending the load address packet"); 4705} 4706 4707 4708void 4709ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list) 4710{ 4711 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything 4712 Process::ModulesDidLoad (module_list); 4713 4714 // After loading shared libraries, we can ask our remote GDB server if 4715 // it needs any symbols. 4716 m_gdb_comm.ServeSymbolLookups(this); 4717} 4718 4719 4720class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed 4721{ 4722public: 4723 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) : 4724 CommandObjectParsed (interpreter, 4725 "process plugin packet speed-test", 4726 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ", 4727 NULL), 4728 m_option_group (interpreter), 4729 m_num_packets (LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, "The number of packets to send of each varying size (default is 1000).", 1000), 4730 m_max_send (LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, "The maximum number of bytes to send in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024), 4731 m_max_recv (LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, "The maximum number of bytes to receive in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024), 4732 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true) 4733 { 4734 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4735 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4736 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4737 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4738 m_option_group.Finalize(); 4739 } 4740 4741 ~CommandObjectProcessGDBRemoteSpeedTest () 4742 { 4743 } 4744 4745 4746 Options * 4747 GetOptions () override 4748 { 4749 return &m_option_group; 4750 } 4751 4752 bool 4753 DoExecute (Args& command, CommandReturnObject &result) override 4754 { 4755 const size_t argc = command.GetArgumentCount(); 4756 if (argc == 0) 4757 { 4758 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4759 if (process) 4760 { 4761 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream()); 4762 result.SetImmediateOutputStream (output_stream_sp); 4763 4764 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 4765 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 4766 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 4767 const bool json = m_json.GetOptionValue().GetCurrentValue(); 4768 if (output_stream_sp) 4769 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp); 4770 else 4771 { 4772 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream()); 4773 } 4774 result.SetStatus (eReturnStatusSuccessFinishResult); 4775 return true; 4776 } 4777 } 4778 else 4779 { 4780 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str()); 4781 } 4782 result.SetStatus (eReturnStatusFailed); 4783 return false; 4784 } 4785protected: 4786 OptionGroupOptions m_option_group; 4787 OptionGroupUInt64 m_num_packets; 4788 OptionGroupUInt64 m_max_send; 4789 OptionGroupUInt64 m_max_recv; 4790 OptionGroupBoolean m_json; 4791 4792}; 4793 4794class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed 4795{ 4796private: 4797 4798public: 4799 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) : 4800 CommandObjectParsed (interpreter, 4801 "process plugin packet history", 4802 "Dumps the packet history buffer. ", 4803 NULL) 4804 { 4805 } 4806 4807 ~CommandObjectProcessGDBRemotePacketHistory () 4808 { 4809 } 4810 4811 bool 4812 DoExecute (Args& command, CommandReturnObject &result) override 4813 { 4814 const size_t argc = command.GetArgumentCount(); 4815 if (argc == 0) 4816 { 4817 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4818 if (process) 4819 { 4820 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 4821 result.SetStatus (eReturnStatusSuccessFinishResult); 4822 return true; 4823 } 4824 } 4825 else 4826 { 4827 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str()); 4828 } 4829 result.SetStatus (eReturnStatusFailed); 4830 return false; 4831 } 4832}; 4833 4834class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed 4835{ 4836private: 4837 4838public: 4839 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) : 4840 CommandObjectParsed (interpreter, 4841 "process plugin packet xfer-size", 4842 "Maximum size that lldb will try to read/write one one chunk.", 4843 NULL) 4844 { 4845 } 4846 4847 ~CommandObjectProcessGDBRemotePacketXferSize () 4848 { 4849 } 4850 4851 bool 4852 DoExecute (Args& command, CommandReturnObject &result) override 4853 { 4854 const size_t argc = command.GetArgumentCount(); 4855 if (argc == 0) 4856 { 4857 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str()); 4858 result.SetStatus (eReturnStatusFailed); 4859 return false; 4860 } 4861 4862 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4863 if (process) 4864 { 4865 const char *packet_size = command.GetArgumentAtIndex(0); 4866 errno = 0; 4867 uint64_t user_specified_max = strtoul (packet_size, NULL, 10); 4868 if (errno == 0 && user_specified_max != 0) 4869 { 4870 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max); 4871 result.SetStatus (eReturnStatusSuccessFinishResult); 4872 return true; 4873 } 4874 } 4875 result.SetStatus (eReturnStatusFailed); 4876 return false; 4877 } 4878}; 4879 4880 4881class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed 4882{ 4883private: 4884 4885public: 4886 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) : 4887 CommandObjectParsed (interpreter, 4888 "process plugin packet send", 4889 "Send a custom packet through the GDB remote protocol and print the answer. " 4890 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.", 4891 NULL) 4892 { 4893 } 4894 4895 ~CommandObjectProcessGDBRemotePacketSend () 4896 { 4897 } 4898 4899 bool 4900 DoExecute (Args& command, CommandReturnObject &result) override 4901 { 4902 const size_t argc = command.GetArgumentCount(); 4903 if (argc == 0) 4904 { 4905 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str()); 4906 result.SetStatus (eReturnStatusFailed); 4907 return false; 4908 } 4909 4910 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4911 if (process) 4912 { 4913 for (size_t i=0; i<argc; ++ i) 4914 { 4915 const char *packet_cstr = command.GetArgumentAtIndex(0); 4916 bool send_async = true; 4917 StringExtractorGDBRemote response; 4918 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 4919 result.SetStatus (eReturnStatusSuccessFinishResult); 4920 Stream &output_strm = result.GetOutputStream(); 4921 output_strm.Printf (" packet: %s\n", packet_cstr); 4922 std::string &response_str = response.GetStringRef(); 4923 4924 if (strstr(packet_cstr, "qGetProfileData") != NULL) 4925 { 4926 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response); 4927 } 4928 4929 if (response_str.empty()) 4930 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 4931 else 4932 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 4933 } 4934 } 4935 return true; 4936 } 4937}; 4938 4939class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw 4940{ 4941private: 4942 4943public: 4944 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) : 4945 CommandObjectRaw (interpreter, 4946 "process plugin packet monitor", 4947 "Send a qRcmd packet through the GDB remote protocol and print the response." 4948 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.", 4949 NULL) 4950 { 4951 } 4952 4953 ~CommandObjectProcessGDBRemotePacketMonitor () 4954 { 4955 } 4956 4957 bool 4958 DoExecute (const char *command, CommandReturnObject &result) override 4959 { 4960 if (command == NULL || command[0] == '\0') 4961 { 4962 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str()); 4963 result.SetStatus (eReturnStatusFailed); 4964 return false; 4965 } 4966 4967 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4968 if (process) 4969 { 4970 StreamString packet; 4971 packet.PutCString("qRcmd,"); 4972 packet.PutBytesAsRawHex8(command, strlen(command)); 4973 const char *packet_cstr = packet.GetString().c_str(); 4974 4975 bool send_async = true; 4976 StringExtractorGDBRemote response; 4977 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 4978 result.SetStatus (eReturnStatusSuccessFinishResult); 4979 Stream &output_strm = result.GetOutputStream(); 4980 output_strm.Printf (" packet: %s\n", packet_cstr); 4981 const std::string &response_str = response.GetStringRef(); 4982 4983 if (response_str.empty()) 4984 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 4985 else 4986 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 4987 } 4988 return true; 4989 } 4990}; 4991 4992class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword 4993{ 4994private: 4995 4996public: 4997 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) : 4998 CommandObjectMultiword (interpreter, 4999 "process plugin packet", 5000 "Commands that deal with GDB remote packets.", 5001 NULL) 5002 { 5003 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter))); 5004 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter))); 5005 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter))); 5006 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter))); 5007 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter))); 5008 } 5009 5010 ~CommandObjectProcessGDBRemotePacket () 5011 { 5012 } 5013}; 5014 5015class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword 5016{ 5017public: 5018 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) : 5019 CommandObjectMultiword (interpreter, 5020 "process plugin", 5021 "A set of commands for operating on a ProcessGDBRemote process.", 5022 "process plugin <subcommand> [<subcommand-options>]") 5023 { 5024 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter))); 5025 } 5026 5027 ~CommandObjectMultiwordProcessGDBRemote () 5028 { 5029 } 5030}; 5031 5032CommandObject * 5033ProcessGDBRemote::GetPluginCommandObject() 5034{ 5035 if (!m_command_sp) 5036 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter())); 5037 return m_command_sp.get(); 5038} 5039