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