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