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