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