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::eMutexTypeNormal), 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 = std::move(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 = std::move(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 = std::move(object->GetStringValue()); 2221 } 2222 else if (key == g_key_description) 2223 { 2224 description = std::move(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] = std::move(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() = std::move(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 ThreadSP thread_sp = SetThreadStopInfo (tid, 2489 expedited_register_map, 2490 signo, 2491 thread_name, 2492 reason, 2493 description, 2494 exc_type, 2495 exc_data, 2496 thread_dispatch_qaddr, 2497 queue_vars_valid, 2498 queue_name, 2499 queue_kind, 2500 queue_serial); 2501 2502 // If the response is old style 'S' packet which does not provide us with thread information 2503 // then update the thread list and choose the first one. 2504 if (!thread_sp) 2505 { 2506 UpdateThreadIDList (); 2507 2508 if (!m_thread_ids.empty ()) 2509 { 2510 Mutex::Locker locker (m_thread_list_real.GetMutex ()); 2511 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false); 2512 } 2513 } 2514 2515 return eStateStopped; 2516 } 2517 break; 2518 2519 case 'W': 2520 case 'X': 2521 // process exited 2522 return eStateExited; 2523 2524 default: 2525 break; 2526 } 2527 return eStateInvalid; 2528 } 2529 2530 void 2531 ProcessGDBRemote::RefreshStateAfterStop () 2532 { 2533 Mutex::Locker locker(m_thread_list_real.GetMutex()); 2534 m_thread_ids.clear(); 2535 // Set the thread stop info. It might have a "threads" key whose value is 2536 // a list of all thread IDs in the current process, so m_thread_ids might 2537 // get set. 2538 2539 // Scope for the lock 2540 { 2541 // Lock the thread stack while we access it 2542 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex); 2543 // Get the number of stop packets on the stack 2544 int nItems = m_stop_packet_stack.size(); 2545 // Iterate over them 2546 for (int i = 0; i < nItems; i++) 2547 { 2548 // Get the thread stop info 2549 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i]; 2550 // Process thread stop info 2551 SetThreadStopInfo(stop_info); 2552 } 2553 // Clear the thread stop stack 2554 m_stop_packet_stack.clear(); 2555 } 2556 2557 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 2558 if (m_thread_ids.empty()) 2559 { 2560 // No, we need to fetch the thread list manually 2561 UpdateThreadIDList(); 2562 } 2563 2564 // If we have queried for a default thread id 2565 if (m_initial_tid != LLDB_INVALID_THREAD_ID) 2566 { 2567 m_thread_list.SetSelectedThreadByID(m_initial_tid); 2568 m_initial_tid = LLDB_INVALID_THREAD_ID; 2569 } 2570 2571 // Let all threads recover from stopping and do any clean up based 2572 // on the previous thread state (if any). 2573 m_thread_list_real.RefreshStateAfterStop(); 2574 2575 } 2576 2577 Error 2578 ProcessGDBRemote::DoHalt (bool &caused_stop) 2579 { 2580 Error error; 2581 2582 bool timed_out = false; 2583 Mutex::Locker locker; 2584 2585 if (m_public_state.GetValue() == eStateAttaching) 2586 { 2587 // We are being asked to halt during an attach. We need to just close 2588 // our file handle and debugserver will go away, and we can be done... 2589 m_gdb_comm.Disconnect(); 2590 } 2591 else 2592 { 2593 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out)) 2594 { 2595 if (timed_out) 2596 error.SetErrorString("timed out sending interrupt packet"); 2597 else 2598 error.SetErrorString("unknown error sending interrupt packet"); 2599 } 2600 2601 caused_stop = m_gdb_comm.GetInterruptWasSent (); 2602 } 2603 return error; 2604 } 2605 2606 Error 2607 ProcessGDBRemote::DoDetach(bool keep_stopped) 2608 { 2609 Error error; 2610 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2611 if (log) 2612 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 2613 2614 error = m_gdb_comm.Detach (keep_stopped); 2615 if (log) 2616 { 2617 if (error.Success()) 2618 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 2619 else 2620 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>"); 2621 } 2622 2623 if (!error.Success()) 2624 return error; 2625 2626 // Sleep for one second to let the process get all detached... 2627 StopAsyncThread (); 2628 2629 SetPrivateState (eStateDetached); 2630 ResumePrivateStateThread(); 2631 2632 //KillDebugserverProcess (); 2633 return error; 2634 } 2635 2636 2637 Error 2638 ProcessGDBRemote::DoDestroy () 2639 { 2640 Error error; 2641 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2642 if (log) 2643 log->Printf ("ProcessGDBRemote::DoDestroy()"); 2644 2645 // There is a bug in older iOS debugservers where they don't shut down the process 2646 // they are debugging properly. If the process is sitting at a breakpoint or an exception, 2647 // this can cause problems with restarting. So we check to see if any of our threads are stopped 2648 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN 2649 // destroy it again. 2650 // 2651 // Note, we don't have a good way to test the version of debugserver, but I happen to know that 2652 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of 2653 // the debugservers with this bug are equal. There really should be a better way to test this! 2654 // 2655 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and 2656 // get called here to destroy again and we're still at a breakpoint or exception, then we should 2657 // just do the straight-forward kill. 2658 // 2659 // And of course, if we weren't able to stop the process by the time we get here, it isn't 2660 // necessary (or helpful) to do any of this. 2661 2662 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) 2663 { 2664 PlatformSP platform_sp = GetTarget().GetPlatform(); 2665 2666 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 2667 if (platform_sp 2668 && platform_sp->GetName() 2669 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) 2670 { 2671 if (m_destroy_tried_resuming) 2672 { 2673 if (log) 2674 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again."); 2675 } 2676 else 2677 { 2678 // At present, the plans are discarded and the breakpoints disabled Process::Destroy, 2679 // but we really need it to happen here and it doesn't matter if we do it twice. 2680 m_thread_list.DiscardThreadPlans(); 2681 DisableAllBreakpointSites(); 2682 2683 bool stop_looks_like_crash = false; 2684 ThreadList &threads = GetThreadList(); 2685 2686 { 2687 Mutex::Locker locker(threads.GetMutex()); 2688 2689 size_t num_threads = threads.GetSize(); 2690 for (size_t i = 0; i < num_threads; i++) 2691 { 2692 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2693 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2694 StopReason reason = eStopReasonInvalid; 2695 if (stop_info_sp) 2696 reason = stop_info_sp->GetStopReason(); 2697 if (reason == eStopReasonBreakpoint 2698 || reason == eStopReasonException) 2699 { 2700 if (log) 2701 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.", 2702 thread_sp->GetProtocolID(), 2703 stop_info_sp->GetDescription()); 2704 stop_looks_like_crash = true; 2705 break; 2706 } 2707 } 2708 } 2709 2710 if (stop_looks_like_crash) 2711 { 2712 if (log) 2713 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill."); 2714 m_destroy_tried_resuming = true; 2715 2716 // If we are going to run again before killing, it would be good to suspend all the threads 2717 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with 2718 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do 2719 // have to run the risk of letting those threads proceed a bit. 2720 2721 { 2722 Mutex::Locker locker(threads.GetMutex()); 2723 2724 size_t num_threads = threads.GetSize(); 2725 for (size_t i = 0; i < num_threads; i++) 2726 { 2727 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 2728 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 2729 StopReason reason = eStopReasonInvalid; 2730 if (stop_info_sp) 2731 reason = stop_info_sp->GetStopReason(); 2732 if (reason != eStopReasonBreakpoint 2733 && reason != eStopReasonException) 2734 { 2735 if (log) 2736 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.", 2737 thread_sp->GetProtocolID()); 2738 thread_sp->SetResumeState(eStateSuspended); 2739 } 2740 } 2741 } 2742 Resume (); 2743 return Destroy(false); 2744 } 2745 } 2746 } 2747 } 2748 2749 // Interrupt if our inferior is running... 2750 int exit_status = SIGABRT; 2751 std::string exit_string; 2752 2753 if (m_gdb_comm.IsConnected()) 2754 { 2755 if (m_public_state.GetValue() != eStateAttaching) 2756 { 2757 StringExtractorGDBRemote response; 2758 bool send_async = true; 2759 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3); 2760 2761 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success) 2762 { 2763 char packet_cmd = response.GetChar(0); 2764 2765 if (packet_cmd == 'W' || packet_cmd == 'X') 2766 { 2767 #if defined(__APPLE__) 2768 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off 2769 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill 2770 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns 2771 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap 2772 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of 2773 // switching ownership back to lldb which was the original parent, and gets confused in the handoff. 2774 // Anyway, so call waitpid here to finally reap it. 2775 PlatformSP platform_sp(GetTarget().GetPlatform()); 2776 if (platform_sp && platform_sp->IsHost()) 2777 { 2778 int status; 2779 ::pid_t reap_pid; 2780 reap_pid = waitpid (GetID(), &status, WNOHANG); 2781 if (log) 2782 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status); 2783 } 2784 #endif 2785 SetLastStopPacket (response); 2786 ClearThreadIDList (); 2787 exit_status = response.GetHexU8(); 2788 } 2789 else 2790 { 2791 if (log) 2792 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str()); 2793 exit_string.assign("got unexpected response to k packet: "); 2794 exit_string.append(response.GetStringRef()); 2795 } 2796 } 2797 else 2798 { 2799 if (log) 2800 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 2801 exit_string.assign("failed to send the k packet"); 2802 } 2803 } 2804 else 2805 { 2806 if (log) 2807 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching"); 2808 exit_string.assign ("killed or interrupted while attaching."); 2809 } 2810 } 2811 else 2812 { 2813 // If we missed setting the exit status on the way out, do it here. 2814 // NB set exit status can be called multiple times, the first one sets the status. 2815 exit_string.assign("destroying when not connected to debugserver"); 2816 } 2817 2818 SetExitStatus(exit_status, exit_string.c_str()); 2819 2820 StopAsyncThread (); 2821 KillDebugserverProcess (); 2822 return error; 2823 } 2824 2825 void 2826 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response) 2827 { 2828 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos; 2829 if (did_exec) 2830 { 2831 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2832 if (log) 2833 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2834 2835 m_thread_list_real.Clear(); 2836 m_thread_list.Clear(); 2837 BuildDynamicRegisterInfo (true); 2838 m_gdb_comm.ResetDiscoverableSettings (did_exec); 2839 } 2840 2841 // Scope the lock 2842 { 2843 // Lock the thread stack while we access it 2844 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex); 2845 2846 // We are are not using non-stop mode, there can only be one last stop 2847 // reply packet, so clear the list. 2848 if (GetTarget().GetNonStopModeEnabled() == false) 2849 m_stop_packet_stack.clear(); 2850 2851 // Add this stop packet to the stop packet stack 2852 // This stack will get popped and examined when we switch to the 2853 // Stopped state 2854 m_stop_packet_stack.push_back(response); 2855 } 2856 } 2857 2858 //------------------------------------------------------------------ 2859 // Process Queries 2860 //------------------------------------------------------------------ 2861 2862 bool 2863 ProcessGDBRemote::IsAlive () 2864 { 2865 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 2866 } 2867 2868 addr_t 2869 ProcessGDBRemote::GetImageInfoAddress() 2870 { 2871 // request the link map address via the $qShlibInfoAddr packet 2872 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); 2873 2874 // the loaded module list can also provides a link map address 2875 if (addr == LLDB_INVALID_ADDRESS) 2876 { 2877 GDBLoadedModuleInfoList list; 2878 if (GetLoadedModuleList (list).Success()) 2879 addr = list.m_link_map; 2880 } 2881 2882 return addr; 2883 } 2884 2885 void 2886 ProcessGDBRemote::WillPublicStop () 2887 { 2888 // See if the GDB remote client supports the JSON threads info. 2889 // If so, we gather stop info for all threads, expedited registers, 2890 // expedited memory, runtime queue information (iOS and MacOSX only), 2891 // and more. Expediting memory will help stack backtracing be much 2892 // faster. Expediting registers will make sure we don't have to read 2893 // the thread registers for GPRs. 2894 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); 2895 2896 if (m_jthreadsinfo_sp) 2897 { 2898 // Now set the stop info for each thread and also expedite any registers 2899 // and memory that was in the jThreadsInfo response. 2900 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); 2901 if (thread_infos) 2902 { 2903 const size_t n = thread_infos->GetSize(); 2904 for (size_t i=0; i<n; ++i) 2905 { 2906 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary(); 2907 if (thread_dict) 2908 SetThreadStopInfo(thread_dict); 2909 } 2910 } 2911 } 2912 } 2913 2914 //------------------------------------------------------------------ 2915 // Process Memory 2916 //------------------------------------------------------------------ 2917 size_t 2918 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2919 { 2920 GetMaxMemorySize (); 2921 if (size > m_max_memory_size) 2922 { 2923 // Keep memory read sizes down to a sane limit. This function will be 2924 // called multiple times in order to complete the task by 2925 // lldb_private::Process so it is ok to do this. 2926 size = m_max_memory_size; 2927 } 2928 2929 char packet[64]; 2930 int packet_len; 2931 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2932 if (binary_memory_read) 2933 { 2934 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size); 2935 } 2936 else 2937 { 2938 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size); 2939 } 2940 assert (packet_len + 1 < (int)sizeof(packet)); 2941 StringExtractorGDBRemote response; 2942 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success) 2943 { 2944 if (response.IsNormalResponse()) 2945 { 2946 error.Clear(); 2947 if (binary_memory_read) 2948 { 2949 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any 2950 // 0x7d character escaping that was present in the packet 2951 2952 size_t data_received_size = response.GetBytesLeft(); 2953 if (data_received_size > size) 2954 { 2955 // Don't write past the end of BUF if the remote debug server gave us too 2956 // much data for some reason. 2957 data_received_size = size; 2958 } 2959 memcpy (buf, response.GetStringRef().data(), data_received_size); 2960 return data_received_size; 2961 } 2962 else 2963 { 2964 return response.GetHexBytes(buf, size, '\xdd'); 2965 } 2966 } 2967 else if (response.IsErrorResponse()) 2968 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2969 else if (response.IsUnsupportedResponse()) 2970 error.SetErrorStringWithFormat("GDB server does not support reading memory"); 2971 else 2972 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str()); 2973 } 2974 else 2975 { 2976 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2977 } 2978 return 0; 2979 } 2980 2981 size_t 2982 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2983 { 2984 GetMaxMemorySize (); 2985 if (size > m_max_memory_size) 2986 { 2987 // Keep memory read sizes down to a sane limit. This function will be 2988 // called multiple times in order to complete the task by 2989 // lldb_private::Process so it is ok to do this. 2990 size = m_max_memory_size; 2991 } 2992 2993 StreamString packet; 2994 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2995 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 2996 StringExtractorGDBRemote response; 2997 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success) 2998 { 2999 if (response.IsOKResponse()) 3000 { 3001 error.Clear(); 3002 return size; 3003 } 3004 else if (response.IsErrorResponse()) 3005 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr); 3006 else if (response.IsUnsupportedResponse()) 3007 error.SetErrorStringWithFormat("GDB server does not support writing memory"); 3008 else 3009 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 3010 } 3011 else 3012 { 3013 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str()); 3014 } 3015 return 0; 3016 } 3017 3018 lldb::addr_t 3019 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 3020 { 3021 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS)); 3022 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 3023 3024 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 3025 switch (supported) 3026 { 3027 case eLazyBoolCalculate: 3028 case eLazyBoolYes: 3029 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 3030 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 3031 return allocated_addr; 3032 3033 case eLazyBoolNo: 3034 // Call mmap() to create memory in the inferior.. 3035 unsigned prot = 0; 3036 if (permissions & lldb::ePermissionsReadable) 3037 prot |= eMmapProtRead; 3038 if (permissions & lldb::ePermissionsWritable) 3039 prot |= eMmapProtWrite; 3040 if (permissions & lldb::ePermissionsExecutable) 3041 prot |= eMmapProtExec; 3042 3043 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 3044 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 3045 m_addr_to_mmap_size[allocated_addr] = size; 3046 else 3047 { 3048 allocated_addr = LLDB_INVALID_ADDRESS; 3049 if (log) 3050 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__); 3051 } 3052 break; 3053 } 3054 3055 if (allocated_addr == LLDB_INVALID_ADDRESS) 3056 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions)); 3057 else 3058 error.Clear(); 3059 return allocated_addr; 3060 } 3061 3062 Error 3063 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr, 3064 MemoryRegionInfo ®ion_info) 3065 { 3066 3067 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info)); 3068 return error; 3069 } 3070 3071 Error 3072 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num) 3073 { 3074 3075 Error error (m_gdb_comm.GetWatchpointSupportInfo (num)); 3076 return error; 3077 } 3078 3079 Error 3080 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after) 3081 { 3082 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after)); 3083 return error; 3084 } 3085 3086 Error 3087 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 3088 { 3089 Error error; 3090 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 3091 3092 switch (supported) 3093 { 3094 case eLazyBoolCalculate: 3095 // We should never be deallocating memory without allocating memory 3096 // first so we should never get eLazyBoolCalculate 3097 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 3098 break; 3099 3100 case eLazyBoolYes: 3101 if (!m_gdb_comm.DeallocateMemory (addr)) 3102 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 3103 break; 3104 3105 case eLazyBoolNo: 3106 // Call munmap() to deallocate memory in the inferior.. 3107 { 3108 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 3109 if (pos != m_addr_to_mmap_size.end() && 3110 InferiorCallMunmap(this, addr, pos->second)) 3111 m_addr_to_mmap_size.erase (pos); 3112 else 3113 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 3114 } 3115 break; 3116 } 3117 3118 return error; 3119 } 3120 3121 3122 //------------------------------------------------------------------ 3123 // Process STDIO 3124 //------------------------------------------------------------------ 3125 size_t 3126 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 3127 { 3128 if (m_stdio_communication.IsConnected()) 3129 { 3130 ConnectionStatus status; 3131 m_stdio_communication.Write(src, src_len, status, NULL); 3132 } 3133 else if (m_stdin_forward) 3134 { 3135 m_gdb_comm.SendStdinNotification(src, src_len); 3136 } 3137 return 0; 3138 } 3139 3140 Error 3141 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site) 3142 { 3143 Error error; 3144 assert(bp_site != NULL); 3145 3146 // Get logging info 3147 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3148 user_id_t site_id = bp_site->GetID(); 3149 3150 // Get the breakpoint address 3151 const addr_t addr = bp_site->GetLoadAddress(); 3152 3153 // Log that a breakpoint was requested 3154 if (log) 3155 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr); 3156 3157 // Breakpoint already exists and is enabled 3158 if (bp_site->IsEnabled()) 3159 { 3160 if (log) 3161 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 3162 return error; 3163 } 3164 3165 // Get the software breakpoint trap opcode size 3166 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 3167 3168 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type 3169 // is supported by the remote stub. These are set to true by default, and later set to false 3170 // only after we receive an unimplemented response when sending a breakpoint packet. This means 3171 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will 3172 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which 3173 // indicates if the user specifically asked for hardware breakpoints. If true then we will 3174 // skip over software breakpoints. 3175 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired())) 3176 { 3177 // Try to send off a software breakpoint packet ($Z0) 3178 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 3179 { 3180 // The breakpoint was placed successfully 3181 bp_site->SetEnabled(true); 3182 bp_site->SetType(BreakpointSite::eExternal); 3183 return error; 3184 } 3185 3186 // SendGDBStoppointTypePacket() will return an error if it was unable to set this 3187 // breakpoint. We need to differentiate between a error specific to placing this breakpoint 3188 // or if we have learned that this breakpoint type is unsupported. To do this, we 3189 // must test the support boolean for this breakpoint type to see if it now indicates that 3190 // this breakpoint type is unsupported. If they are still supported then we should return 3191 // with the error code. If they are now unsupported, then we would like to fall through 3192 // and try another form of breakpoint. 3193 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 3194 return error; 3195 3196 // We reach here when software breakpoints have been found to be unsupported. For future 3197 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is 3198 // known not to be supported. 3199 if (log) 3200 log->Printf("Software breakpoints are unsupported"); 3201 3202 // So we will fall through and try a hardware breakpoint 3203 } 3204 3205 // The process of setting a hardware breakpoint is much the same as above. We check the 3206 // supported boolean for this breakpoint type, and if it is thought to be supported then we 3207 // will try to set this breakpoint with a hardware breakpoint. 3208 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) 3209 { 3210 // Try to send off a hardware breakpoint packet ($Z1) 3211 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 3212 { 3213 // The breakpoint was placed successfully 3214 bp_site->SetEnabled(true); 3215 bp_site->SetType(BreakpointSite::eHardware); 3216 return error; 3217 } 3218 3219 // Check if the error was something other then an unsupported breakpoint type 3220 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) 3221 { 3222 // Unable to set this hardware breakpoint 3223 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)"); 3224 return error; 3225 } 3226 3227 // We will reach here when the stub gives an unsupported response to a hardware breakpoint 3228 if (log) 3229 log->Printf("Hardware breakpoints are unsupported"); 3230 3231 // Finally we will falling through to a #trap style breakpoint 3232 } 3233 3234 // Don't fall through when hardware breakpoints were specifically requested 3235 if (bp_site->HardwareRequired()) 3236 { 3237 error.SetErrorString("hardware breakpoints are not supported"); 3238 return error; 3239 } 3240 3241 // As a last resort we want to place a manual breakpoint. An instruction 3242 // is placed into the process memory using memory write packets. 3243 return EnableSoftwareBreakpoint(bp_site); 3244 } 3245 3246 Error 3247 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site) 3248 { 3249 Error error; 3250 assert (bp_site != NULL); 3251 addr_t addr = bp_site->GetLoadAddress(); 3252 user_id_t site_id = bp_site->GetID(); 3253 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 3254 if (log) 3255 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr); 3256 3257 if (bp_site->IsEnabled()) 3258 { 3259 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 3260 3261 BreakpointSite::Type bp_type = bp_site->GetType(); 3262 switch (bp_type) 3263 { 3264 case BreakpointSite::eSoftware: 3265 error = DisableSoftwareBreakpoint (bp_site); 3266 break; 3267 3268 case BreakpointSite::eHardware: 3269 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size)) 3270 error.SetErrorToGenericError(); 3271 break; 3272 3273 case BreakpointSite::eExternal: 3274 { 3275 GDBStoppointType stoppoint_type; 3276 if (bp_site->IsHardware()) 3277 stoppoint_type = eBreakpointHardware; 3278 else 3279 stoppoint_type = eBreakpointSoftware; 3280 3281 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size)) 3282 error.SetErrorToGenericError(); 3283 } 3284 break; 3285 } 3286 if (error.Success()) 3287 bp_site->SetEnabled(false); 3288 } 3289 else 3290 { 3291 if (log) 3292 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 3293 return error; 3294 } 3295 3296 if (error.Success()) 3297 error.SetErrorToGenericError(); 3298 return error; 3299 } 3300 3301 // Pre-requisite: wp != NULL. 3302 static GDBStoppointType 3303 GetGDBStoppointType (Watchpoint *wp) 3304 { 3305 assert(wp); 3306 bool watch_read = wp->WatchpointRead(); 3307 bool watch_write = wp->WatchpointWrite(); 3308 3309 // watch_read and watch_write cannot both be false. 3310 assert(watch_read || watch_write); 3311 if (watch_read && watch_write) 3312 return eWatchpointReadWrite; 3313 else if (watch_read) 3314 return eWatchpointRead; 3315 else // Must be watch_write, then. 3316 return eWatchpointWrite; 3317 } 3318 3319 Error 3320 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify) 3321 { 3322 Error error; 3323 if (wp) 3324 { 3325 user_id_t watchID = wp->GetID(); 3326 addr_t addr = wp->GetLoadAddress(); 3327 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3328 if (log) 3329 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID); 3330 if (wp->IsEnabled()) 3331 { 3332 if (log) 3333 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr); 3334 return error; 3335 } 3336 3337 GDBStoppointType type = GetGDBStoppointType(wp); 3338 // Pass down an appropriate z/Z packet... 3339 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 3340 { 3341 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 3342 { 3343 wp->SetEnabled(true, notify); 3344 return error; 3345 } 3346 else 3347 error.SetErrorString("sending gdb watchpoint packet failed"); 3348 } 3349 else 3350 error.SetErrorString("watchpoints not supported"); 3351 } 3352 else 3353 { 3354 error.SetErrorString("Watchpoint argument was NULL."); 3355 } 3356 if (error.Success()) 3357 error.SetErrorToGenericError(); 3358 return error; 3359 } 3360 3361 Error 3362 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify) 3363 { 3364 Error error; 3365 if (wp) 3366 { 3367 user_id_t watchID = wp->GetID(); 3368 3369 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 3370 3371 addr_t addr = wp->GetLoadAddress(); 3372 3373 if (log) 3374 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr); 3375 3376 if (!wp->IsEnabled()) 3377 { 3378 if (log) 3379 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 3380 // See also 'class WatchpointSentry' within StopInfo.cpp. 3381 // This disabling attempt might come from the user-supplied actions, we'll route it in order for 3382 // the watchpoint object to intelligently process this action. 3383 wp->SetEnabled(false, notify); 3384 return error; 3385 } 3386 3387 if (wp->IsHardware()) 3388 { 3389 GDBStoppointType type = GetGDBStoppointType(wp); 3390 // Pass down an appropriate z/Z packet... 3391 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 3392 { 3393 wp->SetEnabled(false, notify); 3394 return error; 3395 } 3396 else 3397 error.SetErrorString("sending gdb watchpoint packet failed"); 3398 } 3399 // TODO: clear software watchpoints if we implement them 3400 } 3401 else 3402 { 3403 error.SetErrorString("Watchpoint argument was NULL."); 3404 } 3405 if (error.Success()) 3406 error.SetErrorToGenericError(); 3407 return error; 3408 } 3409 3410 void 3411 ProcessGDBRemote::Clear() 3412 { 3413 m_flags = 0; 3414 m_thread_list_real.Clear(); 3415 m_thread_list.Clear(); 3416 } 3417 3418 Error 3419 ProcessGDBRemote::DoSignal (int signo) 3420 { 3421 Error error; 3422 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3423 if (log) 3424 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 3425 3426 if (!m_gdb_comm.SendAsyncSignal (signo)) 3427 error.SetErrorStringWithFormat("failed to send signal %i", signo); 3428 return error; 3429 } 3430 3431 Error 3432 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info) 3433 { 3434 Error error; 3435 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 3436 { 3437 // If we locate debugserver, keep that located version around 3438 static FileSpec g_debugserver_file_spec; 3439 3440 ProcessLaunchInfo debugserver_launch_info; 3441 // Make debugserver run in its own session so signals generated by 3442 // special terminal key sequences (^C) don't affect debugserver. 3443 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); 3444 3445 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false); 3446 debugserver_launch_info.SetUserID(process_info.GetUserID()); 3447 3448 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__)) 3449 // On iOS, still do a local connection using a random port 3450 const char *hostname = "127.0.0.1"; 3451 uint16_t port = get_random_port (); 3452 #else 3453 // Set hostname being NULL to do the reverse connect where debugserver 3454 // will bind to port zero and it will communicate back to us the port 3455 // that we will connect to 3456 const char *hostname = NULL; 3457 uint16_t port = 0; 3458 #endif 3459 3460 error = m_gdb_comm.StartDebugserverProcess (hostname, 3461 port, 3462 debugserver_launch_info, 3463 port); 3464 3465 if (error.Success ()) 3466 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 3467 else 3468 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3469 3470 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 3471 StartAsyncThread (); 3472 3473 if (error.Fail()) 3474 { 3475 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 3476 3477 if (log) 3478 log->Printf("failed to start debugserver process: %s", error.AsCString()); 3479 return error; 3480 } 3481 3482 if (m_gdb_comm.IsConnected()) 3483 { 3484 // Finish the connection process by doing the handshake without connecting (send NULL URL) 3485 ConnectToDebugserver (NULL); 3486 } 3487 else 3488 { 3489 StreamString connect_url; 3490 connect_url.Printf("connect://%s:%u", hostname, port); 3491 error = ConnectToDebugserver (connect_url.GetString().c_str()); 3492 } 3493 3494 } 3495 return error; 3496 } 3497 3498 bool 3499 ProcessGDBRemote::MonitorDebugserverProcess 3500 ( 3501 void *callback_baton, 3502 lldb::pid_t debugserver_pid, 3503 bool exited, // True if the process did exit 3504 int signo, // Zero for no signal 3505 int exit_status // Exit value of process if signal is zero 3506 ) 3507 { 3508 // The baton is a "ProcessGDBRemote *". Now this class might be gone 3509 // and might not exist anymore, so we need to carefully try to get the 3510 // target for this process first since we have a race condition when 3511 // we are done running between getting the notice that the inferior 3512 // process has died and the debugserver that was debugging this process. 3513 // In our test suite, we are also continually running process after 3514 // process, so we must be very careful to make sure: 3515 // 1 - process object hasn't been deleted already 3516 // 2 - that a new process object hasn't been recreated in its place 3517 3518 // "debugserver_pid" argument passed in is the process ID for 3519 // debugserver that we are tracking... 3520 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3521 3522 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 3523 3524 // Get a shared pointer to the target that has a matching process pointer. 3525 // This target could be gone, or the target could already have a new process 3526 // object inside of it 3527 TargetSP target_sp (Debugger::FindTargetWithProcess(process)); 3528 3529 if (log) 3530 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 3531 3532 if (target_sp) 3533 { 3534 // We found a process in a target that matches, but another thread 3535 // might be in the process of launching a new process that will 3536 // soon replace it, so get a shared pointer to the process so we 3537 // can keep it alive. 3538 ProcessSP process_sp (target_sp->GetProcessSP()); 3539 // Now we have a shared pointer to the process that can't go away on us 3540 // so we now make sure it was the same as the one passed in, and also make 3541 // sure that our previous "process *" didn't get deleted and have a new 3542 // "process *" created in its place with the same pointer. To verify this 3543 // we make sure the process has our debugserver process ID. If we pass all 3544 // of these tests, then we are sure that this process is the one we were 3545 // looking for. 3546 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid) 3547 { 3548 // Sleep for a half a second to make sure our inferior process has 3549 // time to set its exit status before we set it incorrectly when 3550 // both the debugserver and the inferior process shut down. 3551 usleep (500000); 3552 // If our process hasn't yet exited, debugserver might have died. 3553 // If the process did exit, the we are reaping it. 3554 const StateType state = process->GetState(); 3555 3556 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 3557 state != eStateInvalid && 3558 state != eStateUnloaded && 3559 state != eStateExited && 3560 state != eStateDetached) 3561 { 3562 char error_str[1024]; 3563 if (signo) 3564 { 3565 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo); 3566 if (signal_cstr) 3567 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 3568 else 3569 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 3570 } 3571 else 3572 { 3573 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 3574 } 3575 3576 process->SetExitStatus (-1, error_str); 3577 } 3578 // Debugserver has exited we need to let our ProcessGDBRemote 3579 // know that it no longer has a debugserver instance 3580 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3581 } 3582 } 3583 return true; 3584 } 3585 3586 void 3587 ProcessGDBRemote::KillDebugserverProcess () 3588 { 3589 m_gdb_comm.Disconnect(); 3590 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 3591 { 3592 Host::Kill (m_debugserver_pid, SIGINT); 3593 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 3594 } 3595 } 3596 3597 void 3598 ProcessGDBRemote::Initialize() 3599 { 3600 static std::once_flag g_once_flag; 3601 3602 std::call_once(g_once_flag, []() 3603 { 3604 PluginManager::RegisterPlugin (GetPluginNameStatic(), 3605 GetPluginDescriptionStatic(), 3606 CreateInstance, 3607 DebuggerInitialize); 3608 }); 3609 } 3610 3611 void 3612 ProcessGDBRemote::DebuggerInitialize (Debugger &debugger) 3613 { 3614 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName())) 3615 { 3616 const bool is_global_setting = true; 3617 PluginManager::CreateSettingForProcessPlugin (debugger, 3618 GetGlobalPluginProperties()->GetValueProperties(), 3619 ConstString ("Properties for the gdb-remote process plug-in."), 3620 is_global_setting); 3621 } 3622 } 3623 3624 bool 3625 ProcessGDBRemote::StartAsyncThread () 3626 { 3627 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3628 3629 if (log) 3630 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 3631 3632 Mutex::Locker start_locker(m_async_thread_state_mutex); 3633 if (!m_async_thread.IsJoinable()) 3634 { 3635 // Create a thread that watches our internal state and controls which 3636 // events make it to clients (into the DCProcess event queue). 3637 3638 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 3639 } 3640 else if (log) 3641 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__); 3642 3643 return m_async_thread.IsJoinable(); 3644 } 3645 3646 void 3647 ProcessGDBRemote::StopAsyncThread () 3648 { 3649 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 3650 3651 if (log) 3652 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 3653 3654 Mutex::Locker start_locker(m_async_thread_state_mutex); 3655 if (m_async_thread.IsJoinable()) 3656 { 3657 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 3658 3659 // This will shut down the async thread. 3660 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 3661 3662 // Stop the stdio thread 3663 m_async_thread.Join(nullptr); 3664 m_async_thread.Reset(); 3665 } 3666 else if (log) 3667 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__); 3668 } 3669 3670 bool 3671 ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet) 3672 { 3673 // get the packet at a string 3674 const std::string &pkt = packet.GetStringRef(); 3675 // skip %stop: 3676 StringExtractorGDBRemote stop_info(pkt.c_str() + 5); 3677 3678 // pass as a thread stop info packet 3679 SetLastStopPacket(stop_info); 3680 3681 // check for more stop reasons 3682 HandleStopReplySequence(); 3683 3684 // if the process is stopped then we need to fake a resume 3685 // so that we can stop properly with the new break. This 3686 // is possible due to SetPrivateState() broadcasting the 3687 // state change as a side effect. 3688 if (GetPrivateState() == lldb::StateType::eStateStopped) 3689 { 3690 SetPrivateState(lldb::StateType::eStateRunning); 3691 } 3692 3693 // since we have some stopped packets we can halt the process 3694 SetPrivateState(lldb::StateType::eStateStopped); 3695 3696 return true; 3697 } 3698 3699 thread_result_t 3700 ProcessGDBRemote::AsyncThread (void *arg) 3701 { 3702 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 3703 3704 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 3705 if (log) 3706 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID()); 3707 3708 Listener listener ("ProcessGDBRemote::AsyncThread"); 3709 EventSP event_sp; 3710 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 3711 eBroadcastBitAsyncThreadShouldExit; 3712 3713 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 3714 { 3715 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit | 3716 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify); 3717 3718 bool done = false; 3719 while (!done) 3720 { 3721 if (log) 3722 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 3723 if (listener.WaitForEvent (NULL, event_sp)) 3724 { 3725 const uint32_t event_type = event_sp->GetType(); 3726 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 3727 { 3728 if (log) 3729 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 3730 3731 switch (event_type) 3732 { 3733 case eBroadcastBitAsyncContinue: 3734 { 3735 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 3736 3737 if (continue_packet) 3738 { 3739 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 3740 const size_t continue_cstr_len = continue_packet->GetByteSize (); 3741 if (log) 3742 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 3743 3744 if (::strstr (continue_cstr, "vAttach") == NULL) 3745 process->SetPrivateState(eStateRunning); 3746 StringExtractorGDBRemote response; 3747 3748 // If in Non-Stop-Mode 3749 if (process->GetTarget().GetNonStopModeEnabled()) 3750 { 3751 // send the vCont packet 3752 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response)) 3753 { 3754 // Something went wrong 3755 done = true; 3756 break; 3757 } 3758 } 3759 // If in All-Stop-Mode 3760 else 3761 { 3762 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 3763 3764 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads. 3765 // The thread ID list might be contained within the "response", or the stop reply packet that 3766 // caused the stop. So clear it now before we give the stop reply packet to the process 3767 // using the process->SetLastStopPacket()... 3768 process->ClearThreadIDList (); 3769 3770 switch (stop_state) 3771 { 3772 case eStateStopped: 3773 case eStateCrashed: 3774 case eStateSuspended: 3775 process->SetLastStopPacket (response); 3776 process->SetPrivateState (stop_state); 3777 break; 3778 3779 case eStateExited: 3780 { 3781 process->SetLastStopPacket (response); 3782 process->ClearThreadIDList(); 3783 response.SetFilePos(1); 3784 3785 int exit_status = response.GetHexU8(); 3786 const char *desc_cstr = NULL; 3787 StringExtractor extractor; 3788 std::string desc_string; 3789 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') 3790 { 3791 std::string desc_token; 3792 while (response.GetNameColonValue (desc_token, desc_string)) 3793 { 3794 if (desc_token == "description") 3795 { 3796 extractor.GetStringRef().swap(desc_string); 3797 extractor.SetFilePos(0); 3798 extractor.GetHexByteString (desc_string); 3799 desc_cstr = desc_string.c_str(); 3800 } 3801 } 3802 } 3803 process->SetExitStatus(exit_status, desc_cstr); 3804 done = true; 3805 break; 3806 } 3807 case eStateInvalid: 3808 process->SetExitStatus(-1, "lost connection"); 3809 break; 3810 3811 default: 3812 process->SetPrivateState (stop_state); 3813 break; 3814 } // switch(stop_state) 3815 } // else // if in All-stop-mode 3816 } // if (continue_packet) 3817 } // case eBroadcastBitAysncContinue 3818 break; 3819 3820 case eBroadcastBitAsyncThreadShouldExit: 3821 if (log) 3822 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 3823 done = true; 3824 break; 3825 3826 default: 3827 if (log) 3828 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 3829 done = true; 3830 break; 3831 } 3832 } 3833 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 3834 { 3835 switch (event_type) 3836 { 3837 case Communication::eBroadcastBitReadThreadDidExit: 3838 process->SetExitStatus (-1, "lost connection"); 3839 done = true; 3840 break; 3841 3842 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: 3843 { 3844 lldb_private::Event *event = event_sp.get(); 3845 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event); 3846 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes()); 3847 // Hand this over to the process to handle 3848 process->HandleNotifyPacket(notify); 3849 break; 3850 } 3851 3852 default: 3853 if (log) 3854 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 3855 done = true; 3856 break; 3857 } 3858 } 3859 } 3860 else 3861 { 3862 if (log) 3863 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 3864 done = true; 3865 } 3866 } 3867 } 3868 3869 if (log) 3870 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID()); 3871 3872 return NULL; 3873 } 3874 3875 //uint32_t 3876 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 3877 //{ 3878 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 3879 // // process and ask it for the list of processes. But if we are local, we can let the Host do it. 3880 // if (m_local_debugserver) 3881 // { 3882 // return Host::ListProcessesMatchingName (name, matches, pids); 3883 // } 3884 // else 3885 // { 3886 // // FIXME: Implement talking to the remote debugserver. 3887 // return 0; 3888 // } 3889 // 3890 //} 3891 // 3892 bool 3893 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 3894 StoppointCallbackContext *context, 3895 lldb::user_id_t break_id, 3896 lldb::user_id_t break_loc_id) 3897 { 3898 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 3899 // run so I can stop it if that's what I want to do. 3900 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3901 if (log) 3902 log->Printf("Hit New Thread Notification breakpoint."); 3903 return false; 3904 } 3905 3906 3907 bool 3908 ProcessGDBRemote::StartNoticingNewThreads() 3909 { 3910 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3911 if (m_thread_create_bp_sp) 3912 { 3913 if (log && log->GetVerbose()) 3914 log->Printf("Enabled noticing new thread breakpoint."); 3915 m_thread_create_bp_sp->SetEnabled(true); 3916 } 3917 else 3918 { 3919 PlatformSP platform_sp (m_target.GetPlatform()); 3920 if (platform_sp) 3921 { 3922 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target); 3923 if (m_thread_create_bp_sp) 3924 { 3925 if (log && log->GetVerbose()) 3926 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); 3927 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3928 } 3929 else 3930 { 3931 if (log) 3932 log->Printf("Failed to create new thread notification breakpoint."); 3933 } 3934 } 3935 } 3936 return m_thread_create_bp_sp.get() != NULL; 3937 } 3938 3939 bool 3940 ProcessGDBRemote::StopNoticingNewThreads() 3941 { 3942 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3943 if (log && log->GetVerbose()) 3944 log->Printf ("Disabling new thread notification breakpoint."); 3945 3946 if (m_thread_create_bp_sp) 3947 m_thread_create_bp_sp->SetEnabled(false); 3948 3949 return true; 3950 } 3951 3952 DynamicLoader * 3953 ProcessGDBRemote::GetDynamicLoader () 3954 { 3955 if (m_dyld_ap.get() == NULL) 3956 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 3957 return m_dyld_ap.get(); 3958 } 3959 3960 Error 3961 ProcessGDBRemote::SendEventData(const char *data) 3962 { 3963 int return_value; 3964 bool was_supported; 3965 3966 Error error; 3967 3968 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported); 3969 if (return_value != 0) 3970 { 3971 if (!was_supported) 3972 error.SetErrorString("Sending events is not supported for this process."); 3973 else 3974 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value); 3975 } 3976 return error; 3977 } 3978 3979 const DataBufferSP 3980 ProcessGDBRemote::GetAuxvData() 3981 { 3982 DataBufferSP buf; 3983 if (m_gdb_comm.GetQXferAuxvReadSupported()) 3984 { 3985 std::string response_string; 3986 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success) 3987 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length())); 3988 } 3989 return buf; 3990 } 3991 3992 StructuredData::ObjectSP 3993 ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid) 3994 { 3995 StructuredData::ObjectSP object_sp; 3996 3997 if (m_gdb_comm.GetThreadExtendedInfoSupported()) 3998 { 3999 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4000 SystemRuntime *runtime = GetSystemRuntime(); 4001 if (runtime) 4002 { 4003 runtime->AddThreadExtendedInfoPacketHints (args_dict); 4004 } 4005 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid); 4006 4007 StreamString packet; 4008 packet << "jThreadExtendedInfo:"; 4009 args_dict->Dump (packet); 4010 4011 // FIXME the final character of a JSON dictionary, '}', is the escape 4012 // character in gdb-remote binary mode. lldb currently doesn't escape 4013 // these characters in its packet output -- so we add the quoted version 4014 // of the } character here manually in case we talk to a debugserver which 4015 // un-escapes the characters at packet read time. 4016 packet << (char) (0x7d ^ 0x20); 4017 4018 StringExtractorGDBRemote response; 4019 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success) 4020 { 4021 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); 4022 if (response_type == StringExtractorGDBRemote::eResponse) 4023 { 4024 if (!response.Empty()) 4025 { 4026 object_sp = StructuredData::ParseJSON (response.GetStringRef()); 4027 } 4028 } 4029 } 4030 } 4031 return object_sp; 4032 } 4033 4034 StructuredData::ObjectSP 4035 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count) 4036 { 4037 StructuredData::ObjectSP object_sp; 4038 4039 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) 4040 { 4041 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 4042 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address); 4043 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count); 4044 4045 StreamString packet; 4046 packet << "jGetLoadedDynamicLibrariesInfos:"; 4047 args_dict->Dump (packet); 4048 4049 // FIXME the final character of a JSON dictionary, '}', is the escape 4050 // character in gdb-remote binary mode. lldb currently doesn't escape 4051 // these characters in its packet output -- so we add the quoted version 4052 // of the } character here manually in case we talk to a debugserver which 4053 // un-escapes the characters at packet read time. 4054 packet << (char) (0x7d ^ 0x20); 4055 4056 StringExtractorGDBRemote response; 4057 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success) 4058 { 4059 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); 4060 if (response_type == StringExtractorGDBRemote::eResponse) 4061 { 4062 if (!response.Empty()) 4063 { 4064 // The packet has already had the 0x7d xor quoting stripped out at the 4065 // GDBRemoteCommunication packet receive level. 4066 object_sp = StructuredData::ParseJSON (response.GetStringRef()); 4067 } 4068 } 4069 } 4070 } 4071 return object_sp; 4072 } 4073 4074 4075 // Establish the largest memory read/write payloads we should use. 4076 // If the remote stub has a max packet size, stay under that size. 4077 // 4078 // If the remote stub's max packet size is crazy large, use a 4079 // reasonable largeish default. 4080 // 4081 // If the remote stub doesn't advertise a max packet size, use a 4082 // conservative default. 4083 4084 void 4085 ProcessGDBRemote::GetMaxMemorySize() 4086 { 4087 const uint64_t reasonable_largeish_default = 128 * 1024; 4088 const uint64_t conservative_default = 512; 4089 4090 if (m_max_memory_size == 0) 4091 { 4092 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 4093 if (stub_max_size != UINT64_MAX && stub_max_size != 0) 4094 { 4095 // Save the stub's claimed maximum packet size 4096 m_remote_stub_max_memory_size = stub_max_size; 4097 4098 // Even if the stub says it can support ginormous packets, 4099 // don't exceed our reasonable largeish default packet size. 4100 if (stub_max_size > reasonable_largeish_default) 4101 { 4102 stub_max_size = reasonable_largeish_default; 4103 } 4104 4105 m_max_memory_size = stub_max_size; 4106 } 4107 else 4108 { 4109 m_max_memory_size = conservative_default; 4110 } 4111 } 4112 } 4113 4114 void 4115 ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max) 4116 { 4117 if (user_specified_max != 0) 4118 { 4119 GetMaxMemorySize (); 4120 4121 if (m_remote_stub_max_memory_size != 0) 4122 { 4123 if (m_remote_stub_max_memory_size < user_specified_max) 4124 { 4125 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big 4126 // as the remote stub says we can go. 4127 } 4128 else 4129 { 4130 m_max_memory_size = user_specified_max; // user's packet size is good 4131 } 4132 } 4133 else 4134 { 4135 m_max_memory_size = user_specified_max; // user's packet size is probably fine 4136 } 4137 } 4138 } 4139 4140 bool 4141 ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec, 4142 const ArchSpec& arch, 4143 ModuleSpec &module_spec) 4144 { 4145 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM); 4146 4147 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec)) 4148 { 4149 if (log) 4150 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s", 4151 __FUNCTION__, module_file_spec.GetPath ().c_str (), 4152 arch.GetTriple ().getTriple ().c_str ()); 4153 return false; 4154 } 4155 4156 if (log) 4157 { 4158 StreamString stream; 4159 module_spec.Dump (stream); 4160 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s", 4161 __FUNCTION__, module_file_spec.GetPath ().c_str (), 4162 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ()); 4163 } 4164 4165 return true; 4166 } 4167 4168 namespace { 4169 4170 typedef std::vector<std::string> stringVec; 4171 4172 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec; 4173 struct RegisterSetInfo 4174 { 4175 ConstString name; 4176 }; 4177 4178 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap; 4179 4180 struct GdbServerTargetInfo 4181 { 4182 std::string arch; 4183 std::string osabi; 4184 stringVec includes; 4185 RegisterSetMap reg_set_map; 4186 XMLNode feature_node; 4187 }; 4188 4189 bool 4190 ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info) 4191 { 4192 if (!feature_node) 4193 return false; 4194 4195 uint32_t prev_reg_num = 0; 4196 uint32_t reg_offset = 0; 4197 4198 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &prev_reg_num, ®_offset](const XMLNode ®_node) -> bool { 4199 std::string gdb_group; 4200 std::string gdb_type; 4201 ConstString reg_name; 4202 ConstString alt_name; 4203 ConstString set_name; 4204 std::vector<uint32_t> value_regs; 4205 std::vector<uint32_t> invalidate_regs; 4206 bool encoding_set = false; 4207 bool format_set = false; 4208 RegisterInfo reg_info = { NULL, // Name 4209 NULL, // Alt name 4210 0, // byte size 4211 reg_offset, // offset 4212 eEncodingUint, // encoding 4213 eFormatHex, // formate 4214 { 4215 LLDB_INVALID_REGNUM, // GCC reg num 4216 LLDB_INVALID_REGNUM, // DWARF reg num 4217 LLDB_INVALID_REGNUM, // generic reg num 4218 prev_reg_num, // GDB reg num 4219 prev_reg_num // native register number 4220 }, 4221 NULL, 4222 NULL 4223 }; 4224 4225 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 { 4226 if (name == "name") 4227 { 4228 reg_name.SetString(value); 4229 } 4230 else if (name == "bitsize") 4231 { 4232 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT; 4233 } 4234 else if (name == "type") 4235 { 4236 gdb_type = value.str(); 4237 } 4238 else if (name == "group") 4239 { 4240 gdb_group = value.str(); 4241 } 4242 else if (name == "regnum") 4243 { 4244 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4245 if (regnum != LLDB_INVALID_REGNUM) 4246 { 4247 reg_info.kinds[eRegisterKindGDB] = regnum; 4248 reg_info.kinds[eRegisterKindLLDB] = regnum; 4249 prev_reg_num = regnum; 4250 } 4251 } 4252 else if (name == "offset") 4253 { 4254 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4255 } 4256 else if (name == "altname") 4257 { 4258 alt_name.SetString(value); 4259 } 4260 else if (name == "encoding") 4261 { 4262 encoding_set = true; 4263 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint); 4264 } 4265 else if (name == "format") 4266 { 4267 format_set = true; 4268 Format format = eFormatInvalid; 4269 if (Args::StringToFormat (value.data(), format, NULL).Success()) 4270 reg_info.format = format; 4271 else if (value == "vector-sint8") 4272 reg_info.format = eFormatVectorOfSInt8; 4273 else if (value == "vector-uint8") 4274 reg_info.format = eFormatVectorOfUInt8; 4275 else if (value == "vector-sint16") 4276 reg_info.format = eFormatVectorOfSInt16; 4277 else if (value == "vector-uint16") 4278 reg_info.format = eFormatVectorOfUInt16; 4279 else if (value == "vector-sint32") 4280 reg_info.format = eFormatVectorOfSInt32; 4281 else if (value == "vector-uint32") 4282 reg_info.format = eFormatVectorOfUInt32; 4283 else if (value == "vector-float32") 4284 reg_info.format = eFormatVectorOfFloat32; 4285 else if (value == "vector-uint128") 4286 reg_info.format = eFormatVectorOfUInt128; 4287 } 4288 else if (name == "group_id") 4289 { 4290 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4291 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id); 4292 if (pos != target_info.reg_set_map.end()) 4293 set_name = pos->second.name; 4294 } 4295 else if (name == "gcc_regnum") 4296 { 4297 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4298 } 4299 else if (name == "dwarf_regnum") 4300 { 4301 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); 4302 } 4303 else if (name == "generic") 4304 { 4305 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data()); 4306 } 4307 else if (name == "value_regnums") 4308 { 4309 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0); 4310 } 4311 else if (name == "invalidate_regnums") 4312 { 4313 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0); 4314 } 4315 else 4316 { 4317 printf("unhandled attribute %s = %s\n", name.data(), value.data()); 4318 } 4319 return true; // Keep iterating through all attributes 4320 }); 4321 4322 if (!gdb_type.empty() && !(encoding_set || format_set)) 4323 { 4324 if (gdb_type.find("int") == 0) 4325 { 4326 reg_info.format = eFormatHex; 4327 reg_info.encoding = eEncodingUint; 4328 } 4329 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") 4330 { 4331 reg_info.format = eFormatAddressInfo; 4332 reg_info.encoding = eEncodingUint; 4333 } 4334 else if (gdb_type == "i387_ext" || gdb_type == "float") 4335 { 4336 reg_info.format = eFormatFloat; 4337 reg_info.encoding = eEncodingIEEE754; 4338 } 4339 } 4340 4341 // Only update the register set name if we didn't get a "reg_set" attribute. 4342 // "set_name" will be empty if we didn't have a "reg_set" attribute. 4343 if (!set_name && !gdb_group.empty()) 4344 set_name.SetCString(gdb_group.c_str()); 4345 4346 reg_info.byte_offset = reg_offset; 4347 assert (reg_info.byte_size != 0); 4348 reg_offset += reg_info.byte_size; 4349 if (!value_regs.empty()) 4350 { 4351 value_regs.push_back(LLDB_INVALID_REGNUM); 4352 reg_info.value_regs = value_regs.data(); 4353 } 4354 if (!invalidate_regs.empty()) 4355 { 4356 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 4357 reg_info.invalidate_regs = invalidate_regs.data(); 4358 } 4359 4360 ++prev_reg_num; 4361 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name); 4362 4363 return true; // Keep iterating through all "reg" elements 4364 }); 4365 return true; 4366 } 4367 4368 } // namespace {} 4369 4370 4371 // query the target of gdb-remote for extended target information 4372 // return: 'true' on success 4373 // 'false' on failure 4374 bool 4375 ProcessGDBRemote::GetGDBServerRegisterInfo () 4376 { 4377 // Make sure LLDB has an XML parser it can use first 4378 if (!XMLDocument::XMLEnabled()) 4379 return false; 4380 4381 // redirect libxml2's error handler since the default prints to stdout 4382 4383 GDBRemoteCommunicationClient & comm = m_gdb_comm; 4384 4385 // check that we have extended feature read support 4386 if ( !comm.GetQXferFeaturesReadSupported( ) ) 4387 return false; 4388 4389 // request the target xml file 4390 std::string raw; 4391 lldb_private::Error lldberr; 4392 if (!comm.ReadExtFeature(ConstString("features"), 4393 ConstString("target.xml"), 4394 raw, 4395 lldberr)) 4396 { 4397 return false; 4398 } 4399 4400 4401 XMLDocument xml_document; 4402 4403 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml")) 4404 { 4405 GdbServerTargetInfo target_info; 4406 4407 XMLNode target_node = xml_document.GetRootElement("target"); 4408 if (target_node) 4409 { 4410 XMLNode feature_node; 4411 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool 4412 { 4413 llvm::StringRef name = node.GetName(); 4414 if (name == "architecture") 4415 { 4416 node.GetElementText(target_info.arch); 4417 } 4418 else if (name == "osabi") 4419 { 4420 node.GetElementText(target_info.osabi); 4421 } 4422 else if (name == "xi:include" || name == "include") 4423 { 4424 llvm::StringRef href = node.GetAttributeValue("href"); 4425 if (!href.empty()) 4426 target_info.includes.push_back(href.str()); 4427 } 4428 else if (name == "feature") 4429 { 4430 feature_node = node; 4431 } 4432 else if (name == "groups") 4433 { 4434 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool { 4435 uint32_t set_id = UINT32_MAX; 4436 RegisterSetInfo set_info; 4437 4438 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool { 4439 if (name == "id") 4440 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); 4441 if (name == "name") 4442 set_info.name = ConstString(value); 4443 return true; // Keep iterating through all attributes 4444 }); 4445 4446 if (set_id != UINT32_MAX) 4447 target_info.reg_set_map[set_id] = set_info; 4448 return true; // Keep iterating through all "group" elements 4449 }); 4450 } 4451 return true; // Keep iterating through all children of the target_node 4452 }); 4453 4454 if (feature_node) 4455 { 4456 ParseRegisters(feature_node, target_info, this->m_register_info); 4457 } 4458 4459 for (const auto &include : target_info.includes) 4460 { 4461 // request register file 4462 std::string xml_data; 4463 if (!comm.ReadExtFeature(ConstString("features"), 4464 ConstString(include), 4465 xml_data, 4466 lldberr)) 4467 continue; 4468 4469 XMLDocument include_xml_document; 4470 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str()); 4471 XMLNode include_feature_node = include_xml_document.GetRootElement("feature"); 4472 if (include_feature_node) 4473 { 4474 ParseRegisters(include_feature_node, target_info, this->m_register_info); 4475 } 4476 } 4477 this->m_register_info.Finalize(GetTarget().GetArchitecture()); 4478 } 4479 } 4480 4481 return m_register_info.GetNumRegisters() > 0; 4482 } 4483 4484 Error 4485 ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list) 4486 { 4487 // Make sure LLDB has an XML parser it can use first 4488 if (!XMLDocument::XMLEnabled()) 4489 return Error (0, ErrorType::eErrorTypeGeneric); 4490 4491 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS); 4492 if (log) 4493 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__); 4494 4495 GDBRemoteCommunicationClient & comm = m_gdb_comm; 4496 4497 // check that we have extended feature read support 4498 if (comm.GetQXferLibrariesSVR4ReadSupported ()) { 4499 list.clear (); 4500 4501 // request the loaded library list 4502 std::string raw; 4503 lldb_private::Error lldberr; 4504 4505 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr)) 4506 return Error (0, ErrorType::eErrorTypeGeneric); 4507 4508 // parse the xml file in memory 4509 if (log) 4510 log->Printf ("parsing: %s", raw.c_str()); 4511 XMLDocument doc; 4512 4513 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4514 return Error (0, ErrorType::eErrorTypeGeneric); 4515 4516 XMLNode root_element = doc.GetRootElement("library-list-svr4"); 4517 if (!root_element) 4518 return Error(); 4519 4520 // main link map structure 4521 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm"); 4522 if (!main_lm.empty()) 4523 { 4524 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0); 4525 } 4526 4527 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool { 4528 4529 GDBLoadedModuleInfoList::LoadedModuleInfo module; 4530 4531 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool { 4532 4533 if (name == "name") 4534 module.set_name (value.str()); 4535 else if (name == "lm") 4536 { 4537 // the address of the link_map struct. 4538 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0)); 4539 } 4540 else if (name == "l_addr") 4541 { 4542 // the displacement as read from the field 'l_addr' of the link_map struct. 4543 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0)); 4544 4545 } 4546 else if (name == "l_ld") 4547 { 4548 // the memory address of the libraries PT_DYAMIC section. 4549 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0)); 4550 } 4551 4552 return true; // Keep iterating over all properties of "library" 4553 }); 4554 4555 if (log) 4556 { 4557 std::string name; 4558 lldb::addr_t lm=0, base=0, ld=0; 4559 4560 module.get_name (name); 4561 module.get_link_map (lm); 4562 module.get_base (base); 4563 module.get_dynamic (ld); 4564 4565 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str()); 4566 } 4567 4568 list.add (module); 4569 return true; // Keep iterating over all "library" elements in the root node 4570 }); 4571 4572 if (log) 4573 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size()); 4574 } else if (comm.GetQXferLibrariesReadSupported ()) { 4575 list.clear (); 4576 4577 // request the loaded library list 4578 std::string raw; 4579 lldb_private::Error lldberr; 4580 4581 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr)) 4582 return Error (0, ErrorType::eErrorTypeGeneric); 4583 4584 if (log) 4585 log->Printf ("parsing: %s", raw.c_str()); 4586 XMLDocument doc; 4587 4588 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) 4589 return Error (0, ErrorType::eErrorTypeGeneric); 4590 4591 XMLNode root_element = doc.GetRootElement("library-list"); 4592 if (!root_element) 4593 return Error(); 4594 4595 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool { 4596 GDBLoadedModuleInfoList::LoadedModuleInfo module; 4597 4598 llvm::StringRef name = library.GetAttributeValue("name"); 4599 module.set_name(name.str()); 4600 4601 // The base address of a given library will be the address of its 4602 // first section. Most remotes send only one section for Windows 4603 // targets for example. 4604 const XMLNode §ion = library.FindFirstChildElementWithName("section"); 4605 llvm::StringRef address = section.GetAttributeValue("address"); 4606 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0)); 4607 4608 if (log) 4609 { 4610 std::string name; 4611 lldb::addr_t base = 0; 4612 module.get_name (name); 4613 module.get_base (base); 4614 4615 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str()); 4616 } 4617 4618 list.add (module); 4619 return true; // Keep iterating over all "library" elements in the root node 4620 }); 4621 4622 if (log) 4623 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size()); 4624 } else { 4625 return Error (0, ErrorType::eErrorTypeGeneric); 4626 } 4627 4628 return Error(); 4629 } 4630 4631 lldb::ModuleSP 4632 ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr) 4633 { 4634 Target &target = m_process->GetTarget(); 4635 ModuleList &modules = target.GetImages(); 4636 ModuleSP module_sp; 4637 4638 bool changed = false; 4639 4640 ModuleSpec module_spec (file, target.GetArchitecture()); 4641 if ((module_sp = modules.FindFirstModule (module_spec))) 4642 { 4643 module_sp->SetLoadAddress (target, base_addr, true, changed); 4644 } 4645 else if ((module_sp = target.GetSharedModule (module_spec))) 4646 { 4647 module_sp->SetLoadAddress (target, base_addr, true, changed); 4648 } 4649 4650 return module_sp; 4651 } 4652 4653 size_t 4654 ProcessGDBRemote::LoadModules () 4655 { 4656 using lldb_private::process_gdb_remote::ProcessGDBRemote; 4657 4658 // request a list of loaded libraries from GDBServer 4659 GDBLoadedModuleInfoList module_list; 4660 if (GetLoadedModuleList (module_list).Fail()) 4661 return 0; 4662 4663 // get a list of all the modules 4664 ModuleList new_modules; 4665 4666 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list) 4667 { 4668 std::string mod_name; 4669 lldb::addr_t mod_base; 4670 4671 bool valid = true; 4672 valid &= modInfo.get_name (mod_name); 4673 valid &= modInfo.get_base (mod_base); 4674 if (!valid) 4675 continue; 4676 4677 // hack (cleaner way to get file name only?) (win/unix compat?) 4678 size_t marker = mod_name.rfind ('/'); 4679 if (marker == std::string::npos) 4680 marker = 0; 4681 else 4682 marker += 1; 4683 4684 FileSpec file (mod_name.c_str()+marker, true); 4685 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base); 4686 4687 if (module_sp.get()) 4688 new_modules.Append (module_sp); 4689 } 4690 4691 if (new_modules.GetSize() > 0) 4692 { 4693 Target & target = m_target; 4694 4695 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool 4696 { 4697 lldb_private::ObjectFile * obj = module_sp->GetObjectFile (); 4698 if (!obj) 4699 return true; 4700 4701 if (obj->GetType () != ObjectFile::Type::eTypeExecutable) 4702 return true; 4703 4704 lldb::ModuleSP module_copy_sp = module_sp; 4705 target.SetExecutableModule (module_copy_sp, false); 4706 return false; 4707 }); 4708 4709 ModuleList &loaded_modules = m_process->GetTarget().GetImages(); 4710 loaded_modules.AppendIfNeeded (new_modules); 4711 m_process->GetTarget().ModulesDidLoad (new_modules); 4712 } 4713 4714 return new_modules.GetSize(); 4715 } 4716 4717 Error 4718 ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr) 4719 { 4720 is_loaded = false; 4721 load_addr = LLDB_INVALID_ADDRESS; 4722 4723 std::string file_path = file.GetPath(false); 4724 if (file_path.empty ()) 4725 return Error("Empty file name specified"); 4726 4727 StreamString packet; 4728 packet.PutCString("qFileLoadAddress:"); 4729 packet.PutCStringAsRawHex8(file_path.c_str()); 4730 4731 StringExtractorGDBRemote response; 4732 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success) 4733 return Error("Sending qFileLoadAddress packet failed"); 4734 4735 if (response.IsErrorResponse()) 4736 { 4737 if (response.GetError() == 1) 4738 { 4739 // The file is not loaded into the inferior 4740 is_loaded = false; 4741 load_addr = LLDB_INVALID_ADDRESS; 4742 return Error(); 4743 } 4744 4745 return Error("Fetching file load address from remote server returned an error"); 4746 } 4747 4748 if (response.IsNormalResponse()) 4749 { 4750 is_loaded = true; 4751 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); 4752 return Error(); 4753 } 4754 4755 return Error("Unknown error happened during sending the load address packet"); 4756 } 4757 4758 4759 void 4760 ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list) 4761 { 4762 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything 4763 Process::ModulesDidLoad (module_list); 4764 4765 // After loading shared libraries, we can ask our remote GDB server if 4766 // it needs any symbols. 4767 m_gdb_comm.ServeSymbolLookups(this); 4768 } 4769 4770 4771 class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed 4772 { 4773 public: 4774 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) : 4775 CommandObjectParsed (interpreter, 4776 "process plugin packet speed-test", 4777 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ", 4778 NULL), 4779 m_option_group (interpreter), 4780 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), 4781 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), 4782 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), 4783 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true) 4784 { 4785 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4786 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4787 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4788 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); 4789 m_option_group.Finalize(); 4790 } 4791 4792 ~CommandObjectProcessGDBRemoteSpeedTest () 4793 { 4794 } 4795 4796 4797 Options * 4798 GetOptions () override 4799 { 4800 return &m_option_group; 4801 } 4802 4803 bool 4804 DoExecute (Args& command, CommandReturnObject &result) override 4805 { 4806 const size_t argc = command.GetArgumentCount(); 4807 if (argc == 0) 4808 { 4809 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4810 if (process) 4811 { 4812 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream()); 4813 result.SetImmediateOutputStream (output_stream_sp); 4814 4815 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); 4816 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); 4817 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); 4818 const bool json = m_json.GetOptionValue().GetCurrentValue(); 4819 if (output_stream_sp) 4820 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp); 4821 else 4822 { 4823 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream()); 4824 } 4825 result.SetStatus (eReturnStatusSuccessFinishResult); 4826 return true; 4827 } 4828 } 4829 else 4830 { 4831 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str()); 4832 } 4833 result.SetStatus (eReturnStatusFailed); 4834 return false; 4835 } 4836 protected: 4837 OptionGroupOptions m_option_group; 4838 OptionGroupUInt64 m_num_packets; 4839 OptionGroupUInt64 m_max_send; 4840 OptionGroupUInt64 m_max_recv; 4841 OptionGroupBoolean m_json; 4842 4843 }; 4844 4845 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed 4846 { 4847 private: 4848 4849 public: 4850 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) : 4851 CommandObjectParsed (interpreter, 4852 "process plugin packet history", 4853 "Dumps the packet history buffer. ", 4854 NULL) 4855 { 4856 } 4857 4858 ~CommandObjectProcessGDBRemotePacketHistory () 4859 { 4860 } 4861 4862 bool 4863 DoExecute (Args& command, CommandReturnObject &result) override 4864 { 4865 const size_t argc = command.GetArgumentCount(); 4866 if (argc == 0) 4867 { 4868 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4869 if (process) 4870 { 4871 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 4872 result.SetStatus (eReturnStatusSuccessFinishResult); 4873 return true; 4874 } 4875 } 4876 else 4877 { 4878 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str()); 4879 } 4880 result.SetStatus (eReturnStatusFailed); 4881 return false; 4882 } 4883 }; 4884 4885 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed 4886 { 4887 private: 4888 4889 public: 4890 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) : 4891 CommandObjectParsed (interpreter, 4892 "process plugin packet xfer-size", 4893 "Maximum size that lldb will try to read/write one one chunk.", 4894 NULL) 4895 { 4896 } 4897 4898 ~CommandObjectProcessGDBRemotePacketXferSize () 4899 { 4900 } 4901 4902 bool 4903 DoExecute (Args& command, CommandReturnObject &result) override 4904 { 4905 const size_t argc = command.GetArgumentCount(); 4906 if (argc == 0) 4907 { 4908 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str()); 4909 result.SetStatus (eReturnStatusFailed); 4910 return false; 4911 } 4912 4913 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4914 if (process) 4915 { 4916 const char *packet_size = command.GetArgumentAtIndex(0); 4917 errno = 0; 4918 uint64_t user_specified_max = strtoul (packet_size, NULL, 10); 4919 if (errno == 0 && user_specified_max != 0) 4920 { 4921 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max); 4922 result.SetStatus (eReturnStatusSuccessFinishResult); 4923 return true; 4924 } 4925 } 4926 result.SetStatus (eReturnStatusFailed); 4927 return false; 4928 } 4929 }; 4930 4931 4932 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed 4933 { 4934 private: 4935 4936 public: 4937 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) : 4938 CommandObjectParsed (interpreter, 4939 "process plugin packet send", 4940 "Send a custom packet through the GDB remote protocol and print the answer. " 4941 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.", 4942 NULL) 4943 { 4944 } 4945 4946 ~CommandObjectProcessGDBRemotePacketSend () 4947 { 4948 } 4949 4950 bool 4951 DoExecute (Args& command, CommandReturnObject &result) override 4952 { 4953 const size_t argc = command.GetArgumentCount(); 4954 if (argc == 0) 4955 { 4956 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str()); 4957 result.SetStatus (eReturnStatusFailed); 4958 return false; 4959 } 4960 4961 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 4962 if (process) 4963 { 4964 for (size_t i=0; i<argc; ++ i) 4965 { 4966 const char *packet_cstr = command.GetArgumentAtIndex(0); 4967 bool send_async = true; 4968 StringExtractorGDBRemote response; 4969 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 4970 result.SetStatus (eReturnStatusSuccessFinishResult); 4971 Stream &output_strm = result.GetOutputStream(); 4972 output_strm.Printf (" packet: %s\n", packet_cstr); 4973 std::string &response_str = response.GetStringRef(); 4974 4975 if (strstr(packet_cstr, "qGetProfileData") != NULL) 4976 { 4977 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response); 4978 } 4979 4980 if (response_str.empty()) 4981 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 4982 else 4983 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 4984 } 4985 } 4986 return true; 4987 } 4988 }; 4989 4990 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw 4991 { 4992 private: 4993 4994 public: 4995 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) : 4996 CommandObjectRaw (interpreter, 4997 "process plugin packet monitor", 4998 "Send a qRcmd packet through the GDB remote protocol and print the response." 4999 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.", 5000 NULL) 5001 { 5002 } 5003 5004 ~CommandObjectProcessGDBRemotePacketMonitor () 5005 { 5006 } 5007 5008 bool 5009 DoExecute (const char *command, CommandReturnObject &result) override 5010 { 5011 if (command == NULL || command[0] == '\0') 5012 { 5013 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str()); 5014 result.SetStatus (eReturnStatusFailed); 5015 return false; 5016 } 5017 5018 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 5019 if (process) 5020 { 5021 StreamString packet; 5022 packet.PutCString("qRcmd,"); 5023 packet.PutBytesAsRawHex8(command, strlen(command)); 5024 const char *packet_cstr = packet.GetString().c_str(); 5025 5026 bool send_async = true; 5027 StringExtractorGDBRemote response; 5028 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 5029 result.SetStatus (eReturnStatusSuccessFinishResult); 5030 Stream &output_strm = result.GetOutputStream(); 5031 output_strm.Printf (" packet: %s\n", packet_cstr); 5032 const std::string &response_str = response.GetStringRef(); 5033 5034 if (response_str.empty()) 5035 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 5036 else 5037 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 5038 } 5039 return true; 5040 } 5041 }; 5042 5043 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword 5044 { 5045 private: 5046 5047 public: 5048 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) : 5049 CommandObjectMultiword (interpreter, 5050 "process plugin packet", 5051 "Commands that deal with GDB remote packets.", 5052 NULL) 5053 { 5054 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter))); 5055 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter))); 5056 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter))); 5057 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter))); 5058 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter))); 5059 } 5060 5061 ~CommandObjectProcessGDBRemotePacket () 5062 { 5063 } 5064 }; 5065 5066 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword 5067 { 5068 public: 5069 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) : 5070 CommandObjectMultiword (interpreter, 5071 "process plugin", 5072 "A set of commands for operating on a ProcessGDBRemote process.", 5073 "process plugin <subcommand> [<subcommand-options>]") 5074 { 5075 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter))); 5076 } 5077 5078 ~CommandObjectMultiwordProcessGDBRemote () 5079 { 5080 } 5081 }; 5082 5083 CommandObject * 5084 ProcessGDBRemote::GetPluginCommandObject() 5085 { 5086 if (!m_command_sp) 5087 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter())); 5088 return m_command_sp.get(); 5089 } 5090