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