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