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