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