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