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