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