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