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