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