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/lldb-python.h" 11 #include "lldb/Host/Config.h" 12 13 // C Includes 14 #include <errno.h> 15 #include <stdlib.h> 16 #ifndef LLDB_DISABLE_POSIX 17 #include <spawn.h> 18 #include <netinet/in.h> 19 #include <sys/mman.h> // for mmap 20 #endif 21 #include <sys/stat.h> 22 #include <sys/types.h> 23 #include <time.h> 24 25 // C++ Includes 26 #include <algorithm> 27 #include <map> 28 29 // Other libraries and framework includes 30 31 #include "lldb/Breakpoint/Watchpoint.h" 32 #include "lldb/Interpreter/Args.h" 33 #include "lldb/Core/ArchSpec.h" 34 #include "lldb/Core/Debugger.h" 35 #include "lldb/Core/ConnectionFileDescriptor.h" 36 #include "lldb/Host/FileSpec.h" 37 #include "lldb/Core/Module.h" 38 #include "lldb/Core/ModuleSpec.h" 39 #include "lldb/Core/PluginManager.h" 40 #include "lldb/Core/State.h" 41 #include "lldb/Core/StreamFile.h" 42 #include "lldb/Core/StreamString.h" 43 #include "lldb/Core/Timer.h" 44 #include "lldb/Core/Value.h" 45 #include "lldb/Host/Symbols.h" 46 #include "lldb/Host/TimeValue.h" 47 #include "lldb/Interpreter/CommandInterpreter.h" 48 #include "lldb/Interpreter/CommandObject.h" 49 #include "lldb/Interpreter/CommandObjectMultiword.h" 50 #include "lldb/Interpreter/CommandReturnObject.h" 51 #ifndef LLDB_DISABLE_PYTHON 52 #include "lldb/Interpreter/PythonDataObjects.h" 53 #endif 54 #include "lldb/Symbol/ObjectFile.h" 55 #include "lldb/Target/DynamicLoader.h" 56 #include "lldb/Target/Target.h" 57 #include "lldb/Target/TargetList.h" 58 #include "lldb/Target/ThreadPlanCallFunction.h" 59 #include "lldb/Target/SystemRuntime.h" 60 #include "lldb/Utility/PseudoTerminal.h" 61 62 // Project includes 63 #include "lldb/Host/Host.h" 64 #include "Plugins/Process/Utility/InferiorCallPOSIX.h" 65 #include "Plugins/Process/Utility/StopInfoMachException.h" 66 #include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h" 67 #include "Utility/StringExtractorGDBRemote.h" 68 #include "GDBRemoteRegisterContext.h" 69 #include "ProcessGDBRemote.h" 70 #include "ProcessGDBRemoteLog.h" 71 #include "ThreadGDBRemote.h" 72 73 74 namespace lldb 75 { 76 // Provide a function that can easily dump the packet history if we know a 77 // ProcessGDBRemote * value (which we can get from logs or from debugging). 78 // We need the function in the lldb namespace so it makes it into the final 79 // executable since the LLDB shared library only exports stuff in the lldb 80 // namespace. This allows you to attach with a debugger and call this 81 // function and get the packet history dumped to a file. 82 void 83 DumpProcessGDBRemotePacketHistory (void *p, const char *path) 84 { 85 lldb_private::StreamFile strm; 86 lldb_private::Error error (strm.GetFile().Open(path, lldb_private::File::eOpenOptionWrite | lldb_private::File::eOpenOptionCanCreate)); 87 if (error.Success()) 88 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm); 89 } 90 } 91 92 #define DEBUGSERVER_BASENAME "debugserver" 93 using namespace lldb; 94 using namespace lldb_private; 95 96 97 namespace { 98 99 static PropertyDefinition 100 g_properties[] = 101 { 102 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." }, 103 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." }, 104 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL } 105 }; 106 107 enum 108 { 109 ePropertyPacketTimeout, 110 ePropertyTargetDefinitionFile 111 }; 112 113 class PluginProperties : public Properties 114 { 115 public: 116 117 static ConstString 118 GetSettingName () 119 { 120 return ProcessGDBRemote::GetPluginNameStatic(); 121 } 122 123 PluginProperties() : 124 Properties () 125 { 126 m_collection_sp.reset (new OptionValueProperties(GetSettingName())); 127 m_collection_sp->Initialize(g_properties); 128 } 129 130 virtual 131 ~PluginProperties() 132 { 133 } 134 135 uint64_t 136 GetPacketTimeout() 137 { 138 const uint32_t idx = ePropertyPacketTimeout; 139 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value); 140 } 141 142 bool 143 SetPacketTimeout(uint64_t timeout) 144 { 145 const uint32_t idx = ePropertyPacketTimeout; 146 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout); 147 } 148 149 FileSpec 150 GetTargetDefinitionFile () const 151 { 152 const uint32_t idx = ePropertyTargetDefinitionFile; 153 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx); 154 } 155 }; 156 157 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP; 158 159 static const ProcessKDPPropertiesSP & 160 GetGlobalPluginProperties() 161 { 162 static ProcessKDPPropertiesSP g_settings_sp; 163 if (!g_settings_sp) 164 g_settings_sp.reset (new PluginProperties ()); 165 return g_settings_sp; 166 } 167 168 } // anonymous namespace end 169 170 // TODO Randomly assigning a port is unsafe. We should get an unused 171 // ephemeral port from the kernel and make sure we reserve it before passing 172 // it to debugserver. 173 174 #if defined (__APPLE__) 175 #define LOW_PORT (IPPORT_RESERVED) 176 #define HIGH_PORT (IPPORT_HIFIRSTAUTO) 177 #else 178 #define LOW_PORT (1024u) 179 #define HIGH_PORT (49151u) 180 #endif 181 182 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__)) 183 static bool rand_initialized = false; 184 185 static inline uint16_t 186 get_random_port () 187 { 188 if (!rand_initialized) 189 { 190 time_t seed = time(NULL); 191 192 rand_initialized = true; 193 srand(seed); 194 } 195 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT; 196 } 197 #endif 198 199 lldb_private::ConstString 200 ProcessGDBRemote::GetPluginNameStatic() 201 { 202 static ConstString g_name("gdb-remote"); 203 return g_name; 204 } 205 206 const char * 207 ProcessGDBRemote::GetPluginDescriptionStatic() 208 { 209 return "GDB Remote protocol based debugging plug-in."; 210 } 211 212 void 213 ProcessGDBRemote::Terminate() 214 { 215 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance); 216 } 217 218 219 lldb::ProcessSP 220 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path) 221 { 222 lldb::ProcessSP process_sp; 223 if (crash_file_path == NULL) 224 process_sp.reset (new ProcessGDBRemote (target, listener)); 225 return process_sp; 226 } 227 228 bool 229 ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name) 230 { 231 if (plugin_specified_by_name) 232 return true; 233 234 // For now we are just making sure the file exists for a given module 235 Module *exe_module = target.GetExecutableModulePointer(); 236 if (exe_module) 237 { 238 ObjectFile *exe_objfile = exe_module->GetObjectFile(); 239 // We can't debug core files... 240 switch (exe_objfile->GetType()) 241 { 242 case ObjectFile::eTypeInvalid: 243 case ObjectFile::eTypeCoreFile: 244 case ObjectFile::eTypeDebugInfo: 245 case ObjectFile::eTypeObjectFile: 246 case ObjectFile::eTypeSharedLibrary: 247 case ObjectFile::eTypeStubLibrary: 248 case ObjectFile::eTypeJIT: 249 return false; 250 case ObjectFile::eTypeExecutable: 251 case ObjectFile::eTypeDynamicLinker: 252 case ObjectFile::eTypeUnknown: 253 break; 254 } 255 return exe_module->GetFileSpec().Exists(); 256 } 257 // However, if there is no executable module, we return true since we might be preparing to attach. 258 return true; 259 } 260 261 //---------------------------------------------------------------------- 262 // ProcessGDBRemote constructor 263 //---------------------------------------------------------------------- 264 ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) : 265 Process (target, listener), 266 m_flags (0), 267 m_gdb_comm(false), 268 m_debugserver_pid (LLDB_INVALID_PROCESS_ID), 269 m_last_stop_packet (), 270 m_last_stop_packet_mutex (Mutex::eMutexTypeNormal), 271 m_register_info (), 272 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"), 273 m_async_thread (LLDB_INVALID_HOST_THREAD), 274 m_async_thread_state(eAsyncThreadNotStarted), 275 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive), 276 m_thread_ids (), 277 m_continue_c_tids (), 278 m_continue_C_tids (), 279 m_continue_s_tids (), 280 m_continue_S_tids (), 281 m_max_memory_size (0), 282 m_remote_stub_max_memory_size (0), 283 m_addr_to_mmap_size (), 284 m_thread_create_bp_sp (), 285 m_waiting_for_attach (false), 286 m_destroy_tried_resuming (false), 287 m_command_sp (), 288 m_breakpoint_pc_offset (0) 289 { 290 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit"); 291 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue"); 292 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit"); 293 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout(); 294 if (timeout_seconds > 0) 295 m_gdb_comm.SetPacketTimeout(timeout_seconds); 296 } 297 298 //---------------------------------------------------------------------- 299 // Destructor 300 //---------------------------------------------------------------------- 301 ProcessGDBRemote::~ProcessGDBRemote() 302 { 303 // m_mach_process.UnregisterNotificationCallbacks (this); 304 Clear(); 305 // We need to call finalize on the process before destroying ourselves 306 // to make sure all of the broadcaster cleanup goes as planned. If we 307 // destruct this class, then Process::~Process() might have problems 308 // trying to fully destroy the broadcaster. 309 Finalize(); 310 311 // The general Finalize is going to try to destroy the process and that SHOULD 312 // shut down the async thread. However, if we don't kill it it will get stranded and 313 // its connection will go away so when it wakes up it will crash. So kill it for sure here. 314 StopAsyncThread(); 315 KillDebugserverProcess(); 316 } 317 318 //---------------------------------------------------------------------- 319 // PluginInterface 320 //---------------------------------------------------------------------- 321 ConstString 322 ProcessGDBRemote::GetPluginName() 323 { 324 return GetPluginNameStatic(); 325 } 326 327 uint32_t 328 ProcessGDBRemote::GetPluginVersion() 329 { 330 return 1; 331 } 332 333 bool 334 ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec) 335 { 336 #ifndef LLDB_DISABLE_PYTHON 337 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); 338 Error error; 339 lldb::ScriptInterpreterObjectSP module_object_sp (interpreter->LoadPluginModule(target_definition_fspec, error)); 340 if (module_object_sp) 341 { 342 lldb::ScriptInterpreterObjectSP target_definition_sp (interpreter->GetDynamicSettings(module_object_sp, 343 &GetTarget(), 344 "gdb-server-target-definition", 345 error)); 346 347 PythonDictionary target_dict(target_definition_sp); 348 349 if (target_dict) 350 { 351 PythonDictionary host_info_dict (target_dict.GetItemForKey("host-info")); 352 if (host_info_dict) 353 { 354 ArchSpec host_arch (host_info_dict.GetItemForKeyAsString(PythonString("triple"))); 355 356 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) 357 { 358 GetTarget().SetArchitecture(host_arch); 359 } 360 361 } 362 m_breakpoint_pc_offset = target_dict.GetItemForKeyAsInteger("breakpoint-pc-offset", 0); 363 364 if (m_register_info.SetRegisterInfo (target_dict, GetTarget().GetArchitecture().GetByteOrder()) > 0) 365 { 366 return true; 367 } 368 } 369 } 370 #endif 371 return false; 372 } 373 374 375 void 376 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force) 377 { 378 if (!force && m_register_info.GetNumRegisters() > 0) 379 return; 380 381 char packet[128]; 382 m_register_info.Clear(); 383 uint32_t reg_offset = 0; 384 uint32_t reg_num = 0; 385 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse; 386 response_type == StringExtractorGDBRemote::eResponse; 387 ++reg_num) 388 { 389 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num); 390 assert (packet_len < (int)sizeof(packet)); 391 StringExtractorGDBRemote response; 392 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success) 393 { 394 response_type = response.GetResponseType(); 395 if (response_type == StringExtractorGDBRemote::eResponse) 396 { 397 std::string name; 398 std::string value; 399 ConstString reg_name; 400 ConstString alt_name; 401 ConstString set_name; 402 std::vector<uint32_t> value_regs; 403 std::vector<uint32_t> invalidate_regs; 404 RegisterInfo reg_info = { NULL, // Name 405 NULL, // Alt name 406 0, // byte size 407 reg_offset, // offset 408 eEncodingUint, // encoding 409 eFormatHex, // formate 410 { 411 LLDB_INVALID_REGNUM, // GCC reg num 412 LLDB_INVALID_REGNUM, // DWARF reg num 413 LLDB_INVALID_REGNUM, // generic reg num 414 reg_num, // GDB reg num 415 reg_num // native register number 416 }, 417 NULL, 418 NULL 419 }; 420 421 while (response.GetNameColonValue(name, value)) 422 { 423 if (name.compare("name") == 0) 424 { 425 reg_name.SetCString(value.c_str()); 426 } 427 else if (name.compare("alt-name") == 0) 428 { 429 alt_name.SetCString(value.c_str()); 430 } 431 else if (name.compare("bitsize") == 0) 432 { 433 reg_info.byte_size = Args::StringToUInt32(value.c_str(), 0, 0) / CHAR_BIT; 434 } 435 else if (name.compare("offset") == 0) 436 { 437 uint32_t offset = Args::StringToUInt32(value.c_str(), UINT32_MAX, 0); 438 if (reg_offset != offset) 439 { 440 reg_offset = offset; 441 } 442 } 443 else if (name.compare("encoding") == 0) 444 { 445 const Encoding encoding = Args::StringToEncoding (value.c_str()); 446 if (encoding != eEncodingInvalid) 447 reg_info.encoding = encoding; 448 } 449 else if (name.compare("format") == 0) 450 { 451 Format format = eFormatInvalid; 452 if (Args::StringToFormat (value.c_str(), format, NULL).Success()) 453 reg_info.format = format; 454 else if (value.compare("binary") == 0) 455 reg_info.format = eFormatBinary; 456 else if (value.compare("decimal") == 0) 457 reg_info.format = eFormatDecimal; 458 else if (value.compare("hex") == 0) 459 reg_info.format = eFormatHex; 460 else if (value.compare("float") == 0) 461 reg_info.format = eFormatFloat; 462 else if (value.compare("vector-sint8") == 0) 463 reg_info.format = eFormatVectorOfSInt8; 464 else if (value.compare("vector-uint8") == 0) 465 reg_info.format = eFormatVectorOfUInt8; 466 else if (value.compare("vector-sint16") == 0) 467 reg_info.format = eFormatVectorOfSInt16; 468 else if (value.compare("vector-uint16") == 0) 469 reg_info.format = eFormatVectorOfUInt16; 470 else if (value.compare("vector-sint32") == 0) 471 reg_info.format = eFormatVectorOfSInt32; 472 else if (value.compare("vector-uint32") == 0) 473 reg_info.format = eFormatVectorOfUInt32; 474 else if (value.compare("vector-float32") == 0) 475 reg_info.format = eFormatVectorOfFloat32; 476 else if (value.compare("vector-uint128") == 0) 477 reg_info.format = eFormatVectorOfUInt128; 478 } 479 else if (name.compare("set") == 0) 480 { 481 set_name.SetCString(value.c_str()); 482 } 483 else if (name.compare("gcc") == 0) 484 { 485 reg_info.kinds[eRegisterKindGCC] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 486 } 487 else if (name.compare("dwarf") == 0) 488 { 489 reg_info.kinds[eRegisterKindDWARF] = Args::StringToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0); 490 } 491 else if (name.compare("generic") == 0) 492 { 493 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str()); 494 } 495 else if (name.compare("container-regs") == 0) 496 { 497 std::pair<llvm::StringRef, llvm::StringRef> value_pair; 498 value_pair.second = value; 499 do 500 { 501 value_pair = value_pair.second.split(','); 502 if (!value_pair.first.empty()) 503 { 504 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16); 505 if (reg != LLDB_INVALID_REGNUM) 506 value_regs.push_back (reg); 507 } 508 } while (!value_pair.second.empty()); 509 } 510 else if (name.compare("invalidate-regs") == 0) 511 { 512 std::pair<llvm::StringRef, llvm::StringRef> value_pair; 513 value_pair.second = value; 514 do 515 { 516 value_pair = value_pair.second.split(','); 517 if (!value_pair.first.empty()) 518 { 519 uint32_t reg = Args::StringToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, 16); 520 if (reg != LLDB_INVALID_REGNUM) 521 invalidate_regs.push_back (reg); 522 } 523 } while (!value_pair.second.empty()); 524 } 525 } 526 527 reg_info.byte_offset = reg_offset; 528 assert (reg_info.byte_size != 0); 529 reg_offset += reg_info.byte_size; 530 if (!value_regs.empty()) 531 { 532 value_regs.push_back(LLDB_INVALID_REGNUM); 533 reg_info.value_regs = value_regs.data(); 534 } 535 if (!invalidate_regs.empty()) 536 { 537 invalidate_regs.push_back(LLDB_INVALID_REGNUM); 538 reg_info.invalidate_regs = invalidate_regs.data(); 539 } 540 541 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); 542 } 543 else 544 { 545 break; // ensure exit before reg_num is incremented 546 } 547 } 548 else 549 { 550 break; 551 } 552 } 553 554 // Check if qHostInfo specified a specific packet timeout for this connection. 555 // If so then lets update our setting so the user knows what the timeout is 556 // and can see it. 557 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout(); 558 if (host_packet_timeout) 559 { 560 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout); 561 } 562 563 564 if (reg_num == 0) 565 { 566 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile (); 567 568 if (target_definition_fspec) 569 { 570 // See if we can get register definitions from a python file 571 if (ParsePythonTargetDefinition (target_definition_fspec)) 572 return; 573 } 574 } 575 576 // We didn't get anything if the accumulated reg_num is zero. See if we are 577 // debugging ARM and fill with a hard coded register set until we can get an 578 // updated debugserver down on the devices. 579 // On the other hand, if the accumulated reg_num is positive, see if we can 580 // add composite registers to the existing primordial ones. 581 bool from_scratch = (reg_num == 0); 582 583 const ArchSpec &target_arch = GetTarget().GetArchitecture(); 584 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture(); 585 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); 586 587 // Use the process' architecture instead of the host arch, if available 588 ArchSpec remote_arch; 589 if (remote_process_arch.IsValid ()) 590 remote_arch = remote_process_arch; 591 else 592 remote_arch = remote_host_arch; 593 594 if (!target_arch.IsValid()) 595 { 596 if (remote_arch.IsValid() 597 && remote_arch.GetMachine() == llvm::Triple::arm 598 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple) 599 m_register_info.HardcodeARMRegisters(from_scratch); 600 } 601 else if (target_arch.GetMachine() == llvm::Triple::arm) 602 { 603 m_register_info.HardcodeARMRegisters(from_scratch); 604 } 605 606 // At this point, we can finalize our register info. 607 m_register_info.Finalize (); 608 } 609 610 Error 611 ProcessGDBRemote::WillLaunch (Module* module) 612 { 613 return WillLaunchOrAttach (); 614 } 615 616 Error 617 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid) 618 { 619 return WillLaunchOrAttach (); 620 } 621 622 Error 623 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) 624 { 625 return WillLaunchOrAttach (); 626 } 627 628 Error 629 ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url) 630 { 631 Error error (WillLaunchOrAttach ()); 632 633 if (error.Fail()) 634 return error; 635 636 error = ConnectToDebugserver (remote_url); 637 638 if (error.Fail()) 639 return error; 640 StartAsyncThread (); 641 642 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 643 if (pid == LLDB_INVALID_PROCESS_ID) 644 { 645 // We don't have a valid process ID, so note that we are connected 646 // and could now request to launch or attach, or get remote process 647 // listings... 648 SetPrivateState (eStateConnected); 649 } 650 else 651 { 652 // We have a valid process 653 SetID (pid); 654 GetThreadList(); 655 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success) 656 { 657 if (!m_target.GetArchitecture().IsValid()) 658 { 659 if (m_gdb_comm.GetProcessArchitecture().IsValid()) 660 { 661 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture()); 662 } 663 else 664 { 665 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture()); 666 } 667 } 668 669 const StateType state = SetThreadStopInfo (m_last_stop_packet); 670 if (state == eStateStopped) 671 { 672 SetPrivateState (state); 673 } 674 else 675 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state)); 676 } 677 else 678 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url); 679 } 680 681 if (error.Success() 682 && !GetTarget().GetArchitecture().IsValid() 683 && m_gdb_comm.GetHostArchitecture().IsValid()) 684 { 685 // Prefer the *process'* architecture over that of the *host*, if available. 686 if (m_gdb_comm.GetProcessArchitecture().IsValid()) 687 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture()); 688 else 689 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture()); 690 } 691 692 return error; 693 } 694 695 Error 696 ProcessGDBRemote::WillLaunchOrAttach () 697 { 698 Error error; 699 m_stdio_communication.Clear (); 700 return error; 701 } 702 703 //---------------------------------------------------------------------- 704 // Process Control 705 //---------------------------------------------------------------------- 706 Error 707 ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info) 708 { 709 Error error; 710 711 uint32_t launch_flags = launch_info.GetFlags().Get(); 712 const char *stdin_path = NULL; 713 const char *stdout_path = NULL; 714 const char *stderr_path = NULL; 715 const char *working_dir = launch_info.GetWorkingDirectory(); 716 717 const ProcessLaunchInfo::FileAction *file_action; 718 file_action = launch_info.GetFileActionForFD (STDIN_FILENO); 719 if (file_action) 720 { 721 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 722 stdin_path = file_action->GetPath(); 723 } 724 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO); 725 if (file_action) 726 { 727 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 728 stdout_path = file_action->GetPath(); 729 } 730 file_action = launch_info.GetFileActionForFD (STDERR_FILENO); 731 if (file_action) 732 { 733 if (file_action->GetAction () == ProcessLaunchInfo::FileAction::eFileActionOpen) 734 stderr_path = file_action->GetPath(); 735 } 736 737 // ::LogSetBitMask (GDBR_LOG_DEFAULT); 738 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); 739 // ::LogSetLogFile ("/dev/stdout"); 740 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 741 742 ObjectFile * object_file = exe_module->GetObjectFile(); 743 if (object_file) 744 { 745 // Make sure we aren't already connected? 746 if (!m_gdb_comm.IsConnected()) 747 { 748 error = LaunchAndConnectToDebugserver (launch_info); 749 } 750 751 if (error.Success()) 752 { 753 lldb_utility::PseudoTerminal pty; 754 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; 755 756 // If the debugserver is local and we aren't disabling STDIO, lets use 757 // a pseudo terminal to instead of relying on the 'O' packets for stdio 758 // since 'O' packets can really slow down debugging if the inferior 759 // does a lot of output. 760 PlatformSP platform_sp (m_target.GetPlatform()); 761 if (platform_sp && platform_sp->IsHost() && !disable_stdio) 762 { 763 const char *slave_name = NULL; 764 if (stdin_path == NULL || stdout_path == NULL || stderr_path == NULL) 765 { 766 if (pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0)) 767 slave_name = pty.GetSlaveName (NULL, 0); 768 } 769 if (stdin_path == NULL) 770 stdin_path = slave_name; 771 772 if (stdout_path == NULL) 773 stdout_path = slave_name; 774 775 if (stderr_path == NULL) 776 stderr_path = slave_name; 777 } 778 779 // Set STDIN to /dev/null if we want STDIO disabled or if either 780 // STDOUT or STDERR have been set to something and STDIN hasn't 781 if (disable_stdio || (stdin_path == NULL && (stdout_path || stderr_path))) 782 stdin_path = "/dev/null"; 783 784 // Set STDOUT to /dev/null if we want STDIO disabled or if either 785 // STDIN or STDERR have been set to something and STDOUT hasn't 786 if (disable_stdio || (stdout_path == NULL && (stdin_path || stderr_path))) 787 stdout_path = "/dev/null"; 788 789 // Set STDERR to /dev/null if we want STDIO disabled or if either 790 // STDIN or STDOUT have been set to something and STDERR hasn't 791 if (disable_stdio || (stderr_path == NULL && (stdin_path || stdout_path))) 792 stderr_path = "/dev/null"; 793 794 if (stdin_path) 795 m_gdb_comm.SetSTDIN (stdin_path); 796 if (stdout_path) 797 m_gdb_comm.SetSTDOUT (stdout_path); 798 if (stderr_path) 799 m_gdb_comm.SetSTDERR (stderr_path); 800 801 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR); 802 803 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName()); 804 805 const char * launch_event_data = launch_info.GetLaunchEventData(); 806 if (launch_event_data != NULL && *launch_event_data != '\0') 807 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data); 808 809 if (working_dir && working_dir[0]) 810 { 811 m_gdb_comm.SetWorkingDir (working_dir); 812 } 813 814 // Send the environment and the program + arguments after we connect 815 const Args &environment = launch_info.GetEnvironmentEntries(); 816 if (environment.GetArgumentCount()) 817 { 818 size_t num_environment_entries = environment.GetArgumentCount(); 819 for (size_t i=0; i<num_environment_entries; ++i) 820 { 821 const char *env_entry = environment.GetArgumentAtIndex(i); 822 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0) 823 break; 824 } 825 } 826 827 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (10); 828 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info); 829 if (arg_packet_err == 0) 830 { 831 std::string error_str; 832 if (m_gdb_comm.GetLaunchSuccess (error_str)) 833 { 834 SetID (m_gdb_comm.GetCurrentProcessID ()); 835 } 836 else 837 { 838 error.SetErrorString (error_str.c_str()); 839 } 840 } 841 else 842 { 843 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err); 844 } 845 846 m_gdb_comm.SetPacketTimeout (old_packet_timeout); 847 848 if (GetID() == LLDB_INVALID_PROCESS_ID) 849 { 850 if (log) 851 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 852 KillDebugserverProcess (); 853 return error; 854 } 855 856 if (m_gdb_comm.SendPacketAndWaitForResponse("?", 1, m_last_stop_packet, false) == GDBRemoteCommunication::PacketResult::Success) 857 { 858 if (!m_target.GetArchitecture().IsValid()) 859 { 860 if (m_gdb_comm.GetProcessArchitecture().IsValid()) 861 { 862 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture()); 863 } 864 else 865 { 866 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture()); 867 } 868 } 869 870 SetPrivateState (SetThreadStopInfo (m_last_stop_packet)); 871 872 if (!disable_stdio) 873 { 874 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd) 875 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor()); 876 } 877 } 878 } 879 else 880 { 881 if (log) 882 log->Printf("failed to connect to debugserver: %s", error.AsCString()); 883 } 884 } 885 else 886 { 887 // Set our user ID to an invalid process ID. 888 SetID(LLDB_INVALID_PROCESS_ID); 889 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s", 890 exe_module->GetFileSpec().GetFilename().AsCString(), 891 exe_module->GetArchitecture().GetArchitectureName()); 892 } 893 return error; 894 895 } 896 897 898 Error 899 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url) 900 { 901 Error error; 902 // Only connect if we have a valid connect URL 903 904 if (connect_url && connect_url[0]) 905 { 906 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor()); 907 if (conn_ap.get()) 908 { 909 const uint32_t max_retry_count = 50; 910 uint32_t retry_count = 0; 911 while (!m_gdb_comm.IsConnected()) 912 { 913 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess) 914 { 915 m_gdb_comm.SetConnection (conn_ap.release()); 916 break; 917 } 918 else if (error.WasInterrupted()) 919 { 920 // If we were interrupted, don't keep retrying. 921 break; 922 } 923 924 retry_count++; 925 926 if (retry_count >= max_retry_count) 927 break; 928 929 usleep (100000); 930 } 931 } 932 } 933 934 if (!m_gdb_comm.IsConnected()) 935 { 936 if (error.Success()) 937 error.SetErrorString("not connected to remote gdb server"); 938 return error; 939 } 940 941 // We always seem to be able to open a connection to a local port 942 // so we need to make sure we can then send data to it. If we can't 943 // then we aren't actually connected to anything, so try and do the 944 // handshake with the remote GDB server and make sure that goes 945 // alright. 946 if (!m_gdb_comm.HandshakeWithServer (&error)) 947 { 948 m_gdb_comm.Disconnect(); 949 if (error.Success()) 950 error.SetErrorString("not connected to remote gdb server"); 951 return error; 952 } 953 m_gdb_comm.GetThreadSuffixSupported (); 954 m_gdb_comm.GetListThreadsInStopReplySupported (); 955 m_gdb_comm.GetHostInfo (); 956 m_gdb_comm.GetVContSupported ('c'); 957 m_gdb_comm.GetVAttachOrWaitSupported(); 958 959 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount(); 960 for (size_t idx = 0; idx < num_cmds; idx++) 961 { 962 StringExtractorGDBRemote response; 963 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false); 964 } 965 return error; 966 } 967 968 void 969 ProcessGDBRemote::DidLaunchOrAttach () 970 { 971 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 972 if (log) 973 log->Printf ("ProcessGDBRemote::DidLaunch()"); 974 if (GetID() != LLDB_INVALID_PROCESS_ID) 975 { 976 BuildDynamicRegisterInfo (false); 977 978 // See if the GDB server supports the qHostInfo information 979 980 ArchSpec gdb_remote_arch = m_gdb_comm.GetHostArchitecture(); 981 982 // See if the GDB server supports the qProcessInfo packet, if so 983 // prefer that over the Host information as it will be more specific 984 // to our process. 985 986 if (m_gdb_comm.GetProcessArchitecture().IsValid()) 987 gdb_remote_arch = m_gdb_comm.GetProcessArchitecture(); 988 989 if (gdb_remote_arch.IsValid()) 990 { 991 ArchSpec &target_arch = GetTarget().GetArchitecture(); 992 993 if (target_arch.IsValid()) 994 { 995 // If the remote host is ARM and we have apple as the vendor, then 996 // ARM executables and shared libraries can have mixed ARM architectures. 997 // You can have an armv6 executable, and if the host is armv7, then the 998 // system will load the best possible architecture for all shared libraries 999 // it has, so we really need to take the remote host architecture as our 1000 // defacto architecture in this case. 1001 1002 if (gdb_remote_arch.GetMachine() == llvm::Triple::arm && 1003 gdb_remote_arch.GetTriple().getVendor() == llvm::Triple::Apple) 1004 { 1005 target_arch = gdb_remote_arch; 1006 } 1007 else 1008 { 1009 // Fill in what is missing in the triple 1010 const llvm::Triple &remote_triple = gdb_remote_arch.GetTriple(); 1011 llvm::Triple &target_triple = target_arch.GetTriple(); 1012 if (target_triple.getVendorName().size() == 0) 1013 { 1014 target_triple.setVendor (remote_triple.getVendor()); 1015 1016 if (target_triple.getOSName().size() == 0) 1017 { 1018 target_triple.setOS (remote_triple.getOS()); 1019 1020 if (target_triple.getEnvironmentName().size() == 0) 1021 target_triple.setEnvironment (remote_triple.getEnvironment()); 1022 } 1023 } 1024 } 1025 } 1026 else 1027 { 1028 // The target doesn't have a valid architecture yet, set it from 1029 // the architecture we got from the remote GDB server 1030 target_arch = gdb_remote_arch; 1031 } 1032 } 1033 } 1034 } 1035 1036 void 1037 ProcessGDBRemote::DidLaunch () 1038 { 1039 DidLaunchOrAttach (); 1040 } 1041 1042 Error 1043 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid) 1044 { 1045 ProcessAttachInfo attach_info; 1046 return DoAttachToProcessWithID(attach_pid, attach_info); 1047 } 1048 1049 Error 1050 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) 1051 { 1052 Error error; 1053 // Clear out and clean up from any current state 1054 Clear(); 1055 if (attach_pid != LLDB_INVALID_PROCESS_ID) 1056 { 1057 // Make sure we aren't already connected? 1058 if (!m_gdb_comm.IsConnected()) 1059 { 1060 error = LaunchAndConnectToDebugserver (attach_info); 1061 1062 if (error.Fail()) 1063 { 1064 const char *error_string = error.AsCString(); 1065 if (error_string == NULL) 1066 error_string = "unable to launch " DEBUGSERVER_BASENAME; 1067 1068 SetExitStatus (-1, error_string); 1069 } 1070 } 1071 1072 if (error.Success()) 1073 { 1074 char packet[64]; 1075 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid); 1076 SetID (attach_pid); 1077 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len)); 1078 } 1079 } 1080 return error; 1081 } 1082 1083 Error 1084 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info) 1085 { 1086 Error error; 1087 // Clear out and clean up from any current state 1088 Clear(); 1089 1090 if (process_name && process_name[0]) 1091 { 1092 // Make sure we aren't already connected? 1093 if (!m_gdb_comm.IsConnected()) 1094 { 1095 error = LaunchAndConnectToDebugserver (attach_info); 1096 1097 if (error.Fail()) 1098 { 1099 const char *error_string = error.AsCString(); 1100 if (error_string == NULL) 1101 error_string = "unable to launch " DEBUGSERVER_BASENAME; 1102 1103 SetExitStatus (-1, error_string); 1104 } 1105 } 1106 1107 if (error.Success()) 1108 { 1109 StreamString packet; 1110 1111 if (attach_info.GetWaitForLaunch()) 1112 { 1113 if (!m_gdb_comm.GetVAttachOrWaitSupported()) 1114 { 1115 packet.PutCString ("vAttachWait"); 1116 } 1117 else 1118 { 1119 if (attach_info.GetIgnoreExisting()) 1120 packet.PutCString("vAttachWait"); 1121 else 1122 packet.PutCString ("vAttachOrWait"); 1123 } 1124 } 1125 else 1126 packet.PutCString("vAttachName"); 1127 packet.PutChar(';'); 1128 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 1129 1130 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize())); 1131 1132 } 1133 } 1134 return error; 1135 } 1136 1137 1138 bool 1139 ProcessGDBRemote::SetExitStatus (int exit_status, const char *cstr) 1140 { 1141 m_gdb_comm.Disconnect(); 1142 return Process::SetExitStatus (exit_status, cstr); 1143 } 1144 1145 void 1146 ProcessGDBRemote::DidAttach () 1147 { 1148 DidLaunchOrAttach (); 1149 } 1150 1151 1152 Error 1153 ProcessGDBRemote::WillResume () 1154 { 1155 m_continue_c_tids.clear(); 1156 m_continue_C_tids.clear(); 1157 m_continue_s_tids.clear(); 1158 m_continue_S_tids.clear(); 1159 return Error(); 1160 } 1161 1162 Error 1163 ProcessGDBRemote::DoResume () 1164 { 1165 Error error; 1166 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1167 if (log) 1168 log->Printf ("ProcessGDBRemote::Resume()"); 1169 1170 Listener listener ("gdb-remote.resume-packet-sent"); 1171 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) 1172 { 1173 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); 1174 1175 const size_t num_threads = GetThreadList().GetSize(); 1176 1177 StreamString continue_packet; 1178 bool continue_packet_error = false; 1179 if (m_gdb_comm.HasAnyVContSupport ()) 1180 { 1181 if (m_continue_c_tids.size() == num_threads || 1182 (m_continue_c_tids.empty() && 1183 m_continue_C_tids.empty() && 1184 m_continue_s_tids.empty() && 1185 m_continue_S_tids.empty())) 1186 { 1187 // All threads are continuing, just send a "c" packet 1188 continue_packet.PutCString ("c"); 1189 } 1190 else 1191 { 1192 continue_packet.PutCString ("vCont"); 1193 1194 if (!m_continue_c_tids.empty()) 1195 { 1196 if (m_gdb_comm.GetVContSupported ('c')) 1197 { 1198 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) 1199 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos); 1200 } 1201 else 1202 continue_packet_error = true; 1203 } 1204 1205 if (!continue_packet_error && !m_continue_C_tids.empty()) 1206 { 1207 if (m_gdb_comm.GetVContSupported ('C')) 1208 { 1209 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) 1210 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); 1211 } 1212 else 1213 continue_packet_error = true; 1214 } 1215 1216 if (!continue_packet_error && !m_continue_s_tids.empty()) 1217 { 1218 if (m_gdb_comm.GetVContSupported ('s')) 1219 { 1220 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) 1221 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos); 1222 } 1223 else 1224 continue_packet_error = true; 1225 } 1226 1227 if (!continue_packet_error && !m_continue_S_tids.empty()) 1228 { 1229 if (m_gdb_comm.GetVContSupported ('S')) 1230 { 1231 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) 1232 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); 1233 } 1234 else 1235 continue_packet_error = true; 1236 } 1237 1238 if (continue_packet_error) 1239 continue_packet.GetString().clear(); 1240 } 1241 } 1242 else 1243 continue_packet_error = true; 1244 1245 if (continue_packet_error) 1246 { 1247 // Either no vCont support, or we tried to use part of the vCont 1248 // packet that wasn't supported by the remote GDB server. 1249 // We need to try and make a simple packet that can do our continue 1250 const size_t num_continue_c_tids = m_continue_c_tids.size(); 1251 const size_t num_continue_C_tids = m_continue_C_tids.size(); 1252 const size_t num_continue_s_tids = m_continue_s_tids.size(); 1253 const size_t num_continue_S_tids = m_continue_S_tids.size(); 1254 if (num_continue_c_tids > 0) 1255 { 1256 if (num_continue_c_tids == num_threads) 1257 { 1258 // All threads are resuming... 1259 m_gdb_comm.SetCurrentThreadForRun (-1); 1260 continue_packet.PutChar ('c'); 1261 continue_packet_error = false; 1262 } 1263 else if (num_continue_c_tids == 1 && 1264 num_continue_C_tids == 0 && 1265 num_continue_s_tids == 0 && 1266 num_continue_S_tids == 0 ) 1267 { 1268 // Only one thread is continuing 1269 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front()); 1270 continue_packet.PutChar ('c'); 1271 continue_packet_error = false; 1272 } 1273 } 1274 1275 if (continue_packet_error && num_continue_C_tids > 0) 1276 { 1277 if ((num_continue_C_tids + num_continue_c_tids) == num_threads && 1278 num_continue_C_tids > 0 && 1279 num_continue_s_tids == 0 && 1280 num_continue_S_tids == 0 ) 1281 { 1282 const int continue_signo = m_continue_C_tids.front().second; 1283 // Only one thread is continuing 1284 if (num_continue_C_tids > 1) 1285 { 1286 // More that one thread with a signal, yet we don't have 1287 // vCont support and we are being asked to resume each 1288 // thread with a signal, we need to make sure they are 1289 // all the same signal, or we can't issue the continue 1290 // accurately with the current support... 1291 if (num_continue_C_tids > 1) 1292 { 1293 continue_packet_error = false; 1294 for (size_t i=1; i<m_continue_C_tids.size(); ++i) 1295 { 1296 if (m_continue_C_tids[i].second != continue_signo) 1297 continue_packet_error = true; 1298 } 1299 } 1300 if (!continue_packet_error) 1301 m_gdb_comm.SetCurrentThreadForRun (-1); 1302 } 1303 else 1304 { 1305 // Set the continue thread ID 1306 continue_packet_error = false; 1307 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first); 1308 } 1309 if (!continue_packet_error) 1310 { 1311 // Add threads continuing with the same signo... 1312 continue_packet.Printf("C%2.2x", continue_signo); 1313 } 1314 } 1315 } 1316 1317 if (continue_packet_error && num_continue_s_tids > 0) 1318 { 1319 if (num_continue_s_tids == num_threads) 1320 { 1321 // All threads are resuming... 1322 m_gdb_comm.SetCurrentThreadForRun (-1); 1323 continue_packet.PutChar ('s'); 1324 continue_packet_error = false; 1325 } 1326 else if (num_continue_c_tids == 0 && 1327 num_continue_C_tids == 0 && 1328 num_continue_s_tids == 1 && 1329 num_continue_S_tids == 0 ) 1330 { 1331 // Only one thread is stepping 1332 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front()); 1333 continue_packet.PutChar ('s'); 1334 continue_packet_error = false; 1335 } 1336 } 1337 1338 if (!continue_packet_error && num_continue_S_tids > 0) 1339 { 1340 if (num_continue_S_tids == num_threads) 1341 { 1342 const int step_signo = m_continue_S_tids.front().second; 1343 // Are all threads trying to step with the same signal? 1344 continue_packet_error = false; 1345 if (num_continue_S_tids > 1) 1346 { 1347 for (size_t i=1; i<num_threads; ++i) 1348 { 1349 if (m_continue_S_tids[i].second != step_signo) 1350 continue_packet_error = true; 1351 } 1352 } 1353 if (!continue_packet_error) 1354 { 1355 // Add threads stepping with the same signo... 1356 m_gdb_comm.SetCurrentThreadForRun (-1); 1357 continue_packet.Printf("S%2.2x", step_signo); 1358 } 1359 } 1360 else if (num_continue_c_tids == 0 && 1361 num_continue_C_tids == 0 && 1362 num_continue_s_tids == 0 && 1363 num_continue_S_tids == 1 ) 1364 { 1365 // Only one thread is stepping with signal 1366 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first); 1367 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); 1368 continue_packet_error = false; 1369 } 1370 } 1371 } 1372 1373 if (continue_packet_error) 1374 { 1375 error.SetErrorString ("can't make continue packet for this resume"); 1376 } 1377 else 1378 { 1379 EventSP event_sp; 1380 TimeValue timeout; 1381 timeout = TimeValue::Now(); 1382 timeout.OffsetWithSeconds (5); 1383 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 1384 { 1385 error.SetErrorString ("Trying to resume but the async thread is dead."); 1386 if (log) 1387 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead."); 1388 return error; 1389 } 1390 1391 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize())); 1392 1393 if (listener.WaitForEvent (&timeout, event_sp) == false) 1394 { 1395 error.SetErrorString("Resume timed out."); 1396 if (log) 1397 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out."); 1398 } 1399 else if (event_sp->BroadcasterIs (&m_async_broadcaster)) 1400 { 1401 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back."); 1402 if (log) 1403 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back."); 1404 return error; 1405 } 1406 } 1407 } 1408 1409 return error; 1410 } 1411 1412 void 1413 ProcessGDBRemote::ClearThreadIDList () 1414 { 1415 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1416 m_thread_ids.clear(); 1417 } 1418 1419 bool 1420 ProcessGDBRemote::UpdateThreadIDList () 1421 { 1422 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1423 bool sequence_mutex_unavailable = false; 1424 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable); 1425 if (sequence_mutex_unavailable) 1426 { 1427 return false; // We just didn't get the list 1428 } 1429 return true; 1430 } 1431 1432 bool 1433 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 1434 { 1435 // locker will keep a mutex locked until it goes out of scope 1436 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1437 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1438 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID()); 1439 1440 size_t num_thread_ids = m_thread_ids.size(); 1441 // The "m_thread_ids" thread ID list should always be updated after each stop 1442 // reply packet, but in case it isn't, update it here. 1443 if (num_thread_ids == 0) 1444 { 1445 if (!UpdateThreadIDList ()) 1446 return false; 1447 num_thread_ids = m_thread_ids.size(); 1448 } 1449 1450 ThreadList old_thread_list_copy(old_thread_list); 1451 if (num_thread_ids > 0) 1452 { 1453 for (size_t i=0; i<num_thread_ids; ++i) 1454 { 1455 tid_t tid = m_thread_ids[i]; 1456 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false)); 1457 if (!thread_sp) 1458 { 1459 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1460 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1461 log->Printf( 1462 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n", 1463 __FUNCTION__, static_cast<void*>(thread_sp.get()), 1464 thread_sp->GetID()); 1465 } 1466 else 1467 { 1468 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1469 log->Printf( 1470 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n", 1471 __FUNCTION__, static_cast<void*>(thread_sp.get()), 1472 thread_sp->GetID()); 1473 } 1474 new_thread_list.AddThread(thread_sp); 1475 } 1476 } 1477 1478 // Whatever that is left in old_thread_list_copy are not 1479 // present in new_thread_list. Remove non-existent threads from internal id table. 1480 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false); 1481 for (size_t i=0; i<old_num_thread_ids; i++) 1482 { 1483 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false)); 1484 if (old_thread_sp) 1485 { 1486 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID(); 1487 m_thread_id_to_index_id_map.erase(old_thread_id); 1488 } 1489 } 1490 1491 return true; 1492 } 1493 1494 1495 StateType 1496 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 1497 { 1498 stop_packet.SetFilePos (0); 1499 const char stop_type = stop_packet.GetChar(); 1500 switch (stop_type) 1501 { 1502 case 'T': 1503 case 'S': 1504 { 1505 // This is a bit of a hack, but is is required. If we did exec, we 1506 // need to clear our thread lists and also know to rebuild our dynamic 1507 // register info before we lookup and threads and populate the expedited 1508 // register values so we need to know this right away so we can cleanup 1509 // and update our registers. 1510 const uint32_t stop_id = GetStopID(); 1511 if (stop_id == 0) 1512 { 1513 // Our first stop, make sure we have a process ID, and also make 1514 // sure we know about our registers 1515 if (GetID() == LLDB_INVALID_PROCESS_ID) 1516 { 1517 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 1518 if (pid != LLDB_INVALID_PROCESS_ID) 1519 SetID (pid); 1520 } 1521 BuildDynamicRegisterInfo (true); 1522 } 1523 // Stop with signal and thread info 1524 const uint8_t signo = stop_packet.GetHexU8(); 1525 std::string name; 1526 std::string value; 1527 std::string thread_name; 1528 std::string reason; 1529 std::string description; 1530 uint32_t exc_type = 0; 1531 std::vector<addr_t> exc_data; 1532 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 1533 ThreadSP thread_sp; 1534 ThreadGDBRemote *gdb_thread = NULL; 1535 1536 while (stop_packet.GetNameColonValue(name, value)) 1537 { 1538 if (name.compare("metype") == 0) 1539 { 1540 // exception type in big endian hex 1541 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16); 1542 } 1543 else if (name.compare("medata") == 0) 1544 { 1545 // exception data in big endian hex 1546 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16)); 1547 } 1548 else if (name.compare("thread") == 0) 1549 { 1550 // thread in big endian hex 1551 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1552 // m_thread_list_real does have its own mutex, but we need to 1553 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...) 1554 // and the m_thread_list_real.AddThread(...) so it doesn't change on us 1555 Mutex::Locker locker (m_thread_list_real.GetMutex ()); 1556 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false); 1557 1558 if (!thread_sp) 1559 { 1560 // Create the thread if we need to 1561 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1562 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1563 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1564 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n", 1565 __FUNCTION__, 1566 static_cast<void*>(thread_sp.get()), 1567 thread_sp->GetID()); 1568 1569 m_thread_list_real.AddThread(thread_sp); 1570 } 1571 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1572 1573 } 1574 else if (name.compare("threads") == 0) 1575 { 1576 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1577 m_thread_ids.clear(); 1578 // A comma separated list of all threads in the current 1579 // process that includes the thread for this stop reply 1580 // packet 1581 size_t comma_pos; 1582 lldb::tid_t tid; 1583 while ((comma_pos = value.find(',')) != std::string::npos) 1584 { 1585 value[comma_pos] = '\0'; 1586 // thread in big endian hex 1587 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1588 if (tid != LLDB_INVALID_THREAD_ID) 1589 m_thread_ids.push_back (tid); 1590 value.erase(0, comma_pos + 1); 1591 } 1592 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1593 if (tid != LLDB_INVALID_THREAD_ID) 1594 m_thread_ids.push_back (tid); 1595 } 1596 else if (name.compare("hexname") == 0) 1597 { 1598 StringExtractor name_extractor; 1599 // Swap "value" over into "name_extractor" 1600 name_extractor.GetStringRef().swap(value); 1601 // Now convert the HEX bytes into a string value 1602 name_extractor.GetHexByteString (value); 1603 thread_name.swap (value); 1604 } 1605 else if (name.compare("name") == 0) 1606 { 1607 thread_name.swap (value); 1608 } 1609 else if (name.compare("qaddr") == 0) 1610 { 1611 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16); 1612 } 1613 else if (name.compare("reason") == 0) 1614 { 1615 reason.swap(value); 1616 } 1617 else if (name.compare("description") == 0) 1618 { 1619 StringExtractor desc_extractor; 1620 // Swap "value" over into "name_extractor" 1621 desc_extractor.GetStringRef().swap(value); 1622 // Now convert the HEX bytes into a string value 1623 desc_extractor.GetHexByteString (thread_name); 1624 } 1625 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1])) 1626 { 1627 // We have a register number that contains an expedited 1628 // register value. Lets supply this register to our thread 1629 // so it won't have to go and read it. 1630 if (gdb_thread) 1631 { 1632 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16); 1633 1634 if (reg != UINT32_MAX) 1635 { 1636 StringExtractor reg_value_extractor; 1637 // Swap "value" over into "reg_value_extractor" 1638 reg_value_extractor.GetStringRef().swap(value); 1639 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor)) 1640 { 1641 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'", 1642 name.c_str(), 1643 reg, 1644 reg, 1645 reg_value_extractor.GetStringRef().c_str(), 1646 stop_packet.GetStringRef().c_str()); 1647 } 1648 } 1649 } 1650 } 1651 } 1652 1653 // If the response is old style 'S' packet which does not provide us with thread information 1654 // then update the thread list and choose the first one. 1655 if (!thread_sp) 1656 { 1657 UpdateThreadIDList (); 1658 1659 if (!m_thread_ids.empty ()) 1660 { 1661 Mutex::Locker locker (m_thread_list_real.GetMutex ()); 1662 thread_sp = m_thread_list_real.FindThreadByProtocolID (m_thread_ids.front (), false); 1663 if (thread_sp) 1664 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get ()); 1665 } 1666 } 1667 1668 if (thread_sp) 1669 { 1670 // Clear the stop info just in case we don't set it to anything 1671 thread_sp->SetStopInfo (StopInfoSP()); 1672 1673 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1674 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str()); 1675 if (exc_type != 0) 1676 { 1677 const size_t exc_data_size = exc_data.size(); 1678 1679 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp, 1680 exc_type, 1681 exc_data_size, 1682 exc_data_size >= 1 ? exc_data[0] : 0, 1683 exc_data_size >= 2 ? exc_data[1] : 0, 1684 exc_data_size >= 3 ? exc_data[2] : 0)); 1685 } 1686 else 1687 { 1688 bool handled = false; 1689 bool did_exec = false; 1690 if (!reason.empty()) 1691 { 1692 if (reason.compare("trace") == 0) 1693 { 1694 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1695 handled = true; 1696 } 1697 else if (reason.compare("breakpoint") == 0) 1698 { 1699 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1700 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1701 if (bp_site_sp) 1702 { 1703 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1704 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1705 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1706 handled = true; 1707 if (bp_site_sp->ValidForThisThread (thread_sp.get())) 1708 { 1709 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1710 } 1711 else 1712 { 1713 StopInfoSP invalid_stop_info_sp; 1714 thread_sp->SetStopInfo (invalid_stop_info_sp); 1715 } 1716 } 1717 } 1718 else if (reason.compare("trap") == 0) 1719 { 1720 // Let the trap just use the standard signal stop reason below... 1721 } 1722 else if (reason.compare("watchpoint") == 0) 1723 { 1724 break_id_t watch_id = LLDB_INVALID_WATCH_ID; 1725 // TODO: locate the watchpoint somehow... 1726 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id)); 1727 handled = true; 1728 } 1729 else if (reason.compare("exception") == 0) 1730 { 1731 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str())); 1732 handled = true; 1733 } 1734 else if (reason.compare("exec") == 0) 1735 { 1736 did_exec = true; 1737 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp)); 1738 handled = true; 1739 } 1740 } 1741 1742 if (!handled && signo && did_exec == false) 1743 { 1744 if (signo == SIGTRAP) 1745 { 1746 // Currently we are going to assume SIGTRAP means we are either 1747 // hitting a breakpoint or hardware single stepping. 1748 handled = true; 1749 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset; 1750 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1751 1752 if (bp_site_sp) 1753 { 1754 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1755 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1756 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1757 if (bp_site_sp->ValidForThisThread (thread_sp.get())) 1758 { 1759 if(m_breakpoint_pc_offset != 0) 1760 thread_sp->GetRegisterContext()->SetPC(pc); 1761 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1762 } 1763 else 1764 { 1765 StopInfoSP invalid_stop_info_sp; 1766 thread_sp->SetStopInfo (invalid_stop_info_sp); 1767 } 1768 } 1769 else 1770 { 1771 // If we were stepping then assume the stop was the result of the trace. If we were 1772 // not stepping then report the SIGTRAP. 1773 // FIXME: We are still missing the case where we single step over a trap instruction. 1774 if (thread_sp->GetTemporaryResumeState() == eStateStepping) 1775 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1776 else 1777 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo)); 1778 } 1779 } 1780 if (!handled) 1781 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo)); 1782 } 1783 1784 if (!description.empty()) 1785 { 1786 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ()); 1787 if (stop_info_sp) 1788 { 1789 stop_info_sp->SetDescription (description.c_str()); 1790 } 1791 else 1792 { 1793 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str())); 1794 } 1795 } 1796 } 1797 } 1798 return eStateStopped; 1799 } 1800 break; 1801 1802 case 'W': 1803 case 'X': 1804 // process exited 1805 return eStateExited; 1806 1807 default: 1808 break; 1809 } 1810 return eStateInvalid; 1811 } 1812 1813 void 1814 ProcessGDBRemote::RefreshStateAfterStop () 1815 { 1816 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1817 m_thread_ids.clear(); 1818 // Set the thread stop info. It might have a "threads" key whose value is 1819 // a list of all thread IDs in the current process, so m_thread_ids might 1820 // get set. 1821 SetThreadStopInfo (m_last_stop_packet); 1822 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 1823 if (m_thread_ids.empty()) 1824 { 1825 // No, we need to fetch the thread list manually 1826 UpdateThreadIDList(); 1827 } 1828 1829 // Let all threads recover from stopping and do any clean up based 1830 // on the previous thread state (if any). 1831 m_thread_list_real.RefreshStateAfterStop(); 1832 1833 } 1834 1835 Error 1836 ProcessGDBRemote::DoHalt (bool &caused_stop) 1837 { 1838 Error error; 1839 1840 bool timed_out = false; 1841 Mutex::Locker locker; 1842 1843 if (m_public_state.GetValue() == eStateAttaching) 1844 { 1845 // We are being asked to halt during an attach. We need to just close 1846 // our file handle and debugserver will go away, and we can be done... 1847 m_gdb_comm.Disconnect(); 1848 } 1849 else 1850 { 1851 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out)) 1852 { 1853 if (timed_out) 1854 error.SetErrorString("timed out sending interrupt packet"); 1855 else 1856 error.SetErrorString("unknown error sending interrupt packet"); 1857 } 1858 1859 caused_stop = m_gdb_comm.GetInterruptWasSent (); 1860 } 1861 return error; 1862 } 1863 1864 Error 1865 ProcessGDBRemote::DoDetach(bool keep_stopped) 1866 { 1867 Error error; 1868 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1869 if (log) 1870 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 1871 1872 error = m_gdb_comm.Detach (keep_stopped); 1873 if (log) 1874 { 1875 if (error.Success()) 1876 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 1877 else 1878 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>"); 1879 } 1880 1881 if (!error.Success()) 1882 return error; 1883 1884 // Sleep for one second to let the process get all detached... 1885 StopAsyncThread (); 1886 1887 SetPrivateState (eStateDetached); 1888 ResumePrivateStateThread(); 1889 1890 //KillDebugserverProcess (); 1891 return error; 1892 } 1893 1894 1895 Error 1896 ProcessGDBRemote::DoDestroy () 1897 { 1898 Error error; 1899 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1900 if (log) 1901 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1902 1903 // There is a bug in older iOS debugservers where they don't shut down the process 1904 // they are debugging properly. If the process is sitting at a breakpoint or an exception, 1905 // this can cause problems with restarting. So we check to see if any of our threads are stopped 1906 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN 1907 // destroy it again. 1908 // 1909 // Note, we don't have a good way to test the version of debugserver, but I happen to know that 1910 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of 1911 // the debugservers with this bug are equal. There really should be a better way to test this! 1912 // 1913 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and 1914 // get called here to destroy again and we're still at a breakpoint or exception, then we should 1915 // just do the straight-forward kill. 1916 // 1917 // And of course, if we weren't able to stop the process by the time we get here, it isn't 1918 // necessary (or helpful) to do any of this. 1919 1920 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) 1921 { 1922 PlatformSP platform_sp = GetTarget().GetPlatform(); 1923 1924 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 1925 if (platform_sp 1926 && platform_sp->GetName() 1927 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) 1928 { 1929 if (m_destroy_tried_resuming) 1930 { 1931 if (log) 1932 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again."); 1933 } 1934 else 1935 { 1936 // At present, the plans are discarded and the breakpoints disabled Process::Destroy, 1937 // but we really need it to happen here and it doesn't matter if we do it twice. 1938 m_thread_list.DiscardThreadPlans(); 1939 DisableAllBreakpointSites(); 1940 1941 bool stop_looks_like_crash = false; 1942 ThreadList &threads = GetThreadList(); 1943 1944 { 1945 Mutex::Locker locker(threads.GetMutex()); 1946 1947 size_t num_threads = threads.GetSize(); 1948 for (size_t i = 0; i < num_threads; i++) 1949 { 1950 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1951 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 1952 StopReason reason = eStopReasonInvalid; 1953 if (stop_info_sp) 1954 reason = stop_info_sp->GetStopReason(); 1955 if (reason == eStopReasonBreakpoint 1956 || reason == eStopReasonException) 1957 { 1958 if (log) 1959 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.", 1960 thread_sp->GetProtocolID(), 1961 stop_info_sp->GetDescription()); 1962 stop_looks_like_crash = true; 1963 break; 1964 } 1965 } 1966 } 1967 1968 if (stop_looks_like_crash) 1969 { 1970 if (log) 1971 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill."); 1972 m_destroy_tried_resuming = true; 1973 1974 // If we are going to run again before killing, it would be good to suspend all the threads 1975 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with 1976 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do 1977 // have to run the risk of letting those threads proceed a bit. 1978 1979 { 1980 Mutex::Locker locker(threads.GetMutex()); 1981 1982 size_t num_threads = threads.GetSize(); 1983 for (size_t i = 0; i < num_threads; i++) 1984 { 1985 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1986 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 1987 StopReason reason = eStopReasonInvalid; 1988 if (stop_info_sp) 1989 reason = stop_info_sp->GetStopReason(); 1990 if (reason != eStopReasonBreakpoint 1991 && reason != eStopReasonException) 1992 { 1993 if (log) 1994 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.", 1995 thread_sp->GetProtocolID()); 1996 thread_sp->SetResumeState(eStateSuspended); 1997 } 1998 } 1999 } 2000 Resume (); 2001 return Destroy(); 2002 } 2003 } 2004 } 2005 } 2006 2007 // Interrupt if our inferior is running... 2008 int exit_status = SIGABRT; 2009 std::string exit_string; 2010 2011 if (m_gdb_comm.IsConnected()) 2012 { 2013 if (m_public_state.GetValue() != eStateAttaching) 2014 { 2015 2016 StringExtractorGDBRemote response; 2017 bool send_async = true; 2018 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3); 2019 2020 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success) 2021 { 2022 char packet_cmd = response.GetChar(0); 2023 2024 if (packet_cmd == 'W' || packet_cmd == 'X') 2025 { 2026 #if defined(__APPLE__) 2027 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off 2028 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill 2029 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns 2030 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap 2031 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of 2032 // switching ownership back to lldb which was the original parent, and gets confused in the handoff. 2033 // Anyway, so call waitpid here to finally reap it. 2034 PlatformSP platform_sp(GetTarget().GetPlatform()); 2035 if (platform_sp && platform_sp->IsHost()) 2036 { 2037 int status; 2038 ::pid_t reap_pid; 2039 reap_pid = waitpid (GetID(), &status, WNOHANG); 2040 if (log) 2041 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status); 2042 } 2043 #endif 2044 SetLastStopPacket (response); 2045 ClearThreadIDList (); 2046 exit_status = response.GetHexU8(); 2047 } 2048 else 2049 { 2050 if (log) 2051 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str()); 2052 exit_string.assign("got unexpected response to k packet: "); 2053 exit_string.append(response.GetStringRef()); 2054 } 2055 } 2056 else 2057 { 2058 if (log) 2059 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 2060 exit_string.assign("failed to send the k packet"); 2061 } 2062 2063 m_gdb_comm.SetPacketTimeout(old_packet_timeout); 2064 } 2065 else 2066 { 2067 if (log) 2068 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching"); 2069 exit_string.assign ("killed or interrupted while attaching."); 2070 } 2071 } 2072 else 2073 { 2074 // If we missed setting the exit status on the way out, do it here. 2075 // NB set exit status can be called multiple times, the first one sets the status. 2076 exit_string.assign("destroying when not connected to debugserver"); 2077 } 2078 2079 SetExitStatus(exit_status, exit_string.c_str()); 2080 2081 StopAsyncThread (); 2082 KillDebugserverProcess (); 2083 return error; 2084 } 2085 2086 void 2087 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response) 2088 { 2089 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex); 2090 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos; 2091 if (did_exec) 2092 { 2093 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2094 if (log) 2095 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2096 2097 m_thread_list_real.Clear(); 2098 m_thread_list.Clear(); 2099 BuildDynamicRegisterInfo (true); 2100 m_gdb_comm.ResetDiscoverableSettings(); 2101 } 2102 m_last_stop_packet = response; 2103 } 2104 2105 2106 //------------------------------------------------------------------ 2107 // Process Queries 2108 //------------------------------------------------------------------ 2109 2110 bool 2111 ProcessGDBRemote::IsAlive () 2112 { 2113 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 2114 } 2115 2116 addr_t 2117 ProcessGDBRemote::GetImageInfoAddress() 2118 { 2119 return m_gdb_comm.GetShlibInfoAddr(); 2120 } 2121 2122 //------------------------------------------------------------------ 2123 // Process Memory 2124 //------------------------------------------------------------------ 2125 size_t 2126 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2127 { 2128 GetMaxMemorySize (); 2129 if (size > m_max_memory_size) 2130 { 2131 // Keep memory read sizes down to a sane limit. This function will be 2132 // called multiple times in order to complete the task by 2133 // lldb_private::Process so it is ok to do this. 2134 size = m_max_memory_size; 2135 } 2136 2137 char packet[64]; 2138 int packet_len; 2139 bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); 2140 if (binary_memory_read) 2141 { 2142 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size); 2143 } 2144 else 2145 { 2146 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size); 2147 } 2148 assert (packet_len + 1 < (int)sizeof(packet)); 2149 StringExtractorGDBRemote response; 2150 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success) 2151 { 2152 if (response.IsNormalResponse()) 2153 { 2154 error.Clear(); 2155 if (binary_memory_read) 2156 { 2157 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any 2158 // 0x7d character escaping that was present in the packet 2159 2160 size_t data_received_size = response.GetBytesLeft(); 2161 if (data_received_size > size) 2162 { 2163 // Don't write past the end of BUF if the remote debug server gave us too 2164 // much data for some reason. 2165 data_received_size = size; 2166 } 2167 memcpy (buf, response.GetStringRef().data(), data_received_size); 2168 return data_received_size; 2169 } 2170 else 2171 { 2172 return response.GetHexBytes(buf, size, '\xdd'); 2173 } 2174 } 2175 else if (response.IsErrorResponse()) 2176 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2177 else if (response.IsUnsupportedResponse()) 2178 error.SetErrorStringWithFormat("GDB server does not support reading memory"); 2179 else 2180 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str()); 2181 } 2182 else 2183 { 2184 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2185 } 2186 return 0; 2187 } 2188 2189 size_t 2190 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2191 { 2192 GetMaxMemorySize (); 2193 if (size > m_max_memory_size) 2194 { 2195 // Keep memory read sizes down to a sane limit. This function will be 2196 // called multiple times in order to complete the task by 2197 // lldb_private::Process so it is ok to do this. 2198 size = m_max_memory_size; 2199 } 2200 2201 StreamString packet; 2202 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2203 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 2204 StringExtractorGDBRemote response; 2205 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success) 2206 { 2207 if (response.IsOKResponse()) 2208 { 2209 error.Clear(); 2210 return size; 2211 } 2212 else if (response.IsErrorResponse()) 2213 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr); 2214 else if (response.IsUnsupportedResponse()) 2215 error.SetErrorStringWithFormat("GDB server does not support writing memory"); 2216 else 2217 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 2218 } 2219 else 2220 { 2221 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str()); 2222 } 2223 return 0; 2224 } 2225 2226 lldb::addr_t 2227 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 2228 { 2229 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2230 2231 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2232 switch (supported) 2233 { 2234 case eLazyBoolCalculate: 2235 case eLazyBoolYes: 2236 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 2237 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 2238 return allocated_addr; 2239 2240 case eLazyBoolNo: 2241 // Call mmap() to create memory in the inferior.. 2242 unsigned prot = 0; 2243 if (permissions & lldb::ePermissionsReadable) 2244 prot |= eMmapProtRead; 2245 if (permissions & lldb::ePermissionsWritable) 2246 prot |= eMmapProtWrite; 2247 if (permissions & lldb::ePermissionsExecutable) 2248 prot |= eMmapProtExec; 2249 2250 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2251 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2252 m_addr_to_mmap_size[allocated_addr] = size; 2253 else 2254 allocated_addr = LLDB_INVALID_ADDRESS; 2255 break; 2256 } 2257 2258 if (allocated_addr == LLDB_INVALID_ADDRESS) 2259 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions)); 2260 else 2261 error.Clear(); 2262 return allocated_addr; 2263 } 2264 2265 Error 2266 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr, 2267 MemoryRegionInfo ®ion_info) 2268 { 2269 2270 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info)); 2271 return error; 2272 } 2273 2274 Error 2275 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num) 2276 { 2277 2278 Error error (m_gdb_comm.GetWatchpointSupportInfo (num)); 2279 return error; 2280 } 2281 2282 Error 2283 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after) 2284 { 2285 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after)); 2286 return error; 2287 } 2288 2289 Error 2290 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 2291 { 2292 Error error; 2293 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2294 2295 switch (supported) 2296 { 2297 case eLazyBoolCalculate: 2298 // We should never be deallocating memory without allocating memory 2299 // first so we should never get eLazyBoolCalculate 2300 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 2301 break; 2302 2303 case eLazyBoolYes: 2304 if (!m_gdb_comm.DeallocateMemory (addr)) 2305 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 2306 break; 2307 2308 case eLazyBoolNo: 2309 // Call munmap() to deallocate memory in the inferior.. 2310 { 2311 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 2312 if (pos != m_addr_to_mmap_size.end() && 2313 InferiorCallMunmap(this, addr, pos->second)) 2314 m_addr_to_mmap_size.erase (pos); 2315 else 2316 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 2317 } 2318 break; 2319 } 2320 2321 return error; 2322 } 2323 2324 2325 //------------------------------------------------------------------ 2326 // Process STDIO 2327 //------------------------------------------------------------------ 2328 size_t 2329 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 2330 { 2331 if (m_stdio_communication.IsConnected()) 2332 { 2333 ConnectionStatus status; 2334 m_stdio_communication.Write(src, src_len, status, NULL); 2335 } 2336 return 0; 2337 } 2338 2339 Error 2340 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site) 2341 { 2342 Error error; 2343 assert(bp_site != NULL); 2344 2345 // Get logging info 2346 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2347 user_id_t site_id = bp_site->GetID(); 2348 2349 // Get the breakpoint address 2350 const addr_t addr = bp_site->GetLoadAddress(); 2351 2352 // Log that a breakpoint was requested 2353 if (log) 2354 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr); 2355 2356 // Breakpoint already exists and is enabled 2357 if (bp_site->IsEnabled()) 2358 { 2359 if (log) 2360 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 2361 return error; 2362 } 2363 2364 // Get the software breakpoint trap opcode size 2365 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); 2366 2367 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type 2368 // is supported by the remote stub. These are set to true by default, and later set to false 2369 // only after we receive an unimplemented response when sending a breakpoint packet. This means 2370 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will 2371 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which 2372 // indicates if the user specifically asked for hardware breakpoints. If true then we will 2373 // skip over software breakpoints. 2374 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired())) 2375 { 2376 // Try to send off a software breakpoint packet ($Z0) 2377 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 2378 { 2379 // The breakpoint was placed successfully 2380 bp_site->SetEnabled(true); 2381 bp_site->SetType(BreakpointSite::eExternal); 2382 return error; 2383 } 2384 2385 // SendGDBStoppointTypePacket() will return an error if it was unable to set this 2386 // breakpoint. We need to differentiate between a error specific to placing this breakpoint 2387 // or if we have learned that this breakpoint type is unsupported. To do this, we 2388 // must test the support boolean for this breakpoint type to see if it now indicates that 2389 // this breakpoint type is unsupported. If they are still supported then we should return 2390 // with the error code. If they are now unsupported, then we would like to fall through 2391 // and try another form of breakpoint. 2392 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) 2393 return error; 2394 2395 // We reach here when software breakpoints have been found to be unsupported. For future 2396 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is 2397 // known not to be supported. 2398 if (log) 2399 log->Printf("Software breakpoints are unsupported"); 2400 2401 // So we will fall through and try a hardware breakpoint 2402 } 2403 2404 // The process of setting a hardware breakpoint is much the same as above. We check the 2405 // supported boolean for this breakpoint type, and if it is thought to be supported then we 2406 // will try to set this breakpoint with a hardware breakpoint. 2407 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) 2408 { 2409 // Try to send off a hardware breakpoint packet ($Z1) 2410 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 2411 { 2412 // The breakpoint was placed successfully 2413 bp_site->SetEnabled(true); 2414 bp_site->SetType(BreakpointSite::eHardware); 2415 return error; 2416 } 2417 2418 // Check if the error was something other then an unsupported breakpoint type 2419 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) 2420 { 2421 // Unable to set this hardware breakpoint 2422 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)"); 2423 return error; 2424 } 2425 2426 // We will reach here when the stub gives an unsported response to a hardware breakpoint 2427 if (log) 2428 log->Printf("Hardware breakpoints are unsupported"); 2429 2430 // Finally we will falling through to a #trap style breakpoint 2431 } 2432 2433 // Don't fall through when hardware breakpoints were specifically requested 2434 if (bp_site->HardwareRequired()) 2435 { 2436 error.SetErrorString("hardware breakpoints are not supported"); 2437 return error; 2438 } 2439 2440 // As a last resort we want to place a manual breakpoint. An instruction 2441 // is placed into the process memory using memory write packets. 2442 return EnableSoftwareBreakpoint(bp_site); 2443 } 2444 2445 Error 2446 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site) 2447 { 2448 Error error; 2449 assert (bp_site != NULL); 2450 addr_t addr = bp_site->GetLoadAddress(); 2451 user_id_t site_id = bp_site->GetID(); 2452 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2453 if (log) 2454 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr); 2455 2456 if (bp_site->IsEnabled()) 2457 { 2458 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2459 2460 BreakpointSite::Type bp_type = bp_site->GetType(); 2461 switch (bp_type) 2462 { 2463 case BreakpointSite::eSoftware: 2464 error = DisableSoftwareBreakpoint (bp_site); 2465 break; 2466 2467 case BreakpointSite::eHardware: 2468 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size)) 2469 error.SetErrorToGenericError(); 2470 break; 2471 2472 case BreakpointSite::eExternal: 2473 { 2474 GDBStoppointType stoppoint_type; 2475 if (bp_site->IsHardware()) 2476 stoppoint_type = eBreakpointHardware; 2477 else 2478 stoppoint_type = eBreakpointSoftware; 2479 2480 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size)) 2481 error.SetErrorToGenericError(); 2482 } 2483 break; 2484 } 2485 if (error.Success()) 2486 bp_site->SetEnabled(false); 2487 } 2488 else 2489 { 2490 if (log) 2491 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 2492 return error; 2493 } 2494 2495 if (error.Success()) 2496 error.SetErrorToGenericError(); 2497 return error; 2498 } 2499 2500 // Pre-requisite: wp != NULL. 2501 static GDBStoppointType 2502 GetGDBStoppointType (Watchpoint *wp) 2503 { 2504 assert(wp); 2505 bool watch_read = wp->WatchpointRead(); 2506 bool watch_write = wp->WatchpointWrite(); 2507 2508 // watch_read and watch_write cannot both be false. 2509 assert(watch_read || watch_write); 2510 if (watch_read && watch_write) 2511 return eWatchpointReadWrite; 2512 else if (watch_read) 2513 return eWatchpointRead; 2514 else // Must be watch_write, then. 2515 return eWatchpointWrite; 2516 } 2517 2518 Error 2519 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify) 2520 { 2521 Error error; 2522 if (wp) 2523 { 2524 user_id_t watchID = wp->GetID(); 2525 addr_t addr = wp->GetLoadAddress(); 2526 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2527 if (log) 2528 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID); 2529 if (wp->IsEnabled()) 2530 { 2531 if (log) 2532 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr); 2533 return error; 2534 } 2535 2536 GDBStoppointType type = GetGDBStoppointType(wp); 2537 // Pass down an appropriate z/Z packet... 2538 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 2539 { 2540 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 2541 { 2542 wp->SetEnabled(true, notify); 2543 return error; 2544 } 2545 else 2546 error.SetErrorString("sending gdb watchpoint packet failed"); 2547 } 2548 else 2549 error.SetErrorString("watchpoints not supported"); 2550 } 2551 else 2552 { 2553 error.SetErrorString("Watchpoint argument was NULL."); 2554 } 2555 if (error.Success()) 2556 error.SetErrorToGenericError(); 2557 return error; 2558 } 2559 2560 Error 2561 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify) 2562 { 2563 Error error; 2564 if (wp) 2565 { 2566 user_id_t watchID = wp->GetID(); 2567 2568 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2569 2570 addr_t addr = wp->GetLoadAddress(); 2571 2572 if (log) 2573 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr); 2574 2575 if (!wp->IsEnabled()) 2576 { 2577 if (log) 2578 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 2579 // See also 'class WatchpointSentry' within StopInfo.cpp. 2580 // This disabling attempt might come from the user-supplied actions, we'll route it in order for 2581 // the watchpoint object to intelligently process this action. 2582 wp->SetEnabled(false, notify); 2583 return error; 2584 } 2585 2586 if (wp->IsHardware()) 2587 { 2588 GDBStoppointType type = GetGDBStoppointType(wp); 2589 // Pass down an appropriate z/Z packet... 2590 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 2591 { 2592 wp->SetEnabled(false, notify); 2593 return error; 2594 } 2595 else 2596 error.SetErrorString("sending gdb watchpoint packet failed"); 2597 } 2598 // TODO: clear software watchpoints if we implement them 2599 } 2600 else 2601 { 2602 error.SetErrorString("Watchpoint argument was NULL."); 2603 } 2604 if (error.Success()) 2605 error.SetErrorToGenericError(); 2606 return error; 2607 } 2608 2609 void 2610 ProcessGDBRemote::Clear() 2611 { 2612 m_flags = 0; 2613 m_thread_list_real.Clear(); 2614 m_thread_list.Clear(); 2615 } 2616 2617 Error 2618 ProcessGDBRemote::DoSignal (int signo) 2619 { 2620 Error error; 2621 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2622 if (log) 2623 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 2624 2625 if (!m_gdb_comm.SendAsyncSignal (signo)) 2626 error.SetErrorStringWithFormat("failed to send signal %i", signo); 2627 return error; 2628 } 2629 2630 Error 2631 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info) 2632 { 2633 Error error; 2634 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 2635 { 2636 // If we locate debugserver, keep that located version around 2637 static FileSpec g_debugserver_file_spec; 2638 2639 ProcessLaunchInfo debugserver_launch_info; 2640 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false); 2641 debugserver_launch_info.SetUserID(process_info.GetUserID()); 2642 2643 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__)) 2644 // On iOS, still do a local connection using a random port 2645 const char *hostname = "127.0.0.1"; 2646 uint16_t port = get_random_port (); 2647 #else 2648 // Set hostname being NULL to do the reverse connect where debugserver 2649 // will bind to port zero and it will communicate back to us the port 2650 // that we will connect to 2651 const char *hostname = NULL; 2652 uint16_t port = 0; 2653 #endif 2654 2655 error = m_gdb_comm.StartDebugserverProcess (hostname, 2656 port, 2657 debugserver_launch_info, 2658 port); 2659 2660 if (error.Success ()) 2661 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 2662 else 2663 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2664 2665 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2666 StartAsyncThread (); 2667 2668 if (error.Fail()) 2669 { 2670 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2671 2672 if (log) 2673 log->Printf("failed to start debugserver process: %s", error.AsCString()); 2674 return error; 2675 } 2676 2677 if (m_gdb_comm.IsConnected()) 2678 { 2679 // Finish the connection process by doing the handshake without connecting (send NULL URL) 2680 ConnectToDebugserver (NULL); 2681 } 2682 else 2683 { 2684 StreamString connect_url; 2685 connect_url.Printf("connect://%s:%u", hostname, port); 2686 error = ConnectToDebugserver (connect_url.GetString().c_str()); 2687 } 2688 2689 } 2690 return error; 2691 } 2692 2693 bool 2694 ProcessGDBRemote::MonitorDebugserverProcess 2695 ( 2696 void *callback_baton, 2697 lldb::pid_t debugserver_pid, 2698 bool exited, // True if the process did exit 2699 int signo, // Zero for no signal 2700 int exit_status // Exit value of process if signal is zero 2701 ) 2702 { 2703 // The baton is a "ProcessGDBRemote *". Now this class might be gone 2704 // and might not exist anymore, so we need to carefully try to get the 2705 // target for this process first since we have a race condition when 2706 // we are done running between getting the notice that the inferior 2707 // process has died and the debugserver that was debugging this process. 2708 // In our test suite, we are also continually running process after 2709 // process, so we must be very careful to make sure: 2710 // 1 - process object hasn't been deleted already 2711 // 2 - that a new process object hasn't been recreated in its place 2712 2713 // "debugserver_pid" argument passed in is the process ID for 2714 // debugserver that we are tracking... 2715 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2716 2717 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 2718 2719 // Get a shared pointer to the target that has a matching process pointer. 2720 // This target could be gone, or the target could already have a new process 2721 // object inside of it 2722 TargetSP target_sp (Debugger::FindTargetWithProcess(process)); 2723 2724 if (log) 2725 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 2726 2727 if (target_sp) 2728 { 2729 // We found a process in a target that matches, but another thread 2730 // might be in the process of launching a new process that will 2731 // soon replace it, so get a shared pointer to the process so we 2732 // can keep it alive. 2733 ProcessSP process_sp (target_sp->GetProcessSP()); 2734 // Now we have a shared pointer to the process that can't go away on us 2735 // so we now make sure it was the same as the one passed in, and also make 2736 // sure that our previous "process *" didn't get deleted and have a new 2737 // "process *" created in its place with the same pointer. To verify this 2738 // we make sure the process has our debugserver process ID. If we pass all 2739 // of these tests, then we are sure that this process is the one we were 2740 // looking for. 2741 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid) 2742 { 2743 // Sleep for a half a second to make sure our inferior process has 2744 // time to set its exit status before we set it incorrectly when 2745 // both the debugserver and the inferior process shut down. 2746 usleep (500000); 2747 // If our process hasn't yet exited, debugserver might have died. 2748 // If the process did exit, the we are reaping it. 2749 const StateType state = process->GetState(); 2750 2751 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 2752 state != eStateInvalid && 2753 state != eStateUnloaded && 2754 state != eStateExited && 2755 state != eStateDetached) 2756 { 2757 char error_str[1024]; 2758 if (signo) 2759 { 2760 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo); 2761 if (signal_cstr) 2762 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 2763 else 2764 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 2765 } 2766 else 2767 { 2768 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 2769 } 2770 2771 process->SetExitStatus (-1, error_str); 2772 } 2773 // Debugserver has exited we need to let our ProcessGDBRemote 2774 // know that it no longer has a debugserver instance 2775 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2776 } 2777 } 2778 return true; 2779 } 2780 2781 void 2782 ProcessGDBRemote::KillDebugserverProcess () 2783 { 2784 m_gdb_comm.Disconnect(); 2785 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2786 { 2787 Host::Kill (m_debugserver_pid, SIGINT); 2788 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2789 } 2790 } 2791 2792 void 2793 ProcessGDBRemote::Initialize() 2794 { 2795 static bool g_initialized = false; 2796 2797 if (g_initialized == false) 2798 { 2799 g_initialized = true; 2800 PluginManager::RegisterPlugin (GetPluginNameStatic(), 2801 GetPluginDescriptionStatic(), 2802 CreateInstance, 2803 DebuggerInitialize); 2804 2805 Log::Callbacks log_callbacks = { 2806 ProcessGDBRemoteLog::DisableLog, 2807 ProcessGDBRemoteLog::EnableLog, 2808 ProcessGDBRemoteLog::ListLogCategories 2809 }; 2810 2811 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 2812 } 2813 } 2814 2815 void 2816 ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger) 2817 { 2818 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName())) 2819 { 2820 const bool is_global_setting = true; 2821 PluginManager::CreateSettingForProcessPlugin (debugger, 2822 GetGlobalPluginProperties()->GetValueProperties(), 2823 ConstString ("Properties for the gdb-remote process plug-in."), 2824 is_global_setting); 2825 } 2826 } 2827 2828 bool 2829 ProcessGDBRemote::StartAsyncThread () 2830 { 2831 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2832 2833 if (log) 2834 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2835 2836 Mutex::Locker start_locker(m_async_thread_state_mutex); 2837 if (m_async_thread_state == eAsyncThreadNotStarted) 2838 { 2839 // Create a thread that watches our internal state and controls which 2840 // events make it to clients (into the DCProcess event queue). 2841 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2842 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2843 { 2844 m_async_thread_state = eAsyncThreadRunning; 2845 return true; 2846 } 2847 else 2848 return false; 2849 } 2850 else 2851 { 2852 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and 2853 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it. 2854 if (log) 2855 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state); 2856 if (m_async_thread_state == eAsyncThreadRunning) 2857 return true; 2858 else 2859 return false; 2860 } 2861 } 2862 2863 void 2864 ProcessGDBRemote::StopAsyncThread () 2865 { 2866 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2867 2868 if (log) 2869 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2870 2871 Mutex::Locker start_locker(m_async_thread_state_mutex); 2872 if (m_async_thread_state == eAsyncThreadRunning) 2873 { 2874 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2875 2876 // This will shut down the async thread. 2877 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 2878 2879 // Stop the stdio thread 2880 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2881 { 2882 Host::ThreadJoin (m_async_thread, NULL, NULL); 2883 } 2884 m_async_thread_state = eAsyncThreadDone; 2885 } 2886 else 2887 { 2888 if (log) 2889 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state); 2890 } 2891 } 2892 2893 2894 thread_result_t 2895 ProcessGDBRemote::AsyncThread (void *arg) 2896 { 2897 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2898 2899 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2900 if (log) 2901 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID()); 2902 2903 Listener listener ("ProcessGDBRemote::AsyncThread"); 2904 EventSP event_sp; 2905 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2906 eBroadcastBitAsyncThreadShouldExit; 2907 2908 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2909 { 2910 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit); 2911 2912 bool done = false; 2913 while (!done) 2914 { 2915 if (log) 2916 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2917 if (listener.WaitForEvent (NULL, event_sp)) 2918 { 2919 const uint32_t event_type = event_sp->GetType(); 2920 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 2921 { 2922 if (log) 2923 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 2924 2925 switch (event_type) 2926 { 2927 case eBroadcastBitAsyncContinue: 2928 { 2929 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2930 2931 if (continue_packet) 2932 { 2933 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2934 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2935 if (log) 2936 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2937 2938 if (::strstr (continue_cstr, "vAttach") == NULL) 2939 process->SetPrivateState(eStateRunning); 2940 StringExtractorGDBRemote response; 2941 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2942 2943 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads. 2944 // The thread ID list might be contained within the "response", or the stop reply packet that 2945 // caused the stop. So clear it now before we give the stop reply packet to the process 2946 // using the process->SetLastStopPacket()... 2947 process->ClearThreadIDList (); 2948 2949 switch (stop_state) 2950 { 2951 case eStateStopped: 2952 case eStateCrashed: 2953 case eStateSuspended: 2954 process->SetLastStopPacket (response); 2955 process->SetPrivateState (stop_state); 2956 break; 2957 2958 case eStateExited: 2959 { 2960 process->SetLastStopPacket (response); 2961 process->ClearThreadIDList(); 2962 response.SetFilePos(1); 2963 2964 int exit_status = response.GetHexU8(); 2965 const char *desc_cstr = NULL; 2966 StringExtractor extractor; 2967 std::string desc_string; 2968 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') 2969 { 2970 std::string desc_token; 2971 while (response.GetNameColonValue (desc_token, desc_string)) 2972 { 2973 if (desc_token == "description") 2974 { 2975 extractor.GetStringRef().swap(desc_string); 2976 extractor.SetFilePos(0); 2977 extractor.GetHexByteString (desc_string); 2978 desc_cstr = desc_string.c_str(); 2979 } 2980 } 2981 } 2982 process->SetExitStatus(exit_status, desc_cstr); 2983 done = true; 2984 break; 2985 } 2986 case eStateInvalid: 2987 process->SetExitStatus(-1, "lost connection"); 2988 break; 2989 2990 default: 2991 process->SetPrivateState (stop_state); 2992 break; 2993 } 2994 } 2995 } 2996 break; 2997 2998 case eBroadcastBitAsyncThreadShouldExit: 2999 if (log) 3000 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 3001 done = true; 3002 break; 3003 3004 default: 3005 if (log) 3006 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 3007 done = true; 3008 break; 3009 } 3010 } 3011 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 3012 { 3013 if (event_type & Communication::eBroadcastBitReadThreadDidExit) 3014 { 3015 process->SetExitStatus (-1, "lost connection"); 3016 done = true; 3017 } 3018 } 3019 } 3020 else 3021 { 3022 if (log) 3023 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 3024 done = true; 3025 } 3026 } 3027 } 3028 3029 if (log) 3030 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID()); 3031 3032 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 3033 return NULL; 3034 } 3035 3036 //uint32_t 3037 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 3038 //{ 3039 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 3040 // // process and ask it for the list of processes. But if we are local, we can let the Host do it. 3041 // if (m_local_debugserver) 3042 // { 3043 // return Host::ListProcessesMatchingName (name, matches, pids); 3044 // } 3045 // else 3046 // { 3047 // // FIXME: Implement talking to the remote debugserver. 3048 // return 0; 3049 // } 3050 // 3051 //} 3052 // 3053 bool 3054 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 3055 lldb_private::StoppointCallbackContext *context, 3056 lldb::user_id_t break_id, 3057 lldb::user_id_t break_loc_id) 3058 { 3059 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 3060 // run so I can stop it if that's what I want to do. 3061 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3062 if (log) 3063 log->Printf("Hit New Thread Notification breakpoint."); 3064 return false; 3065 } 3066 3067 3068 bool 3069 ProcessGDBRemote::StartNoticingNewThreads() 3070 { 3071 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3072 if (m_thread_create_bp_sp) 3073 { 3074 if (log && log->GetVerbose()) 3075 log->Printf("Enabled noticing new thread breakpoint."); 3076 m_thread_create_bp_sp->SetEnabled(true); 3077 } 3078 else 3079 { 3080 PlatformSP platform_sp (m_target.GetPlatform()); 3081 if (platform_sp) 3082 { 3083 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target); 3084 if (m_thread_create_bp_sp) 3085 { 3086 if (log && log->GetVerbose()) 3087 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); 3088 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3089 } 3090 else 3091 { 3092 if (log) 3093 log->Printf("Failed to create new thread notification breakpoint."); 3094 } 3095 } 3096 } 3097 return m_thread_create_bp_sp.get() != NULL; 3098 } 3099 3100 bool 3101 ProcessGDBRemote::StopNoticingNewThreads() 3102 { 3103 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3104 if (log && log->GetVerbose()) 3105 log->Printf ("Disabling new thread notification breakpoint."); 3106 3107 if (m_thread_create_bp_sp) 3108 m_thread_create_bp_sp->SetEnabled(false); 3109 3110 return true; 3111 } 3112 3113 lldb_private::DynamicLoader * 3114 ProcessGDBRemote::GetDynamicLoader () 3115 { 3116 if (m_dyld_ap.get() == NULL) 3117 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 3118 return m_dyld_ap.get(); 3119 } 3120 3121 Error 3122 ProcessGDBRemote::SendEventData(const char *data) 3123 { 3124 int return_value; 3125 bool was_supported; 3126 3127 Error error; 3128 3129 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported); 3130 if (return_value != 0) 3131 { 3132 if (!was_supported) 3133 error.SetErrorString("Sending events is not supported for this process."); 3134 else 3135 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value); 3136 } 3137 return error; 3138 } 3139 3140 const DataBufferSP 3141 ProcessGDBRemote::GetAuxvData() 3142 { 3143 DataBufferSP buf; 3144 if (m_gdb_comm.GetQXferAuxvReadSupported()) 3145 { 3146 std::string response_string; 3147 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success) 3148 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length())); 3149 } 3150 return buf; 3151 } 3152 3153 StructuredData::ObjectSP 3154 ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid) 3155 { 3156 StructuredData::ObjectSP object_sp; 3157 3158 if (m_gdb_comm.GetThreadExtendedInfoSupported()) 3159 { 3160 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); 3161 SystemRuntime *runtime = GetSystemRuntime(); 3162 if (runtime) 3163 { 3164 runtime->AddThreadExtendedInfoPacketHints (args_dict); 3165 } 3166 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid); 3167 3168 StreamString packet; 3169 packet << "jThreadExtendedInfo:"; 3170 args_dict->Dump (packet); 3171 3172 // FIXME the final character of a JSON dictionary, '}', is the escape 3173 // character in gdb-remote binary mode. lldb currently doesn't escape 3174 // these characters in its packet output -- so we add the quoted version 3175 // of the } character here manually in case we talk to a debugserver which 3176 // un-escapes the chracters at packet read time. 3177 packet << (char) (0x7d ^ 0x20); 3178 3179 StringExtractorGDBRemote response; 3180 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success) 3181 { 3182 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); 3183 if (response_type == StringExtractorGDBRemote::eResponse) 3184 { 3185 if (!response.Empty()) 3186 { 3187 // The packet has already had the 0x7d xor quoting stripped out at the 3188 // GDBRemoteCommunication packet receive level. 3189 object_sp = StructuredData::ParseJSON (response.GetStringRef()); 3190 } 3191 } 3192 } 3193 } 3194 return object_sp; 3195 } 3196 3197 // Establish the largest memory read/write payloads we should use. 3198 // If the remote stub has a max packet size, stay under that size. 3199 // 3200 // If the remote stub's max packet size is crazy large, use a 3201 // reasonable largeish default. 3202 // 3203 // If the remote stub doesn't advertise a max packet size, use a 3204 // conservative default. 3205 3206 void 3207 ProcessGDBRemote::GetMaxMemorySize() 3208 { 3209 const uint64_t reasonable_largeish_default = 128 * 1024; 3210 const uint64_t conservative_default = 512; 3211 3212 if (m_max_memory_size == 0) 3213 { 3214 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); 3215 if (stub_max_size != UINT64_MAX && stub_max_size != 0) 3216 { 3217 // Save the stub's claimed maximum packet size 3218 m_remote_stub_max_memory_size = stub_max_size; 3219 3220 // Even if the stub says it can support ginormous packets, 3221 // don't exceed our resonable largeish default packet size. 3222 if (stub_max_size > reasonable_largeish_default) 3223 { 3224 stub_max_size = reasonable_largeish_default; 3225 } 3226 3227 m_max_memory_size = stub_max_size; 3228 } 3229 else 3230 { 3231 m_max_memory_size = conservative_default; 3232 } 3233 } 3234 } 3235 3236 void 3237 ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max) 3238 { 3239 if (user_specified_max != 0) 3240 { 3241 GetMaxMemorySize (); 3242 3243 if (m_remote_stub_max_memory_size != 0) 3244 { 3245 if (m_remote_stub_max_memory_size < user_specified_max) 3246 { 3247 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big 3248 // as the remote stub says we can go. 3249 } 3250 else 3251 { 3252 m_max_memory_size = user_specified_max; // user's packet size is good 3253 } 3254 } 3255 else 3256 { 3257 m_max_memory_size = user_specified_max; // user's packet size is probably fine 3258 } 3259 } 3260 } 3261 3262 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed 3263 { 3264 private: 3265 3266 public: 3267 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) : 3268 CommandObjectParsed (interpreter, 3269 "process plugin packet history", 3270 "Dumps the packet history buffer. ", 3271 NULL) 3272 { 3273 } 3274 3275 ~CommandObjectProcessGDBRemotePacketHistory () 3276 { 3277 } 3278 3279 bool 3280 DoExecute (Args& command, CommandReturnObject &result) 3281 { 3282 const size_t argc = command.GetArgumentCount(); 3283 if (argc == 0) 3284 { 3285 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3286 if (process) 3287 { 3288 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 3289 result.SetStatus (eReturnStatusSuccessFinishResult); 3290 return true; 3291 } 3292 } 3293 else 3294 { 3295 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str()); 3296 } 3297 result.SetStatus (eReturnStatusFailed); 3298 return false; 3299 } 3300 }; 3301 3302 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed 3303 { 3304 private: 3305 3306 public: 3307 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) : 3308 CommandObjectParsed (interpreter, 3309 "process plugin packet xfer-size", 3310 "Maximum size that lldb will try to read/write one one chunk.", 3311 NULL) 3312 { 3313 } 3314 3315 ~CommandObjectProcessGDBRemotePacketXferSize () 3316 { 3317 } 3318 3319 bool 3320 DoExecute (Args& command, CommandReturnObject &result) 3321 { 3322 const size_t argc = command.GetArgumentCount(); 3323 if (argc == 0) 3324 { 3325 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str()); 3326 result.SetStatus (eReturnStatusFailed); 3327 return false; 3328 } 3329 3330 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3331 if (process) 3332 { 3333 const char *packet_size = command.GetArgumentAtIndex(0); 3334 errno = 0; 3335 uint64_t user_specified_max = strtoul (packet_size, NULL, 10); 3336 if (errno == 0 && user_specified_max != 0) 3337 { 3338 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max); 3339 result.SetStatus (eReturnStatusSuccessFinishResult); 3340 return true; 3341 } 3342 } 3343 result.SetStatus (eReturnStatusFailed); 3344 return false; 3345 } 3346 }; 3347 3348 3349 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed 3350 { 3351 private: 3352 3353 public: 3354 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) : 3355 CommandObjectParsed (interpreter, 3356 "process plugin packet send", 3357 "Send a custom packet through the GDB remote protocol and print the answer. " 3358 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.", 3359 NULL) 3360 { 3361 } 3362 3363 ~CommandObjectProcessGDBRemotePacketSend () 3364 { 3365 } 3366 3367 bool 3368 DoExecute (Args& command, CommandReturnObject &result) 3369 { 3370 const size_t argc = command.GetArgumentCount(); 3371 if (argc == 0) 3372 { 3373 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str()); 3374 result.SetStatus (eReturnStatusFailed); 3375 return false; 3376 } 3377 3378 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3379 if (process) 3380 { 3381 for (size_t i=0; i<argc; ++ i) 3382 { 3383 const char *packet_cstr = command.GetArgumentAtIndex(0); 3384 bool send_async = true; 3385 StringExtractorGDBRemote response; 3386 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 3387 result.SetStatus (eReturnStatusSuccessFinishResult); 3388 Stream &output_strm = result.GetOutputStream(); 3389 output_strm.Printf (" packet: %s\n", packet_cstr); 3390 std::string &response_str = response.GetStringRef(); 3391 3392 if (strstr(packet_cstr, "qGetProfileData") != NULL) 3393 { 3394 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response); 3395 } 3396 3397 if (response_str.empty()) 3398 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 3399 else 3400 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 3401 } 3402 } 3403 return true; 3404 } 3405 }; 3406 3407 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw 3408 { 3409 private: 3410 3411 public: 3412 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) : 3413 CommandObjectRaw (interpreter, 3414 "process plugin packet monitor", 3415 "Send a qRcmd packet through the GDB remote protocol and print the response." 3416 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.", 3417 NULL) 3418 { 3419 } 3420 3421 ~CommandObjectProcessGDBRemotePacketMonitor () 3422 { 3423 } 3424 3425 bool 3426 DoExecute (const char *command, CommandReturnObject &result) 3427 { 3428 if (command == NULL || command[0] == '\0') 3429 { 3430 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str()); 3431 result.SetStatus (eReturnStatusFailed); 3432 return false; 3433 } 3434 3435 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3436 if (process) 3437 { 3438 StreamString packet; 3439 packet.PutCString("qRcmd,"); 3440 packet.PutBytesAsRawHex8(command, strlen(command)); 3441 const char *packet_cstr = packet.GetString().c_str(); 3442 3443 bool send_async = true; 3444 StringExtractorGDBRemote response; 3445 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 3446 result.SetStatus (eReturnStatusSuccessFinishResult); 3447 Stream &output_strm = result.GetOutputStream(); 3448 output_strm.Printf (" packet: %s\n", packet_cstr); 3449 const std::string &response_str = response.GetStringRef(); 3450 3451 if (response_str.empty()) 3452 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 3453 else 3454 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 3455 } 3456 return true; 3457 } 3458 }; 3459 3460 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword 3461 { 3462 private: 3463 3464 public: 3465 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) : 3466 CommandObjectMultiword (interpreter, 3467 "process plugin packet", 3468 "Commands that deal with GDB remote packets.", 3469 NULL) 3470 { 3471 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter))); 3472 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter))); 3473 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter))); 3474 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter))); 3475 } 3476 3477 ~CommandObjectProcessGDBRemotePacket () 3478 { 3479 } 3480 }; 3481 3482 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword 3483 { 3484 public: 3485 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) : 3486 CommandObjectMultiword (interpreter, 3487 "process plugin", 3488 "A set of commands for operating on a ProcessGDBRemote process.", 3489 "process plugin <subcommand> [<subcommand-options>]") 3490 { 3491 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter))); 3492 } 3493 3494 ~CommandObjectMultiwordProcessGDBRemote () 3495 { 3496 } 3497 }; 3498 3499 CommandObject * 3500 ProcessGDBRemote::GetPluginCommandObject() 3501 { 3502 if (!m_command_sp) 3503 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter())); 3504 return m_command_sp.get(); 3505 } 3506