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