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.GetArguments().GetConstArgumentVector()); 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 void 1162 ProcessGDBRemote::DidAttach () 1163 { 1164 DidLaunchOrAttach (); 1165 } 1166 1167 1168 Error 1169 ProcessGDBRemote::WillResume () 1170 { 1171 m_continue_c_tids.clear(); 1172 m_continue_C_tids.clear(); 1173 m_continue_s_tids.clear(); 1174 m_continue_S_tids.clear(); 1175 return Error(); 1176 } 1177 1178 Error 1179 ProcessGDBRemote::DoResume () 1180 { 1181 Error error; 1182 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 1183 if (log) 1184 log->Printf ("ProcessGDBRemote::Resume()"); 1185 1186 Listener listener ("gdb-remote.resume-packet-sent"); 1187 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) 1188 { 1189 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); 1190 1191 const size_t num_threads = GetThreadList().GetSize(); 1192 1193 StreamString continue_packet; 1194 bool continue_packet_error = false; 1195 if (m_gdb_comm.HasAnyVContSupport ()) 1196 { 1197 if (m_continue_c_tids.size() == num_threads) 1198 { 1199 // All threads are continuing, just send a "c" packet 1200 continue_packet.PutCString ("c"); 1201 } 1202 else 1203 { 1204 continue_packet.PutCString ("vCont"); 1205 1206 if (!m_continue_c_tids.empty()) 1207 { 1208 if (m_gdb_comm.GetVContSupported ('c')) 1209 { 1210 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) 1211 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos); 1212 } 1213 else 1214 continue_packet_error = true; 1215 } 1216 1217 if (!continue_packet_error && !m_continue_C_tids.empty()) 1218 { 1219 if (m_gdb_comm.GetVContSupported ('C')) 1220 { 1221 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) 1222 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); 1223 } 1224 else 1225 continue_packet_error = true; 1226 } 1227 1228 if (!continue_packet_error && !m_continue_s_tids.empty()) 1229 { 1230 if (m_gdb_comm.GetVContSupported ('s')) 1231 { 1232 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) 1233 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos); 1234 } 1235 else 1236 continue_packet_error = true; 1237 } 1238 1239 if (!continue_packet_error && !m_continue_S_tids.empty()) 1240 { 1241 if (m_gdb_comm.GetVContSupported ('S')) 1242 { 1243 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) 1244 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); 1245 } 1246 else 1247 continue_packet_error = true; 1248 } 1249 1250 if (continue_packet_error) 1251 continue_packet.GetString().clear(); 1252 } 1253 } 1254 else 1255 continue_packet_error = true; 1256 1257 if (continue_packet_error) 1258 { 1259 // Either no vCont support, or we tried to use part of the vCont 1260 // packet that wasn't supported by the remote GDB server. 1261 // We need to try and make a simple packet that can do our continue 1262 const size_t num_continue_c_tids = m_continue_c_tids.size(); 1263 const size_t num_continue_C_tids = m_continue_C_tids.size(); 1264 const size_t num_continue_s_tids = m_continue_s_tids.size(); 1265 const size_t num_continue_S_tids = m_continue_S_tids.size(); 1266 if (num_continue_c_tids > 0) 1267 { 1268 if (num_continue_c_tids == num_threads) 1269 { 1270 // All threads are resuming... 1271 m_gdb_comm.SetCurrentThreadForRun (-1); 1272 continue_packet.PutChar ('c'); 1273 continue_packet_error = false; 1274 } 1275 else if (num_continue_c_tids == 1 && 1276 num_continue_C_tids == 0 && 1277 num_continue_s_tids == 0 && 1278 num_continue_S_tids == 0 ) 1279 { 1280 // Only one thread is continuing 1281 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front()); 1282 continue_packet.PutChar ('c'); 1283 continue_packet_error = false; 1284 } 1285 } 1286 1287 if (continue_packet_error && num_continue_C_tids > 0) 1288 { 1289 if ((num_continue_C_tids + num_continue_c_tids) == num_threads && 1290 num_continue_C_tids > 0 && 1291 num_continue_s_tids == 0 && 1292 num_continue_S_tids == 0 ) 1293 { 1294 const int continue_signo = m_continue_C_tids.front().second; 1295 // Only one thread is continuing 1296 if (num_continue_C_tids > 1) 1297 { 1298 // More that one thread with a signal, yet we don't have 1299 // vCont support and we are being asked to resume each 1300 // thread with a signal, we need to make sure they are 1301 // all the same signal, or we can't issue the continue 1302 // accurately with the current support... 1303 if (num_continue_C_tids > 1) 1304 { 1305 continue_packet_error = false; 1306 for (size_t i=1; i<m_continue_C_tids.size(); ++i) 1307 { 1308 if (m_continue_C_tids[i].second != continue_signo) 1309 continue_packet_error = true; 1310 } 1311 } 1312 if (!continue_packet_error) 1313 m_gdb_comm.SetCurrentThreadForRun (-1); 1314 } 1315 else 1316 { 1317 // Set the continue thread ID 1318 continue_packet_error = false; 1319 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first); 1320 } 1321 if (!continue_packet_error) 1322 { 1323 // Add threads continuing with the same signo... 1324 continue_packet.Printf("C%2.2x", continue_signo); 1325 } 1326 } 1327 } 1328 1329 if (continue_packet_error && num_continue_s_tids > 0) 1330 { 1331 if (num_continue_s_tids == num_threads) 1332 { 1333 // All threads are resuming... 1334 m_gdb_comm.SetCurrentThreadForRun (-1); 1335 continue_packet.PutChar ('s'); 1336 continue_packet_error = false; 1337 } 1338 else if (num_continue_c_tids == 0 && 1339 num_continue_C_tids == 0 && 1340 num_continue_s_tids == 1 && 1341 num_continue_S_tids == 0 ) 1342 { 1343 // Only one thread is stepping 1344 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front()); 1345 continue_packet.PutChar ('s'); 1346 continue_packet_error = false; 1347 } 1348 } 1349 1350 if (!continue_packet_error && num_continue_S_tids > 0) 1351 { 1352 if (num_continue_S_tids == num_threads) 1353 { 1354 const int step_signo = m_continue_S_tids.front().second; 1355 // Are all threads trying to step with the same signal? 1356 continue_packet_error = false; 1357 if (num_continue_S_tids > 1) 1358 { 1359 for (size_t i=1; i<num_threads; ++i) 1360 { 1361 if (m_continue_S_tids[i].second != step_signo) 1362 continue_packet_error = true; 1363 } 1364 } 1365 if (!continue_packet_error) 1366 { 1367 // Add threads stepping with the same signo... 1368 m_gdb_comm.SetCurrentThreadForRun (-1); 1369 continue_packet.Printf("S%2.2x", step_signo); 1370 } 1371 } 1372 else if (num_continue_c_tids == 0 && 1373 num_continue_C_tids == 0 && 1374 num_continue_s_tids == 0 && 1375 num_continue_S_tids == 1 ) 1376 { 1377 // Only one thread is stepping with signal 1378 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first); 1379 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); 1380 continue_packet_error = false; 1381 } 1382 } 1383 } 1384 1385 if (continue_packet_error) 1386 { 1387 error.SetErrorString ("can't make continue packet for this resume"); 1388 } 1389 else 1390 { 1391 EventSP event_sp; 1392 TimeValue timeout; 1393 timeout = TimeValue::Now(); 1394 timeout.OffsetWithSeconds (5); 1395 if (!IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 1396 { 1397 error.SetErrorString ("Trying to resume but the async thread is dead."); 1398 if (log) 1399 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead."); 1400 return error; 1401 } 1402 1403 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize())); 1404 1405 if (listener.WaitForEvent (&timeout, event_sp) == false) 1406 { 1407 error.SetErrorString("Resume timed out."); 1408 if (log) 1409 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out."); 1410 } 1411 else if (event_sp->BroadcasterIs (&m_async_broadcaster)) 1412 { 1413 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back."); 1414 if (log) 1415 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back."); 1416 return error; 1417 } 1418 } 1419 } 1420 1421 return error; 1422 } 1423 1424 void 1425 ProcessGDBRemote::ClearThreadIDList () 1426 { 1427 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1428 m_thread_ids.clear(); 1429 } 1430 1431 bool 1432 ProcessGDBRemote::UpdateThreadIDList () 1433 { 1434 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1435 bool sequence_mutex_unavailable = false; 1436 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable); 1437 if (sequence_mutex_unavailable) 1438 { 1439 return false; // We just didn't get the list 1440 } 1441 return true; 1442 } 1443 1444 bool 1445 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) 1446 { 1447 // locker will keep a mutex locked until it goes out of scope 1448 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1449 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1450 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID()); 1451 1452 size_t num_thread_ids = m_thread_ids.size(); 1453 // The "m_thread_ids" thread ID list should always be updated after each stop 1454 // reply packet, but in case it isn't, update it here. 1455 if (num_thread_ids == 0) 1456 { 1457 if (!UpdateThreadIDList ()) 1458 return false; 1459 num_thread_ids = m_thread_ids.size(); 1460 } 1461 1462 ThreadList old_thread_list_copy(old_thread_list); 1463 if (num_thread_ids > 0) 1464 { 1465 for (size_t i=0; i<num_thread_ids; ++i) 1466 { 1467 tid_t tid = m_thread_ids[i]; 1468 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false)); 1469 if (!thread_sp) 1470 { 1471 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1472 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1473 log->Printf( 1474 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n", 1475 __FUNCTION__, 1476 thread_sp.get(), 1477 thread_sp->GetID()); 1478 } 1479 else 1480 { 1481 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1482 log->Printf( 1483 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n", 1484 __FUNCTION__, 1485 thread_sp.get(), 1486 thread_sp->GetID()); 1487 } 1488 new_thread_list.AddThread(thread_sp); 1489 } 1490 } 1491 1492 // Whatever that is left in old_thread_list_copy are not 1493 // present in new_thread_list. Remove non-existent threads from internal id table. 1494 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false); 1495 for (size_t i=0; i<old_num_thread_ids; i++) 1496 { 1497 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false)); 1498 if (old_thread_sp) 1499 { 1500 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID(); 1501 m_thread_id_to_index_id_map.erase(old_thread_id); 1502 } 1503 } 1504 1505 return true; 1506 } 1507 1508 1509 StateType 1510 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet) 1511 { 1512 stop_packet.SetFilePos (0); 1513 const char stop_type = stop_packet.GetChar(); 1514 switch (stop_type) 1515 { 1516 case 'T': 1517 case 'S': 1518 { 1519 // This is a bit of a hack, but is is required. If we did exec, we 1520 // need to clear our thread lists and also know to rebuild our dynamic 1521 // register info before we lookup and threads and populate the expedited 1522 // register values so we need to know this right away so we can cleanup 1523 // and update our registers. 1524 const uint32_t stop_id = GetStopID(); 1525 if (stop_id == 0) 1526 { 1527 // Our first stop, make sure we have a process ID, and also make 1528 // sure we know about our registers 1529 if (GetID() == LLDB_INVALID_PROCESS_ID) 1530 { 1531 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID (); 1532 if (pid != LLDB_INVALID_PROCESS_ID) 1533 SetID (pid); 1534 } 1535 BuildDynamicRegisterInfo (true); 1536 } 1537 // Stop with signal and thread info 1538 const uint8_t signo = stop_packet.GetHexU8(); 1539 std::string name; 1540 std::string value; 1541 std::string thread_name; 1542 std::string reason; 1543 std::string description; 1544 uint32_t exc_type = 0; 1545 std::vector<addr_t> exc_data; 1546 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; 1547 ThreadSP thread_sp; 1548 ThreadGDBRemote *gdb_thread = NULL; 1549 1550 while (stop_packet.GetNameColonValue(name, value)) 1551 { 1552 if (name.compare("metype") == 0) 1553 { 1554 // exception type in big endian hex 1555 exc_type = Args::StringToUInt32 (value.c_str(), 0, 16); 1556 } 1557 else if (name.compare("medata") == 0) 1558 { 1559 // exception data in big endian hex 1560 exc_data.push_back(Args::StringToUInt64 (value.c_str(), 0, 16)); 1561 } 1562 else if (name.compare("thread") == 0) 1563 { 1564 // thread in big endian hex 1565 lldb::tid_t tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1566 // m_thread_list_real does have its own mutex, but we need to 1567 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...) 1568 // and the m_thread_list_real.AddThread(...) so it doesn't change on us 1569 Mutex::Locker locker (m_thread_list_real.GetMutex ()); 1570 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false); 1571 1572 if (!thread_sp) 1573 { 1574 // Create the thread if we need to 1575 thread_sp.reset (new ThreadGDBRemote (*this, tid)); 1576 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD)); 1577 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE)) 1578 log->Printf ("ProcessGDBRemote::%s Adding new thread: %p for thread ID: 0x%" PRIx64 ".\n", 1579 __FUNCTION__, 1580 thread_sp.get(), 1581 thread_sp->GetID()); 1582 1583 m_thread_list_real.AddThread(thread_sp); 1584 } 1585 gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get()); 1586 1587 } 1588 else if (name.compare("threads") == 0) 1589 { 1590 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1591 m_thread_ids.clear(); 1592 // A comma separated list of all threads in the current 1593 // process that includes the thread for this stop reply 1594 // packet 1595 size_t comma_pos; 1596 lldb::tid_t tid; 1597 while ((comma_pos = value.find(',')) != std::string::npos) 1598 { 1599 value[comma_pos] = '\0'; 1600 // thread in big endian hex 1601 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1602 if (tid != LLDB_INVALID_THREAD_ID) 1603 m_thread_ids.push_back (tid); 1604 value.erase(0, comma_pos + 1); 1605 1606 } 1607 tid = Args::StringToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16); 1608 if (tid != LLDB_INVALID_THREAD_ID) 1609 m_thread_ids.push_back (tid); 1610 } 1611 else if (name.compare("hexname") == 0) 1612 { 1613 StringExtractor name_extractor; 1614 // Swap "value" over into "name_extractor" 1615 name_extractor.GetStringRef().swap(value); 1616 // Now convert the HEX bytes into a string value 1617 name_extractor.GetHexByteString (value); 1618 thread_name.swap (value); 1619 } 1620 else if (name.compare("name") == 0) 1621 { 1622 thread_name.swap (value); 1623 } 1624 else if (name.compare("qaddr") == 0) 1625 { 1626 thread_dispatch_qaddr = Args::StringToUInt64 (value.c_str(), 0, 16); 1627 } 1628 else if (name.compare("reason") == 0) 1629 { 1630 reason.swap(value); 1631 } 1632 else if (name.compare("description") == 0) 1633 { 1634 StringExtractor desc_extractor; 1635 // Swap "value" over into "name_extractor" 1636 desc_extractor.GetStringRef().swap(value); 1637 // Now convert the HEX bytes into a string value 1638 desc_extractor.GetHexByteString (thread_name); 1639 } 1640 else if (name.size() == 2 && ::isxdigit(name[0]) && ::isxdigit(name[1])) 1641 { 1642 // We have a register number that contains an expedited 1643 // register value. Lets supply this register to our thread 1644 // so it won't have to go and read it. 1645 if (gdb_thread) 1646 { 1647 uint32_t reg = Args::StringToUInt32 (name.c_str(), UINT32_MAX, 16); 1648 1649 if (reg != UINT32_MAX) 1650 { 1651 StringExtractor reg_value_extractor; 1652 // Swap "value" over into "reg_value_extractor" 1653 reg_value_extractor.GetStringRef().swap(value); 1654 if (!gdb_thread->PrivateSetRegisterValue (reg, reg_value_extractor)) 1655 { 1656 Host::SetCrashDescriptionWithFormat("Setting thread register '%s' (decoded to %u (0x%x)) with value '%s' for stop packet: '%s'", 1657 name.c_str(), 1658 reg, 1659 reg, 1660 reg_value_extractor.GetStringRef().c_str(), 1661 stop_packet.GetStringRef().c_str()); 1662 } 1663 } 1664 } 1665 } 1666 } 1667 1668 if (thread_sp) 1669 { 1670 // Clear the stop info just in case we don't set it to anything 1671 thread_sp->SetStopInfo (StopInfoSP()); 1672 1673 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr); 1674 gdb_thread->SetName (thread_name.empty() ? NULL : thread_name.c_str()); 1675 if (exc_type != 0) 1676 { 1677 const size_t exc_data_size = exc_data.size(); 1678 1679 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp, 1680 exc_type, 1681 exc_data_size, 1682 exc_data_size >= 1 ? exc_data[0] : 0, 1683 exc_data_size >= 2 ? exc_data[1] : 0, 1684 exc_data_size >= 3 ? exc_data[2] : 0)); 1685 } 1686 else 1687 { 1688 bool handled = false; 1689 bool did_exec = false; 1690 if (!reason.empty()) 1691 { 1692 if (reason.compare("trace") == 0) 1693 { 1694 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1695 handled = true; 1696 } 1697 else if (reason.compare("breakpoint") == 0) 1698 { 1699 addr_t pc = thread_sp->GetRegisterContext()->GetPC(); 1700 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1701 if (bp_site_sp) 1702 { 1703 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1704 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1705 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1706 handled = true; 1707 if (bp_site_sp->ValidForThisThread (thread_sp.get())) 1708 { 1709 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1710 } 1711 else 1712 { 1713 StopInfoSP invalid_stop_info_sp; 1714 thread_sp->SetStopInfo (invalid_stop_info_sp); 1715 } 1716 } 1717 1718 } 1719 else if (reason.compare("trap") == 0) 1720 { 1721 // Let the trap just use the standard signal stop reason below... 1722 } 1723 else if (reason.compare("watchpoint") == 0) 1724 { 1725 break_id_t watch_id = LLDB_INVALID_WATCH_ID; 1726 // TODO: locate the watchpoint somehow... 1727 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id)); 1728 handled = true; 1729 } 1730 else if (reason.compare("exception") == 0) 1731 { 1732 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str())); 1733 handled = true; 1734 } 1735 else if (reason.compare("exec") == 0) 1736 { 1737 did_exec = true; 1738 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp)); 1739 handled = true; 1740 } 1741 } 1742 1743 if (signo && did_exec == false) 1744 { 1745 if (signo == SIGTRAP) 1746 { 1747 // Currently we are going to assume SIGTRAP means we are either 1748 // hitting a breakpoint or hardware single stepping. 1749 handled = true; 1750 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset; 1751 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc); 1752 1753 if (bp_site_sp) 1754 { 1755 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread, 1756 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that 1757 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc. 1758 if (bp_site_sp->ValidForThisThread (thread_sp.get())) 1759 { 1760 if(m_breakpoint_pc_offset != 0) 1761 thread_sp->GetRegisterContext()->SetPC(pc); 1762 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID())); 1763 } 1764 else 1765 { 1766 StopInfoSP invalid_stop_info_sp; 1767 thread_sp->SetStopInfo (invalid_stop_info_sp); 1768 } 1769 } 1770 else 1771 { 1772 // If we were stepping then assume the stop was the result of the trace. If we were 1773 // not stepping then report the SIGTRAP. 1774 // FIXME: We are still missing the case where we single step over a trap instruction. 1775 if (thread_sp->GetTemporaryResumeState() == eStateStepping) 1776 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp)); 1777 else 1778 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo)); 1779 } 1780 } 1781 if (!handled) 1782 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo)); 1783 } 1784 1785 if (!description.empty()) 1786 { 1787 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ()); 1788 if (stop_info_sp) 1789 { 1790 stop_info_sp->SetDescription (description.c_str()); 1791 } 1792 else 1793 { 1794 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str())); 1795 } 1796 } 1797 } 1798 } 1799 return eStateStopped; 1800 } 1801 break; 1802 1803 case 'W': 1804 // process exited 1805 return eStateExited; 1806 1807 default: 1808 break; 1809 } 1810 return eStateInvalid; 1811 } 1812 1813 void 1814 ProcessGDBRemote::RefreshStateAfterStop () 1815 { 1816 Mutex::Locker locker(m_thread_list_real.GetMutex()); 1817 m_thread_ids.clear(); 1818 // Set the thread stop info. It might have a "threads" key whose value is 1819 // a list of all thread IDs in the current process, so m_thread_ids might 1820 // get set. 1821 SetThreadStopInfo (m_last_stop_packet); 1822 // Check to see if SetThreadStopInfo() filled in m_thread_ids? 1823 if (m_thread_ids.empty()) 1824 { 1825 // No, we need to fetch the thread list manually 1826 UpdateThreadIDList(); 1827 } 1828 1829 // Let all threads recover from stopping and do any clean up based 1830 // on the previous thread state (if any). 1831 m_thread_list_real.RefreshStateAfterStop(); 1832 1833 } 1834 1835 Error 1836 ProcessGDBRemote::DoHalt (bool &caused_stop) 1837 { 1838 Error error; 1839 1840 bool timed_out = false; 1841 Mutex::Locker locker; 1842 1843 if (m_public_state.GetValue() == eStateAttaching) 1844 { 1845 // We are being asked to halt during an attach. We need to just close 1846 // our file handle and debugserver will go away, and we can be done... 1847 m_gdb_comm.Disconnect(); 1848 } 1849 else 1850 { 1851 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out)) 1852 { 1853 if (timed_out) 1854 error.SetErrorString("timed out sending interrupt packet"); 1855 else 1856 error.SetErrorString("unknown error sending interrupt packet"); 1857 } 1858 1859 caused_stop = m_gdb_comm.GetInterruptWasSent (); 1860 } 1861 return error; 1862 } 1863 1864 Error 1865 ProcessGDBRemote::DoDetach(bool keep_stopped) 1866 { 1867 Error error; 1868 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1869 if (log) 1870 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); 1871 1872 DisableAllBreakpointSites (); 1873 1874 m_thread_list.DiscardThreadPlans(); 1875 1876 error = m_gdb_comm.Detach (keep_stopped); 1877 if (log) 1878 { 1879 if (error.Success()) 1880 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully"); 1881 else 1882 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>"); 1883 } 1884 1885 if (!error.Success()) 1886 return error; 1887 1888 // Sleep for one second to let the process get all detached... 1889 StopAsyncThread (); 1890 1891 SetPrivateState (eStateDetached); 1892 ResumePrivateStateThread(); 1893 1894 //KillDebugserverProcess (); 1895 return error; 1896 } 1897 1898 1899 Error 1900 ProcessGDBRemote::DoDestroy () 1901 { 1902 Error error; 1903 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 1904 if (log) 1905 log->Printf ("ProcessGDBRemote::DoDestroy()"); 1906 1907 // There is a bug in older iOS debugservers where they don't shut down the process 1908 // they are debugging properly. If the process is sitting at a breakpoint or an exception, 1909 // this can cause problems with restarting. So we check to see if any of our threads are stopped 1910 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN 1911 // destroy it again. 1912 // 1913 // Note, we don't have a good way to test the version of debugserver, but I happen to know that 1914 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of 1915 // the debugservers with this bug are equal. There really should be a better way to test this! 1916 // 1917 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and 1918 // get called here to destroy again and we're still at a breakpoint or exception, then we should 1919 // just do the straight-forward kill. 1920 // 1921 // And of course, if we weren't able to stop the process by the time we get here, it isn't 1922 // necessary (or helpful) to do any of this. 1923 1924 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) 1925 { 1926 PlatformSP platform_sp = GetTarget().GetPlatform(); 1927 1928 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. 1929 if (platform_sp 1930 && platform_sp->GetName() 1931 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) 1932 { 1933 if (m_destroy_tried_resuming) 1934 { 1935 if (log) 1936 log->PutCString ("ProcessGDBRemote::DoDestroy()Tried resuming to destroy once already, not doing it again."); 1937 } 1938 else 1939 { 1940 // At present, the plans are discarded and the breakpoints disabled Process::Destroy, 1941 // but we really need it to happen here and it doesn't matter if we do it twice. 1942 m_thread_list.DiscardThreadPlans(); 1943 DisableAllBreakpointSites(); 1944 1945 bool stop_looks_like_crash = false; 1946 ThreadList &threads = GetThreadList(); 1947 1948 { 1949 Mutex::Locker locker(threads.GetMutex()); 1950 1951 size_t num_threads = threads.GetSize(); 1952 for (size_t i = 0; i < num_threads; i++) 1953 { 1954 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1955 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 1956 StopReason reason = eStopReasonInvalid; 1957 if (stop_info_sp) 1958 reason = stop_info_sp->GetStopReason(); 1959 if (reason == eStopReasonBreakpoint 1960 || reason == eStopReasonException) 1961 { 1962 if (log) 1963 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.", 1964 thread_sp->GetProtocolID(), 1965 stop_info_sp->GetDescription()); 1966 stop_looks_like_crash = true; 1967 break; 1968 } 1969 } 1970 } 1971 1972 if (stop_looks_like_crash) 1973 { 1974 if (log) 1975 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill."); 1976 m_destroy_tried_resuming = true; 1977 1978 // If we are going to run again before killing, it would be good to suspend all the threads 1979 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with 1980 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do 1981 // have to run the risk of letting those threads proceed a bit. 1982 1983 { 1984 Mutex::Locker locker(threads.GetMutex()); 1985 1986 size_t num_threads = threads.GetSize(); 1987 for (size_t i = 0; i < num_threads; i++) 1988 { 1989 ThreadSP thread_sp = threads.GetThreadAtIndex(i); 1990 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); 1991 StopReason reason = eStopReasonInvalid; 1992 if (stop_info_sp) 1993 reason = stop_info_sp->GetStopReason(); 1994 if (reason != eStopReasonBreakpoint 1995 && reason != eStopReasonException) 1996 { 1997 if (log) 1998 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.", 1999 thread_sp->GetProtocolID()); 2000 thread_sp->SetResumeState(eStateSuspended); 2001 } 2002 } 2003 } 2004 Resume (); 2005 return Destroy(); 2006 } 2007 } 2008 } 2009 } 2010 2011 // Interrupt if our inferior is running... 2012 int exit_status = SIGABRT; 2013 std::string exit_string; 2014 2015 if (m_gdb_comm.IsConnected()) 2016 { 2017 if (m_public_state.GetValue() != eStateAttaching) 2018 { 2019 2020 StringExtractorGDBRemote response; 2021 bool send_async = true; 2022 const uint32_t old_packet_timeout = m_gdb_comm.SetPacketTimeout (3); 2023 2024 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async)) 2025 { 2026 char packet_cmd = response.GetChar(0); 2027 2028 if (packet_cmd == 'W' || packet_cmd == 'X') 2029 { 2030 SetLastStopPacket (response); 2031 ClearThreadIDList (); 2032 exit_status = response.GetHexU8(); 2033 } 2034 else 2035 { 2036 if (log) 2037 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str()); 2038 exit_string.assign("got unexpected response to k packet: "); 2039 exit_string.append(response.GetStringRef()); 2040 } 2041 } 2042 else 2043 { 2044 if (log) 2045 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 2046 exit_string.assign("failed to send the k packet"); 2047 } 2048 2049 m_gdb_comm.SetPacketTimeout(old_packet_timeout); 2050 } 2051 else 2052 { 2053 if (log) 2054 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet"); 2055 exit_string.assign ("killed or interrupted while attaching."); 2056 } 2057 } 2058 else 2059 { 2060 // If we missed setting the exit status on the way out, do it here. 2061 // NB set exit status can be called multiple times, the first one sets the status. 2062 exit_string.assign("destroying when not connected to debugserver"); 2063 } 2064 2065 SetExitStatus(exit_status, exit_string.c_str()); 2066 2067 StopAsyncThread (); 2068 KillDebugserverProcess (); 2069 return error; 2070 } 2071 2072 void 2073 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response) 2074 { 2075 lldb_private::Mutex::Locker locker (m_last_stop_packet_mutex); 2076 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos; 2077 if (did_exec) 2078 { 2079 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2080 if (log) 2081 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec"); 2082 2083 m_thread_list_real.Clear(); 2084 m_thread_list.Clear(); 2085 BuildDynamicRegisterInfo (true); 2086 m_gdb_comm.ResetDiscoverableSettings(); 2087 } 2088 m_last_stop_packet = response; 2089 } 2090 2091 2092 //------------------------------------------------------------------ 2093 // Process Queries 2094 //------------------------------------------------------------------ 2095 2096 bool 2097 ProcessGDBRemote::IsAlive () 2098 { 2099 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited; 2100 } 2101 2102 addr_t 2103 ProcessGDBRemote::GetImageInfoAddress() 2104 { 2105 return m_gdb_comm.GetShlibInfoAddr(); 2106 } 2107 2108 //------------------------------------------------------------------ 2109 // Process Memory 2110 //------------------------------------------------------------------ 2111 size_t 2112 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error) 2113 { 2114 if (size > m_max_memory_size) 2115 { 2116 // Keep memory read sizes down to a sane limit. This function will be 2117 // called multiple times in order to complete the task by 2118 // lldb_private::Process so it is ok to do this. 2119 size = m_max_memory_size; 2120 } 2121 2122 char packet[64]; 2123 const int packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size); 2124 assert (packet_len + 1 < (int)sizeof(packet)); 2125 StringExtractorGDBRemote response; 2126 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true)) 2127 { 2128 if (response.IsNormalResponse()) 2129 { 2130 error.Clear(); 2131 return response.GetHexBytes(buf, size, '\xdd'); 2132 } 2133 else if (response.IsErrorResponse()) 2134 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); 2135 else if (response.IsUnsupportedResponse()) 2136 error.SetErrorStringWithFormat("GDB server does not support reading memory"); 2137 else 2138 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str()); 2139 } 2140 else 2141 { 2142 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); 2143 } 2144 return 0; 2145 } 2146 2147 size_t 2148 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error) 2149 { 2150 if (size > m_max_memory_size) 2151 { 2152 // Keep memory read sizes down to a sane limit. This function will be 2153 // called multiple times in order to complete the task by 2154 // lldb_private::Process so it is ok to do this. 2155 size = m_max_memory_size; 2156 } 2157 2158 StreamString packet; 2159 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); 2160 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder()); 2161 StringExtractorGDBRemote response; 2162 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true)) 2163 { 2164 if (response.IsOKResponse()) 2165 { 2166 error.Clear(); 2167 return size; 2168 } 2169 else if (response.IsErrorResponse()) 2170 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr); 2171 else if (response.IsUnsupportedResponse()) 2172 error.SetErrorStringWithFormat("GDB server does not support writing memory"); 2173 else 2174 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str()); 2175 } 2176 else 2177 { 2178 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str()); 2179 } 2180 return 0; 2181 } 2182 2183 lldb::addr_t 2184 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 2185 { 2186 addr_t allocated_addr = LLDB_INVALID_ADDRESS; 2187 2188 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2189 switch (supported) 2190 { 2191 case eLazyBoolCalculate: 2192 case eLazyBoolYes: 2193 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions); 2194 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes) 2195 return allocated_addr; 2196 2197 case eLazyBoolNo: 2198 // Call mmap() to create memory in the inferior.. 2199 unsigned prot = 0; 2200 if (permissions & lldb::ePermissionsReadable) 2201 prot |= eMmapProtRead; 2202 if (permissions & lldb::ePermissionsWritable) 2203 prot |= eMmapProtWrite; 2204 if (permissions & lldb::ePermissionsExecutable) 2205 prot |= eMmapProtExec; 2206 2207 if (InferiorCallMmap(this, allocated_addr, 0, size, prot, 2208 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) 2209 m_addr_to_mmap_size[allocated_addr] = size; 2210 else 2211 allocated_addr = LLDB_INVALID_ADDRESS; 2212 break; 2213 } 2214 2215 if (allocated_addr == LLDB_INVALID_ADDRESS) 2216 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions)); 2217 else 2218 error.Clear(); 2219 return allocated_addr; 2220 } 2221 2222 Error 2223 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr, 2224 MemoryRegionInfo ®ion_info) 2225 { 2226 2227 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info)); 2228 return error; 2229 } 2230 2231 Error 2232 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num) 2233 { 2234 2235 Error error (m_gdb_comm.GetWatchpointSupportInfo (num)); 2236 return error; 2237 } 2238 2239 Error 2240 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after) 2241 { 2242 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after)); 2243 return error; 2244 } 2245 2246 Error 2247 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr) 2248 { 2249 Error error; 2250 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); 2251 2252 switch (supported) 2253 { 2254 case eLazyBoolCalculate: 2255 // We should never be deallocating memory without allocating memory 2256 // first so we should never get eLazyBoolCalculate 2257 error.SetErrorString ("tried to deallocate memory without ever allocating memory"); 2258 break; 2259 2260 case eLazyBoolYes: 2261 if (!m_gdb_comm.DeallocateMemory (addr)) 2262 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 2263 break; 2264 2265 case eLazyBoolNo: 2266 // Call munmap() to deallocate memory in the inferior.. 2267 { 2268 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); 2269 if (pos != m_addr_to_mmap_size.end() && 2270 InferiorCallMunmap(this, addr, pos->second)) 2271 m_addr_to_mmap_size.erase (pos); 2272 else 2273 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr); 2274 } 2275 break; 2276 } 2277 2278 return error; 2279 } 2280 2281 2282 //------------------------------------------------------------------ 2283 // Process STDIO 2284 //------------------------------------------------------------------ 2285 size_t 2286 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error) 2287 { 2288 if (m_stdio_communication.IsConnected()) 2289 { 2290 ConnectionStatus status; 2291 m_stdio_communication.Write(src, src_len, status, NULL); 2292 } 2293 return 0; 2294 } 2295 2296 Error 2297 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site) 2298 { 2299 Error error; 2300 assert (bp_site != NULL); 2301 2302 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2303 user_id_t site_id = bp_site->GetID(); 2304 const addr_t addr = bp_site->GetLoadAddress(); 2305 if (log) 2306 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr); 2307 2308 if (bp_site->IsEnabled()) 2309 { 2310 if (log) 2311 log->Printf ("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr); 2312 return error; 2313 } 2314 else 2315 { 2316 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2317 2318 if (bp_site->HardwareRequired()) 2319 { 2320 // Try and set hardware breakpoint, and if that fails, fall through 2321 // and set a software breakpoint? 2322 if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointHardware)) 2323 { 2324 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0) 2325 { 2326 bp_site->SetEnabled(true); 2327 bp_site->SetType (BreakpointSite::eHardware); 2328 } 2329 else 2330 { 2331 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)"); 2332 } 2333 } 2334 else 2335 { 2336 error.SetErrorString("hardware breakpoints are not supported"); 2337 } 2338 return error; 2339 } 2340 else if (m_gdb_comm.SupportsGDBStoppointPacket (eBreakpointSoftware)) 2341 { 2342 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0) 2343 { 2344 bp_site->SetEnabled(true); 2345 bp_site->SetType (BreakpointSite::eExternal); 2346 return error; 2347 } 2348 } 2349 2350 return EnableSoftwareBreakpoint (bp_site); 2351 } 2352 2353 if (log) 2354 { 2355 const char *err_string = error.AsCString(); 2356 log->Printf ("ProcessGDBRemote::EnableBreakpointSite () error for breakpoint at 0x%8.8" PRIx64 ": %s", 2357 bp_site->GetLoadAddress(), 2358 err_string ? err_string : "NULL"); 2359 } 2360 // We shouldn't reach here on a successful breakpoint enable... 2361 if (error.Success()) 2362 error.SetErrorToGenericError(); 2363 return error; 2364 } 2365 2366 Error 2367 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site) 2368 { 2369 Error error; 2370 assert (bp_site != NULL); 2371 addr_t addr = bp_site->GetLoadAddress(); 2372 user_id_t site_id = bp_site->GetID(); 2373 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); 2374 if (log) 2375 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr); 2376 2377 if (bp_site->IsEnabled()) 2378 { 2379 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site); 2380 2381 BreakpointSite::Type bp_type = bp_site->GetType(); 2382 switch (bp_type) 2383 { 2384 case BreakpointSite::eSoftware: 2385 error = DisableSoftwareBreakpoint (bp_site); 2386 break; 2387 2388 case BreakpointSite::eHardware: 2389 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2390 error.SetErrorToGenericError(); 2391 break; 2392 2393 case BreakpointSite::eExternal: 2394 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr, bp_op_size)) 2395 error.SetErrorToGenericError(); 2396 break; 2397 } 2398 if (error.Success()) 2399 bp_site->SetEnabled(false); 2400 } 2401 else 2402 { 2403 if (log) 2404 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr); 2405 return error; 2406 } 2407 2408 if (error.Success()) 2409 error.SetErrorToGenericError(); 2410 return error; 2411 } 2412 2413 // Pre-requisite: wp != NULL. 2414 static GDBStoppointType 2415 GetGDBStoppointType (Watchpoint *wp) 2416 { 2417 assert(wp); 2418 bool watch_read = wp->WatchpointRead(); 2419 bool watch_write = wp->WatchpointWrite(); 2420 2421 // watch_read and watch_write cannot both be false. 2422 assert(watch_read || watch_write); 2423 if (watch_read && watch_write) 2424 return eWatchpointReadWrite; 2425 else if (watch_read) 2426 return eWatchpointRead; 2427 else // Must be watch_write, then. 2428 return eWatchpointWrite; 2429 } 2430 2431 Error 2432 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify) 2433 { 2434 Error error; 2435 if (wp) 2436 { 2437 user_id_t watchID = wp->GetID(); 2438 addr_t addr = wp->GetLoadAddress(); 2439 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2440 if (log) 2441 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID); 2442 if (wp->IsEnabled()) 2443 { 2444 if (log) 2445 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr); 2446 return error; 2447 } 2448 2449 GDBStoppointType type = GetGDBStoppointType(wp); 2450 // Pass down an appropriate z/Z packet... 2451 if (m_gdb_comm.SupportsGDBStoppointPacket (type)) 2452 { 2453 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) 2454 { 2455 wp->SetEnabled(true, notify); 2456 return error; 2457 } 2458 else 2459 error.SetErrorString("sending gdb watchpoint packet failed"); 2460 } 2461 else 2462 error.SetErrorString("watchpoints not supported"); 2463 } 2464 else 2465 { 2466 error.SetErrorString("Watchpoint argument was NULL."); 2467 } 2468 if (error.Success()) 2469 error.SetErrorToGenericError(); 2470 return error; 2471 } 2472 2473 Error 2474 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify) 2475 { 2476 Error error; 2477 if (wp) 2478 { 2479 user_id_t watchID = wp->GetID(); 2480 2481 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); 2482 2483 addr_t addr = wp->GetLoadAddress(); 2484 2485 if (log) 2486 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr); 2487 2488 if (!wp->IsEnabled()) 2489 { 2490 if (log) 2491 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr); 2492 // See also 'class WatchpointSentry' within StopInfo.cpp. 2493 // This disabling attempt might come from the user-supplied actions, we'll route it in order for 2494 // the watchpoint object to intelligently process this action. 2495 wp->SetEnabled(false, notify); 2496 return error; 2497 } 2498 2499 if (wp->IsHardware()) 2500 { 2501 GDBStoppointType type = GetGDBStoppointType(wp); 2502 // Pass down an appropriate z/Z packet... 2503 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) 2504 { 2505 wp->SetEnabled(false, notify); 2506 return error; 2507 } 2508 else 2509 error.SetErrorString("sending gdb watchpoint packet failed"); 2510 } 2511 // TODO: clear software watchpoints if we implement them 2512 } 2513 else 2514 { 2515 error.SetErrorString("Watchpoint argument was NULL."); 2516 } 2517 if (error.Success()) 2518 error.SetErrorToGenericError(); 2519 return error; 2520 } 2521 2522 void 2523 ProcessGDBRemote::Clear() 2524 { 2525 m_flags = 0; 2526 m_thread_list_real.Clear(); 2527 m_thread_list.Clear(); 2528 } 2529 2530 Error 2531 ProcessGDBRemote::DoSignal (int signo) 2532 { 2533 Error error; 2534 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2535 if (log) 2536 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo); 2537 2538 if (!m_gdb_comm.SendAsyncSignal (signo)) 2539 error.SetErrorStringWithFormat("failed to send signal %i", signo); 2540 return error; 2541 } 2542 2543 Error 2544 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url) 2545 { 2546 ProcessLaunchInfo launch_info; 2547 return StartDebugserverProcess(debugserver_url, launch_info); 2548 } 2549 2550 Error 2551 ProcessGDBRemote::StartDebugserverProcess (const char *debugserver_url, const ProcessInfo &process_info) // The connection string to use in the spawned debugserver ("localhost:1234" or "/dev/tty...") 2552 { 2553 Error error; 2554 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) 2555 { 2556 // If we locate debugserver, keep that located version around 2557 static FileSpec g_debugserver_file_spec; 2558 2559 ProcessLaunchInfo debugserver_launch_info; 2560 char debugserver_path[PATH_MAX]; 2561 FileSpec &debugserver_file_spec = debugserver_launch_info.GetExecutableFile(); 2562 2563 // Always check to see if we have an environment override for the path 2564 // to the debugserver to use and use it if we do. 2565 const char *env_debugserver_path = getenv("LLDB_DEBUGSERVER_PATH"); 2566 if (env_debugserver_path) 2567 debugserver_file_spec.SetFile (env_debugserver_path, false); 2568 else 2569 debugserver_file_spec = g_debugserver_file_spec; 2570 bool debugserver_exists = debugserver_file_spec.Exists(); 2571 if (!debugserver_exists) 2572 { 2573 // The debugserver binary is in the LLDB.framework/Resources 2574 // directory. 2575 if (Host::GetLLDBPath (ePathTypeSupportExecutableDir, debugserver_file_spec)) 2576 { 2577 debugserver_file_spec.GetFilename().SetCString(DEBUGSERVER_BASENAME); 2578 debugserver_exists = debugserver_file_spec.Exists(); 2579 if (debugserver_exists) 2580 { 2581 g_debugserver_file_spec = debugserver_file_spec; 2582 } 2583 else 2584 { 2585 g_debugserver_file_spec.Clear(); 2586 debugserver_file_spec.Clear(); 2587 } 2588 } 2589 } 2590 2591 if (debugserver_exists) 2592 { 2593 debugserver_file_spec.GetPath (debugserver_path, sizeof(debugserver_path)); 2594 2595 m_stdio_communication.Clear(); 2596 2597 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2598 2599 Args &debugserver_args = debugserver_launch_info.GetArguments(); 2600 char arg_cstr[PATH_MAX]; 2601 2602 // Start args with "debugserver /file/path -r --" 2603 debugserver_args.AppendArgument(debugserver_path); 2604 debugserver_args.AppendArgument(debugserver_url); 2605 // use native registers, not the GDB registers 2606 debugserver_args.AppendArgument("--native-regs"); 2607 // make debugserver run in its own session so signals generated by 2608 // special terminal key sequences (^C) don't affect debugserver 2609 debugserver_args.AppendArgument("--setsid"); 2610 2611 const char *env_debugserver_log_file = getenv("LLDB_DEBUGSERVER_LOG_FILE"); 2612 if (env_debugserver_log_file) 2613 { 2614 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-file=%s", env_debugserver_log_file); 2615 debugserver_args.AppendArgument(arg_cstr); 2616 } 2617 2618 const char *env_debugserver_log_flags = getenv("LLDB_DEBUGSERVER_LOG_FLAGS"); 2619 if (env_debugserver_log_flags) 2620 { 2621 ::snprintf (arg_cstr, sizeof(arg_cstr), "--log-flags=%s", env_debugserver_log_flags); 2622 debugserver_args.AppendArgument(arg_cstr); 2623 } 2624 // debugserver_args.AppendArgument("--log-file=/tmp/debugserver.txt"); 2625 // debugserver_args.AppendArgument("--log-flags=0x802e0e"); 2626 2627 // We currently send down all arguments, attach pids, or attach 2628 // process names in dedicated GDB server packets, so we don't need 2629 // to pass them as arguments. This is currently because of all the 2630 // things we need to setup prior to launching: the environment, 2631 // current working dir, file actions, etc. 2632 #if 0 2633 // Now append the program arguments 2634 if (inferior_argv) 2635 { 2636 // Terminate the debugserver args so we can now append the inferior args 2637 debugserver_args.AppendArgument("--"); 2638 2639 for (int i = 0; inferior_argv[i] != NULL; ++i) 2640 debugserver_args.AppendArgument (inferior_argv[i]); 2641 } 2642 else if (attach_pid != LLDB_INVALID_PROCESS_ID) 2643 { 2644 ::snprintf (arg_cstr, sizeof(arg_cstr), "--attach=%u", attach_pid); 2645 debugserver_args.AppendArgument (arg_cstr); 2646 } 2647 else if (attach_name && attach_name[0]) 2648 { 2649 if (wait_for_launch) 2650 debugserver_args.AppendArgument ("--waitfor"); 2651 else 2652 debugserver_args.AppendArgument ("--attach"); 2653 debugserver_args.AppendArgument (attach_name); 2654 } 2655 #endif 2656 2657 ProcessLaunchInfo::FileAction file_action; 2658 2659 // Close STDIN, STDOUT and STDERR. We might need to redirect them 2660 // to "/dev/null" if we run into any problems. 2661 file_action.Close (STDIN_FILENO); 2662 debugserver_launch_info.AppendFileAction (file_action); 2663 file_action.Close (STDOUT_FILENO); 2664 debugserver_launch_info.AppendFileAction (file_action); 2665 file_action.Close (STDERR_FILENO); 2666 debugserver_launch_info.AppendFileAction (file_action); 2667 2668 if (log) 2669 { 2670 StreamString strm; 2671 debugserver_args.Dump (&strm); 2672 log->Printf("%s arguments:\n%s", debugserver_args.GetArgumentAtIndex(0), strm.GetData()); 2673 } 2674 2675 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false); 2676 debugserver_launch_info.SetUserID(process_info.GetUserID()); 2677 2678 error = Host::LaunchProcess(debugserver_launch_info); 2679 2680 if (error.Success ()) 2681 m_debugserver_pid = debugserver_launch_info.GetProcessID(); 2682 else 2683 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2684 2685 if (error.Fail() || log) 2686 error.PutToLog(log, "Host::LaunchProcess (launch_info) => pid=%" PRIu64 ", path='%s'", m_debugserver_pid, debugserver_path); 2687 } 2688 else 2689 { 2690 error.SetErrorStringWithFormat ("unable to locate " DEBUGSERVER_BASENAME); 2691 } 2692 2693 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2694 StartAsyncThread (); 2695 } 2696 return error; 2697 } 2698 2699 bool 2700 ProcessGDBRemote::MonitorDebugserverProcess 2701 ( 2702 void *callback_baton, 2703 lldb::pid_t debugserver_pid, 2704 bool exited, // True if the process did exit 2705 int signo, // Zero for no signal 2706 int exit_status // Exit value of process if signal is zero 2707 ) 2708 { 2709 // The baton is a "ProcessGDBRemote *". Now this class might be gone 2710 // and might not exist anymore, so we need to carefully try to get the 2711 // target for this process first since we have a race condition when 2712 // we are done running between getting the notice that the inferior 2713 // process has died and the debugserver that was debugging this process. 2714 // In our test suite, we are also continually running process after 2715 // process, so we must be very careful to make sure: 2716 // 1 - process object hasn't been deleted already 2717 // 2 - that a new process object hasn't been recreated in its place 2718 2719 // "debugserver_pid" argument passed in is the process ID for 2720 // debugserver that we are tracking... 2721 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2722 2723 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton; 2724 2725 // Get a shared pointer to the target that has a matching process pointer. 2726 // This target could be gone, or the target could already have a new process 2727 // object inside of it 2728 TargetSP target_sp (Debugger::FindTargetWithProcess(process)); 2729 2730 if (log) 2731 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status); 2732 2733 if (target_sp) 2734 { 2735 // We found a process in a target that matches, but another thread 2736 // might be in the process of launching a new process that will 2737 // soon replace it, so get a shared pointer to the process so we 2738 // can keep it alive. 2739 ProcessSP process_sp (target_sp->GetProcessSP()); 2740 // Now we have a shared pointer to the process that can't go away on us 2741 // so we now make sure it was the same as the one passed in, and also make 2742 // sure that our previous "process *" didn't get deleted and have a new 2743 // "process *" created in its place with the same pointer. To verify this 2744 // we make sure the process has our debugserver process ID. If we pass all 2745 // of these tests, then we are sure that this process is the one we were 2746 // looking for. 2747 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid) 2748 { 2749 // Sleep for a half a second to make sure our inferior process has 2750 // time to set its exit status before we set it incorrectly when 2751 // both the debugserver and the inferior process shut down. 2752 usleep (500000); 2753 // If our process hasn't yet exited, debugserver might have died. 2754 // If the process did exit, the we are reaping it. 2755 const StateType state = process->GetState(); 2756 2757 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID && 2758 state != eStateInvalid && 2759 state != eStateUnloaded && 2760 state != eStateExited && 2761 state != eStateDetached) 2762 { 2763 char error_str[1024]; 2764 if (signo) 2765 { 2766 const char *signal_cstr = process->GetUnixSignals().GetSignalAsCString (signo); 2767 if (signal_cstr) 2768 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); 2769 else 2770 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); 2771 } 2772 else 2773 { 2774 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); 2775 } 2776 2777 process->SetExitStatus (-1, error_str); 2778 } 2779 // Debugserver has exited we need to let our ProcessGDBRemote 2780 // know that it no longer has a debugserver instance 2781 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2782 } 2783 } 2784 return true; 2785 } 2786 2787 void 2788 ProcessGDBRemote::KillDebugserverProcess () 2789 { 2790 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) 2791 { 2792 Host::Kill (m_debugserver_pid, SIGINT); 2793 m_debugserver_pid = LLDB_INVALID_PROCESS_ID; 2794 } 2795 } 2796 2797 void 2798 ProcessGDBRemote::Initialize() 2799 { 2800 static bool g_initialized = false; 2801 2802 if (g_initialized == false) 2803 { 2804 g_initialized = true; 2805 PluginManager::RegisterPlugin (GetPluginNameStatic(), 2806 GetPluginDescriptionStatic(), 2807 CreateInstance, 2808 DebuggerInitialize); 2809 2810 Log::Callbacks log_callbacks = { 2811 ProcessGDBRemoteLog::DisableLog, 2812 ProcessGDBRemoteLog::EnableLog, 2813 ProcessGDBRemoteLog::ListLogCategories 2814 }; 2815 2816 Log::RegisterLogChannel (ProcessGDBRemote::GetPluginNameStatic(), log_callbacks); 2817 } 2818 } 2819 2820 void 2821 ProcessGDBRemote::DebuggerInitialize (lldb_private::Debugger &debugger) 2822 { 2823 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName())) 2824 { 2825 const bool is_global_setting = true; 2826 PluginManager::CreateSettingForProcessPlugin (debugger, 2827 GetGlobalPluginProperties()->GetValueProperties(), 2828 ConstString ("Properties for the gdb-remote process plug-in."), 2829 is_global_setting); 2830 } 2831 } 2832 2833 bool 2834 ProcessGDBRemote::StartAsyncThread () 2835 { 2836 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2837 2838 if (log) 2839 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2840 2841 Mutex::Locker start_locker(m_async_thread_state_mutex); 2842 if (m_async_thread_state == eAsyncThreadNotStarted) 2843 { 2844 // Create a thread that watches our internal state and controls which 2845 // events make it to clients (into the DCProcess event queue). 2846 m_async_thread = Host::ThreadCreate ("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL); 2847 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2848 { 2849 m_async_thread_state = eAsyncThreadRunning; 2850 return true; 2851 } 2852 else 2853 return false; 2854 } 2855 else 2856 { 2857 // Somebody tried to start the async thread while it was either being started or stopped. If the former, and 2858 // it started up successfully, then say all's well. Otherwise it is an error, since we aren't going to restart it. 2859 if (log) 2860 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state); 2861 if (m_async_thread_state == eAsyncThreadRunning) 2862 return true; 2863 else 2864 return false; 2865 } 2866 } 2867 2868 void 2869 ProcessGDBRemote::StopAsyncThread () 2870 { 2871 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); 2872 2873 if (log) 2874 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__); 2875 2876 Mutex::Locker start_locker(m_async_thread_state_mutex); 2877 if (m_async_thread_state == eAsyncThreadRunning) 2878 { 2879 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit); 2880 2881 // This will shut down the async thread. 2882 m_gdb_comm.Disconnect(); // Disconnect from the debug server. 2883 2884 // Stop the stdio thread 2885 if (IS_VALID_LLDB_HOST_THREAD(m_async_thread)) 2886 { 2887 Host::ThreadJoin (m_async_thread, NULL, NULL); 2888 } 2889 m_async_thread_state = eAsyncThreadDone; 2890 } 2891 else 2892 { 2893 if (log) 2894 log->Printf ("ProcessGDBRemote::%s () - Called when Async thread was in state: %d.", __FUNCTION__, m_async_thread_state); 2895 } 2896 } 2897 2898 2899 thread_result_t 2900 ProcessGDBRemote::AsyncThread (void *arg) 2901 { 2902 ProcessGDBRemote *process = (ProcessGDBRemote*) arg; 2903 2904 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS)); 2905 if (log) 2906 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID()); 2907 2908 Listener listener ("ProcessGDBRemote::AsyncThread"); 2909 EventSP event_sp; 2910 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue | 2911 eBroadcastBitAsyncThreadShouldExit; 2912 2913 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask) 2914 { 2915 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit); 2916 2917 bool done = false; 2918 while (!done) 2919 { 2920 if (log) 2921 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); 2922 if (listener.WaitForEvent (NULL, event_sp)) 2923 { 2924 const uint32_t event_type = event_sp->GetType(); 2925 if (event_sp->BroadcasterIs (&process->m_async_broadcaster)) 2926 { 2927 if (log) 2928 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); 2929 2930 switch (event_type) 2931 { 2932 case eBroadcastBitAsyncContinue: 2933 { 2934 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); 2935 2936 if (continue_packet) 2937 { 2938 const char *continue_cstr = (const char *)continue_packet->GetBytes (); 2939 const size_t continue_cstr_len = continue_packet->GetByteSize (); 2940 if (log) 2941 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); 2942 2943 if (::strstr (continue_cstr, "vAttach") == NULL) 2944 process->SetPrivateState(eStateRunning); 2945 StringExtractorGDBRemote response; 2946 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response); 2947 2948 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads. 2949 // The thread ID list might be contained within the "response", or the stop reply packet that 2950 // caused the stop. So clear it now before we give the stop reply packet to the process 2951 // using the process->SetLastStopPacket()... 2952 process->ClearThreadIDList (); 2953 2954 switch (stop_state) 2955 { 2956 case eStateStopped: 2957 case eStateCrashed: 2958 case eStateSuspended: 2959 process->SetLastStopPacket (response); 2960 process->SetPrivateState (stop_state); 2961 break; 2962 2963 case eStateExited: 2964 process->SetLastStopPacket (response); 2965 process->ClearThreadIDList(); 2966 response.SetFilePos(1); 2967 process->SetExitStatus(response.GetHexU8(), NULL); 2968 done = true; 2969 break; 2970 2971 case eStateInvalid: 2972 process->SetExitStatus(-1, "lost connection"); 2973 break; 2974 2975 default: 2976 process->SetPrivateState (stop_state); 2977 break; 2978 } 2979 } 2980 } 2981 break; 2982 2983 case eBroadcastBitAsyncThreadShouldExit: 2984 if (log) 2985 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); 2986 done = true; 2987 break; 2988 2989 default: 2990 if (log) 2991 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); 2992 done = true; 2993 break; 2994 } 2995 } 2996 else if (event_sp->BroadcasterIs (&process->m_gdb_comm)) 2997 { 2998 if (event_type & Communication::eBroadcastBitReadThreadDidExit) 2999 { 3000 process->SetExitStatus (-1, "lost connection"); 3001 done = true; 3002 } 3003 } 3004 } 3005 else 3006 { 3007 if (log) 3008 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); 3009 done = true; 3010 } 3011 } 3012 } 3013 3014 if (log) 3015 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID()); 3016 3017 process->m_async_thread = LLDB_INVALID_HOST_THREAD; 3018 return NULL; 3019 } 3020 3021 //uint32_t 3022 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids) 3023 //{ 3024 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver 3025 // // process and ask it for the list of processes. But if we are local, we can let the Host do it. 3026 // if (m_local_debugserver) 3027 // { 3028 // return Host::ListProcessesMatchingName (name, matches, pids); 3029 // } 3030 // else 3031 // { 3032 // // FIXME: Implement talking to the remote debugserver. 3033 // return 0; 3034 // } 3035 // 3036 //} 3037 // 3038 bool 3039 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton, 3040 lldb_private::StoppointCallbackContext *context, 3041 lldb::user_id_t break_id, 3042 lldb::user_id_t break_loc_id) 3043 { 3044 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to 3045 // run so I can stop it if that's what I want to do. 3046 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3047 if (log) 3048 log->Printf("Hit New Thread Notification breakpoint."); 3049 return false; 3050 } 3051 3052 3053 bool 3054 ProcessGDBRemote::StartNoticingNewThreads() 3055 { 3056 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3057 if (m_thread_create_bp_sp) 3058 { 3059 if (log && log->GetVerbose()) 3060 log->Printf("Enabled noticing new thread breakpoint."); 3061 m_thread_create_bp_sp->SetEnabled(true); 3062 } 3063 else 3064 { 3065 PlatformSP platform_sp (m_target.GetPlatform()); 3066 if (platform_sp) 3067 { 3068 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target); 3069 if (m_thread_create_bp_sp) 3070 { 3071 if (log && log->GetVerbose()) 3072 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); 3073 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); 3074 } 3075 else 3076 { 3077 if (log) 3078 log->Printf("Failed to create new thread notification breakpoint."); 3079 } 3080 } 3081 } 3082 return m_thread_create_bp_sp.get() != NULL; 3083 } 3084 3085 bool 3086 ProcessGDBRemote::StopNoticingNewThreads() 3087 { 3088 Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP)); 3089 if (log && log->GetVerbose()) 3090 log->Printf ("Disabling new thread notification breakpoint."); 3091 3092 if (m_thread_create_bp_sp) 3093 m_thread_create_bp_sp->SetEnabled(false); 3094 3095 return true; 3096 } 3097 3098 lldb_private::DynamicLoader * 3099 ProcessGDBRemote::GetDynamicLoader () 3100 { 3101 if (m_dyld_ap.get() == NULL) 3102 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL)); 3103 return m_dyld_ap.get(); 3104 } 3105 3106 3107 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed 3108 { 3109 private: 3110 3111 public: 3112 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) : 3113 CommandObjectParsed (interpreter, 3114 "process plugin packet history", 3115 "Dumps the packet history buffer. ", 3116 NULL) 3117 { 3118 } 3119 3120 ~CommandObjectProcessGDBRemotePacketHistory () 3121 { 3122 } 3123 3124 bool 3125 DoExecute (Args& command, CommandReturnObject &result) 3126 { 3127 const size_t argc = command.GetArgumentCount(); 3128 if (argc == 0) 3129 { 3130 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3131 if (process) 3132 { 3133 process->GetGDBRemote().DumpHistory(result.GetOutputStream()); 3134 result.SetStatus (eReturnStatusSuccessFinishResult); 3135 return true; 3136 } 3137 } 3138 else 3139 { 3140 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str()); 3141 } 3142 result.SetStatus (eReturnStatusFailed); 3143 return false; 3144 } 3145 }; 3146 3147 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed 3148 { 3149 private: 3150 3151 public: 3152 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) : 3153 CommandObjectParsed (interpreter, 3154 "process plugin packet send", 3155 "Send a custom packet through the GDB remote protocol and print the answer. " 3156 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.", 3157 NULL) 3158 { 3159 } 3160 3161 ~CommandObjectProcessGDBRemotePacketSend () 3162 { 3163 } 3164 3165 bool 3166 DoExecute (Args& command, CommandReturnObject &result) 3167 { 3168 const size_t argc = command.GetArgumentCount(); 3169 if (argc == 0) 3170 { 3171 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str()); 3172 result.SetStatus (eReturnStatusFailed); 3173 return false; 3174 } 3175 3176 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3177 if (process) 3178 { 3179 for (size_t i=0; i<argc; ++ i) 3180 { 3181 const char *packet_cstr = command.GetArgumentAtIndex(0); 3182 bool send_async = true; 3183 StringExtractorGDBRemote response; 3184 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 3185 result.SetStatus (eReturnStatusSuccessFinishResult); 3186 Stream &output_strm = result.GetOutputStream(); 3187 output_strm.Printf (" packet: %s\n", packet_cstr); 3188 std::string &response_str = response.GetStringRef(); 3189 3190 if (strstr(packet_cstr, "qGetProfileData") != NULL) 3191 { 3192 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response); 3193 } 3194 3195 if (response_str.empty()) 3196 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 3197 else 3198 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 3199 } 3200 } 3201 return true; 3202 } 3203 }; 3204 3205 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw 3206 { 3207 private: 3208 3209 public: 3210 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) : 3211 CommandObjectRaw (interpreter, 3212 "process plugin packet monitor", 3213 "Send a qRcmd packet through the GDB remote protocol and print the response." 3214 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.", 3215 NULL) 3216 { 3217 } 3218 3219 ~CommandObjectProcessGDBRemotePacketMonitor () 3220 { 3221 } 3222 3223 bool 3224 DoExecute (const char *command, CommandReturnObject &result) 3225 { 3226 if (command == NULL || command[0] == '\0') 3227 { 3228 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str()); 3229 result.SetStatus (eReturnStatusFailed); 3230 return false; 3231 } 3232 3233 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); 3234 if (process) 3235 { 3236 StreamString packet; 3237 packet.PutCString("qRcmd,"); 3238 packet.PutBytesAsRawHex8(command, strlen(command)); 3239 const char *packet_cstr = packet.GetString().c_str(); 3240 3241 bool send_async = true; 3242 StringExtractorGDBRemote response; 3243 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async); 3244 result.SetStatus (eReturnStatusSuccessFinishResult); 3245 Stream &output_strm = result.GetOutputStream(); 3246 output_strm.Printf (" packet: %s\n", packet_cstr); 3247 const std::string &response_str = response.GetStringRef(); 3248 3249 if (response_str.empty()) 3250 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n"); 3251 else 3252 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str()); 3253 } 3254 return true; 3255 } 3256 }; 3257 3258 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword 3259 { 3260 private: 3261 3262 public: 3263 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) : 3264 CommandObjectMultiword (interpreter, 3265 "process plugin packet", 3266 "Commands that deal with GDB remote packets.", 3267 NULL) 3268 { 3269 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter))); 3270 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter))); 3271 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter))); 3272 } 3273 3274 ~CommandObjectProcessGDBRemotePacket () 3275 { 3276 } 3277 }; 3278 3279 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword 3280 { 3281 public: 3282 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) : 3283 CommandObjectMultiword (interpreter, 3284 "process plugin", 3285 "A set of commands for operating on a ProcessGDBRemote process.", 3286 "process plugin <subcommand> [<subcommand-options>]") 3287 { 3288 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter))); 3289 } 3290 3291 ~CommandObjectMultiwordProcessGDBRemote () 3292 { 3293 } 3294 }; 3295 3296 CommandObject * 3297 ProcessGDBRemote::GetPluginCommandObject() 3298 { 3299 if (!m_command_sp) 3300 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter())); 3301 return m_command_sp.get(); 3302 } 3303