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