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