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