1 //===-- ProcessGDBRemote.cpp ------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Host/Config.h"
15 #ifndef LLDB_DISABLE_POSIX
16 #include <netinet/in.h>
17 #include <sys/mman.h> // for mmap
20 #include <sys/types.h>
28 #include "lldb/Breakpoint/Watchpoint.h"
29 #include "lldb/Interpreter/Args.h"
30 #include "lldb/Core/ArchSpec.h"
31 #include "lldb/Core/Debugger.h"
32 #include "lldb/Host/ConnectionFileDescriptor.h"
33 #include "lldb/Host/FileSpec.h"
34 #include "lldb/Core/Module.h"
35 #include "lldb/Core/ModuleSpec.h"
36 #include "lldb/Core/PluginManager.h"
37 #include "lldb/Core/State.h"
38 #include "lldb/Core/StreamFile.h"
39 #include "lldb/Core/StreamString.h"
40 #include "lldb/Core/Timer.h"
41 #include "lldb/Core/Value.h"
42 #include "lldb/DataFormatters/FormatManager.h"
43 #include "lldb/Host/HostThread.h"
44 #include "lldb/Host/StringConvert.h"
45 #include "lldb/Host/Symbols.h"
46 #include "lldb/Host/ThreadLauncher.h"
47 #include "lldb/Host/TimeValue.h"
48 #include "lldb/Host/XML.h"
49 #include "lldb/Interpreter/CommandInterpreter.h"
50 #include "lldb/Interpreter/CommandObject.h"
51 #include "lldb/Interpreter/CommandObjectMultiword.h"
52 #include "lldb/Interpreter/CommandReturnObject.h"
53 #include "lldb/Interpreter/OptionValueProperties.h"
54 #include "lldb/Interpreter/Options.h"
55 #include "lldb/Interpreter/OptionGroupBoolean.h"
56 #include "lldb/Interpreter/OptionGroupUInt64.h"
57 #include "lldb/Interpreter/Property.h"
58 #include "lldb/Symbol/ObjectFile.h"
59 #include "lldb/Target/DynamicLoader.h"
60 #include "lldb/Target/Target.h"
61 #include "lldb/Target/TargetList.h"
62 #include "lldb/Target/ThreadPlanCallFunction.h"
63 #include "lldb/Target/SystemRuntime.h"
64 #include "lldb/Utility/PseudoTerminal.h"
67 #include "lldb/Host/Host.h"
68 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
69 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
70 #include "Plugins/Process/Utility/StopInfoMachException.h"
71 #include "Utility/StringExtractorGDBRemote.h"
72 #include "GDBRemoteRegisterContext.h"
73 #include "ProcessGDBRemote.h"
74 #include "ProcessGDBRemoteLog.h"
75 #include "ThreadGDBRemote.h"
77 #define DEBUGSERVER_BASENAME "debugserver"
79 using namespace lldb_private;
80 using namespace lldb_private::process_gdb_remote;
84 // Provide a function that can easily dump the packet history if we know a
85 // ProcessGDBRemote * value (which we can get from logs or from debugging).
86 // We need the function in the lldb namespace so it makes it into the final
87 // executable since the LLDB shared library only exports stuff in the lldb
88 // namespace. This allows you to attach with a debugger and call this
89 // function and get the packet history dumped to a file.
91 DumpProcessGDBRemotePacketHistory (void *p, const char *path)
94 Error error (strm.GetFile().Open(path, File::eOpenOptionWrite | File::eOpenOptionCanCreate));
96 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory (strm);
102 static PropertyDefinition
105 { "packet-timeout" , OptionValue::eTypeUInt64 , true , 1, NULL, NULL, "Specify the default packet timeout in seconds." },
106 { "target-definition-file" , OptionValue::eTypeFileSpec , true, 0 , NULL, NULL, "The file that provides the description for remote target registers." },
107 { NULL , OptionValue::eTypeInvalid, false, 0, NULL, NULL, NULL }
112 ePropertyPacketTimeout,
113 ePropertyTargetDefinitionFile
116 class PluginProperties : public Properties
123 return ProcessGDBRemote::GetPluginNameStatic();
129 m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
130 m_collection_sp->Initialize(g_properties);
141 const uint32_t idx = ePropertyPacketTimeout;
142 return m_collection_sp->GetPropertyAtIndexAsUInt64(NULL, idx, g_properties[idx].default_uint_value);
146 SetPacketTimeout(uint64_t timeout)
148 const uint32_t idx = ePropertyPacketTimeout;
149 return m_collection_sp->SetPropertyAtIndexAsUInt64(NULL, idx, timeout);
153 GetTargetDefinitionFile () const
155 const uint32_t idx = ePropertyTargetDefinitionFile;
156 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
160 typedef std::shared_ptr<PluginProperties> ProcessKDPPropertiesSP;
162 static const ProcessKDPPropertiesSP &
163 GetGlobalPluginProperties()
165 static ProcessKDPPropertiesSP g_settings_sp;
167 g_settings_sp.reset (new PluginProperties ());
168 return g_settings_sp;
171 } // anonymous namespace end
173 class ProcessGDBRemote::GDBLoadedModuleInfoList
177 class LoadedModuleInfo
192 for (uint32_t i = 0; i < e_num; ++i)
196 void set_name (const std::string & name)
199 m_has[e_has_name] = true;
201 bool get_name (std::string & out) const
204 return m_has[e_has_name];
207 void set_base (const lldb::addr_t base)
210 m_has[e_has_base] = true;
212 bool get_base (lldb::addr_t & out) const
215 return m_has[e_has_base];
218 void set_link_map (const lldb::addr_t addr)
221 m_has[e_has_link_map] = true;
223 bool get_link_map (lldb::addr_t & out) const
226 return m_has[e_has_link_map];
229 void set_dynamic (const lldb::addr_t addr)
232 m_has[e_has_dynamic] = true;
234 bool get_dynamic (lldb::addr_t & out) const
237 return m_has[e_has_dynamic];
240 bool has_info (e_data_point datum)
242 assert (datum < e_num);
250 lldb::addr_t m_link_map;
252 lldb::addr_t m_dynamic;
255 GDBLoadedModuleInfoList ()
257 , m_link_map (LLDB_INVALID_ADDRESS)
260 void add (const LoadedModuleInfo & mod)
262 m_list.push_back (mod);
270 std::vector<LoadedModuleInfo> m_list;
271 lldb::addr_t m_link_map;
274 // TODO Randomly assigning a port is unsafe. We should get an unused
275 // ephemeral port from the kernel and make sure we reserve it before passing
276 // it to debugserver.
278 #if defined (__APPLE__)
279 #define LOW_PORT (IPPORT_RESERVED)
280 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
282 #define LOW_PORT (1024u)
283 #define HIGH_PORT (49151u)
286 #if defined(__APPLE__) && (defined(__arm__) || defined(__arm64__) || defined(__aarch64__))
287 static bool rand_initialized = false;
289 static inline uint16_t
292 if (!rand_initialized)
294 time_t seed = time(NULL);
296 rand_initialized = true;
299 return (rand() % (HIGH_PORT - LOW_PORT)) + LOW_PORT;
304 ProcessGDBRemote::GetPluginNameStatic()
306 static ConstString g_name("gdb-remote");
311 ProcessGDBRemote::GetPluginDescriptionStatic()
313 return "GDB Remote protocol based debugging plug-in.";
317 ProcessGDBRemote::Terminate()
319 PluginManager::UnregisterPlugin (ProcessGDBRemote::CreateInstance);
324 ProcessGDBRemote::CreateInstance (Target &target, Listener &listener, const FileSpec *crash_file_path)
326 lldb::ProcessSP process_sp;
327 if (crash_file_path == NULL)
328 process_sp.reset (new ProcessGDBRemote (target, listener));
333 ProcessGDBRemote::CanDebug (Target &target, bool plugin_specified_by_name)
335 if (plugin_specified_by_name)
338 // For now we are just making sure the file exists for a given module
339 Module *exe_module = target.GetExecutableModulePointer();
342 ObjectFile *exe_objfile = exe_module->GetObjectFile();
343 // We can't debug core files...
344 switch (exe_objfile->GetType())
346 case ObjectFile::eTypeInvalid:
347 case ObjectFile::eTypeCoreFile:
348 case ObjectFile::eTypeDebugInfo:
349 case ObjectFile::eTypeObjectFile:
350 case ObjectFile::eTypeSharedLibrary:
351 case ObjectFile::eTypeStubLibrary:
352 case ObjectFile::eTypeJIT:
354 case ObjectFile::eTypeExecutable:
355 case ObjectFile::eTypeDynamicLinker:
356 case ObjectFile::eTypeUnknown:
359 return exe_module->GetFileSpec().Exists();
361 // However, if there is no executable module, we return true since we might be preparing to attach.
365 //----------------------------------------------------------------------
366 // ProcessGDBRemote constructor
367 //----------------------------------------------------------------------
368 ProcessGDBRemote::ProcessGDBRemote(Target& target, Listener &listener) :
369 Process (target, listener),
372 m_debugserver_pid (LLDB_INVALID_PROCESS_ID),
373 m_last_stop_packet_mutex (Mutex::eMutexTypeRecursive),
375 m_async_broadcaster (NULL, "lldb.process.gdb-remote.async-broadcaster"),
376 m_async_thread_state_mutex(Mutex::eMutexTypeRecursive),
378 m_threads_info_sp (),
379 m_continue_c_tids (),
380 m_continue_C_tids (),
381 m_continue_s_tids (),
382 m_continue_S_tids (),
383 m_max_memory_size (0),
384 m_remote_stub_max_memory_size (0),
385 m_addr_to_mmap_size (),
386 m_thread_create_bp_sp (),
387 m_waiting_for_attach (false),
388 m_destroy_tried_resuming (false),
390 m_breakpoint_pc_offset (0),
391 m_initial_tid (LLDB_INVALID_THREAD_ID)
393 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadShouldExit, "async thread should exit");
394 m_async_broadcaster.SetEventName (eBroadcastBitAsyncContinue, "async thread continue");
395 m_async_broadcaster.SetEventName (eBroadcastBitAsyncThreadDidExit, "async thread did exit");
396 const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout();
397 if (timeout_seconds > 0)
398 m_gdb_comm.SetPacketTimeout(timeout_seconds);
401 //----------------------------------------------------------------------
403 //----------------------------------------------------------------------
404 ProcessGDBRemote::~ProcessGDBRemote()
406 // m_mach_process.UnregisterNotificationCallbacks (this);
408 // We need to call finalize on the process before destroying ourselves
409 // to make sure all of the broadcaster cleanup goes as planned. If we
410 // destruct this class, then Process::~Process() might have problems
411 // trying to fully destroy the broadcaster.
414 // The general Finalize is going to try to destroy the process and that SHOULD
415 // shut down the async thread. However, if we don't kill it it will get stranded and
416 // its connection will go away so when it wakes up it will crash. So kill it for sure here.
418 KillDebugserverProcess();
421 //----------------------------------------------------------------------
423 //----------------------------------------------------------------------
425 ProcessGDBRemote::GetPluginName()
427 return GetPluginNameStatic();
431 ProcessGDBRemote::GetPluginVersion()
437 ProcessGDBRemote::ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
439 ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
441 StructuredData::ObjectSP module_object_sp(interpreter->LoadPluginModule(target_definition_fspec, error));
442 if (module_object_sp)
444 StructuredData::DictionarySP target_definition_sp(
445 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error));
447 if (target_definition_sp)
449 StructuredData::ObjectSP target_object(target_definition_sp->GetValueForKey("host-info"));
452 if (auto host_info_dict = target_object->GetAsDictionary())
454 StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple");
455 if (auto triple_string_value = triple_value->GetAsString())
457 std::string triple_string = triple_string_value->GetValue();
458 ArchSpec host_arch(triple_string.c_str());
459 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture()))
461 GetTarget().SetArchitecture(host_arch);
466 m_breakpoint_pc_offset = 0;
467 StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset");
468 if (breakpoint_pc_offset_value)
470 if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger())
471 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
474 if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0)
484 SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_regiter_numbers, std::vector<uint32_t> ®nums, int base)
487 std::pair<llvm::StringRef, llvm::StringRef> value_pair;
488 value_pair.second = comma_separated_regiter_numbers;
491 value_pair = value_pair.second.split(',');
492 if (!value_pair.first.empty())
494 uint32_t reg = StringConvert::ToUInt32 (value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base);
495 if (reg != LLDB_INVALID_REGNUM)
496 regnums.push_back (reg);
498 } while (!value_pair.second.empty());
499 return regnums.size();
504 ProcessGDBRemote::BuildDynamicRegisterInfo (bool force)
506 if (!force && m_register_info.GetNumRegisters() > 0)
509 m_register_info.Clear();
511 // Check if qHostInfo specified a specific packet timeout for this connection.
512 // If so then lets update our setting so the user knows what the timeout is
514 const uint32_t host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
515 if (host_packet_timeout)
517 GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout);
520 // Register info search order:
521 // 1 - Use the target definition python file if one is specified.
522 // 2 - If the target definition doesn't have any of the info from the target.xml (registers) then proceed to read the target.xml.
523 // 3 - Fall back on the qRegisterInfo packets.
525 FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile ();
526 if (target_definition_fspec)
528 // See if we can get register definitions from a python file
529 if (ParsePythonTargetDefinition (target_definition_fspec))
533 if (GetGDBServerRegisterInfo ())
537 uint32_t reg_offset = 0;
538 uint32_t reg_num = 0;
539 for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse;
540 response_type == StringExtractorGDBRemote::eResponse;
543 const int packet_len = ::snprintf (packet, sizeof(packet), "qRegisterInfo%x", reg_num);
544 assert (packet_len < (int)sizeof(packet));
545 StringExtractorGDBRemote response;
546 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, false) == GDBRemoteCommunication::PacketResult::Success)
548 response_type = response.GetResponseType();
549 if (response_type == StringExtractorGDBRemote::eResponse)
553 ConstString reg_name;
554 ConstString alt_name;
555 ConstString set_name;
556 std::vector<uint32_t> value_regs;
557 std::vector<uint32_t> invalidate_regs;
558 RegisterInfo reg_info = { NULL, // Name
561 reg_offset, // offset
562 eEncodingUint, // encoding
563 eFormatHex, // formate
565 LLDB_INVALID_REGNUM, // GCC reg num
566 LLDB_INVALID_REGNUM, // DWARF reg num
567 LLDB_INVALID_REGNUM, // generic reg num
568 reg_num, // GDB reg num
569 reg_num // native register number
575 while (response.GetNameColonValue(name, value))
577 if (name.compare("name") == 0)
579 reg_name.SetCString(value.c_str());
581 else if (name.compare("alt-name") == 0)
583 alt_name.SetCString(value.c_str());
585 else if (name.compare("bitsize") == 0)
587 reg_info.byte_size = StringConvert::ToUInt32(value.c_str(), 0, 0) / CHAR_BIT;
589 else if (name.compare("offset") == 0)
591 uint32_t offset = StringConvert::ToUInt32(value.c_str(), UINT32_MAX, 0);
592 if (reg_offset != offset)
597 else if (name.compare("encoding") == 0)
599 const Encoding encoding = Args::StringToEncoding (value.c_str());
600 if (encoding != eEncodingInvalid)
601 reg_info.encoding = encoding;
603 else if (name.compare("format") == 0)
605 Format format = eFormatInvalid;
606 if (Args::StringToFormat (value.c_str(), format, NULL).Success())
607 reg_info.format = format;
608 else if (value.compare("binary") == 0)
609 reg_info.format = eFormatBinary;
610 else if (value.compare("decimal") == 0)
611 reg_info.format = eFormatDecimal;
612 else if (value.compare("hex") == 0)
613 reg_info.format = eFormatHex;
614 else if (value.compare("float") == 0)
615 reg_info.format = eFormatFloat;
616 else if (value.compare("vector-sint8") == 0)
617 reg_info.format = eFormatVectorOfSInt8;
618 else if (value.compare("vector-uint8") == 0)
619 reg_info.format = eFormatVectorOfUInt8;
620 else if (value.compare("vector-sint16") == 0)
621 reg_info.format = eFormatVectorOfSInt16;
622 else if (value.compare("vector-uint16") == 0)
623 reg_info.format = eFormatVectorOfUInt16;
624 else if (value.compare("vector-sint32") == 0)
625 reg_info.format = eFormatVectorOfSInt32;
626 else if (value.compare("vector-uint32") == 0)
627 reg_info.format = eFormatVectorOfUInt32;
628 else if (value.compare("vector-float32") == 0)
629 reg_info.format = eFormatVectorOfFloat32;
630 else if (value.compare("vector-uint128") == 0)
631 reg_info.format = eFormatVectorOfUInt128;
633 else if (name.compare("set") == 0)
635 set_name.SetCString(value.c_str());
637 else if (name.compare("gcc") == 0)
639 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
641 else if (name.compare("dwarf") == 0)
643 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.c_str(), LLDB_INVALID_REGNUM, 0);
645 else if (name.compare("generic") == 0)
647 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister (value.c_str());
649 else if (name.compare("container-regs") == 0)
651 SplitCommaSeparatedRegisterNumberString(value, value_regs, 16);
653 else if (name.compare("invalidate-regs") == 0)
655 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16);
659 reg_info.byte_offset = reg_offset;
660 assert (reg_info.byte_size != 0);
661 reg_offset += reg_info.byte_size;
662 if (!value_regs.empty())
664 value_regs.push_back(LLDB_INVALID_REGNUM);
665 reg_info.value_regs = value_regs.data();
667 if (!invalidate_regs.empty())
669 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
670 reg_info.invalidate_regs = invalidate_regs.data();
673 m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name);
677 break; // ensure exit before reg_num is incremented
686 if (m_register_info.GetNumRegisters() > 0)
688 m_register_info.Finalize(GetTarget().GetArchitecture());
692 // We didn't get anything if the accumulated reg_num is zero. See if we are
693 // debugging ARM and fill with a hard coded register set until we can get an
694 // updated debugserver down on the devices.
695 // On the other hand, if the accumulated reg_num is positive, see if we can
696 // add composite registers to the existing primordial ones.
697 bool from_scratch = (m_register_info.GetNumRegisters() == 0);
699 const ArchSpec &target_arch = GetTarget().GetArchitecture();
700 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
701 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
703 // Use the process' architecture instead of the host arch, if available
704 ArchSpec remote_arch;
705 if (remote_process_arch.IsValid ())
706 remote_arch = remote_process_arch;
708 remote_arch = remote_host_arch;
710 if (!target_arch.IsValid())
712 if (remote_arch.IsValid()
713 && remote_arch.GetMachine() == llvm::Triple::arm
714 && remote_arch.GetTriple().getVendor() == llvm::Triple::Apple)
715 m_register_info.HardcodeARMRegisters(from_scratch);
717 else if (target_arch.GetMachine() == llvm::Triple::arm)
719 m_register_info.HardcodeARMRegisters(from_scratch);
722 // At this point, we can finalize our register info.
723 m_register_info.Finalize (GetTarget().GetArchitecture());
727 ProcessGDBRemote::WillLaunch (Module* module)
729 return WillLaunchOrAttach ();
733 ProcessGDBRemote::WillAttachToProcessWithID (lldb::pid_t pid)
735 return WillLaunchOrAttach ();
739 ProcessGDBRemote::WillAttachToProcessWithName (const char *process_name, bool wait_for_launch)
741 return WillLaunchOrAttach ();
745 ProcessGDBRemote::DoConnectRemote (Stream *strm, const char *remote_url)
747 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
748 Error error (WillLaunchOrAttach ());
753 error = ConnectToDebugserver (remote_url);
759 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
760 if (pid == LLDB_INVALID_PROCESS_ID)
762 // We don't have a valid process ID, so note that we are connected
763 // and could now request to launch or attach, or get remote process
765 SetPrivateState (eStateConnected);
769 // We have a valid process
772 StringExtractorGDBRemote response;
773 if (m_gdb_comm.GetStopReply(response))
775 SetLastStopPacket(response);
777 // '?' Packets must be handled differently in non-stop mode
778 if (GetTarget().GetNonStopModeEnabled())
779 HandleStopReplySequence();
781 if (!m_target.GetArchitecture().IsValid())
783 if (m_gdb_comm.GetProcessArchitecture().IsValid())
785 m_target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
789 m_target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
793 const StateType state = SetThreadStopInfo (response);
794 if (state == eStateStopped)
796 SetPrivateState (state);
799 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but state was not stopped: %s", pid, remote_url, StateAsCString (state));
802 error.SetErrorStringWithFormat ("Process %" PRIu64 " was reported after connecting to '%s', but no stop reply packet was received", pid, remote_url);
806 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");
810 && !GetTarget().GetArchitecture().IsValid()
811 && m_gdb_comm.GetHostArchitecture().IsValid())
813 // Prefer the *process'* architecture over that of the *host*, if available.
814 if (m_gdb_comm.GetProcessArchitecture().IsValid())
815 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
817 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
821 log->Printf ("ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID (), GetTarget ().GetArchitecture ().GetTriple ().getTriple ().c_str ());
825 PlatformSP platform_sp = GetTarget().GetPlatform();
826 if (platform_sp && platform_sp->IsConnected())
827 SetUnixSignals(platform_sp->GetUnixSignals());
829 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
836 ProcessGDBRemote::WillLaunchOrAttach ()
839 m_stdio_communication.Clear ();
843 //----------------------------------------------------------------------
845 //----------------------------------------------------------------------
847 ProcessGDBRemote::DoLaunch (Module *exe_module, ProcessLaunchInfo &launch_info)
849 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
853 log->Printf ("ProcessGDBRemote::%s() entered", __FUNCTION__);
855 uint32_t launch_flags = launch_info.GetFlags().Get();
856 FileSpec stdin_file_spec{};
857 FileSpec stdout_file_spec{};
858 FileSpec stderr_file_spec{};
859 FileSpec working_dir = launch_info.GetWorkingDirectory();
861 const FileAction *file_action;
862 file_action = launch_info.GetFileActionForFD (STDIN_FILENO);
865 if (file_action->GetAction() == FileAction::eFileActionOpen)
866 stdin_file_spec = file_action->GetFileSpec();
868 file_action = launch_info.GetFileActionForFD (STDOUT_FILENO);
871 if (file_action->GetAction() == FileAction::eFileActionOpen)
872 stdout_file_spec = file_action->GetFileSpec();
874 file_action = launch_info.GetFileActionForFD (STDERR_FILENO);
877 if (file_action->GetAction() == FileAction::eFileActionOpen)
878 stderr_file_spec = file_action->GetFileSpec();
883 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
884 log->Printf ("ProcessGDBRemote::%s provided with STDIO paths via launch_info: stdin=%s, stdout=%s, stderr=%s",
886 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
887 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
888 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
890 log->Printf ("ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__);
893 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
894 if (stdin_file_spec || disable_stdio)
896 // the inferior will be reading stdin from the specified file
897 // or stdio is completely disabled
898 m_stdin_forward = false;
902 m_stdin_forward = true;
905 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
906 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | LLDB_LOG_OPTION_PREPEND_TIMESTAMP | LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
907 // ::LogSetLogFile ("/dev/stdout");
909 ObjectFile * object_file = exe_module->GetObjectFile();
912 // Make sure we aren't already connected?
913 if (!m_gdb_comm.IsConnected())
915 error = LaunchAndConnectToDebugserver (launch_info);
920 lldb_utility::PseudoTerminal pty;
921 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
923 PlatformSP platform_sp (m_target.GetPlatform());
926 // set to /dev/null unless redirected to a file above
927 if (!stdin_file_spec)
928 stdin_file_spec.SetFile("/dev/null", false);
929 if (!stdout_file_spec)
930 stdout_file_spec.SetFile("/dev/null", false);
931 if (!stderr_file_spec)
932 stderr_file_spec.SetFile("/dev/null", false);
934 else if (platform_sp && platform_sp->IsHost())
936 // If the debugserver is local and we aren't disabling STDIO, lets use
937 // a pseudo terminal to instead of relying on the 'O' packets for stdio
938 // since 'O' packets can really slow down debugging if the inferior
939 // does a lot of output.
940 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
941 pty.OpenFirstAvailableMaster(O_RDWR|O_NOCTTY, NULL, 0))
943 FileSpec slave_name{pty.GetSlaveName(NULL, 0), false};
945 if (!stdin_file_spec)
946 stdin_file_spec = slave_name;
948 if (!stdout_file_spec)
949 stdout_file_spec = slave_name;
951 if (!stderr_file_spec)
952 stderr_file_spec = slave_name;
955 log->Printf ("ProcessGDBRemote::%s adjusted STDIO paths for local platform (IsHost() is true) using slave: stdin=%s, stdout=%s, stderr=%s",
957 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
958 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
959 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
963 log->Printf ("ProcessGDBRemote::%s final STDIO paths after all adjustments: stdin=%s, stdout=%s, stderr=%s",
965 stdin_file_spec ? stdin_file_spec.GetCString() : "<null>",
966 stdout_file_spec ? stdout_file_spec.GetCString() : "<null>",
967 stderr_file_spec ? stderr_file_spec.GetCString() : "<null>");
970 m_gdb_comm.SetSTDIN(stdin_file_spec);
971 if (stdout_file_spec)
972 m_gdb_comm.SetSTDOUT(stdout_file_spec);
973 if (stderr_file_spec)
974 m_gdb_comm.SetSTDERR(stderr_file_spec);
976 m_gdb_comm.SetDisableASLR (launch_flags & eLaunchFlagDisableASLR);
977 m_gdb_comm.SetDetachOnError (launch_flags & eLaunchFlagDetachOnError);
979 m_gdb_comm.SendLaunchArchPacket (m_target.GetArchitecture().GetArchitectureName());
981 const char * launch_event_data = launch_info.GetLaunchEventData();
982 if (launch_event_data != NULL && *launch_event_data != '\0')
983 m_gdb_comm.SendLaunchEventDataPacket (launch_event_data);
987 m_gdb_comm.SetWorkingDir (working_dir);
990 // Send the environment and the program + arguments after we connect
991 const Args &environment = launch_info.GetEnvironmentEntries();
992 if (environment.GetArgumentCount())
994 size_t num_environment_entries = environment.GetArgumentCount();
995 for (size_t i=0; i<num_environment_entries; ++i)
997 const char *env_entry = environment.GetArgumentAtIndex(i);
998 if (env_entry == NULL || m_gdb_comm.SendEnvironmentPacket(env_entry) != 0)
1004 // Scope for the scoped timeout object
1005 GDBRemoteCommunication::ScopedTimeout timeout (m_gdb_comm, 10);
1007 int arg_packet_err = m_gdb_comm.SendArgumentsPacket (launch_info);
1008 if (arg_packet_err == 0)
1010 std::string error_str;
1011 if (m_gdb_comm.GetLaunchSuccess (error_str))
1013 SetID (m_gdb_comm.GetCurrentProcessID ());
1017 error.SetErrorString (error_str.c_str());
1022 error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err);
1026 if (GetID() == LLDB_INVALID_PROCESS_ID)
1029 log->Printf("failed to connect to debugserver: %s", error.AsCString());
1030 KillDebugserverProcess ();
1034 StringExtractorGDBRemote response;
1035 if (m_gdb_comm.GetStopReply(response))
1037 SetLastStopPacket(response);
1038 // '?' Packets must be handled differently in non-stop mode
1039 if (GetTarget().GetNonStopModeEnabled())
1040 HandleStopReplySequence();
1042 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
1044 if (process_arch.IsValid())
1046 m_target.MergeArchitecture(process_arch);
1050 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
1051 if (host_arch.IsValid())
1052 m_target.MergeArchitecture(host_arch);
1055 SetPrivateState (SetThreadStopInfo (response));
1059 if (pty.GetMasterFileDescriptor() != lldb_utility::PseudoTerminal::invalid_fd)
1060 SetSTDIOFileDescriptor (pty.ReleaseMasterFileDescriptor());
1067 log->Printf("failed to connect to debugserver: %s", error.AsCString());
1072 // Set our user ID to an invalid process ID.
1073 SetID(LLDB_INVALID_PROCESS_ID);
1074 error.SetErrorStringWithFormat ("failed to get object file from '%s' for arch %s",
1075 exe_module->GetFileSpec().GetFilename().AsCString(),
1076 exe_module->GetArchitecture().GetArchitectureName());
1084 ProcessGDBRemote::ConnectToDebugserver (const char *connect_url)
1087 // Only connect if we have a valid connect URL
1088 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
1090 if (connect_url && connect_url[0])
1093 log->Printf("ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url);
1094 std::unique_ptr<ConnectionFileDescriptor> conn_ap(new ConnectionFileDescriptor());
1097 const uint32_t max_retry_count = 50;
1098 uint32_t retry_count = 0;
1099 while (!m_gdb_comm.IsConnected())
1101 if (conn_ap->Connect(connect_url, &error) == eConnectionStatusSuccess)
1103 m_gdb_comm.SetConnection (conn_ap.release());
1106 else if (error.WasInterrupted())
1108 // If we were interrupted, don't keep retrying.
1114 if (retry_count >= max_retry_count)
1122 if (!m_gdb_comm.IsConnected())
1124 if (error.Success())
1125 error.SetErrorString("not connected to remote gdb server");
1130 // Start the communications read thread so all incoming data can be
1131 // parsed into packets and queued as they arrive.
1132 if (GetTarget().GetNonStopModeEnabled())
1133 m_gdb_comm.StartReadThread();
1135 // We always seem to be able to open a connection to a local port
1136 // so we need to make sure we can then send data to it. If we can't
1137 // then we aren't actually connected to anything, so try and do the
1138 // handshake with the remote GDB server and make sure that goes
1140 if (!m_gdb_comm.HandshakeWithServer (&error))
1142 m_gdb_comm.Disconnect();
1143 if (error.Success())
1144 error.SetErrorString("not connected to remote gdb server");
1148 // Send $QNonStop:1 packet on startup if required
1149 if (GetTarget().GetNonStopModeEnabled())
1150 GetTarget().SetNonStopModeEnabled (m_gdb_comm.SetNonStopMode(true));
1152 m_gdb_comm.GetEchoSupported ();
1153 m_gdb_comm.GetThreadSuffixSupported ();
1154 m_gdb_comm.GetListThreadsInStopReplySupported ();
1155 m_gdb_comm.GetHostInfo ();
1156 m_gdb_comm.GetVContSupported ('c');
1157 m_gdb_comm.GetVAttachOrWaitSupported();
1159 // Ask the remote server for the default thread id
1160 if (GetTarget().GetNonStopModeEnabled())
1161 m_gdb_comm.GetDefaultThreadId(m_initial_tid);
1164 size_t num_cmds = GetExtraStartupCommands().GetArgumentCount();
1165 for (size_t idx = 0; idx < num_cmds; idx++)
1167 StringExtractorGDBRemote response;
1168 m_gdb_comm.SendPacketAndWaitForResponse (GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false);
1174 ProcessGDBRemote::DidLaunchOrAttach (ArchSpec& process_arch)
1176 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1178 log->Printf ("ProcessGDBRemote::DidLaunch()");
1179 if (GetID() != LLDB_INVALID_PROCESS_ID)
1181 BuildDynamicRegisterInfo (false);
1183 // See if the GDB server supports the qHostInfo information
1186 // See if the GDB server supports the qProcessInfo packet, if so
1187 // prefer that over the Host information as it will be more specific
1190 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1191 if (remote_process_arch.IsValid())
1193 process_arch = remote_process_arch;
1195 log->Printf ("ProcessGDBRemote::%s gdb-remote had process architecture, using %s %s",
1197 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1198 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1202 process_arch = m_gdb_comm.GetHostArchitecture();
1204 log->Printf ("ProcessGDBRemote::%s gdb-remote did not have process architecture, using gdb-remote host architecture %s %s",
1206 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1207 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1210 if (process_arch.IsValid())
1212 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1213 if (target_arch.IsValid())
1216 log->Printf ("ProcessGDBRemote::%s analyzing target arch, currently %s %s",
1218 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1219 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1221 // If the remote host is ARM and we have apple as the vendor, then
1222 // ARM executables and shared libraries can have mixed ARM architectures.
1223 // You can have an armv6 executable, and if the host is armv7, then the
1224 // system will load the best possible architecture for all shared libraries
1225 // it has, so we really need to take the remote host architecture as our
1226 // defacto architecture in this case.
1228 if (process_arch.GetMachine() == llvm::Triple::arm &&
1229 process_arch.GetTriple().getVendor() == llvm::Triple::Apple)
1231 GetTarget().SetArchitecture (process_arch);
1233 log->Printf ("ProcessGDBRemote::%s remote process is ARM/Apple, setting target arch to %s %s",
1235 process_arch.GetArchitectureName () ? process_arch.GetArchitectureName () : "<null>",
1236 process_arch.GetTriple().getTriple ().c_str() ? process_arch.GetTriple().getTriple ().c_str() : "<null>");
1240 // Fill in what is missing in the triple
1241 const llvm::Triple &remote_triple = process_arch.GetTriple();
1242 llvm::Triple new_target_triple = target_arch.GetTriple();
1243 if (new_target_triple.getVendorName().size() == 0)
1245 new_target_triple.setVendor (remote_triple.getVendor());
1247 if (new_target_triple.getOSName().size() == 0)
1249 new_target_triple.setOS (remote_triple.getOS());
1251 if (new_target_triple.getEnvironmentName().size() == 0)
1252 new_target_triple.setEnvironment (remote_triple.getEnvironment());
1255 ArchSpec new_target_arch = target_arch;
1256 new_target_arch.SetTriple(new_target_triple);
1257 GetTarget().SetArchitecture(new_target_arch);
1262 log->Printf ("ProcessGDBRemote::%s final target arch after adjustments for remote architecture: %s %s",
1264 target_arch.GetArchitectureName () ? target_arch.GetArchitectureName () : "<null>",
1265 target_arch.GetTriple().getTriple ().c_str() ? target_arch.GetTriple().getTriple ().c_str() : "<null>");
1269 // The target doesn't have a valid architecture yet, set it from
1270 // the architecture we got from the remote GDB server
1271 GetTarget().SetArchitecture (process_arch);
1278 ProcessGDBRemote::DidLaunch ()
1280 ArchSpec process_arch;
1281 DidLaunchOrAttach (process_arch);
1285 ProcessGDBRemote::DoAttachToProcessWithID (lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info)
1287 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1291 log->Printf ("ProcessGDBRemote::%s()", __FUNCTION__);
1293 // Clear out and clean up from any current state
1295 if (attach_pid != LLDB_INVALID_PROCESS_ID)
1297 // Make sure we aren't already connected?
1298 if (!m_gdb_comm.IsConnected())
1300 error = LaunchAndConnectToDebugserver (attach_info);
1304 const char *error_string = error.AsCString();
1305 if (error_string == NULL)
1306 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1308 SetExitStatus (-1, error_string);
1312 if (error.Success())
1314 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1317 const int packet_len = ::snprintf (packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1319 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet, packet_len));
1327 ProcessGDBRemote::DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info)
1330 // Clear out and clean up from any current state
1333 if (process_name && process_name[0])
1335 // Make sure we aren't already connected?
1336 if (!m_gdb_comm.IsConnected())
1338 error = LaunchAndConnectToDebugserver (attach_info);
1342 const char *error_string = error.AsCString();
1343 if (error_string == NULL)
1344 error_string = "unable to launch " DEBUGSERVER_BASENAME;
1346 SetExitStatus (-1, error_string);
1350 if (error.Success())
1352 StreamString packet;
1354 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1356 if (attach_info.GetWaitForLaunch())
1358 if (!m_gdb_comm.GetVAttachOrWaitSupported())
1360 packet.PutCString ("vAttachWait");
1364 if (attach_info.GetIgnoreExisting())
1365 packet.PutCString("vAttachWait");
1367 packet.PutCString ("vAttachOrWait");
1371 packet.PutCString("vAttachName");
1372 packet.PutChar(';');
1373 packet.PutBytesAsRawHex8(process_name, strlen(process_name), lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
1375 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (packet.GetData(), packet.GetSize()));
1383 ProcessGDBRemote::DidExit ()
1385 // When we exit, disconnect from the GDB server communications
1386 m_gdb_comm.Disconnect();
1390 ProcessGDBRemote::DidAttach (ArchSpec &process_arch)
1392 // If you can figure out what the architecture is, fill it in here.
1393 process_arch.Clear();
1394 DidLaunchOrAttach (process_arch);
1399 ProcessGDBRemote::WillResume ()
1401 m_continue_c_tids.clear();
1402 m_continue_C_tids.clear();
1403 m_continue_s_tids.clear();
1404 m_continue_S_tids.clear();
1409 ProcessGDBRemote::DoResume ()
1412 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
1414 log->Printf ("ProcessGDBRemote::Resume()");
1416 Listener listener ("gdb-remote.resume-packet-sent");
1417 if (listener.StartListeningForEvents (&m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent))
1419 listener.StartListeningForEvents (&m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1421 const size_t num_threads = GetThreadList().GetSize();
1423 StreamString continue_packet;
1424 bool continue_packet_error = false;
1425 if (m_gdb_comm.HasAnyVContSupport ())
1427 if (!GetTarget().GetNonStopModeEnabled() &&
1428 (m_continue_c_tids.size() == num_threads ||
1429 (m_continue_c_tids.empty() &&
1430 m_continue_C_tids.empty() &&
1431 m_continue_s_tids.empty() &&
1432 m_continue_S_tids.empty())))
1434 // All threads are continuing, just send a "c" packet
1435 continue_packet.PutCString ("c");
1439 continue_packet.PutCString ("vCont");
1441 if (!m_continue_c_tids.empty())
1443 if (m_gdb_comm.GetVContSupported ('c'))
1445 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)
1446 continue_packet.Printf(";c:%4.4" PRIx64, *t_pos);
1449 continue_packet_error = true;
1452 if (!continue_packet_error && !m_continue_C_tids.empty())
1454 if (m_gdb_comm.GetVContSupported ('C'))
1456 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)
1457 continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1460 continue_packet_error = true;
1463 if (!continue_packet_error && !m_continue_s_tids.empty())
1465 if (m_gdb_comm.GetVContSupported ('s'))
1467 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)
1468 continue_packet.Printf(";s:%4.4" PRIx64, *t_pos);
1471 continue_packet_error = true;
1474 if (!continue_packet_error && !m_continue_S_tids.empty())
1476 if (m_gdb_comm.GetVContSupported ('S'))
1478 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)
1479 continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first);
1482 continue_packet_error = true;
1485 if (continue_packet_error)
1486 continue_packet.GetString().clear();
1490 continue_packet_error = true;
1492 if (continue_packet_error)
1494 // Either no vCont support, or we tried to use part of the vCont
1495 // packet that wasn't supported by the remote GDB server.
1496 // We need to try and make a simple packet that can do our continue
1497 const size_t num_continue_c_tids = m_continue_c_tids.size();
1498 const size_t num_continue_C_tids = m_continue_C_tids.size();
1499 const size_t num_continue_s_tids = m_continue_s_tids.size();
1500 const size_t num_continue_S_tids = m_continue_S_tids.size();
1501 if (num_continue_c_tids > 0)
1503 if (num_continue_c_tids == num_threads)
1505 // All threads are resuming...
1506 m_gdb_comm.SetCurrentThreadForRun (-1);
1507 continue_packet.PutChar ('c');
1508 continue_packet_error = false;
1510 else if (num_continue_c_tids == 1 &&
1511 num_continue_C_tids == 0 &&
1512 num_continue_s_tids == 0 &&
1513 num_continue_S_tids == 0 )
1515 // Only one thread is continuing
1516 m_gdb_comm.SetCurrentThreadForRun (m_continue_c_tids.front());
1517 continue_packet.PutChar ('c');
1518 continue_packet_error = false;
1522 if (continue_packet_error && num_continue_C_tids > 0)
1524 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1525 num_continue_C_tids > 0 &&
1526 num_continue_s_tids == 0 &&
1527 num_continue_S_tids == 0 )
1529 const int continue_signo = m_continue_C_tids.front().second;
1530 // Only one thread is continuing
1531 if (num_continue_C_tids > 1)
1533 // More that one thread with a signal, yet we don't have
1534 // vCont support and we are being asked to resume each
1535 // thread with a signal, we need to make sure they are
1536 // all the same signal, or we can't issue the continue
1537 // accurately with the current support...
1538 if (num_continue_C_tids > 1)
1540 continue_packet_error = false;
1541 for (size_t i=1; i<m_continue_C_tids.size(); ++i)
1543 if (m_continue_C_tids[i].second != continue_signo)
1544 continue_packet_error = true;
1547 if (!continue_packet_error)
1548 m_gdb_comm.SetCurrentThreadForRun (-1);
1552 // Set the continue thread ID
1553 continue_packet_error = false;
1554 m_gdb_comm.SetCurrentThreadForRun (m_continue_C_tids.front().first);
1556 if (!continue_packet_error)
1558 // Add threads continuing with the same signo...
1559 continue_packet.Printf("C%2.2x", continue_signo);
1564 if (continue_packet_error && num_continue_s_tids > 0)
1566 if (num_continue_s_tids == num_threads)
1568 // All threads are resuming...
1569 m_gdb_comm.SetCurrentThreadForRun (-1);
1571 // If in Non-Stop-Mode use vCont when stepping
1572 if (GetTarget().GetNonStopModeEnabled())
1574 if (m_gdb_comm.GetVContSupported('s'))
1575 continue_packet.PutCString("vCont;s");
1577 continue_packet.PutChar('s');
1580 continue_packet.PutChar('s');
1582 continue_packet_error = false;
1584 else if (num_continue_c_tids == 0 &&
1585 num_continue_C_tids == 0 &&
1586 num_continue_s_tids == 1 &&
1587 num_continue_S_tids == 0 )
1589 // Only one thread is stepping
1590 m_gdb_comm.SetCurrentThreadForRun (m_continue_s_tids.front());
1591 continue_packet.PutChar ('s');
1592 continue_packet_error = false;
1596 if (!continue_packet_error && num_continue_S_tids > 0)
1598 if (num_continue_S_tids == num_threads)
1600 const int step_signo = m_continue_S_tids.front().second;
1601 // Are all threads trying to step with the same signal?
1602 continue_packet_error = false;
1603 if (num_continue_S_tids > 1)
1605 for (size_t i=1; i<num_threads; ++i)
1607 if (m_continue_S_tids[i].second != step_signo)
1608 continue_packet_error = true;
1611 if (!continue_packet_error)
1613 // Add threads stepping with the same signo...
1614 m_gdb_comm.SetCurrentThreadForRun (-1);
1615 continue_packet.Printf("S%2.2x", step_signo);
1618 else if (num_continue_c_tids == 0 &&
1619 num_continue_C_tids == 0 &&
1620 num_continue_s_tids == 0 &&
1621 num_continue_S_tids == 1 )
1623 // Only one thread is stepping with signal
1624 m_gdb_comm.SetCurrentThreadForRun (m_continue_S_tids.front().first);
1625 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1626 continue_packet_error = false;
1631 if (continue_packet_error)
1633 error.SetErrorString ("can't make continue packet for this resume");
1639 timeout = TimeValue::Now();
1640 timeout.OffsetWithSeconds (5);
1641 if (!m_async_thread.IsJoinable())
1643 error.SetErrorString ("Trying to resume but the async thread is dead.");
1645 log->Printf ("ProcessGDBRemote::DoResume: Trying to resume but the async thread is dead.");
1649 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncContinue, new EventDataBytes (continue_packet.GetData(), continue_packet.GetSize()));
1651 if (listener.WaitForEvent (&timeout, event_sp) == false)
1653 error.SetErrorString("Resume timed out.");
1655 log->Printf ("ProcessGDBRemote::DoResume: Resume timed out.");
1657 else if (event_sp->BroadcasterIs (&m_async_broadcaster))
1659 error.SetErrorString ("Broadcast continue, but the async thread was killed before we got an ack back.");
1661 log->Printf ("ProcessGDBRemote::DoResume: Broadcast continue, but the async thread was killed before we got an ack back.");
1671 ProcessGDBRemote::HandleStopReplySequence ()
1676 StringExtractorGDBRemote response;
1677 m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false);
1679 // OK represents end of signal list
1680 if (response.IsOKResponse())
1683 // If not OK or a normal packet we have a problem
1684 if (!response.IsNormalResponse())
1687 SetLastStopPacket(response);
1692 ProcessGDBRemote::ClearThreadIDList ()
1694 Mutex::Locker locker(m_thread_list_real.GetMutex());
1695 m_thread_ids.clear();
1699 ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue (std::string &value)
1701 m_thread_ids.clear();
1704 while ((comma_pos = value.find(',')) != std::string::npos)
1706 value[comma_pos] = '\0';
1707 // thread in big endian hex
1708 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1709 if (tid != LLDB_INVALID_THREAD_ID)
1710 m_thread_ids.push_back (tid);
1711 value.erase(0, comma_pos + 1);
1713 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
1714 if (tid != LLDB_INVALID_THREAD_ID)
1715 m_thread_ids.push_back (tid);
1716 return m_thread_ids.size();
1720 ProcessGDBRemote::UpdateThreadIDList ()
1722 Mutex::Locker locker(m_thread_list_real.GetMutex());
1724 if (m_threads_info_sp)
1726 // If we have the JSON threads info, we can get the thread list from that
1727 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray();
1728 if (thread_infos && thread_infos->GetSize() > 0)
1730 m_thread_ids.clear();
1731 thread_infos->ForEach([this](StructuredData::Object* object) -> bool {
1732 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1735 // Set the thread stop info from the JSON dictionary
1736 SetThreadStopInfo (thread_dict);
1737 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1738 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1739 m_thread_ids.push_back(tid);
1741 return true; // Keep iterating through all thread_info objects
1744 if (!m_thread_ids.empty())
1749 // See if we can get the thread IDs from the current stop reply packets
1750 // that might contain a "threads" key/value pair
1752 // Lock the thread stack while we access it
1753 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
1754 // Get the number of stop packets on the stack
1755 int nItems = m_stop_packet_stack.size();
1756 // Iterate over them
1757 for (int i = 0; i < nItems; i++)
1759 // Get the thread stop info
1760 StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i];
1761 const std::string &stop_info_str = stop_info.GetStringRef();
1762 const size_t threads_pos = stop_info_str.find(";threads:");
1763 if (threads_pos != std::string::npos)
1765 const size_t start = threads_pos + strlen(";threads:");
1766 const size_t end = stop_info_str.find(';', start);
1767 if (end != std::string::npos)
1769 std::string value = stop_info_str.substr(start, end - start);
1770 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1777 bool sequence_mutex_unavailable = false;
1778 m_gdb_comm.GetCurrentThreadIDs (m_thread_ids, sequence_mutex_unavailable);
1779 if (sequence_mutex_unavailable)
1781 return false; // We just didn't get the list
1787 ProcessGDBRemote::UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list)
1789 // locker will keep a mutex locked until it goes out of scope
1790 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_THREAD));
1791 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1792 log->Printf ("ProcessGDBRemote::%s (pid = %" PRIu64 ")", __FUNCTION__, GetID());
1794 size_t num_thread_ids = m_thread_ids.size();
1795 // The "m_thread_ids" thread ID list should always be updated after each stop
1796 // reply packet, but in case it isn't, update it here.
1797 if (num_thread_ids == 0)
1799 if (!UpdateThreadIDList ())
1801 num_thread_ids = m_thread_ids.size();
1804 ThreadList old_thread_list_copy(old_thread_list);
1805 if (num_thread_ids > 0)
1807 for (size_t i=0; i<num_thread_ids; ++i)
1809 tid_t tid = m_thread_ids[i];
1810 ThreadSP thread_sp (old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1813 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1814 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1816 "ProcessGDBRemote::%s Making new thread: %p for thread ID: 0x%" PRIx64 ".\n",
1817 __FUNCTION__, static_cast<void*>(thread_sp.get()),
1818 thread_sp->GetID());
1822 if (log && log->GetMask().Test(GDBR_LOG_VERBOSE))
1824 "ProcessGDBRemote::%s Found old thread: %p for thread ID: 0x%" PRIx64 ".\n",
1825 __FUNCTION__, static_cast<void*>(thread_sp.get()),
1826 thread_sp->GetID());
1828 new_thread_list.AddThread(thread_sp);
1832 // Whatever that is left in old_thread_list_copy are not
1833 // present in new_thread_list. Remove non-existent threads from internal id table.
1834 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1835 for (size_t i=0; i<old_num_thread_ids; i++)
1837 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex (i, false));
1840 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1841 m_thread_id_to_index_id_map.erase(old_thread_id);
1849 ProcessGDBRemote::CalculateThreadStopInfo (ThreadGDBRemote *thread)
1851 // See if we got thread stop infos for all threads via the "jThreadsInfo" packet
1852 if (m_threads_info_sp)
1854 StructuredData::Array *thread_infos = m_threads_info_sp->GetAsArray();
1858 const size_t n = thread_infos->GetSize();
1859 for (size_t i=0; i<n; ++i)
1861 StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1864 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid, LLDB_INVALID_THREAD_ID))
1866 if (tid == thread->GetID())
1867 return SetThreadStopInfo(thread_dict);
1874 // Fall back to using the qThreadStopInfo packet
1875 StringExtractorGDBRemote stop_packet;
1876 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1877 return SetThreadStopInfo (stop_packet) == eStateStopped;
1883 ProcessGDBRemote::SetThreadStopInfo (lldb::tid_t tid,
1884 ExpeditedRegisterMap &expedited_register_map,
1886 const std::string &thread_name,
1887 const std::string &reason,
1888 const std::string &description,
1890 const std::vector<addr_t> &exc_data,
1891 addr_t thread_dispatch_qaddr,
1892 bool queue_vars_valid, // Set to true if queue_name, queue_kind and queue_serial are valid
1893 std::string &queue_name,
1894 QueueKind queue_kind,
1895 uint64_t queue_serial)
1898 if (tid != LLDB_INVALID_THREAD_ID)
1900 // Scope for "locker" below
1902 // m_thread_list_real does have its own mutex, but we need to
1903 // hold onto the mutex between the call to m_thread_list_real.FindThreadByID(...)
1904 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1905 Mutex::Locker locker (m_thread_list_real.GetMutex ());
1906 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1910 // Create the thread if we need to
1911 thread_sp.reset (new ThreadGDBRemote (*this, tid));
1912 m_thread_list_real.AddThread(thread_sp);
1918 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *> (thread_sp.get());
1919 gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true);
1921 for (const auto &pair : expedited_register_map)
1923 StringExtractor reg_value_extractor;
1924 reg_value_extractor.GetStringRef() = pair.second;
1925 gdb_thread->PrivateSetRegisterValue (pair.first, reg_value_extractor);
1928 // Clear the stop info just in case we don't set it to anything
1929 thread_sp->SetStopInfo (StopInfoSP());
1930 thread_sp->SetName (thread_name.empty() ? NULL : thread_name.c_str());
1932 gdb_thread->SetThreadDispatchQAddr (thread_dispatch_qaddr);
1933 // Check if the GDB server was able to provide the queue name, kind and serial number
1934 if (queue_vars_valid)
1935 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial);
1937 gdb_thread->ClearQueueInfo();
1942 const size_t exc_data_size = exc_data.size();
1944 thread_sp->SetStopInfo (StopInfoMachException::CreateStopReasonWithMachException (*thread_sp,
1947 exc_data_size >= 1 ? exc_data[0] : 0,
1948 exc_data_size >= 2 ? exc_data[1] : 0,
1949 exc_data_size >= 3 ? exc_data[2] : 0));
1953 bool handled = false;
1954 bool did_exec = false;
1955 if (!reason.empty())
1957 if (reason.compare("trace") == 0)
1959 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
1962 else if (reason.compare("breakpoint") == 0)
1964 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1965 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1968 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
1969 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
1970 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
1972 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
1974 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
1978 StopInfoSP invalid_stop_info_sp;
1979 thread_sp->SetStopInfo (invalid_stop_info_sp);
1983 else if (reason.compare("trap") == 0)
1985 // Let the trap just use the standard signal stop reason below...
1987 else if (reason.compare("watchpoint") == 0)
1989 StringExtractor desc_extractor(description.c_str());
1990 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1991 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1992 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1993 watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1994 if (wp_addr != LLDB_INVALID_ADDRESS)
1996 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1999 wp_sp->SetHardwareIndex(wp_index);
2000 watch_id = wp_sp->GetID();
2003 if (watch_id == LLDB_INVALID_WATCH_ID)
2005 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_WATCHPOINTS));
2006 if (log) log->Printf ("failed to find watchpoint");
2008 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithWatchpointID (*thread_sp, watch_id, wp_hit_addr));
2011 else if (reason.compare("exception") == 0)
2013 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException(*thread_sp, description.c_str()));
2016 else if (reason.compare("exec") == 0)
2019 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithExec(*thread_sp));
2024 if (!handled && signo && did_exec == false)
2026 if (signo == SIGTRAP)
2028 // Currently we are going to assume SIGTRAP means we are either
2029 // hitting a breakpoint or hardware single stepping.
2031 addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2032 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2036 // If the breakpoint is for this thread, then we'll report the hit, but if it is for another thread,
2037 // we can just report no reason. We don't need to worry about stepping over the breakpoint here, that
2038 // will be taken care of when the thread resumes and notices that there's a breakpoint under the pc.
2039 if (bp_site_sp->ValidForThisThread (thread_sp.get()))
2041 if(m_breakpoint_pc_offset != 0)
2042 thread_sp->GetRegisterContext()->SetPC(pc);
2043 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithBreakpointSiteID (*thread_sp, bp_site_sp->GetID()));
2047 StopInfoSP invalid_stop_info_sp;
2048 thread_sp->SetStopInfo (invalid_stop_info_sp);
2053 // If we were stepping then assume the stop was the result of the trace. If we were
2054 // not stepping then report the SIGTRAP.
2055 // FIXME: We are still missing the case where we single step over a trap instruction.
2056 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2057 thread_sp->SetStopInfo (StopInfo::CreateStopReasonToTrace (*thread_sp));
2059 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal(*thread_sp, signo, description.c_str()));
2063 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithSignal (*thread_sp, signo, description.c_str()));
2066 if (!description.empty())
2068 lldb::StopInfoSP stop_info_sp (thread_sp->GetStopInfo ());
2071 const char *stop_info_desc = stop_info_sp->GetDescription();
2072 if (!stop_info_desc || !stop_info_desc[0])
2073 stop_info_sp->SetDescription (description.c_str());
2077 thread_sp->SetStopInfo (StopInfo::CreateStopReasonWithException (*thread_sp, description.c_str()));
2087 ProcessGDBRemote::SetThreadStopInfo (StructuredData::Dictionary *thread_dict)
2089 static ConstString g_key_tid("tid");
2090 static ConstString g_key_name("name");
2091 static ConstString g_key_reason("reason");
2092 static ConstString g_key_metype("metype");
2093 static ConstString g_key_medata("medata");
2094 static ConstString g_key_qaddr("qaddr");
2095 static ConstString g_key_queue_name("qname");
2096 static ConstString g_key_queue_kind("qkind");
2097 static ConstString g_key_queue_serial("qserial");
2098 static ConstString g_key_registers("registers");
2099 static ConstString g_key_memory("memory");
2100 static ConstString g_key_address("address");
2101 static ConstString g_key_bytes("bytes");
2102 static ConstString g_key_description("description");
2104 // Stop with signal and thread info
2105 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2108 std::string thread_name;
2110 std::string description;
2111 uint32_t exc_type = 0;
2112 std::vector<addr_t> exc_data;
2113 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2114 ExpeditedRegisterMap expedited_register_map;
2115 bool queue_vars_valid = false;
2116 std::string queue_name;
2117 QueueKind queue_kind = eQueueKindUnknown;
2118 uint64_t queue_serial = 0;
2119 // Iterate through all of the thread dictionary key/value pairs from the structured data dictionary
2121 thread_dict->ForEach([this,
2123 &expedited_register_map,
2130 &thread_dispatch_qaddr,
2135 (ConstString key, StructuredData::Object* object) -> bool
2137 if (key == g_key_tid)
2139 // thread in big endian hex
2140 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
2142 else if (key == g_key_metype)
2144 // exception type in big endian hex
2145 exc_type = object->GetIntegerValue(0);
2147 else if (key == g_key_medata)
2149 // exception data in big endian hex
2150 StructuredData::Array *array = object->GetAsArray();
2153 array->ForEach([&exc_data](StructuredData::Object* object) -> bool {
2154 exc_data.push_back(object->GetIntegerValue());
2155 return true; // Keep iterating through all array items
2159 else if (key == g_key_name)
2161 thread_name = std::move(object->GetStringValue());
2163 else if (key == g_key_qaddr)
2165 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
2167 else if (key == g_key_queue_name)
2169 queue_vars_valid = true;
2170 queue_name = std::move(object->GetStringValue());
2172 else if (key == g_key_queue_kind)
2174 std::string queue_kind_str = object->GetStringValue();
2175 if (queue_kind_str == "serial")
2177 queue_vars_valid = true;
2178 queue_kind = eQueueKindSerial;
2180 else if (queue_kind_str == "concurrent")
2182 queue_vars_valid = true;
2183 queue_kind = eQueueKindConcurrent;
2186 else if (key == g_key_queue_serial)
2188 queue_serial = object->GetIntegerValue(0);
2189 if (queue_serial != 0)
2190 queue_vars_valid = true;
2192 else if (key == g_key_reason)
2194 reason = std::move(object->GetStringValue());
2196 else if (key == g_key_description)
2198 description = std::move(object->GetStringValue());
2200 else if (key == g_key_registers)
2202 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2206 registers_dict->ForEach([&expedited_register_map](ConstString key, StructuredData::Object* object) -> bool {
2207 const uint32_t reg = StringConvert::ToUInt32 (key.GetCString(), UINT32_MAX, 10);
2208 if (reg != UINT32_MAX)
2209 expedited_register_map[reg] = std::move(object->GetStringValue());
2210 return true; // Keep iterating through all array items
2214 else if (key == g_key_memory)
2216 StructuredData::Array *array = object->GetAsArray();
2219 array->ForEach([this](StructuredData::Object* object) -> bool {
2220 StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary();
2223 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2224 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>("address", mem_cache_addr))
2226 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2228 StringExtractor bytes;
2229 if (mem_cache_dict->GetValueForKeyAsString("bytes", bytes.GetStringRef()))
2231 bytes.SetFilePos(0);
2233 const size_t byte_size = bytes.GetStringRef().size()/2;
2234 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2235 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2236 if (bytes_copied == byte_size)
2237 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2242 return true; // Keep iterating through all array items
2247 return true; // Keep iterating through all dictionary key/value pairs
2250 SetThreadStopInfo (tid,
2251 expedited_register_map,
2258 thread_dispatch_qaddr,
2264 return eStateExited;
2268 ProcessGDBRemote::SetThreadStopInfo (StringExtractor& stop_packet)
2270 stop_packet.SetFilePos (0);
2271 const char stop_type = stop_packet.GetChar();
2277 // This is a bit of a hack, but is is required. If we did exec, we
2278 // need to clear our thread lists and also know to rebuild our dynamic
2279 // register info before we lookup and threads and populate the expedited
2280 // register values so we need to know this right away so we can cleanup
2281 // and update our registers.
2282 const uint32_t stop_id = GetStopID();
2285 // Our first stop, make sure we have a process ID, and also make
2286 // sure we know about our registers
2287 if (GetID() == LLDB_INVALID_PROCESS_ID)
2289 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID ();
2290 if (pid != LLDB_INVALID_PROCESS_ID)
2293 BuildDynamicRegisterInfo (true);
2295 // Stop with signal and thread info
2296 lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2297 const uint8_t signo = stop_packet.GetHexU8();
2300 std::string thread_name;
2302 std::string description;
2303 uint32_t exc_type = 0;
2304 std::vector<addr_t> exc_data;
2305 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2306 bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid
2307 std::string queue_name;
2308 QueueKind queue_kind = eQueueKindUnknown;
2309 uint64_t queue_serial = 0;
2310 ExpeditedRegisterMap expedited_register_map;
2311 while (stop_packet.GetNameColonValue(key, value))
2313 if (key.compare("metype") == 0)
2315 // exception type in big endian hex
2316 exc_type = StringConvert::ToUInt32 (value.c_str(), 0, 16);
2318 else if (key.compare("medata") == 0)
2320 // exception data in big endian hex
2321 exc_data.push_back(StringConvert::ToUInt64 (value.c_str(), 0, 16));
2323 else if (key.compare("thread") == 0)
2325 // thread in big endian hex
2326 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
2328 else if (key.compare("threads") == 0)
2330 Mutex::Locker locker(m_thread_list_real.GetMutex());
2331 m_thread_ids.clear();
2332 // A comma separated list of all threads in the current
2333 // process that includes the thread for this stop reply
2337 while ((comma_pos = value.find(',')) != std::string::npos)
2339 value[comma_pos] = '\0';
2340 // thread in big endian hex
2341 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
2342 if (tid != LLDB_INVALID_THREAD_ID)
2343 m_thread_ids.push_back (tid);
2344 value.erase(0, comma_pos + 1);
2346 tid = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_THREAD_ID, 16);
2347 if (tid != LLDB_INVALID_THREAD_ID)
2348 m_thread_ids.push_back (tid);
2350 else if (key.compare("hexname") == 0)
2352 StringExtractor name_extractor;
2353 // Swap "value" over into "name_extractor"
2354 name_extractor.GetStringRef().swap(value);
2355 // Now convert the HEX bytes into a string value
2356 name_extractor.GetHexByteString (value);
2357 thread_name.swap (value);
2359 else if (key.compare("name") == 0)
2361 thread_name.swap (value);
2363 else if (key.compare("qaddr") == 0)
2365 thread_dispatch_qaddr = StringConvert::ToUInt64 (value.c_str(), 0, 16);
2367 else if (key.compare("qname") == 0)
2369 queue_vars_valid = true;
2370 StringExtractor name_extractor;
2371 // Swap "value" over into "name_extractor"
2372 name_extractor.GetStringRef().swap(value);
2373 // Now convert the HEX bytes into a string value
2374 name_extractor.GetHexByteString (value);
2375 queue_name.swap (value);
2377 else if (key.compare("qkind") == 0)
2379 if (value == "serial")
2381 queue_vars_valid = true;
2382 queue_kind = eQueueKindSerial;
2384 else if (value == "concurrent")
2386 queue_vars_valid = true;
2387 queue_kind = eQueueKindConcurrent;
2390 else if (key.compare("qserial") == 0)
2392 queue_serial = StringConvert::ToUInt64 (value.c_str(), 0, 0);
2393 if (queue_serial != 0)
2394 queue_vars_valid = true;
2396 else if (key.compare("reason") == 0)
2400 else if (key.compare("description") == 0)
2402 StringExtractor desc_extractor;
2403 // Swap "value" over into "name_extractor"
2404 desc_extractor.GetStringRef().swap(value);
2405 // Now convert the HEX bytes into a string value
2406 desc_extractor.GetHexByteString (value);
2407 description.swap(value);
2409 else if (key.compare("memory") == 0)
2411 // Expedited memory. GDB servers can choose to send back expedited memory
2412 // that can populate the L1 memory cache in the process so that things like
2413 // the frame pointer backchain can be expedited. This will help stack
2414 // backtracing be more efficient by not having to send as many memory read
2415 // requests down the remote GDB server.
2417 // Key/value pair format: memory:<addr>=<bytes>;
2418 // <addr> is a number whose base will be interpreted by the prefix:
2419 // "0x[0-9a-fA-F]+" for hex
2420 // "0[0-7]+" for octal
2421 // "[1-9]+" for decimal
2422 // <bytes> is native endian ASCII hex bytes just like the register values
2423 llvm::StringRef value_ref(value);
2424 std::pair<llvm::StringRef, llvm::StringRef> pair;
2425 pair = value_ref.split('=');
2426 if (!pair.first.empty() && !pair.second.empty())
2428 std::string addr_str(pair.first.str());
2429 const lldb::addr_t mem_cache_addr = StringConvert::ToUInt64(addr_str.c_str(), LLDB_INVALID_ADDRESS, 0);
2430 if (mem_cache_addr != LLDB_INVALID_ADDRESS)
2432 StringExtractor bytes;
2433 bytes.GetStringRef() = std::move(pair.second.str());
2434 const size_t byte_size = bytes.GetStringRef().size()/2;
2435 DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0));
2436 const size_t bytes_copied = bytes.GetHexBytes (data_buffer_sp->GetBytes(), byte_size, 0);
2437 if (bytes_copied == byte_size)
2438 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2442 else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0)
2444 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2445 lldb::addr_t wp_addr = StringConvert::ToUInt64 (value.c_str(), LLDB_INVALID_ADDRESS, 16);
2446 WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2447 uint32_t wp_index = LLDB_INVALID_INDEX32;
2450 wp_index = wp_sp->GetHardwareIndex();
2452 reason = "watchpoint";
2454 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2455 description = ostr.GetString().c_str();
2457 else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1]))
2459 uint32_t reg = StringConvert::ToUInt32 (key.c_str(), UINT32_MAX, 16);
2460 if (reg != UINT32_MAX)
2461 expedited_register_map[reg] = std::move(value);
2465 if (tid == LLDB_INVALID_THREAD_ID)
2467 // A thread id may be invalid if the response is old style 'S' packet which does not provide the
2468 // thread information. So update the thread list and choose the first one.
2469 UpdateThreadIDList ();
2471 if (!m_thread_ids.empty ())
2473 tid = m_thread_ids.front ();
2477 ThreadSP thread_sp = SetThreadStopInfo (tid,
2478 expedited_register_map,
2485 thread_dispatch_qaddr,
2491 return eStateStopped;
2498 return eStateExited;
2503 return eStateInvalid;
2507 ProcessGDBRemote::RefreshStateAfterStop ()
2509 Mutex::Locker locker(m_thread_list_real.GetMutex());
2510 m_thread_ids.clear();
2511 // Set the thread stop info. It might have a "threads" key whose value is
2512 // a list of all thread IDs in the current process, so m_thread_ids might
2515 // Scope for the lock
2517 // Lock the thread stack while we access it
2518 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2519 // Get the number of stop packets on the stack
2520 int nItems = m_stop_packet_stack.size();
2521 // Iterate over them
2522 for (int i = 0; i < nItems; i++)
2524 // Get the thread stop info
2525 StringExtractorGDBRemote stop_info = m_stop_packet_stack[i];
2526 // Process thread stop info
2527 SetThreadStopInfo(stop_info);
2529 // Clear the thread stop stack
2530 m_stop_packet_stack.clear();
2533 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2534 if (m_thread_ids.empty())
2536 // No, we need to fetch the thread list manually
2537 UpdateThreadIDList();
2540 // If we have queried for a default thread id
2541 if (m_initial_tid != LLDB_INVALID_THREAD_ID)
2543 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2544 m_initial_tid = LLDB_INVALID_THREAD_ID;
2547 // Fetch the threads via an efficient packet that gets stop infos for all threads
2548 // only if we have more than one thread
2549 if (m_thread_ids.size() > 1)
2550 m_threads_info_sp = m_gdb_comm.GetThreadsInfo();
2552 // Let all threads recover from stopping and do any clean up based
2553 // on the previous thread state (if any).
2554 m_thread_list_real.RefreshStateAfterStop();
2559 ProcessGDBRemote::DoHalt (bool &caused_stop)
2563 bool timed_out = false;
2564 Mutex::Locker locker;
2566 if (m_public_state.GetValue() == eStateAttaching)
2568 // We are being asked to halt during an attach. We need to just close
2569 // our file handle and debugserver will go away, and we can be done...
2570 m_gdb_comm.Disconnect();
2574 if (!m_gdb_comm.SendInterrupt (locker, 2, timed_out))
2577 error.SetErrorString("timed out sending interrupt packet");
2579 error.SetErrorString("unknown error sending interrupt packet");
2582 caused_stop = m_gdb_comm.GetInterruptWasSent ();
2588 ProcessGDBRemote::DoDetach(bool keep_stopped)
2591 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2593 log->Printf ("ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2595 error = m_gdb_comm.Detach (keep_stopped);
2598 if (error.Success())
2599 log->PutCString ("ProcessGDBRemote::DoDetach() detach packet sent successfully");
2601 log->Printf ("ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : "<unknown error>");
2604 if (!error.Success())
2607 // Sleep for one second to let the process get all detached...
2610 SetPrivateState (eStateDetached);
2611 ResumePrivateStateThread();
2613 //KillDebugserverProcess ();
2619 ProcessGDBRemote::DoDestroy ()
2622 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2624 log->Printf ("ProcessGDBRemote::DoDestroy()");
2626 #if 0 // XXX Currently no iOS target support on FreeBSD
2627 // There is a bug in older iOS debugservers where they don't shut down the process
2628 // they are debugging properly. If the process is sitting at a breakpoint or an exception,
2629 // this can cause problems with restarting. So we check to see if any of our threads are stopped
2630 // at a breakpoint, and if so we remove all the breakpoints, resume the process, and THEN
2631 // destroy it again.
2633 // Note, we don't have a good way to test the version of debugserver, but I happen to know that
2634 // the set of all the iOS debugservers which don't support GetThreadSuffixSupported() and that of
2635 // the debugservers with this bug are equal. There really should be a better way to test this!
2637 // We also use m_destroy_tried_resuming to make sure we only do this once, if we resume and then halt and
2638 // get called here to destroy again and we're still at a breakpoint or exception, then we should
2639 // just do the straight-forward kill.
2641 // And of course, if we weren't able to stop the process by the time we get here, it isn't
2642 // necessary (or helpful) to do any of this.
2644 if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning)
2646 PlatformSP platform_sp = GetTarget().GetPlatform();
2648 // FIXME: These should be ConstStrings so we aren't doing strcmp'ing.
2650 && platform_sp->GetName()
2651 && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic())
2653 if (m_destroy_tried_resuming)
2656 log->PutCString ("ProcessGDBRemote::DoDestroy() - Tried resuming to destroy once already, not doing it again.");
2660 // At present, the plans are discarded and the breakpoints disabled Process::Destroy,
2661 // but we really need it to happen here and it doesn't matter if we do it twice.
2662 m_thread_list.DiscardThreadPlans();
2663 DisableAllBreakpointSites();
2665 bool stop_looks_like_crash = false;
2666 ThreadList &threads = GetThreadList();
2669 Mutex::Locker locker(threads.GetMutex());
2671 size_t num_threads = threads.GetSize();
2672 for (size_t i = 0; i < num_threads; i++)
2674 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2675 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2676 StopReason reason = eStopReasonInvalid;
2678 reason = stop_info_sp->GetStopReason();
2679 if (reason == eStopReasonBreakpoint
2680 || reason == eStopReasonException)
2683 log->Printf ("ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.",
2684 thread_sp->GetProtocolID(),
2685 stop_info_sp->GetDescription());
2686 stop_looks_like_crash = true;
2692 if (stop_looks_like_crash)
2695 log->PutCString ("ProcessGDBRemote::DoDestroy() - Stopped at a breakpoint, continue and then kill.");
2696 m_destroy_tried_resuming = true;
2698 // If we are going to run again before killing, it would be good to suspend all the threads
2699 // before resuming so they won't get into more trouble. Sadly, for the threads stopped with
2700 // the breakpoint or exception, the exception doesn't get cleared if it is suspended, so we do
2701 // have to run the risk of letting those threads proceed a bit.
2704 Mutex::Locker locker(threads.GetMutex());
2706 size_t num_threads = threads.GetSize();
2707 for (size_t i = 0; i < num_threads; i++)
2709 ThreadSP thread_sp = threads.GetThreadAtIndex(i);
2710 StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo();
2711 StopReason reason = eStopReasonInvalid;
2713 reason = stop_info_sp->GetStopReason();
2714 if (reason != eStopReasonBreakpoint
2715 && reason != eStopReasonException)
2718 log->Printf ("ProcessGDBRemote::DoDestroy() - Suspending thread: 0x%4.4" PRIx64 " before running.",
2719 thread_sp->GetProtocolID());
2720 thread_sp->SetResumeState(eStateSuspended);
2725 return Destroy(false);
2732 // Interrupt if our inferior is running...
2733 int exit_status = SIGABRT;
2734 std::string exit_string;
2736 if (m_gdb_comm.IsConnected())
2738 if (m_public_state.GetValue() != eStateAttaching)
2740 StringExtractorGDBRemote response;
2741 bool send_async = true;
2742 GDBRemoteCommunication::ScopedTimeout (m_gdb_comm, 3);
2744 if (m_gdb_comm.SendPacketAndWaitForResponse("k", 1, response, send_async) == GDBRemoteCommunication::PacketResult::Success)
2746 char packet_cmd = response.GetChar(0);
2748 if (packet_cmd == 'W' || packet_cmd == 'X')
2750 #if defined(__APPLE__)
2751 // For Native processes on Mac OS X, we launch through the Host Platform, then hand the process off
2752 // to debugserver, which becomes the parent process through "PT_ATTACH". Then when we go to kill
2753 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then we call waitpid which returns
2754 // with no error and the correct status. But amusingly enough that doesn't seem to actually reap
2755 // the process, but instead it is left around as a Zombie. Probably the kernel is in the process of
2756 // switching ownership back to lldb which was the original parent, and gets confused in the handoff.
2757 // Anyway, so call waitpid here to finally reap it.
2758 PlatformSP platform_sp(GetTarget().GetPlatform());
2759 if (platform_sp && platform_sp->IsHost())
2763 reap_pid = waitpid (GetID(), &status, WNOHANG);
2765 log->Printf ("Reaped pid: %d, status: %d.\n", reap_pid, status);
2768 SetLastStopPacket (response);
2769 ClearThreadIDList ();
2770 exit_status = response.GetHexU8();
2775 log->Printf ("ProcessGDBRemote::DoDestroy - got unexpected response to k packet: %s", response.GetStringRef().c_str());
2776 exit_string.assign("got unexpected response to k packet: ");
2777 exit_string.append(response.GetStringRef());
2783 log->Printf ("ProcessGDBRemote::DoDestroy - failed to send k packet");
2784 exit_string.assign("failed to send the k packet");
2790 log->Printf ("ProcessGDBRemote::DoDestroy - killed or interrupted while attaching");
2791 exit_string.assign ("killed or interrupted while attaching.");
2796 // If we missed setting the exit status on the way out, do it here.
2797 // NB set exit status can be called multiple times, the first one sets the status.
2798 exit_string.assign("destroying when not connected to debugserver");
2801 SetExitStatus(exit_status, exit_string.c_str());
2804 KillDebugserverProcess ();
2809 ProcessGDBRemote::SetLastStopPacket (const StringExtractorGDBRemote &response)
2811 const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos;
2814 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
2816 log->Printf ("ProcessGDBRemote::SetLastStopPacket () - detected exec");
2818 m_thread_list_real.Clear();
2819 m_thread_list.Clear();
2820 BuildDynamicRegisterInfo (true);
2821 m_gdb_comm.ResetDiscoverableSettings (did_exec);
2826 // Lock the thread stack while we access it
2827 Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex);
2828 // Add this stop packet to the stop packet stack
2829 // This stack will get popped and examined when we switch to the
2831 m_stop_packet_stack.push_back(response);
2836 //------------------------------------------------------------------
2838 //------------------------------------------------------------------
2841 ProcessGDBRemote::IsAlive ()
2843 return m_gdb_comm.IsConnected() && m_private_state.GetValue() != eStateExited;
2847 ProcessGDBRemote::GetImageInfoAddress()
2849 // request the link map address via the $qShlibInfoAddr packet
2850 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2852 // the loaded module list can also provides a link map address
2853 if (addr == LLDB_INVALID_ADDRESS)
2855 GDBLoadedModuleInfoList list;
2856 if (GetLoadedModuleList (list).Success())
2857 addr = list.m_link_map;
2863 //------------------------------------------------------------------
2865 //------------------------------------------------------------------
2867 ProcessGDBRemote::DoReadMemory (addr_t addr, void *buf, size_t size, Error &error)
2869 GetMaxMemorySize ();
2870 if (size > m_max_memory_size)
2872 // Keep memory read sizes down to a sane limit. This function will be
2873 // called multiple times in order to complete the task by
2874 // lldb_private::Process so it is ok to do this.
2875 size = m_max_memory_size;
2880 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2881 if (binary_memory_read)
2883 packet_len = ::snprintf (packet, sizeof(packet), "x0x%" PRIx64 ",0x%" PRIx64, (uint64_t)addr, (uint64_t)size);
2887 packet_len = ::snprintf (packet, sizeof(packet), "m%" PRIx64 ",%" PRIx64, (uint64_t)addr, (uint64_t)size);
2889 assert (packet_len + 1 < (int)sizeof(packet));
2890 StringExtractorGDBRemote response;
2891 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, packet_len, response, true) == GDBRemoteCommunication::PacketResult::Success)
2893 if (response.IsNormalResponse())
2896 if (binary_memory_read)
2898 // The lower level GDBRemoteCommunication packet receive layer has already de-quoted any
2899 // 0x7d character escaping that was present in the packet
2901 size_t data_received_size = response.GetBytesLeft();
2902 if (data_received_size > size)
2904 // Don't write past the end of BUF if the remote debug server gave us too
2905 // much data for some reason.
2906 data_received_size = size;
2908 memcpy (buf, response.GetStringRef().data(), data_received_size);
2909 return data_received_size;
2913 return response.GetHexBytes(buf, size, '\xdd');
2916 else if (response.IsErrorResponse())
2917 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2918 else if (response.IsUnsupportedResponse())
2919 error.SetErrorStringWithFormat("GDB server does not support reading memory");
2921 error.SetErrorStringWithFormat("unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().c_str());
2925 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2931 ProcessGDBRemote::DoWriteMemory (addr_t addr, const void *buf, size_t size, Error &error)
2933 GetMaxMemorySize ();
2934 if (size > m_max_memory_size)
2936 // Keep memory read sizes down to a sane limit. This function will be
2937 // called multiple times in order to complete the task by
2938 // lldb_private::Process so it is ok to do this.
2939 size = m_max_memory_size;
2942 StreamString packet;
2943 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2944 packet.PutBytesAsRawHex8(buf, size, lldb::endian::InlHostByteOrder(), lldb::endian::InlHostByteOrder());
2945 StringExtractorGDBRemote response;
2946 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, true) == GDBRemoteCommunication::PacketResult::Success)
2948 if (response.IsOKResponse())
2953 else if (response.IsErrorResponse())
2954 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr);
2955 else if (response.IsUnsupportedResponse())
2956 error.SetErrorStringWithFormat("GDB server does not support writing memory");
2958 error.SetErrorStringWithFormat("unexpected response to GDB server memory write packet '%s': '%s'", packet.GetString().c_str(), response.GetStringRef().c_str());
2962 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetString().c_str());
2968 ProcessGDBRemote::DoAllocateMemory (size_t size, uint32_t permissions, Error &error)
2970 Log *log (GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS|LIBLLDB_LOG_EXPRESSIONS));
2971 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2973 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2976 case eLazyBoolCalculate:
2978 allocated_addr = m_gdb_comm.AllocateMemory (size, permissions);
2979 if (allocated_addr != LLDB_INVALID_ADDRESS || supported == eLazyBoolYes)
2980 return allocated_addr;
2983 // Call mmap() to create memory in the inferior..
2985 if (permissions & lldb::ePermissionsReadable)
2986 prot |= eMmapProtRead;
2987 if (permissions & lldb::ePermissionsWritable)
2988 prot |= eMmapProtWrite;
2989 if (permissions & lldb::ePermissionsExecutable)
2990 prot |= eMmapProtExec;
2992 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2993 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2994 m_addr_to_mmap_size[allocated_addr] = size;
2997 allocated_addr = LLDB_INVALID_ADDRESS;
2999 log->Printf ("ProcessGDBRemote::%s no direct stub support for memory allocation, and InferiorCallMmap also failed - is stub missing register context save/restore capability?", __FUNCTION__);
3004 if (allocated_addr == LLDB_INVALID_ADDRESS)
3005 error.SetErrorStringWithFormat("unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString (permissions));
3008 return allocated_addr;
3012 ProcessGDBRemote::GetMemoryRegionInfo (addr_t load_addr,
3013 MemoryRegionInfo ®ion_info)
3016 Error error (m_gdb_comm.GetMemoryRegionInfo (load_addr, region_info));
3021 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num)
3024 Error error (m_gdb_comm.GetWatchpointSupportInfo (num));
3029 ProcessGDBRemote::GetWatchpointSupportInfo (uint32_t &num, bool& after)
3031 Error error (m_gdb_comm.GetWatchpointSupportInfo (num, after, GetTarget().GetArchitecture()));
3036 ProcessGDBRemote::DoDeallocateMemory (lldb::addr_t addr)
3039 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3043 case eLazyBoolCalculate:
3044 // We should never be deallocating memory without allocating memory
3045 // first so we should never get eLazyBoolCalculate
3046 error.SetErrorString ("tried to deallocate memory without ever allocating memory");
3050 if (!m_gdb_comm.DeallocateMemory (addr))
3051 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
3055 // Call munmap() to deallocate memory in the inferior..
3057 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3058 if (pos != m_addr_to_mmap_size.end() &&
3059 InferiorCallMunmap(this, addr, pos->second))
3060 m_addr_to_mmap_size.erase (pos);
3062 error.SetErrorStringWithFormat("unable to deallocate memory at 0x%" PRIx64, addr);
3071 //------------------------------------------------------------------
3073 //------------------------------------------------------------------
3075 ProcessGDBRemote::PutSTDIN (const char *src, size_t src_len, Error &error)
3077 if (m_stdio_communication.IsConnected())
3079 ConnectionStatus status;
3080 m_stdio_communication.Write(src, src_len, status, NULL);
3082 else if (m_stdin_forward)
3084 m_gdb_comm.SendStdinNotification(src, src_len);
3090 ProcessGDBRemote::EnableBreakpointSite (BreakpointSite *bp_site)
3093 assert(bp_site != NULL);
3096 Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3097 user_id_t site_id = bp_site->GetID();
3099 // Get the breakpoint address
3100 const addr_t addr = bp_site->GetLoadAddress();
3102 // Log that a breakpoint was requested
3104 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr);
3106 // Breakpoint already exists and is enabled
3107 if (bp_site->IsEnabled())
3110 log->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr);
3114 // Get the software breakpoint trap opcode size
3115 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3117 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this breakpoint type
3118 // is supported by the remote stub. These are set to true by default, and later set to false
3119 // only after we receive an unimplemented response when sending a breakpoint packet. This means
3120 // initially that unless we were specifically instructed to use a hardware breakpoint, LLDB will
3121 // attempt to set a software breakpoint. HardwareRequired() also queries a boolean variable which
3122 // indicates if the user specifically asked for hardware breakpoints. If true then we will
3123 // skip over software breakpoints.
3124 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired()))
3126 // Try to send off a software breakpoint packet ($Z0)
3127 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, true, addr, bp_op_size) == 0)
3129 // The breakpoint was placed successfully
3130 bp_site->SetEnabled(true);
3131 bp_site->SetType(BreakpointSite::eExternal);
3135 // SendGDBStoppointTypePacket() will return an error if it was unable to set this
3136 // breakpoint. We need to differentiate between a error specific to placing this breakpoint
3137 // or if we have learned that this breakpoint type is unsupported. To do this, we
3138 // must test the support boolean for this breakpoint type to see if it now indicates that
3139 // this breakpoint type is unsupported. If they are still supported then we should return
3140 // with the error code. If they are now unsupported, then we would like to fall through
3141 // and try another form of breakpoint.
3142 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
3145 // We reach here when software breakpoints have been found to be unsupported. For future
3146 // calls to set a breakpoint, we will not attempt to set a breakpoint with a type that is
3147 // known not to be supported.
3149 log->Printf("Software breakpoints are unsupported");
3151 // So we will fall through and try a hardware breakpoint
3154 // The process of setting a hardware breakpoint is much the same as above. We check the
3155 // supported boolean for this breakpoint type, and if it is thought to be supported then we
3156 // will try to set this breakpoint with a hardware breakpoint.
3157 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3159 // Try to send off a hardware breakpoint packet ($Z1)
3160 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, true, addr, bp_op_size) == 0)
3162 // The breakpoint was placed successfully
3163 bp_site->SetEnabled(true);
3164 bp_site->SetType(BreakpointSite::eHardware);
3168 // Check if the error was something other then an unsupported breakpoint type
3169 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware))
3171 // Unable to set this hardware breakpoint
3172 error.SetErrorString("failed to set hardware breakpoint (hardware breakpoint resources might be exhausted or unavailable)");
3176 // We will reach here when the stub gives an unsupported response to a hardware breakpoint
3178 log->Printf("Hardware breakpoints are unsupported");
3180 // Finally we will falling through to a #trap style breakpoint
3183 // Don't fall through when hardware breakpoints were specifically requested
3184 if (bp_site->HardwareRequired())
3186 error.SetErrorString("hardware breakpoints are not supported");
3190 // As a last resort we want to place a manual breakpoint. An instruction
3191 // is placed into the process memory using memory write packets.
3192 return EnableSoftwareBreakpoint(bp_site);
3196 ProcessGDBRemote::DisableBreakpointSite (BreakpointSite *bp_site)
3199 assert (bp_site != NULL);
3200 addr_t addr = bp_site->GetLoadAddress();
3201 user_id_t site_id = bp_site->GetID();
3202 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS));
3204 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr);
3206 if (bp_site->IsEnabled())
3208 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode (bp_site);
3210 BreakpointSite::Type bp_type = bp_site->GetType();
3213 case BreakpointSite::eSoftware:
3214 error = DisableSoftwareBreakpoint (bp_site);
3217 case BreakpointSite::eHardware:
3218 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size))
3219 error.SetErrorToGenericError();
3222 case BreakpointSite::eExternal:
3224 GDBStoppointType stoppoint_type;
3225 if (bp_site->IsHardware())
3226 stoppoint_type = eBreakpointHardware;
3228 stoppoint_type = eBreakpointSoftware;
3230 if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size))
3231 error.SetErrorToGenericError();
3235 if (error.Success())
3236 bp_site->SetEnabled(false);
3241 log->Printf ("ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr);
3245 if (error.Success())
3246 error.SetErrorToGenericError();
3250 // Pre-requisite: wp != NULL.
3251 static GDBStoppointType
3252 GetGDBStoppointType (Watchpoint *wp)
3255 bool watch_read = wp->WatchpointRead();
3256 bool watch_write = wp->WatchpointWrite();
3258 // watch_read and watch_write cannot both be false.
3259 assert(watch_read || watch_write);
3260 if (watch_read && watch_write)
3261 return eWatchpointReadWrite;
3262 else if (watch_read)
3263 return eWatchpointRead;
3264 else // Must be watch_write, then.
3265 return eWatchpointWrite;
3269 ProcessGDBRemote::EnableWatchpoint (Watchpoint *wp, bool notify)
3274 user_id_t watchID = wp->GetID();
3275 addr_t addr = wp->GetLoadAddress();
3276 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3278 log->Printf ("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID);
3279 if (wp->IsEnabled())
3282 log->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr);
3286 GDBStoppointType type = GetGDBStoppointType(wp);
3287 // Pass down an appropriate z/Z packet...
3288 if (m_gdb_comm.SupportsGDBStoppointPacket (type))
3290 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0)
3292 wp->SetEnabled(true, notify);
3296 error.SetErrorString("sending gdb watchpoint packet failed");
3299 error.SetErrorString("watchpoints not supported");
3303 error.SetErrorString("Watchpoint argument was NULL.");
3305 if (error.Success())
3306 error.SetErrorToGenericError();
3311 ProcessGDBRemote::DisableWatchpoint (Watchpoint *wp, bool notify)
3316 user_id_t watchID = wp->GetID();
3318 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS));
3320 addr_t addr = wp->GetLoadAddress();
3323 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr);
3325 if (!wp->IsEnabled())
3328 log->Printf ("ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr);
3329 // See also 'class WatchpointSentry' within StopInfo.cpp.
3330 // This disabling attempt might come from the user-supplied actions, we'll route it in order for
3331 // the watchpoint object to intelligently process this action.
3332 wp->SetEnabled(false, notify);
3336 if (wp->IsHardware())
3338 GDBStoppointType type = GetGDBStoppointType(wp);
3339 // Pass down an appropriate z/Z packet...
3340 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0)
3342 wp->SetEnabled(false, notify);
3346 error.SetErrorString("sending gdb watchpoint packet failed");
3348 // TODO: clear software watchpoints if we implement them
3352 error.SetErrorString("Watchpoint argument was NULL.");
3354 if (error.Success())
3355 error.SetErrorToGenericError();
3360 ProcessGDBRemote::Clear()
3363 m_thread_list_real.Clear();
3364 m_thread_list.Clear();
3368 ProcessGDBRemote::DoSignal (int signo)
3371 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3373 log->Printf ("ProcessGDBRemote::DoSignal (signal = %d)", signo);
3375 if (!m_gdb_comm.SendAsyncSignal (signo))
3376 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3381 ProcessGDBRemote::LaunchAndConnectToDebugserver (const ProcessInfo &process_info)
3384 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID)
3386 // If we locate debugserver, keep that located version around
3387 static FileSpec g_debugserver_file_spec;
3389 ProcessLaunchInfo debugserver_launch_info;
3390 // Make debugserver run in its own session so signals generated by
3391 // special terminal key sequences (^C) don't affect debugserver.
3392 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3394 debugserver_launch_info.SetMonitorProcessCallback (MonitorDebugserverProcess, this, false);
3395 debugserver_launch_info.SetUserID(process_info.GetUserID());
3397 #if defined (__APPLE__) && (defined (__arm__) || defined (__arm64__) || defined (__aarch64__))
3398 // On iOS, still do a local connection using a random port
3399 const char *hostname = "127.0.0.1";
3400 uint16_t port = get_random_port ();
3402 // Set hostname being NULL to do the reverse connect where debugserver
3403 // will bind to port zero and it will communicate back to us the port
3404 // that we will connect to
3405 const char *hostname = NULL;
3409 error = m_gdb_comm.StartDebugserverProcess (hostname,
3411 debugserver_launch_info,
3414 if (error.Success ())
3415 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3417 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3419 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3420 StartAsyncThread ();
3424 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3427 log->Printf("failed to start debugserver process: %s", error.AsCString());
3431 if (m_gdb_comm.IsConnected())
3433 // Finish the connection process by doing the handshake without connecting (send NULL URL)
3434 ConnectToDebugserver (NULL);
3438 StreamString connect_url;
3439 connect_url.Printf("connect://%s:%u", hostname, port);
3440 error = ConnectToDebugserver (connect_url.GetString().c_str());
3448 ProcessGDBRemote::MonitorDebugserverProcess
3450 void *callback_baton,
3451 lldb::pid_t debugserver_pid,
3452 bool exited, // True if the process did exit
3453 int signo, // Zero for no signal
3454 int exit_status // Exit value of process if signal is zero
3457 // The baton is a "ProcessGDBRemote *". Now this class might be gone
3458 // and might not exist anymore, so we need to carefully try to get the
3459 // target for this process first since we have a race condition when
3460 // we are done running between getting the notice that the inferior
3461 // process has died and the debugserver that was debugging this process.
3462 // In our test suite, we are also continually running process after
3463 // process, so we must be very careful to make sure:
3464 // 1 - process object hasn't been deleted already
3465 // 2 - that a new process object hasn't been recreated in its place
3467 // "debugserver_pid" argument passed in is the process ID for
3468 // debugserver that we are tracking...
3469 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3471 ProcessGDBRemote *process = (ProcessGDBRemote *)callback_baton;
3473 // Get a shared pointer to the target that has a matching process pointer.
3474 // This target could be gone, or the target could already have a new process
3475 // object inside of it
3476 TargetSP target_sp (Debugger::FindTargetWithProcess(process));
3479 log->Printf ("ProcessGDBRemote::MonitorDebugserverProcess (baton=%p, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", callback_baton, debugserver_pid, signo, signo, exit_status);
3483 // We found a process in a target that matches, but another thread
3484 // might be in the process of launching a new process that will
3485 // soon replace it, so get a shared pointer to the process so we
3486 // can keep it alive.
3487 ProcessSP process_sp (target_sp->GetProcessSP());
3488 // Now we have a shared pointer to the process that can't go away on us
3489 // so we now make sure it was the same as the one passed in, and also make
3490 // sure that our previous "process *" didn't get deleted and have a new
3491 // "process *" created in its place with the same pointer. To verify this
3492 // we make sure the process has our debugserver process ID. If we pass all
3493 // of these tests, then we are sure that this process is the one we were
3495 if (process_sp && process == process_sp.get() && process->m_debugserver_pid == debugserver_pid)
3497 // Sleep for a half a second to make sure our inferior process has
3498 // time to set its exit status before we set it incorrectly when
3499 // both the debugserver and the inferior process shut down.
3501 // If our process hasn't yet exited, debugserver might have died.
3502 // If the process did exit, the we are reaping it.
3503 const StateType state = process->GetState();
3505 if (process->m_debugserver_pid != LLDB_INVALID_PROCESS_ID &&
3506 state != eStateInvalid &&
3507 state != eStateUnloaded &&
3508 state != eStateExited &&
3509 state != eStateDetached)
3511 char error_str[1024];
3514 const char *signal_cstr = process->GetUnixSignals()->GetSignalAsCString(signo);
3516 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3518 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with signal %i", signo);
3522 ::snprintf (error_str, sizeof (error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status);
3525 process->SetExitStatus (-1, error_str);
3527 // Debugserver has exited we need to let our ProcessGDBRemote
3528 // know that it no longer has a debugserver instance
3529 process->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3536 ProcessGDBRemote::KillDebugserverProcess ()
3538 m_gdb_comm.Disconnect();
3539 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID)
3541 Host::Kill (m_debugserver_pid, SIGINT);
3542 m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3547 ProcessGDBRemote::Initialize()
3549 static std::once_flag g_once_flag;
3551 std::call_once(g_once_flag, []()
3553 PluginManager::RegisterPlugin (GetPluginNameStatic(),
3554 GetPluginDescriptionStatic(),
3556 DebuggerInitialize);
3561 ProcessGDBRemote::DebuggerInitialize (Debugger &debugger)
3563 if (!PluginManager::GetSettingForProcessPlugin(debugger, PluginProperties::GetSettingName()))
3565 const bool is_global_setting = true;
3566 PluginManager::CreateSettingForProcessPlugin (debugger,
3567 GetGlobalPluginProperties()->GetValueProperties(),
3568 ConstString ("Properties for the gdb-remote process plug-in."),
3574 ProcessGDBRemote::StartAsyncThread ()
3576 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3579 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3581 Mutex::Locker start_locker(m_async_thread_state_mutex);
3582 if (!m_async_thread.IsJoinable())
3584 // Create a thread that watches our internal state and controls which
3585 // events make it to clients (into the DCProcess event queue).
3587 m_async_thread = ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", ProcessGDBRemote::AsyncThread, this, NULL);
3590 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was already running.", __FUNCTION__);
3592 return m_async_thread.IsJoinable();
3596 ProcessGDBRemote::StopAsyncThread ()
3598 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS));
3601 log->Printf ("ProcessGDBRemote::%s ()", __FUNCTION__);
3603 Mutex::Locker start_locker(m_async_thread_state_mutex);
3604 if (m_async_thread.IsJoinable())
3606 m_async_broadcaster.BroadcastEvent (eBroadcastBitAsyncThreadShouldExit);
3608 // This will shut down the async thread.
3609 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3611 // Stop the stdio thread
3612 m_async_thread.Join(nullptr);
3613 m_async_thread.Reset();
3616 log->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__);
3620 ProcessGDBRemote::HandleNotifyPacket (StringExtractorGDBRemote &packet)
3622 // get the packet at a string
3623 const std::string &pkt = packet.GetStringRef();
3625 StringExtractorGDBRemote stop_info(pkt.c_str() + 5);
3627 // pass as a thread stop info packet
3628 SetLastStopPacket(stop_info);
3630 // check for more stop reasons
3631 HandleStopReplySequence();
3633 // if the process is stopped then we need to fake a resume
3634 // so that we can stop properly with the new break. This
3635 // is possible due to SetPrivateState() broadcasting the
3636 // state change as a side effect.
3637 if (GetPrivateState() == lldb::StateType::eStateStopped)
3639 SetPrivateState(lldb::StateType::eStateRunning);
3642 // since we have some stopped packets we can halt the process
3643 SetPrivateState(lldb::StateType::eStateStopped);
3649 ProcessGDBRemote::AsyncThread (void *arg)
3651 ProcessGDBRemote *process = (ProcessGDBRemote*) arg;
3653 Log *log (ProcessGDBRemoteLog::GetLogIfAllCategoriesSet (GDBR_LOG_PROCESS));
3655 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID());
3657 Listener listener ("ProcessGDBRemote::AsyncThread");
3659 const uint32_t desired_event_mask = eBroadcastBitAsyncContinue |
3660 eBroadcastBitAsyncThreadShouldExit;
3662 if (listener.StartListeningForEvents (&process->m_async_broadcaster, desired_event_mask) == desired_event_mask)
3664 listener.StartListeningForEvents (&process->m_gdb_comm, Communication::eBroadcastBitReadThreadDidExit |
3665 GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify);
3671 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID());
3672 if (listener.WaitForEvent (NULL, event_sp))
3674 const uint32_t event_type = event_sp->GetType();
3675 if (event_sp->BroadcasterIs (&process->m_async_broadcaster))
3678 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type);
3682 case eBroadcastBitAsyncContinue:
3684 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get());
3686 if (continue_packet)
3688 const char *continue_cstr = (const char *)continue_packet->GetBytes ();
3689 const size_t continue_cstr_len = continue_packet->GetByteSize ();
3691 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr);
3693 if (::strstr (continue_cstr, "vAttach") == NULL)
3694 process->SetPrivateState(eStateRunning);
3695 StringExtractorGDBRemote response;
3697 // If in Non-Stop-Mode
3698 if (process->GetTarget().GetNonStopModeEnabled())
3700 // send the vCont packet
3701 if (!process->GetGDBRemote().SendvContPacket(process, continue_cstr, continue_cstr_len, response))
3703 // Something went wrong
3708 // If in All-Stop-Mode
3711 StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse (process, continue_cstr, continue_cstr_len, response);
3713 // We need to immediately clear the thread ID list so we are sure to get a valid list of threads.
3714 // The thread ID list might be contained within the "response", or the stop reply packet that
3715 // caused the stop. So clear it now before we give the stop reply packet to the process
3716 // using the process->SetLastStopPacket()...
3717 process->ClearThreadIDList ();
3723 case eStateSuspended:
3724 process->SetLastStopPacket (response);
3725 process->SetPrivateState (stop_state);
3730 process->SetLastStopPacket (response);
3731 process->ClearThreadIDList();
3732 response.SetFilePos(1);
3734 int exit_status = response.GetHexU8();
3735 const char *desc_cstr = NULL;
3736 StringExtractor extractor;
3737 std::string desc_string;
3738 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';')
3740 std::string desc_token;
3741 while (response.GetNameColonValue (desc_token, desc_string))
3743 if (desc_token == "description")
3745 extractor.GetStringRef().swap(desc_string);
3746 extractor.SetFilePos(0);
3747 extractor.GetHexByteString (desc_string);
3748 desc_cstr = desc_string.c_str();
3752 process->SetExitStatus(exit_status, desc_cstr);
3757 process->SetExitStatus(-1, "lost connection");
3761 process->SetPrivateState (stop_state);
3763 } // switch(stop_state)
3764 } // else // if in All-stop-mode
3765 } // if (continue_packet)
3766 } // case eBroadcastBitAysncContinue
3769 case eBroadcastBitAsyncThreadShouldExit:
3771 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID());
3777 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3782 else if (event_sp->BroadcasterIs (&process->m_gdb_comm))
3786 case Communication::eBroadcastBitReadThreadDidExit:
3787 process->SetExitStatus (-1, "lost connection");
3791 case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify:
3793 lldb_private::Event *event = event_sp.get();
3794 const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event);
3795 StringExtractorGDBRemote notify((const char*)continue_packet->GetBytes());
3796 // Hand this over to the process to handle
3797 process->HandleNotifyPacket(notify);
3803 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type);
3812 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID());
3819 log->Printf ("ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID());
3825 //ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList &matches, std::vector<lldb::pid_t> &pids)
3827 // // If we are planning to launch the debugserver remotely, then we need to fire up a debugserver
3828 // // process and ask it for the list of processes. But if we are local, we can let the Host do it.
3829 // if (m_local_debugserver)
3831 // return Host::ListProcessesMatchingName (name, matches, pids);
3835 // // FIXME: Implement talking to the remote debugserver.
3842 ProcessGDBRemote::NewThreadNotifyBreakpointHit (void *baton,
3843 StoppointCallbackContext *context,
3844 lldb::user_id_t break_id,
3845 lldb::user_id_t break_loc_id)
3847 // I don't think I have to do anything here, just make sure I notice the new thread when it starts to
3848 // run so I can stop it if that's what I want to do.
3849 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3851 log->Printf("Hit New Thread Notification breakpoint.");
3857 ProcessGDBRemote::StartNoticingNewThreads()
3859 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3860 if (m_thread_create_bp_sp)
3862 if (log && log->GetVerbose())
3863 log->Printf("Enabled noticing new thread breakpoint.");
3864 m_thread_create_bp_sp->SetEnabled(true);
3868 PlatformSP platform_sp (m_target.GetPlatform());
3871 m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(m_target);
3872 if (m_thread_create_bp_sp)
3874 if (log && log->GetVerbose())
3875 log->Printf("Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID());
3876 m_thread_create_bp_sp->SetCallback (ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3881 log->Printf("Failed to create new thread notification breakpoint.");
3885 return m_thread_create_bp_sp.get() != NULL;
3889 ProcessGDBRemote::StopNoticingNewThreads()
3891 Log *log (GetLogIfAllCategoriesSet (LIBLLDB_LOG_STEP));
3892 if (log && log->GetVerbose())
3893 log->Printf ("Disabling new thread notification breakpoint.");
3895 if (m_thread_create_bp_sp)
3896 m_thread_create_bp_sp->SetEnabled(false);
3902 ProcessGDBRemote::GetDynamicLoader ()
3904 if (m_dyld_ap.get() == NULL)
3905 m_dyld_ap.reset (DynamicLoader::FindPlugin(this, NULL));
3906 return m_dyld_ap.get();
3910 ProcessGDBRemote::SendEventData(const char *data)
3917 return_value = m_gdb_comm.SendLaunchEventDataPacket (data, &was_supported);
3918 if (return_value != 0)
3921 error.SetErrorString("Sending events is not supported for this process.");
3923 error.SetErrorStringWithFormat("Error sending event data: %d.", return_value);
3929 ProcessGDBRemote::GetAuxvData()
3932 if (m_gdb_comm.GetQXferAuxvReadSupported())
3934 std::string response_string;
3935 if (m_gdb_comm.SendPacketsAndConcatenateResponses("qXfer:auxv:read::", response_string) == GDBRemoteCommunication::PacketResult::Success)
3936 buf.reset(new DataBufferHeap(response_string.c_str(), response_string.length()));
3941 StructuredData::ObjectSP
3942 ProcessGDBRemote::GetExtendedInfoForThread (lldb::tid_t tid)
3944 StructuredData::ObjectSP object_sp;
3946 if (m_gdb_comm.GetThreadExtendedInfoSupported())
3948 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3949 SystemRuntime *runtime = GetSystemRuntime();
3952 runtime->AddThreadExtendedInfoPacketHints (args_dict);
3954 args_dict->GetAsDictionary()->AddIntegerItem ("thread", tid);
3956 StreamString packet;
3957 packet << "jThreadExtendedInfo:";
3958 args_dict->Dump (packet);
3960 // FIXME the final character of a JSON dictionary, '}', is the escape
3961 // character in gdb-remote binary mode. lldb currently doesn't escape
3962 // these characters in its packet output -- so we add the quoted version
3963 // of the } character here manually in case we talk to a debugserver which
3964 // un-escapes the characters at packet read time.
3965 packet << (char) (0x7d ^ 0x20);
3967 StringExtractorGDBRemote response;
3968 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
3970 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
3971 if (response_type == StringExtractorGDBRemote::eResponse)
3973 if (!response.Empty())
3975 object_sp = StructuredData::ParseJSON (response.GetStringRef());
3983 StructuredData::ObjectSP
3984 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count)
3986 StructuredData::ObjectSP object_sp;
3988 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported())
3990 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3991 args_dict->GetAsDictionary()->AddIntegerItem ("image_list_address", image_list_address);
3992 args_dict->GetAsDictionary()->AddIntegerItem ("image_count", image_count);
3994 StreamString packet;
3995 packet << "jGetLoadedDynamicLibrariesInfos:";
3996 args_dict->Dump (packet);
3998 // FIXME the final character of a JSON dictionary, '}', is the escape
3999 // character in gdb-remote binary mode. lldb currently doesn't escape
4000 // these characters in its packet output -- so we add the quoted version
4001 // of the } character here manually in case we talk to a debugserver which
4002 // un-escapes the characters at packet read time.
4003 packet << (char) (0x7d ^ 0x20);
4005 StringExtractorGDBRemote response;
4006 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetData(), packet.GetSize(), response, false) == GDBRemoteCommunication::PacketResult::Success)
4008 StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType();
4009 if (response_type == StringExtractorGDBRemote::eResponse)
4011 if (!response.Empty())
4013 // The packet has already had the 0x7d xor quoting stripped out at the
4014 // GDBRemoteCommunication packet receive level.
4015 object_sp = StructuredData::ParseJSON (response.GetStringRef());
4024 // Establish the largest memory read/write payloads we should use.
4025 // If the remote stub has a max packet size, stay under that size.
4027 // If the remote stub's max packet size is crazy large, use a
4028 // reasonable largeish default.
4030 // If the remote stub doesn't advertise a max packet size, use a
4031 // conservative default.
4034 ProcessGDBRemote::GetMaxMemorySize()
4036 const uint64_t reasonable_largeish_default = 128 * 1024;
4037 const uint64_t conservative_default = 512;
4039 if (m_max_memory_size == 0)
4041 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4042 if (stub_max_size != UINT64_MAX && stub_max_size != 0)
4044 // Save the stub's claimed maximum packet size
4045 m_remote_stub_max_memory_size = stub_max_size;
4047 // Even if the stub says it can support ginormous packets,
4048 // don't exceed our reasonable largeish default packet size.
4049 if (stub_max_size > reasonable_largeish_default)
4051 stub_max_size = reasonable_largeish_default;
4054 m_max_memory_size = stub_max_size;
4058 m_max_memory_size = conservative_default;
4064 ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize (uint64_t user_specified_max)
4066 if (user_specified_max != 0)
4068 GetMaxMemorySize ();
4070 if (m_remote_stub_max_memory_size != 0)
4072 if (m_remote_stub_max_memory_size < user_specified_max)
4074 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a packet size too big, go as big
4075 // as the remote stub says we can go.
4079 m_max_memory_size = user_specified_max; // user's packet size is good
4084 m_max_memory_size = user_specified_max; // user's packet size is probably fine
4090 ProcessGDBRemote::GetModuleSpec(const FileSpec& module_file_spec,
4091 const ArchSpec& arch,
4092 ModuleSpec &module_spec)
4094 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
4096 if (!m_gdb_comm.GetModuleInfo (module_file_spec, arch, module_spec))
4099 log->Printf ("ProcessGDBRemote::%s - failed to get module info for %s:%s",
4100 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4101 arch.GetTriple ().getTriple ().c_str ());
4107 StreamString stream;
4108 module_spec.Dump (stream);
4109 log->Printf ("ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4110 __FUNCTION__, module_file_spec.GetPath ().c_str (),
4111 arch.GetTriple ().getTriple ().c_str (), stream.GetString ().c_str ());
4119 typedef std::vector<std::string> stringVec;
4121 typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4122 struct RegisterSetInfo
4127 typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4129 struct GdbServerTargetInfo
4134 RegisterSetMap reg_set_map;
4135 XMLNode feature_node;
4139 ParseRegisters (XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info)
4144 uint32_t prev_reg_num = 0;
4145 uint32_t reg_offset = 0;
4147 feature_node.ForEachChildElementWithName("reg", [&target_info, &dyn_reg_info, &prev_reg_num, ®_offset](const XMLNode ®_node) -> bool {
4148 std::string gdb_group;
4149 std::string gdb_type;
4150 ConstString reg_name;
4151 ConstString alt_name;
4152 ConstString set_name;
4153 std::vector<uint32_t> value_regs;
4154 std::vector<uint32_t> invalidate_regs;
4155 bool encoding_set = false;
4156 bool format_set = false;
4157 RegisterInfo reg_info = { NULL, // Name
4160 reg_offset, // offset
4161 eEncodingUint, // encoding
4162 eFormatHex, // formate
4164 LLDB_INVALID_REGNUM, // GCC reg num
4165 LLDB_INVALID_REGNUM, // DWARF reg num
4166 LLDB_INVALID_REGNUM, // generic reg num
4167 prev_reg_num, // GDB reg num
4168 prev_reg_num // native register number
4174 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, ®_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, ®_info, &prev_reg_num, ®_offset](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4177 reg_name.SetString(value);
4179 else if (name == "bitsize")
4181 reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT;
4183 else if (name == "type")
4185 gdb_type = value.str();
4187 else if (name == "group")
4189 gdb_group = value.str();
4191 else if (name == "regnum")
4193 const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4194 if (regnum != LLDB_INVALID_REGNUM)
4196 reg_info.kinds[eRegisterKindGDB] = regnum;
4197 reg_info.kinds[eRegisterKindLLDB] = regnum;
4198 prev_reg_num = regnum;
4201 else if (name == "offset")
4203 reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4205 else if (name == "altname")
4207 alt_name.SetString(value);
4209 else if (name == "encoding")
4211 encoding_set = true;
4212 reg_info.encoding = Args::StringToEncoding (value.data(), eEncodingUint);
4214 else if (name == "format")
4217 Format format = eFormatInvalid;
4218 if (Args::StringToFormat (value.data(), format, NULL).Success())
4219 reg_info.format = format;
4220 else if (value == "vector-sint8")
4221 reg_info.format = eFormatVectorOfSInt8;
4222 else if (value == "vector-uint8")
4223 reg_info.format = eFormatVectorOfUInt8;
4224 else if (value == "vector-sint16")
4225 reg_info.format = eFormatVectorOfSInt16;
4226 else if (value == "vector-uint16")
4227 reg_info.format = eFormatVectorOfUInt16;
4228 else if (value == "vector-sint32")
4229 reg_info.format = eFormatVectorOfSInt32;
4230 else if (value == "vector-uint32")
4231 reg_info.format = eFormatVectorOfUInt32;
4232 else if (value == "vector-float32")
4233 reg_info.format = eFormatVectorOfFloat32;
4234 else if (value == "vector-uint128")
4235 reg_info.format = eFormatVectorOfUInt128;
4237 else if (name == "group_id")
4239 const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4240 RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id);
4241 if (pos != target_info.reg_set_map.end())
4242 set_name = pos->second.name;
4244 else if (name == "gcc_regnum")
4246 reg_info.kinds[eRegisterKindGCC] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4248 else if (name == "dwarf_regnum")
4250 reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0);
4252 else if (name == "generic")
4254 reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value.data());
4256 else if (name == "value_regnums")
4258 SplitCommaSeparatedRegisterNumberString(value, value_regs, 0);
4260 else if (name == "invalidate_regnums")
4262 SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0);
4266 printf("unhandled attribute %s = %s\n", name.data(), value.data());
4268 return true; // Keep iterating through all attributes
4271 if (!gdb_type.empty() && !(encoding_set || format_set))
4273 if (gdb_type.find("int") == 0)
4275 reg_info.format = eFormatHex;
4276 reg_info.encoding = eEncodingUint;
4278 else if (gdb_type == "data_ptr" || gdb_type == "code_ptr")
4280 reg_info.format = eFormatAddressInfo;
4281 reg_info.encoding = eEncodingUint;
4283 else if (gdb_type == "i387_ext" || gdb_type == "float")
4285 reg_info.format = eFormatFloat;
4286 reg_info.encoding = eEncodingIEEE754;
4290 // Only update the register set name if we didn't get a "reg_set" attribute.
4291 // "set_name" will be empty if we didn't have a "reg_set" attribute.
4292 if (!set_name && !gdb_group.empty())
4293 set_name.SetCString(gdb_group.c_str());
4295 reg_info.byte_offset = reg_offset;
4296 assert (reg_info.byte_size != 0);
4297 reg_offset += reg_info.byte_size;
4298 if (!value_regs.empty())
4300 value_regs.push_back(LLDB_INVALID_REGNUM);
4301 reg_info.value_regs = value_regs.data();
4303 if (!invalidate_regs.empty())
4305 invalidate_regs.push_back(LLDB_INVALID_REGNUM);
4306 reg_info.invalidate_regs = invalidate_regs.data();
4310 dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name);
4312 return true; // Keep iterating through all "reg" elements
4320 // query the target of gdb-remote for extended target information
4321 // return: 'true' on success
4322 // 'false' on failure
4324 ProcessGDBRemote::GetGDBServerRegisterInfo ()
4326 // Make sure LLDB has an XML parser it can use first
4327 if (!XMLDocument::XMLEnabled())
4330 // redirect libxml2's error handler since the default prints to stdout
4332 GDBRemoteCommunicationClient & comm = m_gdb_comm;
4334 // check that we have extended feature read support
4335 if ( !comm.GetQXferFeaturesReadSupported( ) )
4338 // request the target xml file
4340 lldb_private::Error lldberr;
4341 if (!comm.ReadExtFeature(ConstString("features"),
4342 ConstString("target.xml"),
4350 XMLDocument xml_document;
4352 if (xml_document.ParseMemory(raw.c_str(), raw.size(), "target.xml"))
4354 GdbServerTargetInfo target_info;
4356 XMLNode target_node = xml_document.GetRootElement("target");
4359 XMLNode feature_node;
4360 target_node.ForEachChildElement([&target_info, this, &feature_node](const XMLNode &node) -> bool
4362 llvm::StringRef name = node.GetName();
4363 if (name == "architecture")
4365 node.GetElementText(target_info.arch);
4367 else if (name == "osabi")
4369 node.GetElementText(target_info.osabi);
4371 else if (name == "xi:include" || name == "include")
4373 llvm::StringRef href = node.GetAttributeValue("href");
4375 target_info.includes.push_back(href.str());
4377 else if (name == "feature")
4379 feature_node = node;
4381 else if (name == "groups")
4383 node.ForEachChildElementWithName("group", [&target_info](const XMLNode &node) -> bool {
4384 uint32_t set_id = UINT32_MAX;
4385 RegisterSetInfo set_info;
4387 node.ForEachAttribute([&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4389 set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0);
4391 set_info.name = ConstString(value);
4392 return true; // Keep iterating through all attributes
4395 if (set_id != UINT32_MAX)
4396 target_info.reg_set_map[set_id] = set_info;
4397 return true; // Keep iterating through all "group" elements
4400 return true; // Keep iterating through all children of the target_node
4405 ParseRegisters(feature_node, target_info, this->m_register_info);
4408 for (const auto &include : target_info.includes)
4410 // request register file
4411 std::string xml_data;
4412 if (!comm.ReadExtFeature(ConstString("features"),
4413 ConstString(include),
4418 XMLDocument include_xml_document;
4419 include_xml_document.ParseMemory(xml_data.data(), xml_data.size(), include.c_str());
4420 XMLNode include_feature_node = include_xml_document.GetRootElement("feature");
4421 if (include_feature_node)
4423 ParseRegisters(include_feature_node, target_info, this->m_register_info);
4426 this->m_register_info.Finalize(GetTarget().GetArchitecture());
4430 return m_register_info.GetNumRegisters() > 0;
4434 ProcessGDBRemote::GetLoadedModuleList (GDBLoadedModuleInfoList & list)
4436 // Make sure LLDB has an XML parser it can use first
4437 if (!XMLDocument::XMLEnabled())
4438 return Error (0, ErrorType::eErrorTypeGeneric);
4440 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PROCESS);
4442 log->Printf ("ProcessGDBRemote::%s", __FUNCTION__);
4444 GDBRemoteCommunicationClient & comm = m_gdb_comm;
4446 // check that we have extended feature read support
4447 if (comm.GetQXferLibrariesSVR4ReadSupported ()) {
4450 // request the loaded library list
4452 lldb_private::Error lldberr;
4454 if (!comm.ReadExtFeature (ConstString ("libraries-svr4"), ConstString (""), raw, lldberr))
4455 return Error (0, ErrorType::eErrorTypeGeneric);
4457 // parse the xml file in memory
4459 log->Printf ("parsing: %s", raw.c_str());
4462 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4463 return Error (0, ErrorType::eErrorTypeGeneric);
4465 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4469 // main link map structure
4470 llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm");
4471 if (!main_lm.empty())
4473 list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0);
4476 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4478 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4480 library.ForEachAttribute([log, &module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool {
4483 module.set_name (value.str());
4484 else if (name == "lm")
4486 // the address of the link_map struct.
4487 module.set_link_map(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4489 else if (name == "l_addr")
4491 // the displacement as read from the field 'l_addr' of the link_map struct.
4492 module.set_base(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4495 else if (name == "l_ld")
4497 // the memory address of the libraries PT_DYAMIC section.
4498 module.set_dynamic(StringConvert::ToUInt64(value.data(), LLDB_INVALID_ADDRESS, 0));
4501 return true; // Keep iterating over all properties of "library"
4507 lldb::addr_t lm=0, base=0, ld=0;
4509 module.get_name (name);
4510 module.get_link_map (lm);
4511 module.get_base (base);
4512 module.get_dynamic (ld);
4514 log->Printf ("found (link_map:0x08%" PRIx64 ", base:0x08%" PRIx64 ", ld:0x08%" PRIx64 ", name:'%s')", lm, base, ld, name.c_str());
4518 return true; // Keep iterating over all "library" elements in the root node
4522 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4523 } else if (comm.GetQXferLibrariesReadSupported ()) {
4526 // request the loaded library list
4528 lldb_private::Error lldberr;
4530 if (!comm.ReadExtFeature (ConstString ("libraries"), ConstString (""), raw, lldberr))
4531 return Error (0, ErrorType::eErrorTypeGeneric);
4534 log->Printf ("parsing: %s", raw.c_str());
4537 if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml"))
4538 return Error (0, ErrorType::eErrorTypeGeneric);
4540 XMLNode root_element = doc.GetRootElement("library-list");
4544 root_element.ForEachChildElementWithName("library", [log, &list](const XMLNode &library) -> bool {
4545 GDBLoadedModuleInfoList::LoadedModuleInfo module;
4547 llvm::StringRef name = library.GetAttributeValue("name");
4548 module.set_name(name.str());
4550 // The base address of a given library will be the address of its
4551 // first section. Most remotes send only one section for Windows
4552 // targets for example.
4553 const XMLNode §ion = library.FindFirstChildElementWithName("section");
4554 llvm::StringRef address = section.GetAttributeValue("address");
4555 module.set_base(StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0));
4560 lldb::addr_t base = 0;
4561 module.get_name (name);
4562 module.get_base (base);
4564 log->Printf ("found (base:0x%" PRIx64 ", name:'%s')", base, name.c_str());
4568 return true; // Keep iterating over all "library" elements in the root node
4572 log->Printf ("found %" PRId32 " modules in total", (int) list.m_list.size());
4574 return Error (0, ErrorType::eErrorTypeGeneric);
4581 ProcessGDBRemote::LoadModuleAtAddress (const FileSpec &file, lldb::addr_t base_addr)
4583 Target &target = m_process->GetTarget();
4584 ModuleList &modules = target.GetImages();
4587 bool changed = false;
4589 ModuleSpec module_spec (file, target.GetArchitecture());
4590 if ((module_sp = modules.FindFirstModule (module_spec)))
4592 module_sp->SetLoadAddress (target, base_addr, true, changed);
4594 else if ((module_sp = target.GetSharedModule (module_spec)))
4596 module_sp->SetLoadAddress (target, base_addr, true, changed);
4603 ProcessGDBRemote::LoadModules ()
4605 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4607 // request a list of loaded libraries from GDBServer
4608 GDBLoadedModuleInfoList module_list;
4609 if (GetLoadedModuleList (module_list).Fail())
4612 // get a list of all the modules
4613 ModuleList new_modules;
4615 for (GDBLoadedModuleInfoList::LoadedModuleInfo & modInfo : module_list.m_list)
4617 std::string mod_name;
4618 lldb::addr_t mod_base;
4621 valid &= modInfo.get_name (mod_name);
4622 valid &= modInfo.get_base (mod_base);
4626 // hack (cleaner way to get file name only?) (win/unix compat?)
4627 size_t marker = mod_name.rfind ('/');
4628 if (marker == std::string::npos)
4633 FileSpec file (mod_name.c_str()+marker, true);
4634 lldb::ModuleSP module_sp = LoadModuleAtAddress (file, mod_base);
4636 if (module_sp.get())
4637 new_modules.Append (module_sp);
4640 if (new_modules.GetSize() > 0)
4642 Target & target = m_target;
4644 new_modules.ForEach ([&target](const lldb::ModuleSP module_sp) -> bool
4646 lldb_private::ObjectFile * obj = module_sp->GetObjectFile ();
4650 if (obj->GetType () != ObjectFile::Type::eTypeExecutable)
4653 lldb::ModuleSP module_copy_sp = module_sp;
4654 target.SetExecutableModule (module_copy_sp, false);
4658 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4659 loaded_modules.AppendIfNeeded (new_modules);
4660 m_process->GetTarget().ModulesDidLoad (new_modules);
4663 return new_modules.GetSize();
4667 ProcessGDBRemote::GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr)
4670 load_addr = LLDB_INVALID_ADDRESS;
4672 std::string file_path = file.GetPath(false);
4673 if (file_path.empty ())
4674 return Error("Empty file name specified");
4676 StreamString packet;
4677 packet.PutCString("qFileLoadAddress:");
4678 packet.PutCStringAsRawHex8(file_path.c_str());
4680 StringExtractorGDBRemote response;
4681 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString().c_str(), response, false) != GDBRemoteCommunication::PacketResult::Success)
4682 return Error("Sending qFileLoadAddress packet failed");
4684 if (response.IsErrorResponse())
4686 if (response.GetError() == 1)
4688 // The file is not loaded into the inferior
4690 load_addr = LLDB_INVALID_ADDRESS;
4694 return Error("Fetching file load address from remote server returned an error");
4697 if (response.IsNormalResponse())
4700 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4704 return Error("Unknown error happened during sending the load address packet");
4709 ProcessGDBRemote::ModulesDidLoad (ModuleList &module_list)
4711 // We must call the lldb_private::Process::ModulesDidLoad () first before we do anything
4712 Process::ModulesDidLoad (module_list);
4714 // After loading shared libraries, we can ask our remote GDB server if
4715 // it needs any symbols.
4716 m_gdb_comm.ServeSymbolLookups(this);
4720 class CommandObjectProcessGDBRemoteSpeedTest: public CommandObjectParsed
4723 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) :
4724 CommandObjectParsed (interpreter,
4725 "process plugin packet speed-test",
4726 "Tests packet speeds of various sizes to determine the performance characteristics of the GDB remote connection. ",
4728 m_option_group (interpreter),
4729 m_num_packets (LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount, "The number of packets to send of each varying size (default is 1000).", 1000),
4730 m_max_send (LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, "The maximum number of bytes to send in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
4731 m_max_recv (LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, "The maximum number of bytes to receive in a packet. Sizes increase in powers of 2 while the size is less than or equal to this option value. (default 1024).", 1024),
4732 m_json (LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true)
4734 m_option_group.Append (&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4735 m_option_group.Append (&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4736 m_option_group.Append (&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4737 m_option_group.Append (&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4738 m_option_group.Finalize();
4741 ~CommandObjectProcessGDBRemoteSpeedTest ()
4747 GetOptions () override
4749 return &m_option_group;
4753 DoExecute (Args& command, CommandReturnObject &result) override
4755 const size_t argc = command.GetArgumentCount();
4758 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4761 StreamSP output_stream_sp (m_interpreter.GetDebugger().GetAsyncOutputStream());
4762 result.SetImmediateOutputStream (output_stream_sp);
4764 const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4765 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4766 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4767 const bool json = m_json.GetOptionValue().GetCurrentValue();
4768 if (output_stream_sp)
4769 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, *output_stream_sp);
4772 process->GetGDBRemote().TestPacketSpeed (num_packets, max_send, max_recv, json, result.GetOutputStream());
4774 result.SetStatus (eReturnStatusSuccessFinishResult);
4780 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4782 result.SetStatus (eReturnStatusFailed);
4786 OptionGroupOptions m_option_group;
4787 OptionGroupUInt64 m_num_packets;
4788 OptionGroupUInt64 m_max_send;
4789 OptionGroupUInt64 m_max_recv;
4790 OptionGroupBoolean m_json;
4794 class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed
4799 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) :
4800 CommandObjectParsed (interpreter,
4801 "process plugin packet history",
4802 "Dumps the packet history buffer. ",
4807 ~CommandObjectProcessGDBRemotePacketHistory ()
4812 DoExecute (Args& command, CommandReturnObject &result) override
4814 const size_t argc = command.GetArgumentCount();
4817 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4820 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4821 result.SetStatus (eReturnStatusSuccessFinishResult);
4827 result.AppendErrorWithFormat ("'%s' takes no arguments", m_cmd_name.c_str());
4829 result.SetStatus (eReturnStatusFailed);
4834 class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed
4839 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) :
4840 CommandObjectParsed (interpreter,
4841 "process plugin packet xfer-size",
4842 "Maximum size that lldb will try to read/write one one chunk.",
4847 ~CommandObjectProcessGDBRemotePacketXferSize ()
4852 DoExecute (Args& command, CommandReturnObject &result) override
4854 const size_t argc = command.GetArgumentCount();
4857 result.AppendErrorWithFormat ("'%s' takes an argument to specify the max amount to be transferred when reading/writing", m_cmd_name.c_str());
4858 result.SetStatus (eReturnStatusFailed);
4862 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4865 const char *packet_size = command.GetArgumentAtIndex(0);
4867 uint64_t user_specified_max = strtoul (packet_size, NULL, 10);
4868 if (errno == 0 && user_specified_max != 0)
4870 process->SetUserSpecifiedMaxMemoryTransferSize (user_specified_max);
4871 result.SetStatus (eReturnStatusSuccessFinishResult);
4875 result.SetStatus (eReturnStatusFailed);
4881 class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed
4886 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) :
4887 CommandObjectParsed (interpreter,
4888 "process plugin packet send",
4889 "Send a custom packet through the GDB remote protocol and print the answer. "
4890 "The packet header and footer will automatically be added to the packet prior to sending and stripped from the result.",
4895 ~CommandObjectProcessGDBRemotePacketSend ()
4900 DoExecute (Args& command, CommandReturnObject &result) override
4902 const size_t argc = command.GetArgumentCount();
4905 result.AppendErrorWithFormat ("'%s' takes a one or more packet content arguments", m_cmd_name.c_str());
4906 result.SetStatus (eReturnStatusFailed);
4910 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4913 for (size_t i=0; i<argc; ++ i)
4915 const char *packet_cstr = command.GetArgumentAtIndex(0);
4916 bool send_async = true;
4917 StringExtractorGDBRemote response;
4918 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4919 result.SetStatus (eReturnStatusSuccessFinishResult);
4920 Stream &output_strm = result.GetOutputStream();
4921 output_strm.Printf (" packet: %s\n", packet_cstr);
4922 std::string &response_str = response.GetStringRef();
4924 if (strstr(packet_cstr, "qGetProfileData") != NULL)
4926 response_str = process->GetGDBRemote().HarmonizeThreadIdsForProfileData(process, response);
4929 if (response_str.empty())
4930 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4932 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4939 class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw
4944 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) :
4945 CommandObjectRaw (interpreter,
4946 "process plugin packet monitor",
4947 "Send a qRcmd packet through the GDB remote protocol and print the response."
4948 "The argument passed to this command will be hex encoded into a valid 'qRcmd' packet, sent and the response will be printed.",
4953 ~CommandObjectProcessGDBRemotePacketMonitor ()
4958 DoExecute (const char *command, CommandReturnObject &result) override
4960 if (command == NULL || command[0] == '\0')
4962 result.AppendErrorWithFormat ("'%s' takes a command string argument", m_cmd_name.c_str());
4963 result.SetStatus (eReturnStatusFailed);
4967 ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4970 StreamString packet;
4971 packet.PutCString("qRcmd,");
4972 packet.PutBytesAsRawHex8(command, strlen(command));
4973 const char *packet_cstr = packet.GetString().c_str();
4975 bool send_async = true;
4976 StringExtractorGDBRemote response;
4977 process->GetGDBRemote().SendPacketAndWaitForResponse(packet_cstr, response, send_async);
4978 result.SetStatus (eReturnStatusSuccessFinishResult);
4979 Stream &output_strm = result.GetOutputStream();
4980 output_strm.Printf (" packet: %s\n", packet_cstr);
4981 const std::string &response_str = response.GetStringRef();
4983 if (response_str.empty())
4984 output_strm.PutCString ("response: \nerror: UNIMPLEMENTED\n");
4986 output_strm.Printf ("response: %s\n", response.GetStringRef().c_str());
4992 class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword
4997 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) :
4998 CommandObjectMultiword (interpreter,
4999 "process plugin packet",
5000 "Commands that deal with GDB remote packets.",
5003 LoadSubCommand ("history", CommandObjectSP (new CommandObjectProcessGDBRemotePacketHistory (interpreter)));
5004 LoadSubCommand ("send", CommandObjectSP (new CommandObjectProcessGDBRemotePacketSend (interpreter)));
5005 LoadSubCommand ("monitor", CommandObjectSP (new CommandObjectProcessGDBRemotePacketMonitor (interpreter)));
5006 LoadSubCommand ("xfer-size", CommandObjectSP (new CommandObjectProcessGDBRemotePacketXferSize (interpreter)));
5007 LoadSubCommand ("speed-test", CommandObjectSP (new CommandObjectProcessGDBRemoteSpeedTest (interpreter)));
5010 ~CommandObjectProcessGDBRemotePacket ()
5015 class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword
5018 CommandObjectMultiwordProcessGDBRemote (CommandInterpreter &interpreter) :
5019 CommandObjectMultiword (interpreter,
5021 "A set of commands for operating on a ProcessGDBRemote process.",
5022 "process plugin <subcommand> [<subcommand-options>]")
5024 LoadSubCommand ("packet", CommandObjectSP (new CommandObjectProcessGDBRemotePacket (interpreter)));
5027 ~CommandObjectMultiwordProcessGDBRemote ()
5033 ProcessGDBRemote::GetPluginCommandObject()
5036 m_command_sp.reset (new CommandObjectMultiwordProcessGDBRemote (GetTarget().GetDebugger().GetCommandInterpreter()));
5037 return m_command_sp.get();