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