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