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