1dda28197Spatrick //===-- ProcessGDBRemote.cpp ----------------------------------------------===//
2061da546Spatrick //
3061da546Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4061da546Spatrick // See https://llvm.org/LICENSE.txt for license information.
5061da546Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6061da546Spatrick //
7061da546Spatrick //===----------------------------------------------------------------------===//
8061da546Spatrick
9061da546Spatrick #include "lldb/Host/Config.h"
10061da546Spatrick
11be691f3bSpatrick #include <cerrno>
12be691f3bSpatrick #include <cstdlib>
13061da546Spatrick #if LLDB_ENABLE_POSIX
14061da546Spatrick #include <netinet/in.h>
15061da546Spatrick #include <sys/mman.h>
16061da546Spatrick #include <sys/socket.h>
17061da546Spatrick #include <unistd.h>
18061da546Spatrick #endif
19061da546Spatrick #include <sys/stat.h>
20dda28197Spatrick #if defined(__APPLE__)
21dda28197Spatrick #include <sys/sysctl.h>
22dda28197Spatrick #endif
23be691f3bSpatrick #include <ctime>
24061da546Spatrick #include <sys/types.h>
25061da546Spatrick
26061da546Spatrick #include "lldb/Breakpoint/Watchpoint.h"
27061da546Spatrick #include "lldb/Core/Debugger.h"
28061da546Spatrick #include "lldb/Core/Module.h"
29061da546Spatrick #include "lldb/Core/ModuleSpec.h"
30061da546Spatrick #include "lldb/Core/PluginManager.h"
31061da546Spatrick #include "lldb/Core/StreamFile.h"
32061da546Spatrick #include "lldb/Core/Value.h"
33061da546Spatrick #include "lldb/DataFormatters/FormatManager.h"
34061da546Spatrick #include "lldb/Host/ConnectionFileDescriptor.h"
35061da546Spatrick #include "lldb/Host/FileSystem.h"
36061da546Spatrick #include "lldb/Host/HostThread.h"
37061da546Spatrick #include "lldb/Host/PosixApi.h"
38061da546Spatrick #include "lldb/Host/PseudoTerminal.h"
39061da546Spatrick #include "lldb/Host/ThreadLauncher.h"
40061da546Spatrick #include "lldb/Host/XML.h"
41061da546Spatrick #include "lldb/Interpreter/CommandInterpreter.h"
42061da546Spatrick #include "lldb/Interpreter/CommandObject.h"
43061da546Spatrick #include "lldb/Interpreter/CommandObjectMultiword.h"
44061da546Spatrick #include "lldb/Interpreter/CommandReturnObject.h"
45061da546Spatrick #include "lldb/Interpreter/OptionArgParser.h"
46061da546Spatrick #include "lldb/Interpreter/OptionGroupBoolean.h"
47061da546Spatrick #include "lldb/Interpreter/OptionGroupUInt64.h"
48061da546Spatrick #include "lldb/Interpreter/OptionValueProperties.h"
49061da546Spatrick #include "lldb/Interpreter/Options.h"
50061da546Spatrick #include "lldb/Interpreter/Property.h"
51061da546Spatrick #include "lldb/Symbol/LocateSymbolFile.h"
52061da546Spatrick #include "lldb/Symbol/ObjectFile.h"
53061da546Spatrick #include "lldb/Target/ABI.h"
54061da546Spatrick #include "lldb/Target/DynamicLoader.h"
55061da546Spatrick #include "lldb/Target/MemoryRegionInfo.h"
56061da546Spatrick #include "lldb/Target/SystemRuntime.h"
57061da546Spatrick #include "lldb/Target/Target.h"
58061da546Spatrick #include "lldb/Target/TargetList.h"
59061da546Spatrick #include "lldb/Target/ThreadPlanCallFunction.h"
60061da546Spatrick #include "lldb/Utility/Args.h"
61061da546Spatrick #include "lldb/Utility/FileSpec.h"
62*f6aab3d8Srobert #include "lldb/Utility/LLDBLog.h"
63061da546Spatrick #include "lldb/Utility/State.h"
64061da546Spatrick #include "lldb/Utility/StreamString.h"
65061da546Spatrick #include "lldb/Utility/Timer.h"
66*f6aab3d8Srobert #include <algorithm>
67*f6aab3d8Srobert #include <csignal>
68*f6aab3d8Srobert #include <map>
69*f6aab3d8Srobert #include <memory>
70*f6aab3d8Srobert #include <mutex>
71*f6aab3d8Srobert #include <optional>
72*f6aab3d8Srobert #include <sstream>
73*f6aab3d8Srobert #include <thread>
74061da546Spatrick
75061da546Spatrick #include "GDBRemoteRegisterContext.h"
76*f6aab3d8Srobert #include "GDBRemoteRegisterFallback.h"
77061da546Spatrick #include "Plugins/Process/Utility/GDBRemoteSignals.h"
78061da546Spatrick #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
79061da546Spatrick #include "Plugins/Process/Utility/StopInfoMachException.h"
80061da546Spatrick #include "ProcessGDBRemote.h"
81061da546Spatrick #include "ProcessGDBRemoteLog.h"
82061da546Spatrick #include "ThreadGDBRemote.h"
83061da546Spatrick #include "lldb/Host/Host.h"
84061da546Spatrick #include "lldb/Utility/StringExtractorGDBRemote.h"
85061da546Spatrick
86061da546Spatrick #include "llvm/ADT/ScopeExit.h"
87061da546Spatrick #include "llvm/ADT/StringSwitch.h"
88*f6aab3d8Srobert #include "llvm/Support/FormatAdapters.h"
89061da546Spatrick #include "llvm/Support/Threading.h"
90061da546Spatrick #include "llvm/Support/raw_ostream.h"
91061da546Spatrick
92061da546Spatrick #define DEBUGSERVER_BASENAME "debugserver"
93061da546Spatrick using namespace lldb;
94061da546Spatrick using namespace lldb_private;
95061da546Spatrick using namespace lldb_private::process_gdb_remote;
96061da546Spatrick
97dda28197Spatrick LLDB_PLUGIN_DEFINE(ProcessGDBRemote)
98dda28197Spatrick
99061da546Spatrick namespace lldb {
100061da546Spatrick // Provide a function that can easily dump the packet history if we know a
101061da546Spatrick // ProcessGDBRemote * value (which we can get from logs or from debugging). We
102061da546Spatrick // need the function in the lldb namespace so it makes it into the final
103061da546Spatrick // executable since the LLDB shared library only exports stuff in the lldb
104061da546Spatrick // namespace. This allows you to attach with a debugger and call this function
105061da546Spatrick // and get the packet history dumped to a file.
DumpProcessGDBRemotePacketHistory(void * p,const char * path)106061da546Spatrick void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
107061da546Spatrick auto file = FileSystem::Instance().Open(
108*f6aab3d8Srobert FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
109061da546Spatrick if (!file) {
110061da546Spatrick llvm::consumeError(file.takeError());
111061da546Spatrick return;
112061da546Spatrick }
113061da546Spatrick StreamFile stream(std::move(file.get()));
114061da546Spatrick ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
115061da546Spatrick }
116061da546Spatrick } // namespace lldb
117061da546Spatrick
118061da546Spatrick namespace {
119061da546Spatrick
120061da546Spatrick #define LLDB_PROPERTIES_processgdbremote
121061da546Spatrick #include "ProcessGDBRemoteProperties.inc"
122061da546Spatrick
123061da546Spatrick enum {
124061da546Spatrick #define LLDB_PROPERTIES_processgdbremote
125061da546Spatrick #include "ProcessGDBRemotePropertiesEnum.inc"
126061da546Spatrick };
127061da546Spatrick
128061da546Spatrick class PluginProperties : public Properties {
129061da546Spatrick public:
GetSettingName()130061da546Spatrick static ConstString GetSettingName() {
131*f6aab3d8Srobert return ConstString(ProcessGDBRemote::GetPluginNameStatic());
132061da546Spatrick }
133061da546Spatrick
PluginProperties()134061da546Spatrick PluginProperties() : Properties() {
135061da546Spatrick m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
136061da546Spatrick m_collection_sp->Initialize(g_processgdbremote_properties);
137061da546Spatrick }
138061da546Spatrick
139be691f3bSpatrick ~PluginProperties() override = default;
140061da546Spatrick
GetPacketTimeout()141061da546Spatrick uint64_t GetPacketTimeout() {
142061da546Spatrick const uint32_t idx = ePropertyPacketTimeout;
143061da546Spatrick return m_collection_sp->GetPropertyAtIndexAsUInt64(
144061da546Spatrick nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
145061da546Spatrick }
146061da546Spatrick
SetPacketTimeout(uint64_t timeout)147061da546Spatrick bool SetPacketTimeout(uint64_t timeout) {
148061da546Spatrick const uint32_t idx = ePropertyPacketTimeout;
149061da546Spatrick return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
150061da546Spatrick }
151061da546Spatrick
GetTargetDefinitionFile() const152061da546Spatrick FileSpec GetTargetDefinitionFile() const {
153061da546Spatrick const uint32_t idx = ePropertyTargetDefinitionFile;
154061da546Spatrick return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
155061da546Spatrick }
156061da546Spatrick
GetUseSVR4() const157061da546Spatrick bool GetUseSVR4() const {
158061da546Spatrick const uint32_t idx = ePropertyUseSVR4;
159061da546Spatrick return m_collection_sp->GetPropertyAtIndexAsBoolean(
160061da546Spatrick nullptr, idx,
161061da546Spatrick g_processgdbremote_properties[idx].default_uint_value != 0);
162061da546Spatrick }
163061da546Spatrick
GetUseGPacketForReading() const164061da546Spatrick bool GetUseGPacketForReading() const {
165061da546Spatrick const uint32_t idx = ePropertyUseGPacketForReading;
166061da546Spatrick return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
167061da546Spatrick }
168061da546Spatrick };
169061da546Spatrick
170061da546Spatrick } // namespace
171061da546Spatrick
GetGlobalPluginProperties()172*f6aab3d8Srobert static PluginProperties &GetGlobalPluginProperties() {
173*f6aab3d8Srobert static PluginProperties g_settings;
174*f6aab3d8Srobert return g_settings;
175*f6aab3d8Srobert }
176*f6aab3d8Srobert
177061da546Spatrick // TODO Randomly assigning a port is unsafe. We should get an unused
178061da546Spatrick // ephemeral port from the kernel and make sure we reserve it before passing it
179061da546Spatrick // to debugserver.
180061da546Spatrick
181061da546Spatrick #if defined(__APPLE__)
182061da546Spatrick #define LOW_PORT (IPPORT_RESERVED)
183061da546Spatrick #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
184061da546Spatrick #else
185061da546Spatrick #define LOW_PORT (1024u)
186061da546Spatrick #define HIGH_PORT (49151u)
187061da546Spatrick #endif
188061da546Spatrick
GetPluginDescriptionStatic()189*f6aab3d8Srobert llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
190061da546Spatrick return "GDB Remote protocol based debugging plug-in.";
191061da546Spatrick }
192061da546Spatrick
Terminate()193061da546Spatrick void ProcessGDBRemote::Terminate() {
194061da546Spatrick PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
195061da546Spatrick }
196061da546Spatrick
CreateInstance(lldb::TargetSP target_sp,ListenerSP listener_sp,const FileSpec * crash_file_path,bool can_connect)197*f6aab3d8Srobert lldb::ProcessSP ProcessGDBRemote::CreateInstance(
198*f6aab3d8Srobert lldb::TargetSP target_sp, ListenerSP listener_sp,
199*f6aab3d8Srobert const FileSpec *crash_file_path, bool can_connect) {
200061da546Spatrick lldb::ProcessSP process_sp;
201061da546Spatrick if (crash_file_path == nullptr)
202*f6aab3d8Srobert process_sp = std::shared_ptr<ProcessGDBRemote>(
203*f6aab3d8Srobert new ProcessGDBRemote(target_sp, listener_sp));
204061da546Spatrick return process_sp;
205061da546Spatrick }
206061da546Spatrick
GetPacketTimeout()207be691f3bSpatrick std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
208*f6aab3d8Srobert return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
209*f6aab3d8Srobert }
210*f6aab3d8Srobert
GetSystemArchitecture()211*f6aab3d8Srobert ArchSpec ProcessGDBRemote::GetSystemArchitecture() {
212*f6aab3d8Srobert return m_gdb_comm.GetHostArchitecture();
213be691f3bSpatrick }
214be691f3bSpatrick
CanDebug(lldb::TargetSP target_sp,bool plugin_specified_by_name)215061da546Spatrick bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
216061da546Spatrick bool plugin_specified_by_name) {
217061da546Spatrick if (plugin_specified_by_name)
218061da546Spatrick return true;
219061da546Spatrick
220061da546Spatrick // For now we are just making sure the file exists for a given module
221061da546Spatrick Module *exe_module = target_sp->GetExecutableModulePointer();
222061da546Spatrick if (exe_module) {
223061da546Spatrick ObjectFile *exe_objfile = exe_module->GetObjectFile();
224061da546Spatrick // We can't debug core files...
225061da546Spatrick switch (exe_objfile->GetType()) {
226061da546Spatrick case ObjectFile::eTypeInvalid:
227061da546Spatrick case ObjectFile::eTypeCoreFile:
228061da546Spatrick case ObjectFile::eTypeDebugInfo:
229061da546Spatrick case ObjectFile::eTypeObjectFile:
230061da546Spatrick case ObjectFile::eTypeSharedLibrary:
231061da546Spatrick case ObjectFile::eTypeStubLibrary:
232061da546Spatrick case ObjectFile::eTypeJIT:
233061da546Spatrick return false;
234061da546Spatrick case ObjectFile::eTypeExecutable:
235061da546Spatrick case ObjectFile::eTypeDynamicLinker:
236061da546Spatrick case ObjectFile::eTypeUnknown:
237061da546Spatrick break;
238061da546Spatrick }
239061da546Spatrick return FileSystem::Instance().Exists(exe_module->GetFileSpec());
240061da546Spatrick }
241061da546Spatrick // However, if there is no executable module, we return true since we might
242061da546Spatrick // be preparing to attach.
243061da546Spatrick return true;
244061da546Spatrick }
245061da546Spatrick
246061da546Spatrick // ProcessGDBRemote constructor
ProcessGDBRemote(lldb::TargetSP target_sp,ListenerSP listener_sp)247061da546Spatrick ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
248061da546Spatrick ListenerSP listener_sp)
249061da546Spatrick : Process(target_sp, listener_sp),
250*f6aab3d8Srobert m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
251061da546Spatrick m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
252061da546Spatrick m_async_listener_sp(
253061da546Spatrick Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
254061da546Spatrick m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
255061da546Spatrick m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
256061da546Spatrick m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
257061da546Spatrick m_max_memory_size(0), m_remote_stub_max_memory_size(0),
258061da546Spatrick m_addr_to_mmap_size(), m_thread_create_bp_sp(),
259*f6aab3d8Srobert m_waiting_for_attach(false),
260061da546Spatrick m_command_sp(), m_breakpoint_pc_offset(0),
261*f6aab3d8Srobert m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
262*f6aab3d8Srobert m_erased_flash_ranges(), m_vfork_in_progress(false) {
263061da546Spatrick m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
264061da546Spatrick "async thread should exit");
265061da546Spatrick m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
266061da546Spatrick "async thread continue");
267061da546Spatrick m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
268061da546Spatrick "async thread did exit");
269061da546Spatrick
270*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Async);
271061da546Spatrick
272061da546Spatrick const uint32_t async_event_mask =
273061da546Spatrick eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
274061da546Spatrick
275061da546Spatrick if (m_async_listener_sp->StartListeningForEvents(
276061da546Spatrick &m_async_broadcaster, async_event_mask) != async_event_mask) {
277061da546Spatrick LLDB_LOGF(log,
278061da546Spatrick "ProcessGDBRemote::%s failed to listen for "
279061da546Spatrick "m_async_broadcaster events",
280061da546Spatrick __FUNCTION__);
281061da546Spatrick }
282061da546Spatrick
283061da546Spatrick const uint64_t timeout_seconds =
284*f6aab3d8Srobert GetGlobalPluginProperties().GetPacketTimeout();
285061da546Spatrick if (timeout_seconds > 0)
286061da546Spatrick m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
287061da546Spatrick
288061da546Spatrick m_use_g_packet_for_reading =
289*f6aab3d8Srobert GetGlobalPluginProperties().GetUseGPacketForReading();
290061da546Spatrick }
291061da546Spatrick
292061da546Spatrick // Destructor
~ProcessGDBRemote()293061da546Spatrick ProcessGDBRemote::~ProcessGDBRemote() {
294061da546Spatrick // m_mach_process.UnregisterNotificationCallbacks (this);
295061da546Spatrick Clear();
296061da546Spatrick // We need to call finalize on the process before destroying ourselves to
297061da546Spatrick // make sure all of the broadcaster cleanup goes as planned. If we destruct
298061da546Spatrick // this class, then Process::~Process() might have problems trying to fully
299061da546Spatrick // destroy the broadcaster.
300061da546Spatrick Finalize();
301061da546Spatrick
302061da546Spatrick // The general Finalize is going to try to destroy the process and that
303061da546Spatrick // SHOULD shut down the async thread. However, if we don't kill it it will
304061da546Spatrick // get stranded and its connection will go away so when it wakes up it will
305061da546Spatrick // crash. So kill it for sure here.
306061da546Spatrick StopAsyncThread();
307061da546Spatrick KillDebugserverProcess();
308061da546Spatrick }
309061da546Spatrick
ParsePythonTargetDefinition(const FileSpec & target_definition_fspec)310061da546Spatrick bool ProcessGDBRemote::ParsePythonTargetDefinition(
311061da546Spatrick const FileSpec &target_definition_fspec) {
312061da546Spatrick ScriptInterpreter *interpreter =
313061da546Spatrick GetTarget().GetDebugger().GetScriptInterpreter();
314061da546Spatrick Status error;
315061da546Spatrick StructuredData::ObjectSP module_object_sp(
316061da546Spatrick interpreter->LoadPluginModule(target_definition_fspec, error));
317061da546Spatrick if (module_object_sp) {
318061da546Spatrick StructuredData::DictionarySP target_definition_sp(
319061da546Spatrick interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
320061da546Spatrick "gdb-server-target-definition", error));
321061da546Spatrick
322061da546Spatrick if (target_definition_sp) {
323061da546Spatrick StructuredData::ObjectSP target_object(
324061da546Spatrick target_definition_sp->GetValueForKey("host-info"));
325061da546Spatrick if (target_object) {
326061da546Spatrick if (auto host_info_dict = target_object->GetAsDictionary()) {
327061da546Spatrick StructuredData::ObjectSP triple_value =
328061da546Spatrick host_info_dict->GetValueForKey("triple");
329061da546Spatrick if (auto triple_string_value = triple_value->GetAsString()) {
330dda28197Spatrick std::string triple_string =
331dda28197Spatrick std::string(triple_string_value->GetValue());
332061da546Spatrick ArchSpec host_arch(triple_string.c_str());
333061da546Spatrick if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
334061da546Spatrick GetTarget().SetArchitecture(host_arch);
335061da546Spatrick }
336061da546Spatrick }
337061da546Spatrick }
338061da546Spatrick }
339061da546Spatrick m_breakpoint_pc_offset = 0;
340061da546Spatrick StructuredData::ObjectSP breakpoint_pc_offset_value =
341061da546Spatrick target_definition_sp->GetValueForKey("breakpoint-pc-offset");
342061da546Spatrick if (breakpoint_pc_offset_value) {
343061da546Spatrick if (auto breakpoint_pc_int_value =
344061da546Spatrick breakpoint_pc_offset_value->GetAsInteger())
345061da546Spatrick m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
346061da546Spatrick }
347061da546Spatrick
348be691f3bSpatrick if (m_register_info_sp->SetRegisterInfo(
349be691f3bSpatrick *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
350061da546Spatrick return true;
351061da546Spatrick }
352061da546Spatrick }
353061da546Spatrick }
354061da546Spatrick return false;
355061da546Spatrick }
356061da546Spatrick
SplitCommaSeparatedRegisterNumberString(const llvm::StringRef & comma_separated_register_numbers,std::vector<uint32_t> & regnums,int base)357061da546Spatrick static size_t SplitCommaSeparatedRegisterNumberString(
358*f6aab3d8Srobert const llvm::StringRef &comma_separated_register_numbers,
359061da546Spatrick std::vector<uint32_t> ®nums, int base) {
360061da546Spatrick regnums.clear();
361*f6aab3d8Srobert for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
362*f6aab3d8Srobert uint32_t reg;
363*f6aab3d8Srobert if (llvm::to_integer(x, reg, base))
364061da546Spatrick regnums.push_back(reg);
365061da546Spatrick }
366061da546Spatrick return regnums.size();
367061da546Spatrick }
368061da546Spatrick
BuildDynamicRegisterInfo(bool force)369061da546Spatrick void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
370be691f3bSpatrick if (!force && m_register_info_sp)
371061da546Spatrick return;
372061da546Spatrick
373be691f3bSpatrick m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
374061da546Spatrick
375061da546Spatrick // Check if qHostInfo specified a specific packet timeout for this
376061da546Spatrick // connection. If so then lets update our setting so the user knows what the
377061da546Spatrick // timeout is and can see it.
378061da546Spatrick const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
379061da546Spatrick if (host_packet_timeout > std::chrono::seconds(0)) {
380*f6aab3d8Srobert GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
381061da546Spatrick }
382061da546Spatrick
383061da546Spatrick // Register info search order:
384061da546Spatrick // 1 - Use the target definition python file if one is specified.
385061da546Spatrick // 2 - If the target definition doesn't have any of the info from the
386061da546Spatrick // target.xml (registers) then proceed to read the target.xml.
387061da546Spatrick // 3 - Fall back on the qRegisterInfo packets.
388*f6aab3d8Srobert // 4 - Use hardcoded defaults if available.
389061da546Spatrick
390061da546Spatrick FileSpec target_definition_fspec =
391*f6aab3d8Srobert GetGlobalPluginProperties().GetTargetDefinitionFile();
392061da546Spatrick if (!FileSystem::Instance().Exists(target_definition_fspec)) {
393061da546Spatrick // If the filename doesn't exist, it may be a ~ not having been expanded -
394061da546Spatrick // try to resolve it.
395061da546Spatrick FileSystem::Instance().Resolve(target_definition_fspec);
396061da546Spatrick }
397061da546Spatrick if (target_definition_fspec) {
398061da546Spatrick // See if we can get register definitions from a python file
399*f6aab3d8Srobert if (ParsePythonTargetDefinition(target_definition_fspec))
400061da546Spatrick return;
401*f6aab3d8Srobert
402*f6aab3d8Srobert Debugger::ReportError("target description file " +
403*f6aab3d8Srobert target_definition_fspec.GetPath() +
404*f6aab3d8Srobert " failed to parse",
405*f6aab3d8Srobert GetTarget().GetDebugger().GetID());
406061da546Spatrick }
407061da546Spatrick
408061da546Spatrick const ArchSpec &target_arch = GetTarget().GetArchitecture();
409061da546Spatrick const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
410061da546Spatrick const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
411061da546Spatrick
412061da546Spatrick // Use the process' architecture instead of the host arch, if available
413061da546Spatrick ArchSpec arch_to_use;
414061da546Spatrick if (remote_process_arch.IsValid())
415061da546Spatrick arch_to_use = remote_process_arch;
416061da546Spatrick else
417061da546Spatrick arch_to_use = remote_host_arch;
418061da546Spatrick
419061da546Spatrick if (!arch_to_use.IsValid())
420061da546Spatrick arch_to_use = target_arch;
421061da546Spatrick
422061da546Spatrick if (GetGDBServerRegisterInfo(arch_to_use))
423061da546Spatrick return;
424061da546Spatrick
425061da546Spatrick char packet[128];
426*f6aab3d8Srobert std::vector<DynamicRegisterInfo::Register> registers;
427061da546Spatrick uint32_t reg_num = 0;
428061da546Spatrick for (StringExtractorGDBRemote::ResponseType response_type =
429061da546Spatrick StringExtractorGDBRemote::eResponse;
430061da546Spatrick response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
431061da546Spatrick const int packet_len =
432061da546Spatrick ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
433061da546Spatrick assert(packet_len < (int)sizeof(packet));
434061da546Spatrick UNUSED_IF_ASSERT_DISABLED(packet_len);
435061da546Spatrick StringExtractorGDBRemote response;
436be691f3bSpatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
437061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
438061da546Spatrick response_type = response.GetResponseType();
439061da546Spatrick if (response_type == StringExtractorGDBRemote::eResponse) {
440061da546Spatrick llvm::StringRef name;
441061da546Spatrick llvm::StringRef value;
442*f6aab3d8Srobert DynamicRegisterInfo::Register reg_info;
443061da546Spatrick
444061da546Spatrick while (response.GetNameColonValue(name, value)) {
445061da546Spatrick if (name.equals("name")) {
446*f6aab3d8Srobert reg_info.name.SetString(value);
447061da546Spatrick } else if (name.equals("alt-name")) {
448*f6aab3d8Srobert reg_info.alt_name.SetString(value);
449061da546Spatrick } else if (name.equals("bitsize")) {
450*f6aab3d8Srobert if (!value.getAsInteger(0, reg_info.byte_size))
451061da546Spatrick reg_info.byte_size /= CHAR_BIT;
452061da546Spatrick } else if (name.equals("offset")) {
453*f6aab3d8Srobert value.getAsInteger(0, reg_info.byte_offset);
454061da546Spatrick } else if (name.equals("encoding")) {
455061da546Spatrick const Encoding encoding = Args::StringToEncoding(value);
456061da546Spatrick if (encoding != eEncodingInvalid)
457061da546Spatrick reg_info.encoding = encoding;
458061da546Spatrick } else if (name.equals("format")) {
459*f6aab3d8Srobert if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
460061da546Spatrick .Success())
461061da546Spatrick reg_info.format =
462061da546Spatrick llvm::StringSwitch<Format>(value)
463061da546Spatrick .Case("binary", eFormatBinary)
464061da546Spatrick .Case("decimal", eFormatDecimal)
465061da546Spatrick .Case("hex", eFormatHex)
466061da546Spatrick .Case("float", eFormatFloat)
467061da546Spatrick .Case("vector-sint8", eFormatVectorOfSInt8)
468061da546Spatrick .Case("vector-uint8", eFormatVectorOfUInt8)
469061da546Spatrick .Case("vector-sint16", eFormatVectorOfSInt16)
470061da546Spatrick .Case("vector-uint16", eFormatVectorOfUInt16)
471061da546Spatrick .Case("vector-sint32", eFormatVectorOfSInt32)
472061da546Spatrick .Case("vector-uint32", eFormatVectorOfUInt32)
473061da546Spatrick .Case("vector-float32", eFormatVectorOfFloat32)
474061da546Spatrick .Case("vector-uint64", eFormatVectorOfUInt64)
475061da546Spatrick .Case("vector-uint128", eFormatVectorOfUInt128)
476061da546Spatrick .Default(eFormatInvalid);
477061da546Spatrick } else if (name.equals("set")) {
478*f6aab3d8Srobert reg_info.set_name.SetString(value);
479061da546Spatrick } else if (name.equals("gcc") || name.equals("ehframe")) {
480*f6aab3d8Srobert value.getAsInteger(0, reg_info.regnum_ehframe);
481061da546Spatrick } else if (name.equals("dwarf")) {
482*f6aab3d8Srobert value.getAsInteger(0, reg_info.regnum_dwarf);
483061da546Spatrick } else if (name.equals("generic")) {
484*f6aab3d8Srobert reg_info.regnum_generic = Args::StringToGenericRegister(value);
485061da546Spatrick } else if (name.equals("container-regs")) {
486*f6aab3d8Srobert SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 16);
487061da546Spatrick } else if (name.equals("invalidate-regs")) {
488*f6aab3d8Srobert SplitCommaSeparatedRegisterNumberString(value, reg_info.invalidate_regs, 16);
489061da546Spatrick }
490061da546Spatrick }
491061da546Spatrick
492061da546Spatrick assert(reg_info.byte_size != 0);
493*f6aab3d8Srobert registers.push_back(reg_info);
494061da546Spatrick } else {
495061da546Spatrick break; // ensure exit before reg_num is incremented
496061da546Spatrick }
497061da546Spatrick } else {
498061da546Spatrick break;
499061da546Spatrick }
500061da546Spatrick }
501061da546Spatrick
502*f6aab3d8Srobert if (registers.empty())
503*f6aab3d8Srobert registers = GetFallbackRegisters(arch_to_use);
504*f6aab3d8Srobert
505*f6aab3d8Srobert AddRemoteRegisters(registers, arch_to_use);
506061da546Spatrick }
507061da546Spatrick
DoWillLaunch(lldb_private::Module * module)508*f6aab3d8Srobert Status ProcessGDBRemote::DoWillLaunch(lldb_private::Module *module) {
509061da546Spatrick return WillLaunchOrAttach();
510061da546Spatrick }
511061da546Spatrick
DoWillAttachToProcessWithID(lldb::pid_t pid)512*f6aab3d8Srobert Status ProcessGDBRemote::DoWillAttachToProcessWithID(lldb::pid_t pid) {
513061da546Spatrick return WillLaunchOrAttach();
514061da546Spatrick }
515061da546Spatrick
DoWillAttachToProcessWithName(const char * process_name,bool wait_for_launch)516*f6aab3d8Srobert Status ProcessGDBRemote::DoWillAttachToProcessWithName(const char *process_name,
517061da546Spatrick bool wait_for_launch) {
518061da546Spatrick return WillLaunchOrAttach();
519061da546Spatrick }
520061da546Spatrick
DoConnectRemote(llvm::StringRef remote_url)521dda28197Spatrick Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
522*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
523*f6aab3d8Srobert
524061da546Spatrick Status error(WillLaunchOrAttach());
525061da546Spatrick if (error.Fail())
526061da546Spatrick return error;
527061da546Spatrick
528061da546Spatrick error = ConnectToDebugserver(remote_url);
529061da546Spatrick if (error.Fail())
530061da546Spatrick return error;
531*f6aab3d8Srobert
532061da546Spatrick StartAsyncThread();
533061da546Spatrick
534061da546Spatrick lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
535061da546Spatrick if (pid == LLDB_INVALID_PROCESS_ID) {
536061da546Spatrick // We don't have a valid process ID, so note that we are connected and
537061da546Spatrick // could now request to launch or attach, or get remote process listings...
538061da546Spatrick SetPrivateState(eStateConnected);
539061da546Spatrick } else {
540061da546Spatrick // We have a valid process
541061da546Spatrick SetID(pid);
542061da546Spatrick GetThreadList();
543061da546Spatrick StringExtractorGDBRemote response;
544061da546Spatrick if (m_gdb_comm.GetStopReply(response)) {
545061da546Spatrick SetLastStopPacket(response);
546061da546Spatrick
547061da546Spatrick Target &target = GetTarget();
548061da546Spatrick if (!target.GetArchitecture().IsValid()) {
549061da546Spatrick if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
550061da546Spatrick target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
551061da546Spatrick } else {
552061da546Spatrick if (m_gdb_comm.GetHostArchitecture().IsValid()) {
553061da546Spatrick target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
554061da546Spatrick }
555061da546Spatrick }
556061da546Spatrick }
557061da546Spatrick
558061da546Spatrick const StateType state = SetThreadStopInfo(response);
559061da546Spatrick if (state != eStateInvalid) {
560061da546Spatrick SetPrivateState(state);
561061da546Spatrick } else
562061da546Spatrick error.SetErrorStringWithFormat(
563061da546Spatrick "Process %" PRIu64 " was reported after connecting to "
564061da546Spatrick "'%s', but state was not stopped: %s",
565061da546Spatrick pid, remote_url.str().c_str(), StateAsCString(state));
566061da546Spatrick } else
567061da546Spatrick error.SetErrorStringWithFormat("Process %" PRIu64
568061da546Spatrick " was reported after connecting to '%s', "
569061da546Spatrick "but no stop reply packet was received",
570061da546Spatrick pid, remote_url.str().c_str());
571061da546Spatrick }
572061da546Spatrick
573061da546Spatrick LLDB_LOGF(log,
574061da546Spatrick "ProcessGDBRemote::%s pid %" PRIu64
575061da546Spatrick ": normalizing target architecture initial triple: %s "
576061da546Spatrick "(GetTarget().GetArchitecture().IsValid() %s, "
577061da546Spatrick "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
578061da546Spatrick __FUNCTION__, GetID(),
579061da546Spatrick GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
580061da546Spatrick GetTarget().GetArchitecture().IsValid() ? "true" : "false",
581061da546Spatrick m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
582061da546Spatrick
583061da546Spatrick if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
584061da546Spatrick m_gdb_comm.GetHostArchitecture().IsValid()) {
585061da546Spatrick // Prefer the *process'* architecture over that of the *host*, if
586061da546Spatrick // available.
587061da546Spatrick if (m_gdb_comm.GetProcessArchitecture().IsValid())
588061da546Spatrick GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
589061da546Spatrick else
590061da546Spatrick GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
591061da546Spatrick }
592061da546Spatrick
593061da546Spatrick LLDB_LOGF(log,
594061da546Spatrick "ProcessGDBRemote::%s pid %" PRIu64
595061da546Spatrick ": normalized target architecture triple: %s",
596061da546Spatrick __FUNCTION__, GetID(),
597061da546Spatrick GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
598061da546Spatrick
599061da546Spatrick return error;
600061da546Spatrick }
601061da546Spatrick
WillLaunchOrAttach()602061da546Spatrick Status ProcessGDBRemote::WillLaunchOrAttach() {
603061da546Spatrick Status error;
604061da546Spatrick m_stdio_communication.Clear();
605061da546Spatrick return error;
606061da546Spatrick }
607061da546Spatrick
608061da546Spatrick // Process Control
DoLaunch(lldb_private::Module * exe_module,ProcessLaunchInfo & launch_info)609061da546Spatrick Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
610061da546Spatrick ProcessLaunchInfo &launch_info) {
611*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
612061da546Spatrick Status error;
613061da546Spatrick
614061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
615061da546Spatrick
616061da546Spatrick uint32_t launch_flags = launch_info.GetFlags().Get();
617061da546Spatrick FileSpec stdin_file_spec{};
618061da546Spatrick FileSpec stdout_file_spec{};
619061da546Spatrick FileSpec stderr_file_spec{};
620061da546Spatrick FileSpec working_dir = launch_info.GetWorkingDirectory();
621061da546Spatrick
622061da546Spatrick const FileAction *file_action;
623061da546Spatrick file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
624061da546Spatrick if (file_action) {
625061da546Spatrick if (file_action->GetAction() == FileAction::eFileActionOpen)
626061da546Spatrick stdin_file_spec = file_action->GetFileSpec();
627061da546Spatrick }
628061da546Spatrick file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
629061da546Spatrick if (file_action) {
630061da546Spatrick if (file_action->GetAction() == FileAction::eFileActionOpen)
631061da546Spatrick stdout_file_spec = file_action->GetFileSpec();
632061da546Spatrick }
633061da546Spatrick file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
634061da546Spatrick if (file_action) {
635061da546Spatrick if (file_action->GetAction() == FileAction::eFileActionOpen)
636061da546Spatrick stderr_file_spec = file_action->GetFileSpec();
637061da546Spatrick }
638061da546Spatrick
639061da546Spatrick if (log) {
640061da546Spatrick if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
641061da546Spatrick LLDB_LOGF(log,
642061da546Spatrick "ProcessGDBRemote::%s provided with STDIO paths via "
643061da546Spatrick "launch_info: stdin=%s, stdout=%s, stderr=%s",
644061da546Spatrick __FUNCTION__,
645*f6aab3d8Srobert stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
646*f6aab3d8Srobert stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
647*f6aab3d8Srobert stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
648061da546Spatrick else
649061da546Spatrick LLDB_LOGF(log,
650061da546Spatrick "ProcessGDBRemote::%s no STDIO paths given via launch_info",
651061da546Spatrick __FUNCTION__);
652061da546Spatrick }
653061da546Spatrick
654061da546Spatrick const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
655061da546Spatrick if (stdin_file_spec || disable_stdio) {
656061da546Spatrick // the inferior will be reading stdin from the specified file or stdio is
657061da546Spatrick // completely disabled
658061da546Spatrick m_stdin_forward = false;
659061da546Spatrick } else {
660061da546Spatrick m_stdin_forward = true;
661061da546Spatrick }
662061da546Spatrick
663061da546Spatrick // ::LogSetBitMask (GDBR_LOG_DEFAULT);
664061da546Spatrick // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
665061da546Spatrick // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
666061da546Spatrick // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
667061da546Spatrick // ::LogSetLogFile ("/dev/stdout");
668061da546Spatrick
669061da546Spatrick error = EstablishConnectionIfNeeded(launch_info);
670061da546Spatrick if (error.Success()) {
671061da546Spatrick PseudoTerminal pty;
672061da546Spatrick const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
673061da546Spatrick
674061da546Spatrick PlatformSP platform_sp(GetTarget().GetPlatform());
675061da546Spatrick if (disable_stdio) {
676061da546Spatrick // set to /dev/null unless redirected to a file above
677061da546Spatrick if (!stdin_file_spec)
678061da546Spatrick stdin_file_spec.SetFile(FileSystem::DEV_NULL,
679061da546Spatrick FileSpec::Style::native);
680061da546Spatrick if (!stdout_file_spec)
681061da546Spatrick stdout_file_spec.SetFile(FileSystem::DEV_NULL,
682061da546Spatrick FileSpec::Style::native);
683061da546Spatrick if (!stderr_file_spec)
684061da546Spatrick stderr_file_spec.SetFile(FileSystem::DEV_NULL,
685061da546Spatrick FileSpec::Style::native);
686061da546Spatrick } else if (platform_sp && platform_sp->IsHost()) {
687061da546Spatrick // If the debugserver is local and we aren't disabling STDIO, lets use
688061da546Spatrick // a pseudo terminal to instead of relying on the 'O' packets for stdio
689061da546Spatrick // since 'O' packets can really slow down debugging if the inferior
690061da546Spatrick // does a lot of output.
691061da546Spatrick if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
692be691f3bSpatrick !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
693be691f3bSpatrick FileSpec secondary_name(pty.GetSecondaryName());
694061da546Spatrick
695061da546Spatrick if (!stdin_file_spec)
696dda28197Spatrick stdin_file_spec = secondary_name;
697061da546Spatrick
698061da546Spatrick if (!stdout_file_spec)
699dda28197Spatrick stdout_file_spec = secondary_name;
700061da546Spatrick
701061da546Spatrick if (!stderr_file_spec)
702dda28197Spatrick stderr_file_spec = secondary_name;
703061da546Spatrick }
704061da546Spatrick LLDB_LOGF(
705061da546Spatrick log,
706061da546Spatrick "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
707dda28197Spatrick "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
708dda28197Spatrick "stderr=%s",
709061da546Spatrick __FUNCTION__,
710*f6aab3d8Srobert stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
711*f6aab3d8Srobert stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
712*f6aab3d8Srobert stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
713061da546Spatrick }
714061da546Spatrick
715061da546Spatrick LLDB_LOGF(log,
716061da546Spatrick "ProcessGDBRemote::%s final STDIO paths after all "
717061da546Spatrick "adjustments: stdin=%s, stdout=%s, stderr=%s",
718061da546Spatrick __FUNCTION__,
719*f6aab3d8Srobert stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
720*f6aab3d8Srobert stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
721*f6aab3d8Srobert stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
722061da546Spatrick
723061da546Spatrick if (stdin_file_spec)
724061da546Spatrick m_gdb_comm.SetSTDIN(stdin_file_spec);
725061da546Spatrick if (stdout_file_spec)
726061da546Spatrick m_gdb_comm.SetSTDOUT(stdout_file_spec);
727061da546Spatrick if (stderr_file_spec)
728061da546Spatrick m_gdb_comm.SetSTDERR(stderr_file_spec);
729061da546Spatrick
730061da546Spatrick m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
731061da546Spatrick m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
732061da546Spatrick
733061da546Spatrick m_gdb_comm.SendLaunchArchPacket(
734061da546Spatrick GetTarget().GetArchitecture().GetArchitectureName());
735061da546Spatrick
736061da546Spatrick const char *launch_event_data = launch_info.GetLaunchEventData();
737061da546Spatrick if (launch_event_data != nullptr && *launch_event_data != '\0')
738061da546Spatrick m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
739061da546Spatrick
740061da546Spatrick if (working_dir) {
741061da546Spatrick m_gdb_comm.SetWorkingDir(working_dir);
742061da546Spatrick }
743061da546Spatrick
744061da546Spatrick // Send the environment and the program + arguments after we connect
745061da546Spatrick m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
746061da546Spatrick
747061da546Spatrick {
748061da546Spatrick // Scope for the scoped timeout object
749061da546Spatrick GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
750061da546Spatrick std::chrono::seconds(10));
751061da546Spatrick
752*f6aab3d8Srobert // Since we can't send argv0 separate from the executable path, we need to
753*f6aab3d8Srobert // make sure to use the actual executable path found in the launch_info...
754*f6aab3d8Srobert Args args = launch_info.GetArguments();
755*f6aab3d8Srobert if (FileSpec exe_file = launch_info.GetExecutableFile())
756*f6aab3d8Srobert args.ReplaceArgumentAtIndex(0, exe_file.GetPath(false));
757*f6aab3d8Srobert if (llvm::Error err = m_gdb_comm.LaunchProcess(args)) {
758*f6aab3d8Srobert error.SetErrorStringWithFormatv("Cannot launch '{0}': {1}",
759*f6aab3d8Srobert args.GetArgumentAtIndex(0),
760*f6aab3d8Srobert llvm::fmt_consume(std::move(err)));
761*f6aab3d8Srobert } else {
762061da546Spatrick SetID(m_gdb_comm.GetCurrentProcessID());
763061da546Spatrick }
764061da546Spatrick }
765061da546Spatrick
766061da546Spatrick if (GetID() == LLDB_INVALID_PROCESS_ID) {
767061da546Spatrick LLDB_LOGF(log, "failed to connect to debugserver: %s",
768061da546Spatrick error.AsCString());
769061da546Spatrick KillDebugserverProcess();
770061da546Spatrick return error;
771061da546Spatrick }
772061da546Spatrick
773061da546Spatrick StringExtractorGDBRemote response;
774061da546Spatrick if (m_gdb_comm.GetStopReply(response)) {
775061da546Spatrick SetLastStopPacket(response);
776061da546Spatrick
777061da546Spatrick const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
778061da546Spatrick
779061da546Spatrick if (process_arch.IsValid()) {
780061da546Spatrick GetTarget().MergeArchitecture(process_arch);
781061da546Spatrick } else {
782061da546Spatrick const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
783061da546Spatrick if (host_arch.IsValid())
784061da546Spatrick GetTarget().MergeArchitecture(host_arch);
785061da546Spatrick }
786061da546Spatrick
787061da546Spatrick SetPrivateState(SetThreadStopInfo(response));
788061da546Spatrick
789061da546Spatrick if (!disable_stdio) {
790dda28197Spatrick if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
791dda28197Spatrick SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
792061da546Spatrick }
793061da546Spatrick }
794061da546Spatrick } else {
795061da546Spatrick LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
796061da546Spatrick }
797061da546Spatrick return error;
798061da546Spatrick }
799061da546Spatrick
ConnectToDebugserver(llvm::StringRef connect_url)800061da546Spatrick Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
801061da546Spatrick Status error;
802061da546Spatrick // Only connect if we have a valid connect URL
803*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
804061da546Spatrick
805061da546Spatrick if (!connect_url.empty()) {
806061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
807061da546Spatrick connect_url.str().c_str());
808061da546Spatrick std::unique_ptr<ConnectionFileDescriptor> conn_up(
809061da546Spatrick new ConnectionFileDescriptor());
810061da546Spatrick if (conn_up) {
811061da546Spatrick const uint32_t max_retry_count = 50;
812061da546Spatrick uint32_t retry_count = 0;
813061da546Spatrick while (!m_gdb_comm.IsConnected()) {
814061da546Spatrick if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
815dda28197Spatrick m_gdb_comm.SetConnection(std::move(conn_up));
816061da546Spatrick break;
817061da546Spatrick }
818061da546Spatrick
819061da546Spatrick retry_count++;
820061da546Spatrick
821061da546Spatrick if (retry_count >= max_retry_count)
822061da546Spatrick break;
823061da546Spatrick
824061da546Spatrick std::this_thread::sleep_for(std::chrono::milliseconds(100));
825061da546Spatrick }
826061da546Spatrick }
827061da546Spatrick }
828061da546Spatrick
829061da546Spatrick if (!m_gdb_comm.IsConnected()) {
830061da546Spatrick if (error.Success())
831061da546Spatrick error.SetErrorString("not connected to remote gdb server");
832061da546Spatrick return error;
833061da546Spatrick }
834061da546Spatrick
835061da546Spatrick // We always seem to be able to open a connection to a local port so we need
836061da546Spatrick // to make sure we can then send data to it. If we can't then we aren't
837061da546Spatrick // actually connected to anything, so try and do the handshake with the
838061da546Spatrick // remote GDB server and make sure that goes alright.
839061da546Spatrick if (!m_gdb_comm.HandshakeWithServer(&error)) {
840061da546Spatrick m_gdb_comm.Disconnect();
841061da546Spatrick if (error.Success())
842061da546Spatrick error.SetErrorString("not connected to remote gdb server");
843061da546Spatrick return error;
844061da546Spatrick }
845061da546Spatrick
846061da546Spatrick m_gdb_comm.GetEchoSupported();
847061da546Spatrick m_gdb_comm.GetThreadSuffixSupported();
848061da546Spatrick m_gdb_comm.GetListThreadsInStopReplySupported();
849061da546Spatrick m_gdb_comm.GetHostInfo();
850061da546Spatrick m_gdb_comm.GetVContSupported('c');
851061da546Spatrick m_gdb_comm.GetVAttachOrWaitSupported();
852061da546Spatrick m_gdb_comm.EnableErrorStringInPacket();
853061da546Spatrick
854*f6aab3d8Srobert // First dispatch any commands from the platform:
855*f6aab3d8Srobert auto handle_cmds = [&] (const Args &args) -> void {
856*f6aab3d8Srobert for (const Args::ArgEntry &entry : args) {
857061da546Spatrick StringExtractorGDBRemote response;
858061da546Spatrick m_gdb_comm.SendPacketAndWaitForResponse(
859*f6aab3d8Srobert entry.c_str(), response);
860061da546Spatrick }
861*f6aab3d8Srobert };
862*f6aab3d8Srobert
863*f6aab3d8Srobert PlatformSP platform_sp = GetTarget().GetPlatform();
864*f6aab3d8Srobert if (platform_sp) {
865*f6aab3d8Srobert handle_cmds(platform_sp->GetExtraStartupCommands());
866*f6aab3d8Srobert }
867*f6aab3d8Srobert
868*f6aab3d8Srobert // Then dispatch any process commands:
869*f6aab3d8Srobert handle_cmds(GetExtraStartupCommands());
870*f6aab3d8Srobert
871061da546Spatrick return error;
872061da546Spatrick }
873061da546Spatrick
DidLaunchOrAttach(ArchSpec & process_arch)874061da546Spatrick void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
875*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
876061da546Spatrick BuildDynamicRegisterInfo(false);
877061da546Spatrick
878dda28197Spatrick // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
879dda28197Spatrick // qProcessInfo as it will be more specific to our process.
880061da546Spatrick
881061da546Spatrick const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
882061da546Spatrick if (remote_process_arch.IsValid()) {
883061da546Spatrick process_arch = remote_process_arch;
884dda28197Spatrick LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
885dda28197Spatrick process_arch.GetArchitectureName(),
886dda28197Spatrick process_arch.GetTriple().getTriple());
887061da546Spatrick } else {
888061da546Spatrick process_arch = m_gdb_comm.GetHostArchitecture();
889dda28197Spatrick LLDB_LOG(log,
890dda28197Spatrick "gdb-remote did not have process architecture, using gdb-remote "
891dda28197Spatrick "host architecture {0} {1}",
892dda28197Spatrick process_arch.GetArchitectureName(),
893dda28197Spatrick process_arch.GetTriple().getTriple());
894061da546Spatrick }
895061da546Spatrick
896*f6aab3d8Srobert if (int addressable_bits = m_gdb_comm.GetAddressingBits()) {
897*f6aab3d8Srobert lldb::addr_t address_mask = ~((1ULL << addressable_bits) - 1);
898be691f3bSpatrick SetCodeAddressMask(address_mask);
899be691f3bSpatrick SetDataAddressMask(address_mask);
900be691f3bSpatrick }
901be691f3bSpatrick
902061da546Spatrick if (process_arch.IsValid()) {
903061da546Spatrick const ArchSpec &target_arch = GetTarget().GetArchitecture();
904061da546Spatrick if (target_arch.IsValid()) {
905dda28197Spatrick LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
906dda28197Spatrick target_arch.GetArchitectureName(),
907dda28197Spatrick target_arch.GetTriple().getTriple());
908061da546Spatrick
909061da546Spatrick // If the remote host is ARM and we have apple as the vendor, then
910061da546Spatrick // ARM executables and shared libraries can have mixed ARM
911061da546Spatrick // architectures.
912061da546Spatrick // You can have an armv6 executable, and if the host is armv7, then the
913061da546Spatrick // system will load the best possible architecture for all shared
914061da546Spatrick // libraries it has, so we really need to take the remote host
915061da546Spatrick // architecture as our defacto architecture in this case.
916061da546Spatrick
917061da546Spatrick if ((process_arch.GetMachine() == llvm::Triple::arm ||
918061da546Spatrick process_arch.GetMachine() == llvm::Triple::thumb) &&
919061da546Spatrick process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
920061da546Spatrick GetTarget().SetArchitecture(process_arch);
921dda28197Spatrick LLDB_LOG(log,
922dda28197Spatrick "remote process is ARM/Apple, "
923dda28197Spatrick "setting target arch to {0} {1}",
924dda28197Spatrick process_arch.GetArchitectureName(),
925dda28197Spatrick process_arch.GetTriple().getTriple());
926061da546Spatrick } else {
927061da546Spatrick // Fill in what is missing in the triple
928061da546Spatrick const llvm::Triple &remote_triple = process_arch.GetTriple();
929061da546Spatrick llvm::Triple new_target_triple = target_arch.GetTriple();
930061da546Spatrick if (new_target_triple.getVendorName().size() == 0) {
931061da546Spatrick new_target_triple.setVendor(remote_triple.getVendor());
932061da546Spatrick
933061da546Spatrick if (new_target_triple.getOSName().size() == 0) {
934061da546Spatrick new_target_triple.setOS(remote_triple.getOS());
935061da546Spatrick
936061da546Spatrick if (new_target_triple.getEnvironmentName().size() == 0)
937dda28197Spatrick new_target_triple.setEnvironment(remote_triple.getEnvironment());
938061da546Spatrick }
939061da546Spatrick
940061da546Spatrick ArchSpec new_target_arch = target_arch;
941061da546Spatrick new_target_arch.SetTriple(new_target_triple);
942061da546Spatrick GetTarget().SetArchitecture(new_target_arch);
943061da546Spatrick }
944061da546Spatrick }
945061da546Spatrick
946dda28197Spatrick LLDB_LOG(log,
947dda28197Spatrick "final target arch after adjustments for remote architecture: "
948dda28197Spatrick "{0} {1}",
949dda28197Spatrick target_arch.GetArchitectureName(),
950dda28197Spatrick target_arch.GetTriple().getTriple());
951061da546Spatrick } else {
952061da546Spatrick // The target doesn't have a valid architecture yet, set it from the
953061da546Spatrick // architecture we got from the remote GDB server
954061da546Spatrick GetTarget().SetArchitecture(process_arch);
955061da546Spatrick }
956061da546Spatrick }
957061da546Spatrick
958*f6aab3d8Srobert // Target and Process are reasonably initailized;
959*f6aab3d8Srobert // load any binaries we have metadata for / set load address.
960*f6aab3d8Srobert LoadStubBinaries();
961dda28197Spatrick MaybeLoadExecutableModule();
962dda28197Spatrick
963061da546Spatrick // Find out which StructuredDataPlugins are supported by the debug monitor.
964061da546Spatrick // These plugins transmit data over async $J packets.
965dda28197Spatrick if (StructuredData::Array *supported_packets =
966dda28197Spatrick m_gdb_comm.GetSupportedStructuredDataPlugins())
967dda28197Spatrick MapSupportedStructuredDataPlugins(*supported_packets);
968*f6aab3d8Srobert
969*f6aab3d8Srobert // If connected to LLDB ("native-signals+"), use signal defs for
970*f6aab3d8Srobert // the remote platform. If connected to GDB, just use the standard set.
971*f6aab3d8Srobert if (!m_gdb_comm.UsesNativeSignals()) {
972*f6aab3d8Srobert SetUnixSignals(std::make_shared<GDBRemoteSignals>());
973*f6aab3d8Srobert } else {
974*f6aab3d8Srobert PlatformSP platform_sp = GetTarget().GetPlatform();
975*f6aab3d8Srobert if (platform_sp && platform_sp->IsConnected())
976*f6aab3d8Srobert SetUnixSignals(platform_sp->GetUnixSignals());
977*f6aab3d8Srobert else
978*f6aab3d8Srobert SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
979*f6aab3d8Srobert }
980*f6aab3d8Srobert }
981*f6aab3d8Srobert
LoadStubBinaries()982*f6aab3d8Srobert void ProcessGDBRemote::LoadStubBinaries() {
983*f6aab3d8Srobert // The remote stub may know about the "main binary" in
984*f6aab3d8Srobert // the context of a firmware debug session, and can
985*f6aab3d8Srobert // give us a UUID and an address/slide of where the
986*f6aab3d8Srobert // binary is loaded in memory.
987*f6aab3d8Srobert UUID standalone_uuid;
988*f6aab3d8Srobert addr_t standalone_value;
989*f6aab3d8Srobert bool standalone_value_is_offset;
990*f6aab3d8Srobert if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value,
991*f6aab3d8Srobert standalone_value_is_offset)) {
992*f6aab3d8Srobert ModuleSP module_sp;
993*f6aab3d8Srobert
994*f6aab3d8Srobert if (standalone_uuid.IsValid()) {
995*f6aab3d8Srobert const bool force_symbol_search = true;
996*f6aab3d8Srobert const bool notify = true;
997*f6aab3d8Srobert DynamicLoader::LoadBinaryWithUUIDAndAddress(
998*f6aab3d8Srobert this, "", standalone_uuid, standalone_value,
999*f6aab3d8Srobert standalone_value_is_offset, force_symbol_search, notify);
1000*f6aab3d8Srobert }
1001*f6aab3d8Srobert }
1002*f6aab3d8Srobert
1003*f6aab3d8Srobert // The remote stub may know about a list of binaries to
1004*f6aab3d8Srobert // force load into the process -- a firmware type situation
1005*f6aab3d8Srobert // where multiple binaries are present in virtual memory,
1006*f6aab3d8Srobert // and we are only given the addresses of the binaries.
1007*f6aab3d8Srobert // Not intended for use with userland debugging, when we use
1008*f6aab3d8Srobert // a DynamicLoader plugin that knows how to find the loaded
1009*f6aab3d8Srobert // binaries, and will track updates as binaries are added.
1010*f6aab3d8Srobert
1011*f6aab3d8Srobert std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
1012*f6aab3d8Srobert if (bin_addrs.size()) {
1013*f6aab3d8Srobert UUID uuid;
1014*f6aab3d8Srobert const bool value_is_slide = false;
1015*f6aab3d8Srobert for (addr_t addr : bin_addrs) {
1016*f6aab3d8Srobert const bool notify = true;
1017*f6aab3d8Srobert // First see if this is a special platform
1018*f6aab3d8Srobert // binary that may determine the DynamicLoader and
1019*f6aab3d8Srobert // Platform to be used in this Process and Target.
1020*f6aab3d8Srobert if (GetTarget()
1021*f6aab3d8Srobert .GetDebugger()
1022*f6aab3d8Srobert .GetPlatformList()
1023*f6aab3d8Srobert .LoadPlatformBinaryAndSetup(this, addr, notify))
1024*f6aab3d8Srobert continue;
1025*f6aab3d8Srobert
1026*f6aab3d8Srobert const bool force_symbol_search = true;
1027*f6aab3d8Srobert // Second manually load this binary into the Target.
1028*f6aab3d8Srobert DynamicLoader::LoadBinaryWithUUIDAndAddress(this, llvm::StringRef(), uuid,
1029*f6aab3d8Srobert addr, value_is_slide,
1030*f6aab3d8Srobert force_symbol_search, notify);
1031*f6aab3d8Srobert }
1032*f6aab3d8Srobert }
1033dda28197Spatrick }
1034dda28197Spatrick
MaybeLoadExecutableModule()1035dda28197Spatrick void ProcessGDBRemote::MaybeLoadExecutableModule() {
1036dda28197Spatrick ModuleSP module_sp = GetTarget().GetExecutableModule();
1037dda28197Spatrick if (!module_sp)
1038dda28197Spatrick return;
1039dda28197Spatrick
1040*f6aab3d8Srobert std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1041dda28197Spatrick if (!offsets)
1042dda28197Spatrick return;
1043dda28197Spatrick
1044dda28197Spatrick bool is_uniform =
1045dda28197Spatrick size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1046dda28197Spatrick offsets->offsets.size();
1047dda28197Spatrick if (!is_uniform)
1048dda28197Spatrick return; // TODO: Handle non-uniform responses.
1049dda28197Spatrick
1050dda28197Spatrick bool changed = false;
1051dda28197Spatrick module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1052dda28197Spatrick /*value_is_offset=*/true, changed);
1053dda28197Spatrick if (changed) {
1054dda28197Spatrick ModuleList list;
1055dda28197Spatrick list.Append(module_sp);
1056dda28197Spatrick m_process->GetTarget().ModulesDidLoad(list);
1057061da546Spatrick }
1058061da546Spatrick }
1059061da546Spatrick
DidLaunch()1060061da546Spatrick void ProcessGDBRemote::DidLaunch() {
1061061da546Spatrick ArchSpec process_arch;
1062061da546Spatrick DidLaunchOrAttach(process_arch);
1063061da546Spatrick }
1064061da546Spatrick
DoAttachToProcessWithID(lldb::pid_t attach_pid,const ProcessAttachInfo & attach_info)1065061da546Spatrick Status ProcessGDBRemote::DoAttachToProcessWithID(
1066061da546Spatrick lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1067*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
1068061da546Spatrick Status error;
1069061da546Spatrick
1070061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1071061da546Spatrick
1072061da546Spatrick // Clear out and clean up from any current state
1073061da546Spatrick Clear();
1074061da546Spatrick if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1075061da546Spatrick error = EstablishConnectionIfNeeded(attach_info);
1076061da546Spatrick if (error.Success()) {
1077061da546Spatrick m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1078061da546Spatrick
1079061da546Spatrick char packet[64];
1080061da546Spatrick const int packet_len =
1081061da546Spatrick ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1082061da546Spatrick SetID(attach_pid);
1083061da546Spatrick m_async_broadcaster.BroadcastEvent(
1084061da546Spatrick eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1085061da546Spatrick } else
1086061da546Spatrick SetExitStatus(-1, error.AsCString());
1087061da546Spatrick }
1088061da546Spatrick
1089061da546Spatrick return error;
1090061da546Spatrick }
1091061da546Spatrick
DoAttachToProcessWithName(const char * process_name,const ProcessAttachInfo & attach_info)1092061da546Spatrick Status ProcessGDBRemote::DoAttachToProcessWithName(
1093061da546Spatrick const char *process_name, const ProcessAttachInfo &attach_info) {
1094061da546Spatrick Status error;
1095061da546Spatrick // Clear out and clean up from any current state
1096061da546Spatrick Clear();
1097061da546Spatrick
1098061da546Spatrick if (process_name && process_name[0]) {
1099061da546Spatrick error = EstablishConnectionIfNeeded(attach_info);
1100061da546Spatrick if (error.Success()) {
1101061da546Spatrick StreamString packet;
1102061da546Spatrick
1103061da546Spatrick m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1104061da546Spatrick
1105061da546Spatrick if (attach_info.GetWaitForLaunch()) {
1106061da546Spatrick if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1107061da546Spatrick packet.PutCString("vAttachWait");
1108061da546Spatrick } else {
1109061da546Spatrick if (attach_info.GetIgnoreExisting())
1110061da546Spatrick packet.PutCString("vAttachWait");
1111061da546Spatrick else
1112061da546Spatrick packet.PutCString("vAttachOrWait");
1113061da546Spatrick }
1114061da546Spatrick } else
1115061da546Spatrick packet.PutCString("vAttachName");
1116061da546Spatrick packet.PutChar(';');
1117061da546Spatrick packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1118061da546Spatrick endian::InlHostByteOrder(),
1119061da546Spatrick endian::InlHostByteOrder());
1120061da546Spatrick
1121061da546Spatrick m_async_broadcaster.BroadcastEvent(
1122061da546Spatrick eBroadcastBitAsyncContinue,
1123061da546Spatrick new EventDataBytes(packet.GetString().data(), packet.GetSize()));
1124061da546Spatrick
1125061da546Spatrick } else
1126061da546Spatrick SetExitStatus(-1, error.AsCString());
1127061da546Spatrick }
1128061da546Spatrick return error;
1129061da546Spatrick }
1130061da546Spatrick
TraceSupported()1131be691f3bSpatrick llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1132be691f3bSpatrick return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
1133061da546Spatrick }
1134061da546Spatrick
TraceStop(const TraceStopRequest & request)1135be691f3bSpatrick llvm::Error ProcessGDBRemote::TraceStop(const TraceStopRequest &request) {
1136be691f3bSpatrick return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1137061da546Spatrick }
1138061da546Spatrick
TraceStart(const llvm::json::Value & request)1139be691f3bSpatrick llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1140be691f3bSpatrick return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1141061da546Spatrick }
1142061da546Spatrick
1143be691f3bSpatrick llvm::Expected<std::string>
TraceGetState(llvm::StringRef type)1144be691f3bSpatrick ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1145be691f3bSpatrick return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
1146061da546Spatrick }
1147061da546Spatrick
1148be691f3bSpatrick llvm::Expected<std::vector<uint8_t>>
TraceGetBinaryData(const TraceGetBinaryDataRequest & request)1149be691f3bSpatrick ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {
1150be691f3bSpatrick return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1151061da546Spatrick }
1152061da546Spatrick
DidExit()1153061da546Spatrick void ProcessGDBRemote::DidExit() {
1154061da546Spatrick // When we exit, disconnect from the GDB server communications
1155061da546Spatrick m_gdb_comm.Disconnect();
1156061da546Spatrick }
1157061da546Spatrick
DidAttach(ArchSpec & process_arch)1158061da546Spatrick void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1159061da546Spatrick // If you can figure out what the architecture is, fill it in here.
1160061da546Spatrick process_arch.Clear();
1161061da546Spatrick DidLaunchOrAttach(process_arch);
1162061da546Spatrick }
1163061da546Spatrick
WillResume()1164061da546Spatrick Status ProcessGDBRemote::WillResume() {
1165061da546Spatrick m_continue_c_tids.clear();
1166061da546Spatrick m_continue_C_tids.clear();
1167061da546Spatrick m_continue_s_tids.clear();
1168061da546Spatrick m_continue_S_tids.clear();
1169061da546Spatrick m_jstopinfo_sp.reset();
1170061da546Spatrick m_jthreadsinfo_sp.reset();
1171061da546Spatrick return Status();
1172061da546Spatrick }
1173061da546Spatrick
DoResume()1174061da546Spatrick Status ProcessGDBRemote::DoResume() {
1175061da546Spatrick Status error;
1176*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
1177061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
1178061da546Spatrick
1179061da546Spatrick ListenerSP listener_sp(
1180061da546Spatrick Listener::MakeListener("gdb-remote.resume-packet-sent"));
1181061da546Spatrick if (listener_sp->StartListeningForEvents(
1182*f6aab3d8Srobert &m_gdb_comm, GDBRemoteClientBase::eBroadcastBitRunPacketSent)) {
1183061da546Spatrick listener_sp->StartListeningForEvents(
1184061da546Spatrick &m_async_broadcaster,
1185061da546Spatrick ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1186061da546Spatrick
1187061da546Spatrick const size_t num_threads = GetThreadList().GetSize();
1188061da546Spatrick
1189061da546Spatrick StreamString continue_packet;
1190061da546Spatrick bool continue_packet_error = false;
1191061da546Spatrick if (m_gdb_comm.HasAnyVContSupport()) {
1192*f6aab3d8Srobert std::string pid_prefix;
1193*f6aab3d8Srobert if (m_gdb_comm.GetMultiprocessSupported())
1194*f6aab3d8Srobert pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1195*f6aab3d8Srobert
1196*f6aab3d8Srobert if (m_continue_c_tids.size() == num_threads ||
1197061da546Spatrick (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1198*f6aab3d8Srobert m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1199*f6aab3d8Srobert // All threads are continuing
1200*f6aab3d8Srobert if (m_gdb_comm.GetMultiprocessSupported())
1201*f6aab3d8Srobert continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1202*f6aab3d8Srobert else
1203061da546Spatrick continue_packet.PutCString("c");
1204061da546Spatrick } else {
1205061da546Spatrick continue_packet.PutCString("vCont");
1206061da546Spatrick
1207061da546Spatrick if (!m_continue_c_tids.empty()) {
1208061da546Spatrick if (m_gdb_comm.GetVContSupported('c')) {
1209061da546Spatrick for (tid_collection::const_iterator
1210061da546Spatrick t_pos = m_continue_c_tids.begin(),
1211061da546Spatrick t_end = m_continue_c_tids.end();
1212061da546Spatrick t_pos != t_end; ++t_pos)
1213*f6aab3d8Srobert continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1214061da546Spatrick } else
1215061da546Spatrick continue_packet_error = true;
1216061da546Spatrick }
1217061da546Spatrick
1218061da546Spatrick if (!continue_packet_error && !m_continue_C_tids.empty()) {
1219061da546Spatrick if (m_gdb_comm.GetVContSupported('C')) {
1220061da546Spatrick for (tid_sig_collection::const_iterator
1221061da546Spatrick s_pos = m_continue_C_tids.begin(),
1222061da546Spatrick s_end = m_continue_C_tids.end();
1223061da546Spatrick s_pos != s_end; ++s_pos)
1224*f6aab3d8Srobert continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1225*f6aab3d8Srobert pid_prefix, s_pos->first);
1226061da546Spatrick } else
1227061da546Spatrick continue_packet_error = true;
1228061da546Spatrick }
1229061da546Spatrick
1230061da546Spatrick if (!continue_packet_error && !m_continue_s_tids.empty()) {
1231061da546Spatrick if (m_gdb_comm.GetVContSupported('s')) {
1232061da546Spatrick for (tid_collection::const_iterator
1233061da546Spatrick t_pos = m_continue_s_tids.begin(),
1234061da546Spatrick t_end = m_continue_s_tids.end();
1235061da546Spatrick t_pos != t_end; ++t_pos)
1236*f6aab3d8Srobert continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1237061da546Spatrick } else
1238061da546Spatrick continue_packet_error = true;
1239061da546Spatrick }
1240061da546Spatrick
1241061da546Spatrick if (!continue_packet_error && !m_continue_S_tids.empty()) {
1242061da546Spatrick if (m_gdb_comm.GetVContSupported('S')) {
1243061da546Spatrick for (tid_sig_collection::const_iterator
1244061da546Spatrick s_pos = m_continue_S_tids.begin(),
1245061da546Spatrick s_end = m_continue_S_tids.end();
1246061da546Spatrick s_pos != s_end; ++s_pos)
1247*f6aab3d8Srobert continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1248*f6aab3d8Srobert pid_prefix, s_pos->first);
1249061da546Spatrick } else
1250061da546Spatrick continue_packet_error = true;
1251061da546Spatrick }
1252061da546Spatrick
1253061da546Spatrick if (continue_packet_error)
1254061da546Spatrick continue_packet.Clear();
1255061da546Spatrick }
1256061da546Spatrick } else
1257061da546Spatrick continue_packet_error = true;
1258061da546Spatrick
1259061da546Spatrick if (continue_packet_error) {
1260061da546Spatrick // Either no vCont support, or we tried to use part of the vCont packet
1261061da546Spatrick // that wasn't supported by the remote GDB server. We need to try and
1262061da546Spatrick // make a simple packet that can do our continue
1263061da546Spatrick const size_t num_continue_c_tids = m_continue_c_tids.size();
1264061da546Spatrick const size_t num_continue_C_tids = m_continue_C_tids.size();
1265061da546Spatrick const size_t num_continue_s_tids = m_continue_s_tids.size();
1266061da546Spatrick const size_t num_continue_S_tids = m_continue_S_tids.size();
1267061da546Spatrick if (num_continue_c_tids > 0) {
1268061da546Spatrick if (num_continue_c_tids == num_threads) {
1269061da546Spatrick // All threads are resuming...
1270061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(-1);
1271061da546Spatrick continue_packet.PutChar('c');
1272061da546Spatrick continue_packet_error = false;
1273061da546Spatrick } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1274061da546Spatrick num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1275061da546Spatrick // Only one thread is continuing
1276061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1277061da546Spatrick continue_packet.PutChar('c');
1278061da546Spatrick continue_packet_error = false;
1279061da546Spatrick }
1280061da546Spatrick }
1281061da546Spatrick
1282061da546Spatrick if (continue_packet_error && num_continue_C_tids > 0) {
1283061da546Spatrick if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1284061da546Spatrick num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1285061da546Spatrick num_continue_S_tids == 0) {
1286061da546Spatrick const int continue_signo = m_continue_C_tids.front().second;
1287061da546Spatrick // Only one thread is continuing
1288061da546Spatrick if (num_continue_C_tids > 1) {
1289061da546Spatrick // More that one thread with a signal, yet we don't have vCont
1290061da546Spatrick // support and we are being asked to resume each thread with a
1291061da546Spatrick // signal, we need to make sure they are all the same signal, or we
1292061da546Spatrick // can't issue the continue accurately with the current support...
1293061da546Spatrick if (num_continue_C_tids > 1) {
1294061da546Spatrick continue_packet_error = false;
1295061da546Spatrick for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1296061da546Spatrick if (m_continue_C_tids[i].second != continue_signo)
1297061da546Spatrick continue_packet_error = true;
1298061da546Spatrick }
1299061da546Spatrick }
1300061da546Spatrick if (!continue_packet_error)
1301061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(-1);
1302061da546Spatrick } else {
1303061da546Spatrick // Set the continue thread ID
1304061da546Spatrick continue_packet_error = false;
1305061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1306061da546Spatrick }
1307061da546Spatrick if (!continue_packet_error) {
1308061da546Spatrick // Add threads continuing with the same signo...
1309061da546Spatrick continue_packet.Printf("C%2.2x", continue_signo);
1310061da546Spatrick }
1311061da546Spatrick }
1312061da546Spatrick }
1313061da546Spatrick
1314061da546Spatrick if (continue_packet_error && num_continue_s_tids > 0) {
1315061da546Spatrick if (num_continue_s_tids == num_threads) {
1316061da546Spatrick // All threads are resuming...
1317061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(-1);
1318061da546Spatrick
1319061da546Spatrick continue_packet.PutChar('s');
1320061da546Spatrick
1321061da546Spatrick continue_packet_error = false;
1322061da546Spatrick } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1323061da546Spatrick num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1324061da546Spatrick // Only one thread is stepping
1325061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1326061da546Spatrick continue_packet.PutChar('s');
1327061da546Spatrick continue_packet_error = false;
1328061da546Spatrick }
1329061da546Spatrick }
1330061da546Spatrick
1331061da546Spatrick if (!continue_packet_error && num_continue_S_tids > 0) {
1332061da546Spatrick if (num_continue_S_tids == num_threads) {
1333061da546Spatrick const int step_signo = m_continue_S_tids.front().second;
1334061da546Spatrick // Are all threads trying to step with the same signal?
1335061da546Spatrick continue_packet_error = false;
1336061da546Spatrick if (num_continue_S_tids > 1) {
1337061da546Spatrick for (size_t i = 1; i < num_threads; ++i) {
1338061da546Spatrick if (m_continue_S_tids[i].second != step_signo)
1339061da546Spatrick continue_packet_error = true;
1340061da546Spatrick }
1341061da546Spatrick }
1342061da546Spatrick if (!continue_packet_error) {
1343061da546Spatrick // Add threads stepping with the same signo...
1344061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(-1);
1345061da546Spatrick continue_packet.Printf("S%2.2x", step_signo);
1346061da546Spatrick }
1347061da546Spatrick } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1348061da546Spatrick num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1349061da546Spatrick // Only one thread is stepping with signal
1350061da546Spatrick m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1351061da546Spatrick continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1352061da546Spatrick continue_packet_error = false;
1353061da546Spatrick }
1354061da546Spatrick }
1355061da546Spatrick }
1356061da546Spatrick
1357061da546Spatrick if (continue_packet_error) {
1358061da546Spatrick error.SetErrorString("can't make continue packet for this resume");
1359061da546Spatrick } else {
1360061da546Spatrick EventSP event_sp;
1361061da546Spatrick if (!m_async_thread.IsJoinable()) {
1362061da546Spatrick error.SetErrorString("Trying to resume but the async thread is dead.");
1363061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1364061da546Spatrick "async thread is dead.");
1365061da546Spatrick return error;
1366061da546Spatrick }
1367061da546Spatrick
1368061da546Spatrick m_async_broadcaster.BroadcastEvent(
1369061da546Spatrick eBroadcastBitAsyncContinue,
1370061da546Spatrick new EventDataBytes(continue_packet.GetString().data(),
1371061da546Spatrick continue_packet.GetSize()));
1372061da546Spatrick
1373061da546Spatrick if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1374061da546Spatrick error.SetErrorString("Resume timed out.");
1375061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1376061da546Spatrick } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1377061da546Spatrick error.SetErrorString("Broadcast continue, but the async thread was "
1378061da546Spatrick "killed before we got an ack back.");
1379061da546Spatrick LLDB_LOGF(log,
1380061da546Spatrick "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1381061da546Spatrick "async thread was killed before we got an ack back.");
1382061da546Spatrick return error;
1383061da546Spatrick }
1384061da546Spatrick }
1385061da546Spatrick }
1386061da546Spatrick
1387061da546Spatrick return error;
1388061da546Spatrick }
1389061da546Spatrick
ClearThreadIDList()1390061da546Spatrick void ProcessGDBRemote::ClearThreadIDList() {
1391061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1392061da546Spatrick m_thread_ids.clear();
1393061da546Spatrick m_thread_pcs.clear();
1394061da546Spatrick }
1395061da546Spatrick
UpdateThreadIDsFromStopReplyThreadsValue(llvm::StringRef value)1396be691f3bSpatrick size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(
1397be691f3bSpatrick llvm::StringRef value) {
1398061da546Spatrick m_thread_ids.clear();
1399be691f3bSpatrick lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1400be691f3bSpatrick StringExtractorGDBRemote thread_ids{value};
1401be691f3bSpatrick
1402be691f3bSpatrick do {
1403be691f3bSpatrick auto pid_tid = thread_ids.GetPidTid(pid);
1404be691f3bSpatrick if (pid_tid && pid_tid->first == pid) {
1405be691f3bSpatrick lldb::tid_t tid = pid_tid->second;
1406be691f3bSpatrick if (tid != LLDB_INVALID_THREAD_ID &&
1407be691f3bSpatrick tid != StringExtractorGDBRemote::AllProcesses)
1408061da546Spatrick m_thread_ids.push_back(tid);
1409061da546Spatrick }
1410be691f3bSpatrick } while (thread_ids.GetChar() == ',');
1411be691f3bSpatrick
1412061da546Spatrick return m_thread_ids.size();
1413061da546Spatrick }
1414061da546Spatrick
UpdateThreadPCsFromStopReplyThreadsValue(llvm::StringRef value)1415*f6aab3d8Srobert size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(
1416*f6aab3d8Srobert llvm::StringRef value) {
1417061da546Spatrick m_thread_pcs.clear();
1418*f6aab3d8Srobert for (llvm::StringRef x : llvm::split(value, ',')) {
1419061da546Spatrick lldb::addr_t pc;
1420*f6aab3d8Srobert if (llvm::to_integer(x, pc, 16))
1421061da546Spatrick m_thread_pcs.push_back(pc);
1422061da546Spatrick }
1423061da546Spatrick return m_thread_pcs.size();
1424061da546Spatrick }
1425061da546Spatrick
UpdateThreadIDList()1426061da546Spatrick bool ProcessGDBRemote::UpdateThreadIDList() {
1427061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1428061da546Spatrick
1429061da546Spatrick if (m_jthreadsinfo_sp) {
1430061da546Spatrick // If we have the JSON threads info, we can get the thread list from that
1431061da546Spatrick StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1432061da546Spatrick if (thread_infos && thread_infos->GetSize() > 0) {
1433061da546Spatrick m_thread_ids.clear();
1434061da546Spatrick m_thread_pcs.clear();
1435061da546Spatrick thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1436061da546Spatrick StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1437061da546Spatrick if (thread_dict) {
1438061da546Spatrick // Set the thread stop info from the JSON dictionary
1439061da546Spatrick SetThreadStopInfo(thread_dict);
1440061da546Spatrick lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1441061da546Spatrick if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1442061da546Spatrick m_thread_ids.push_back(tid);
1443061da546Spatrick }
1444061da546Spatrick return true; // Keep iterating through all thread_info objects
1445061da546Spatrick });
1446061da546Spatrick }
1447061da546Spatrick if (!m_thread_ids.empty())
1448061da546Spatrick return true;
1449061da546Spatrick } else {
1450061da546Spatrick // See if we can get the thread IDs from the current stop reply packets
1451061da546Spatrick // that might contain a "threads" key/value pair
1452061da546Spatrick
1453*f6aab3d8Srobert if (m_last_stop_packet) {
1454061da546Spatrick // Get the thread stop info
1455*f6aab3d8Srobert StringExtractorGDBRemote &stop_info = *m_last_stop_packet;
1456*f6aab3d8Srobert const std::string &stop_info_str = std::string(stop_info.GetStringRef());
1457061da546Spatrick
1458061da546Spatrick m_thread_pcs.clear();
1459061da546Spatrick const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1460061da546Spatrick if (thread_pcs_pos != std::string::npos) {
1461061da546Spatrick const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1462061da546Spatrick const size_t end = stop_info_str.find(';', start);
1463061da546Spatrick if (end != std::string::npos) {
1464061da546Spatrick std::string value = stop_info_str.substr(start, end - start);
1465061da546Spatrick UpdateThreadPCsFromStopReplyThreadsValue(value);
1466061da546Spatrick }
1467061da546Spatrick }
1468061da546Spatrick
1469061da546Spatrick const size_t threads_pos = stop_info_str.find(";threads:");
1470061da546Spatrick if (threads_pos != std::string::npos) {
1471061da546Spatrick const size_t start = threads_pos + strlen(";threads:");
1472061da546Spatrick const size_t end = stop_info_str.find(';', start);
1473061da546Spatrick if (end != std::string::npos) {
1474061da546Spatrick std::string value = stop_info_str.substr(start, end - start);
1475061da546Spatrick if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1476061da546Spatrick return true;
1477061da546Spatrick }
1478061da546Spatrick }
1479061da546Spatrick }
1480061da546Spatrick }
1481061da546Spatrick
1482061da546Spatrick bool sequence_mutex_unavailable = false;
1483061da546Spatrick m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1484061da546Spatrick if (sequence_mutex_unavailable) {
1485061da546Spatrick return false; // We just didn't get the list
1486061da546Spatrick }
1487061da546Spatrick return true;
1488061da546Spatrick }
1489061da546Spatrick
DoUpdateThreadList(ThreadList & old_thread_list,ThreadList & new_thread_list)1490be691f3bSpatrick bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list,
1491061da546Spatrick ThreadList &new_thread_list) {
1492061da546Spatrick // locker will keep a mutex locked until it goes out of scope
1493*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Thread);
1494061da546Spatrick LLDB_LOGV(log, "pid = {0}", GetID());
1495061da546Spatrick
1496061da546Spatrick size_t num_thread_ids = m_thread_ids.size();
1497061da546Spatrick // The "m_thread_ids" thread ID list should always be updated after each stop
1498061da546Spatrick // reply packet, but in case it isn't, update it here.
1499061da546Spatrick if (num_thread_ids == 0) {
1500061da546Spatrick if (!UpdateThreadIDList())
1501061da546Spatrick return false;
1502061da546Spatrick num_thread_ids = m_thread_ids.size();
1503061da546Spatrick }
1504061da546Spatrick
1505061da546Spatrick ThreadList old_thread_list_copy(old_thread_list);
1506061da546Spatrick if (num_thread_ids > 0) {
1507061da546Spatrick for (size_t i = 0; i < num_thread_ids; ++i) {
1508061da546Spatrick tid_t tid = m_thread_ids[i];
1509061da546Spatrick ThreadSP thread_sp(
1510061da546Spatrick old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1511061da546Spatrick if (!thread_sp) {
1512061da546Spatrick thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1513061da546Spatrick LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1514061da546Spatrick thread_sp.get(), thread_sp->GetID());
1515061da546Spatrick } else {
1516061da546Spatrick LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1517061da546Spatrick thread_sp.get(), thread_sp->GetID());
1518061da546Spatrick }
1519061da546Spatrick
1520061da546Spatrick SetThreadPc(thread_sp, i);
1521061da546Spatrick new_thread_list.AddThreadSortedByIndexID(thread_sp);
1522061da546Spatrick }
1523061da546Spatrick }
1524061da546Spatrick
1525061da546Spatrick // Whatever that is left in old_thread_list_copy are not present in
1526061da546Spatrick // new_thread_list. Remove non-existent threads from internal id table.
1527061da546Spatrick size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1528061da546Spatrick for (size_t i = 0; i < old_num_thread_ids; i++) {
1529061da546Spatrick ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1530061da546Spatrick if (old_thread_sp) {
1531061da546Spatrick lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1532061da546Spatrick m_thread_id_to_index_id_map.erase(old_thread_id);
1533061da546Spatrick }
1534061da546Spatrick }
1535061da546Spatrick
1536061da546Spatrick return true;
1537061da546Spatrick }
1538061da546Spatrick
SetThreadPc(const ThreadSP & thread_sp,uint64_t index)1539061da546Spatrick void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1540061da546Spatrick if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1541061da546Spatrick GetByteOrder() != eByteOrderInvalid) {
1542061da546Spatrick ThreadGDBRemote *gdb_thread =
1543061da546Spatrick static_cast<ThreadGDBRemote *>(thread_sp.get());
1544061da546Spatrick RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1545061da546Spatrick if (reg_ctx_sp) {
1546061da546Spatrick uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1547061da546Spatrick eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1548061da546Spatrick if (pc_regnum != LLDB_INVALID_REGNUM) {
1549061da546Spatrick gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1550061da546Spatrick }
1551061da546Spatrick }
1552061da546Spatrick }
1553061da546Spatrick }
1554061da546Spatrick
GetThreadStopInfoFromJSON(ThreadGDBRemote * thread,const StructuredData::ObjectSP & thread_infos_sp)1555061da546Spatrick bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1556061da546Spatrick ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1557061da546Spatrick // See if we got thread stop infos for all threads via the "jThreadsInfo"
1558061da546Spatrick // packet
1559061da546Spatrick if (thread_infos_sp) {
1560061da546Spatrick StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1561061da546Spatrick if (thread_infos) {
1562061da546Spatrick lldb::tid_t tid;
1563061da546Spatrick const size_t n = thread_infos->GetSize();
1564061da546Spatrick for (size_t i = 0; i < n; ++i) {
1565061da546Spatrick StructuredData::Dictionary *thread_dict =
1566061da546Spatrick thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1567061da546Spatrick if (thread_dict) {
1568061da546Spatrick if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1569061da546Spatrick "tid", tid, LLDB_INVALID_THREAD_ID)) {
1570061da546Spatrick if (tid == thread->GetID())
1571061da546Spatrick return (bool)SetThreadStopInfo(thread_dict);
1572061da546Spatrick }
1573061da546Spatrick }
1574061da546Spatrick }
1575061da546Spatrick }
1576061da546Spatrick }
1577061da546Spatrick return false;
1578061da546Spatrick }
1579061da546Spatrick
CalculateThreadStopInfo(ThreadGDBRemote * thread)1580061da546Spatrick bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1581061da546Spatrick // See if we got thread stop infos for all threads via the "jThreadsInfo"
1582061da546Spatrick // packet
1583061da546Spatrick if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1584061da546Spatrick return true;
1585061da546Spatrick
1586061da546Spatrick // See if we got thread stop info for any threads valid stop info reasons
1587061da546Spatrick // threads via the "jstopinfo" packet stop reply packet key/value pair?
1588061da546Spatrick if (m_jstopinfo_sp) {
1589061da546Spatrick // If we have "jstopinfo" then we have stop descriptions for all threads
1590061da546Spatrick // that have stop reasons, and if there is no entry for a thread, then it
1591061da546Spatrick // has no stop reason.
1592061da546Spatrick thread->GetRegisterContext()->InvalidateIfNeeded(true);
1593061da546Spatrick if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1594061da546Spatrick thread->SetStopInfo(StopInfoSP());
1595061da546Spatrick }
1596061da546Spatrick return true;
1597061da546Spatrick }
1598061da546Spatrick
1599061da546Spatrick // Fall back to using the qThreadStopInfo packet
1600061da546Spatrick StringExtractorGDBRemote stop_packet;
1601061da546Spatrick if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1602061da546Spatrick return SetThreadStopInfo(stop_packet) == eStateStopped;
1603061da546Spatrick return false;
1604061da546Spatrick }
1605061da546Spatrick
SetThreadStopInfo(lldb::tid_t tid,ExpeditedRegisterMap & expedited_register_map,uint8_t signo,const std::string & thread_name,const std::string & reason,const std::string & description,uint32_t exc_type,const std::vector<addr_t> & exc_data,addr_t thread_dispatch_qaddr,bool queue_vars_valid,LazyBool associated_with_dispatch_queue,addr_t dispatch_queue_t,std::string & queue_name,QueueKind queue_kind,uint64_t queue_serial)1606061da546Spatrick ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1607061da546Spatrick lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1608061da546Spatrick uint8_t signo, const std::string &thread_name, const std::string &reason,
1609061da546Spatrick const std::string &description, uint32_t exc_type,
1610061da546Spatrick const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1611061da546Spatrick bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1612061da546Spatrick // queue_serial are valid
1613061da546Spatrick LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1614061da546Spatrick std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1615*f6aab3d8Srobert
1616*f6aab3d8Srobert if (tid == LLDB_INVALID_THREAD_ID)
1617*f6aab3d8Srobert return nullptr;
1618*f6aab3d8Srobert
1619061da546Spatrick ThreadSP thread_sp;
1620061da546Spatrick // Scope for "locker" below
1621061da546Spatrick {
1622*f6aab3d8Srobert // m_thread_list_real does have its own mutex, but we need to hold onto the
1623*f6aab3d8Srobert // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1624*f6aab3d8Srobert // m_thread_list_real.AddThread(...) so it doesn't change on us
1625*f6aab3d8Srobert std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1626061da546Spatrick thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1627061da546Spatrick
1628061da546Spatrick if (!thread_sp) {
1629061da546Spatrick // Create the thread if we need to
1630061da546Spatrick thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1631061da546Spatrick m_thread_list_real.AddThread(thread_sp);
1632061da546Spatrick }
1633061da546Spatrick }
1634061da546Spatrick
1635*f6aab3d8Srobert ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1636be691f3bSpatrick RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1637be691f3bSpatrick
1638be691f3bSpatrick gdb_reg_ctx_sp->InvalidateIfNeeded(true);
1639061da546Spatrick
1640061da546Spatrick auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1641*f6aab3d8Srobert if (iter != m_thread_ids.end())
1642061da546Spatrick SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1643061da546Spatrick
1644061da546Spatrick for (const auto &pair : expedited_register_map) {
1645061da546Spatrick StringExtractor reg_value_extractor(pair.second);
1646*f6aab3d8Srobert WritableDataBufferSP buffer_sp(
1647*f6aab3d8Srobert new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1648061da546Spatrick reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1649*f6aab3d8Srobert uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1650be691f3bSpatrick eRegisterKindProcessPlugin, pair.first);
1651be691f3bSpatrick gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1652be691f3bSpatrick }
1653be691f3bSpatrick
1654be691f3bSpatrick // AArch64 SVE specific code below calls AArch64SVEReconfigure to update
1655be691f3bSpatrick // SVE register sizes and offsets if value of VG register has changed
1656be691f3bSpatrick // since last stop.
1657be691f3bSpatrick const ArchSpec &arch = GetTarget().GetArchitecture();
1658be691f3bSpatrick if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1659be691f3bSpatrick GDBRemoteRegisterContext *reg_ctx_sp =
1660be691f3bSpatrick static_cast<GDBRemoteRegisterContext *>(
1661be691f3bSpatrick gdb_thread->GetRegisterContext().get());
1662be691f3bSpatrick
1663be691f3bSpatrick if (reg_ctx_sp)
1664be691f3bSpatrick reg_ctx_sp->AArch64SVEReconfigure();
1665061da546Spatrick }
1666061da546Spatrick
1667061da546Spatrick thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1668061da546Spatrick
1669061da546Spatrick gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1670*f6aab3d8Srobert // Check if the GDB server was able to provide the queue name, kind and serial
1671*f6aab3d8Srobert // number
1672061da546Spatrick if (queue_vars_valid)
1673*f6aab3d8Srobert gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1674*f6aab3d8Srobert dispatch_queue_t, associated_with_dispatch_queue);
1675061da546Spatrick else
1676061da546Spatrick gdb_thread->ClearQueueInfo();
1677061da546Spatrick
1678*f6aab3d8Srobert gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);
1679061da546Spatrick
1680061da546Spatrick if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1681061da546Spatrick gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1682061da546Spatrick
1683*f6aab3d8Srobert // Make sure we update our thread stop reason just once, but don't overwrite
1684*f6aab3d8Srobert // the stop info for threads that haven't moved:
1685*f6aab3d8Srobert StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1686*f6aab3d8Srobert if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1687*f6aab3d8Srobert current_stop_info_sp) {
1688*f6aab3d8Srobert thread_sp->SetStopInfo(current_stop_info_sp);
1689*f6aab3d8Srobert return thread_sp;
1690*f6aab3d8Srobert }
1691*f6aab3d8Srobert
1692061da546Spatrick if (!thread_sp->StopInfoIsUpToDate()) {
1693061da546Spatrick thread_sp->SetStopInfo(StopInfoSP());
1694*f6aab3d8Srobert // If there's a memory thread backed by this thread, we need to use it to
1695*f6aab3d8Srobert // calculate StopInfo.
1696*f6aab3d8Srobert if (ThreadSP memory_thread_sp = m_thread_list.GetBackingThread(thread_sp))
1697061da546Spatrick thread_sp = memory_thread_sp;
1698061da546Spatrick
1699061da546Spatrick if (exc_type != 0) {
1700061da546Spatrick const size_t exc_data_size = exc_data.size();
1701061da546Spatrick
1702061da546Spatrick thread_sp->SetStopInfo(
1703061da546Spatrick StopInfoMachException::CreateStopReasonWithMachException(
1704061da546Spatrick *thread_sp, exc_type, exc_data_size,
1705061da546Spatrick exc_data_size >= 1 ? exc_data[0] : 0,
1706061da546Spatrick exc_data_size >= 2 ? exc_data[1] : 0,
1707061da546Spatrick exc_data_size >= 3 ? exc_data[2] : 0));
1708061da546Spatrick } else {
1709061da546Spatrick bool handled = false;
1710061da546Spatrick bool did_exec = false;
1711061da546Spatrick if (!reason.empty()) {
1712061da546Spatrick if (reason == "trace") {
1713061da546Spatrick addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1714*f6aab3d8Srobert lldb::BreakpointSiteSP bp_site_sp =
1715*f6aab3d8Srobert thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1716*f6aab3d8Srobert pc);
1717061da546Spatrick
1718*f6aab3d8Srobert // If the current pc is a breakpoint site then the StopInfo should be
1719*f6aab3d8Srobert // set to Breakpoint Otherwise, it will be set to Trace.
1720be691f3bSpatrick if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1721061da546Spatrick thread_sp->SetStopInfo(
1722061da546Spatrick StopInfo::CreateStopReasonWithBreakpointSiteID(
1723061da546Spatrick *thread_sp, bp_site_sp->GetID()));
1724061da546Spatrick } else
1725061da546Spatrick thread_sp->SetStopInfo(
1726061da546Spatrick StopInfo::CreateStopReasonToTrace(*thread_sp));
1727061da546Spatrick handled = true;
1728061da546Spatrick } else if (reason == "breakpoint") {
1729061da546Spatrick addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1730*f6aab3d8Srobert lldb::BreakpointSiteSP bp_site_sp =
1731*f6aab3d8Srobert thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1732*f6aab3d8Srobert pc);
1733061da546Spatrick if (bp_site_sp) {
1734*f6aab3d8Srobert // If the breakpoint is for this thread, then we'll report the hit,
1735*f6aab3d8Srobert // but if it is for another thread, we can just report no reason.
1736*f6aab3d8Srobert // We don't need to worry about stepping over the breakpoint here,
1737*f6aab3d8Srobert // that will be taken care of when the thread resumes and notices
1738*f6aab3d8Srobert // that there's a breakpoint under the pc.
1739061da546Spatrick handled = true;
1740be691f3bSpatrick if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1741061da546Spatrick thread_sp->SetStopInfo(
1742061da546Spatrick StopInfo::CreateStopReasonWithBreakpointSiteID(
1743061da546Spatrick *thread_sp, bp_site_sp->GetID()));
1744061da546Spatrick } else {
1745061da546Spatrick StopInfoSP invalid_stop_info_sp;
1746061da546Spatrick thread_sp->SetStopInfo(invalid_stop_info_sp);
1747061da546Spatrick }
1748061da546Spatrick }
1749061da546Spatrick } else if (reason == "trap") {
1750061da546Spatrick // Let the trap just use the standard signal stop reason below...
1751061da546Spatrick } else if (reason == "watchpoint") {
1752061da546Spatrick StringExtractor desc_extractor(description.c_str());
1753061da546Spatrick addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1754061da546Spatrick uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1755061da546Spatrick addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1756061da546Spatrick watch_id_t watch_id = LLDB_INVALID_WATCH_ID;
1757061da546Spatrick if (wp_addr != LLDB_INVALID_ADDRESS) {
1758061da546Spatrick WatchpointSP wp_sp;
1759061da546Spatrick ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1760061da546Spatrick if ((core >= ArchSpec::kCore_mips_first &&
1761061da546Spatrick core <= ArchSpec::kCore_mips_last) ||
1762061da546Spatrick (core >= ArchSpec::eCore_arm_generic &&
1763061da546Spatrick core <= ArchSpec::eCore_arm_aarch64))
1764061da546Spatrick wp_sp =
1765*f6aab3d8Srobert GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
1766*f6aab3d8Srobert if (!wp_sp)
1767*f6aab3d8Srobert wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1768061da546Spatrick if (wp_sp) {
1769061da546Spatrick wp_sp->SetHardwareIndex(wp_index);
1770061da546Spatrick watch_id = wp_sp->GetID();
1771061da546Spatrick }
1772061da546Spatrick }
1773061da546Spatrick if (watch_id == LLDB_INVALID_WATCH_ID) {
1774*f6aab3d8Srobert Log *log(GetLog(GDBRLog::Watchpoints));
1775061da546Spatrick LLDB_LOGF(log, "failed to find watchpoint");
1776061da546Spatrick }
1777061da546Spatrick thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1778061da546Spatrick *thread_sp, watch_id, wp_hit_addr));
1779061da546Spatrick handled = true;
1780061da546Spatrick } else if (reason == "exception") {
1781061da546Spatrick thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1782061da546Spatrick *thread_sp, description.c_str()));
1783061da546Spatrick handled = true;
1784061da546Spatrick } else if (reason == "exec") {
1785061da546Spatrick did_exec = true;
1786061da546Spatrick thread_sp->SetStopInfo(
1787061da546Spatrick StopInfo::CreateStopReasonWithExec(*thread_sp));
1788061da546Spatrick handled = true;
1789be691f3bSpatrick } else if (reason == "processor trace") {
1790be691f3bSpatrick thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1791be691f3bSpatrick *thread_sp, description.c_str()));
1792*f6aab3d8Srobert } else if (reason == "fork") {
1793*f6aab3d8Srobert StringExtractor desc_extractor(description.c_str());
1794*f6aab3d8Srobert lldb::pid_t child_pid =
1795*f6aab3d8Srobert desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1796*f6aab3d8Srobert lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1797*f6aab3d8Srobert thread_sp->SetStopInfo(
1798*f6aab3d8Srobert StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));
1799*f6aab3d8Srobert handled = true;
1800*f6aab3d8Srobert } else if (reason == "vfork") {
1801*f6aab3d8Srobert StringExtractor desc_extractor(description.c_str());
1802*f6aab3d8Srobert lldb::pid_t child_pid =
1803*f6aab3d8Srobert desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1804*f6aab3d8Srobert lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1805*f6aab3d8Srobert thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1806*f6aab3d8Srobert *thread_sp, child_pid, child_tid));
1807*f6aab3d8Srobert handled = true;
1808*f6aab3d8Srobert } else if (reason == "vforkdone") {
1809*f6aab3d8Srobert thread_sp->SetStopInfo(
1810*f6aab3d8Srobert StopInfo::CreateStopReasonVForkDone(*thread_sp));
1811*f6aab3d8Srobert handled = true;
1812061da546Spatrick }
1813061da546Spatrick } else if (!signo) {
1814061da546Spatrick addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1815061da546Spatrick lldb::BreakpointSiteSP bp_site_sp =
1816*f6aab3d8Srobert thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1817061da546Spatrick
1818*f6aab3d8Srobert // If the current pc is a breakpoint site then the StopInfo should be
1819*f6aab3d8Srobert // set to Breakpoint even though the remote stub did not set it as such.
1820*f6aab3d8Srobert // This can happen when the thread is involuntarily interrupted (e.g.
1821*f6aab3d8Srobert // due to stops on other threads) just as it is about to execute the
1822*f6aab3d8Srobert // breakpoint instruction.
1823be691f3bSpatrick if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1824*f6aab3d8Srobert thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(
1825061da546Spatrick *thread_sp, bp_site_sp->GetID()));
1826061da546Spatrick handled = true;
1827061da546Spatrick }
1828061da546Spatrick }
1829061da546Spatrick
1830061da546Spatrick if (!handled && signo && !did_exec) {
1831061da546Spatrick if (signo == SIGTRAP) {
1832061da546Spatrick // Currently we are going to assume SIGTRAP means we are either
1833061da546Spatrick // hitting a breakpoint or hardware single stepping.
1834061da546Spatrick handled = true;
1835*f6aab3d8Srobert addr_t pc =
1836*f6aab3d8Srobert thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1837*f6aab3d8Srobert lldb::BreakpointSiteSP bp_site_sp =
1838*f6aab3d8Srobert thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1839*f6aab3d8Srobert pc);
1840061da546Spatrick
1841061da546Spatrick if (bp_site_sp) {
1842*f6aab3d8Srobert // If the breakpoint is for this thread, then we'll report the hit,
1843*f6aab3d8Srobert // but if it is for another thread, we can just report no reason.
1844*f6aab3d8Srobert // We don't need to worry about stepping over the breakpoint here,
1845*f6aab3d8Srobert // that will be taken care of when the thread resumes and notices
1846*f6aab3d8Srobert // that there's a breakpoint under the pc.
1847be691f3bSpatrick if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1848061da546Spatrick if (m_breakpoint_pc_offset != 0)
1849061da546Spatrick thread_sp->GetRegisterContext()->SetPC(pc);
1850061da546Spatrick thread_sp->SetStopInfo(
1851061da546Spatrick StopInfo::CreateStopReasonWithBreakpointSiteID(
1852061da546Spatrick *thread_sp, bp_site_sp->GetID()));
1853061da546Spatrick } else {
1854061da546Spatrick StopInfoSP invalid_stop_info_sp;
1855061da546Spatrick thread_sp->SetStopInfo(invalid_stop_info_sp);
1856061da546Spatrick }
1857061da546Spatrick } else {
1858*f6aab3d8Srobert // If we were stepping then assume the stop was the result of the
1859*f6aab3d8Srobert // trace. If we were not stepping then report the SIGTRAP.
1860*f6aab3d8Srobert // FIXME: We are still missing the case where we single step over a
1861*f6aab3d8Srobert // trap instruction.
1862061da546Spatrick if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1863061da546Spatrick thread_sp->SetStopInfo(
1864061da546Spatrick StopInfo::CreateStopReasonToTrace(*thread_sp));
1865061da546Spatrick else
1866061da546Spatrick thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1867061da546Spatrick *thread_sp, signo, description.c_str()));
1868061da546Spatrick }
1869061da546Spatrick }
1870061da546Spatrick if (!handled)
1871061da546Spatrick thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1872061da546Spatrick *thread_sp, signo, description.c_str()));
1873061da546Spatrick }
1874061da546Spatrick
1875061da546Spatrick if (!description.empty()) {
1876061da546Spatrick lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1877061da546Spatrick if (stop_info_sp) {
1878061da546Spatrick const char *stop_info_desc = stop_info_sp->GetDescription();
1879061da546Spatrick if (!stop_info_desc || !stop_info_desc[0])
1880061da546Spatrick stop_info_sp->SetDescription(description.c_str());
1881061da546Spatrick } else {
1882061da546Spatrick thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1883061da546Spatrick *thread_sp, description.c_str()));
1884061da546Spatrick }
1885061da546Spatrick }
1886061da546Spatrick }
1887061da546Spatrick }
1888061da546Spatrick return thread_sp;
1889061da546Spatrick }
1890061da546Spatrick
1891061da546Spatrick lldb::ThreadSP
SetThreadStopInfo(StructuredData::Dictionary * thread_dict)1892061da546Spatrick ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
1893061da546Spatrick static ConstString g_key_tid("tid");
1894061da546Spatrick static ConstString g_key_name("name");
1895061da546Spatrick static ConstString g_key_reason("reason");
1896061da546Spatrick static ConstString g_key_metype("metype");
1897061da546Spatrick static ConstString g_key_medata("medata");
1898061da546Spatrick static ConstString g_key_qaddr("qaddr");
1899061da546Spatrick static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
1900061da546Spatrick static ConstString g_key_associated_with_dispatch_queue(
1901061da546Spatrick "associated_with_dispatch_queue");
1902061da546Spatrick static ConstString g_key_queue_name("qname");
1903061da546Spatrick static ConstString g_key_queue_kind("qkind");
1904061da546Spatrick static ConstString g_key_queue_serial_number("qserialnum");
1905061da546Spatrick static ConstString g_key_registers("registers");
1906061da546Spatrick static ConstString g_key_memory("memory");
1907061da546Spatrick static ConstString g_key_address("address");
1908061da546Spatrick static ConstString g_key_bytes("bytes");
1909061da546Spatrick static ConstString g_key_description("description");
1910061da546Spatrick static ConstString g_key_signal("signal");
1911061da546Spatrick
1912061da546Spatrick // Stop with signal and thread info
1913061da546Spatrick lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
1914061da546Spatrick uint8_t signo = 0;
1915061da546Spatrick std::string value;
1916061da546Spatrick std::string thread_name;
1917061da546Spatrick std::string reason;
1918061da546Spatrick std::string description;
1919061da546Spatrick uint32_t exc_type = 0;
1920061da546Spatrick std::vector<addr_t> exc_data;
1921061da546Spatrick addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1922061da546Spatrick ExpeditedRegisterMap expedited_register_map;
1923061da546Spatrick bool queue_vars_valid = false;
1924061da546Spatrick addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
1925061da546Spatrick LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
1926061da546Spatrick std::string queue_name;
1927061da546Spatrick QueueKind queue_kind = eQueueKindUnknown;
1928061da546Spatrick uint64_t queue_serial_number = 0;
1929061da546Spatrick // Iterate through all of the thread dictionary key/value pairs from the
1930061da546Spatrick // structured data dictionary
1931061da546Spatrick
1932*f6aab3d8Srobert // FIXME: we're silently ignoring invalid data here
1933061da546Spatrick thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
1934061da546Spatrick &signo, &reason, &description, &exc_type, &exc_data,
1935061da546Spatrick &thread_dispatch_qaddr, &queue_vars_valid,
1936061da546Spatrick &associated_with_dispatch_queue, &dispatch_queue_t,
1937061da546Spatrick &queue_name, &queue_kind, &queue_serial_number](
1938061da546Spatrick ConstString key,
1939061da546Spatrick StructuredData::Object *object) -> bool {
1940061da546Spatrick if (key == g_key_tid) {
1941061da546Spatrick // thread in big endian hex
1942061da546Spatrick tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID);
1943061da546Spatrick } else if (key == g_key_metype) {
1944061da546Spatrick // exception type in big endian hex
1945061da546Spatrick exc_type = object->GetIntegerValue(0);
1946061da546Spatrick } else if (key == g_key_medata) {
1947061da546Spatrick // exception data in big endian hex
1948061da546Spatrick StructuredData::Array *array = object->GetAsArray();
1949061da546Spatrick if (array) {
1950061da546Spatrick array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
1951061da546Spatrick exc_data.push_back(object->GetIntegerValue());
1952061da546Spatrick return true; // Keep iterating through all array items
1953061da546Spatrick });
1954061da546Spatrick }
1955061da546Spatrick } else if (key == g_key_name) {
1956dda28197Spatrick thread_name = std::string(object->GetStringValue());
1957061da546Spatrick } else if (key == g_key_qaddr) {
1958061da546Spatrick thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS);
1959061da546Spatrick } else if (key == g_key_queue_name) {
1960061da546Spatrick queue_vars_valid = true;
1961dda28197Spatrick queue_name = std::string(object->GetStringValue());
1962061da546Spatrick } else if (key == g_key_queue_kind) {
1963dda28197Spatrick std::string queue_kind_str = std::string(object->GetStringValue());
1964061da546Spatrick if (queue_kind_str == "serial") {
1965061da546Spatrick queue_vars_valid = true;
1966061da546Spatrick queue_kind = eQueueKindSerial;
1967061da546Spatrick } else if (queue_kind_str == "concurrent") {
1968061da546Spatrick queue_vars_valid = true;
1969061da546Spatrick queue_kind = eQueueKindConcurrent;
1970061da546Spatrick }
1971061da546Spatrick } else if (key == g_key_queue_serial_number) {
1972061da546Spatrick queue_serial_number = object->GetIntegerValue(0);
1973061da546Spatrick if (queue_serial_number != 0)
1974061da546Spatrick queue_vars_valid = true;
1975061da546Spatrick } else if (key == g_key_dispatch_queue_t) {
1976061da546Spatrick dispatch_queue_t = object->GetIntegerValue(0);
1977061da546Spatrick if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
1978061da546Spatrick queue_vars_valid = true;
1979061da546Spatrick } else if (key == g_key_associated_with_dispatch_queue) {
1980061da546Spatrick queue_vars_valid = true;
1981061da546Spatrick bool associated = object->GetBooleanValue();
1982061da546Spatrick if (associated)
1983061da546Spatrick associated_with_dispatch_queue = eLazyBoolYes;
1984061da546Spatrick else
1985061da546Spatrick associated_with_dispatch_queue = eLazyBoolNo;
1986061da546Spatrick } else if (key == g_key_reason) {
1987dda28197Spatrick reason = std::string(object->GetStringValue());
1988061da546Spatrick } else if (key == g_key_description) {
1989dda28197Spatrick description = std::string(object->GetStringValue());
1990061da546Spatrick } else if (key == g_key_registers) {
1991061da546Spatrick StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
1992061da546Spatrick
1993061da546Spatrick if (registers_dict) {
1994061da546Spatrick registers_dict->ForEach(
1995061da546Spatrick [&expedited_register_map](ConstString key,
1996061da546Spatrick StructuredData::Object *object) -> bool {
1997*f6aab3d8Srobert uint32_t reg;
1998*f6aab3d8Srobert if (llvm::to_integer(key.AsCString(), reg))
1999dda28197Spatrick expedited_register_map[reg] =
2000dda28197Spatrick std::string(object->GetStringValue());
2001061da546Spatrick return true; // Keep iterating through all array items
2002061da546Spatrick });
2003061da546Spatrick }
2004061da546Spatrick } else if (key == g_key_memory) {
2005061da546Spatrick StructuredData::Array *array = object->GetAsArray();
2006061da546Spatrick if (array) {
2007061da546Spatrick array->ForEach([this](StructuredData::Object *object) -> bool {
2008061da546Spatrick StructuredData::Dictionary *mem_cache_dict =
2009061da546Spatrick object->GetAsDictionary();
2010061da546Spatrick if (mem_cache_dict) {
2011061da546Spatrick lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2012061da546Spatrick if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2013061da546Spatrick "address", mem_cache_addr)) {
2014061da546Spatrick if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2015061da546Spatrick llvm::StringRef str;
2016061da546Spatrick if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2017061da546Spatrick StringExtractor bytes(str);
2018061da546Spatrick bytes.SetFilePos(0);
2019061da546Spatrick
2020061da546Spatrick const size_t byte_size = bytes.GetStringRef().size() / 2;
2021*f6aab3d8Srobert WritableDataBufferSP data_buffer_sp(
2022*f6aab3d8Srobert new DataBufferHeap(byte_size, 0));
2023061da546Spatrick const size_t bytes_copied =
2024061da546Spatrick bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2025061da546Spatrick if (bytes_copied == byte_size)
2026061da546Spatrick m_memory_cache.AddL1CacheData(mem_cache_addr,
2027061da546Spatrick data_buffer_sp);
2028061da546Spatrick }
2029061da546Spatrick }
2030061da546Spatrick }
2031061da546Spatrick }
2032061da546Spatrick return true; // Keep iterating through all array items
2033061da546Spatrick });
2034061da546Spatrick }
2035061da546Spatrick
2036061da546Spatrick } else if (key == g_key_signal)
2037061da546Spatrick signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2038061da546Spatrick return true; // Keep iterating through all dictionary key/value pairs
2039061da546Spatrick });
2040061da546Spatrick
2041061da546Spatrick return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2042061da546Spatrick reason, description, exc_type, exc_data,
2043061da546Spatrick thread_dispatch_qaddr, queue_vars_valid,
2044061da546Spatrick associated_with_dispatch_queue, dispatch_queue_t,
2045061da546Spatrick queue_name, queue_kind, queue_serial_number);
2046061da546Spatrick }
2047061da546Spatrick
SetThreadStopInfo(StringExtractor & stop_packet)2048061da546Spatrick StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2049be691f3bSpatrick lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2050061da546Spatrick stop_packet.SetFilePos(0);
2051061da546Spatrick const char stop_type = stop_packet.GetChar();
2052061da546Spatrick switch (stop_type) {
2053061da546Spatrick case 'T':
2054061da546Spatrick case 'S': {
2055061da546Spatrick // This is a bit of a hack, but is is required. If we did exec, we need to
2056061da546Spatrick // clear our thread lists and also know to rebuild our dynamic register
2057061da546Spatrick // info before we lookup and threads and populate the expedited register
2058061da546Spatrick // values so we need to know this right away so we can cleanup and update
2059061da546Spatrick // our registers.
2060061da546Spatrick const uint32_t stop_id = GetStopID();
2061061da546Spatrick if (stop_id == 0) {
2062061da546Spatrick // Our first stop, make sure we have a process ID, and also make sure we
2063061da546Spatrick // know about our registers
2064be691f3bSpatrick if (GetID() == LLDB_INVALID_PROCESS_ID && pid != LLDB_INVALID_PROCESS_ID)
2065061da546Spatrick SetID(pid);
2066061da546Spatrick BuildDynamicRegisterInfo(true);
2067061da546Spatrick }
2068061da546Spatrick // Stop with signal and thread info
2069be691f3bSpatrick lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID;
2070061da546Spatrick lldb::tid_t tid = LLDB_INVALID_THREAD_ID;
2071061da546Spatrick const uint8_t signo = stop_packet.GetHexU8();
2072061da546Spatrick llvm::StringRef key;
2073061da546Spatrick llvm::StringRef value;
2074061da546Spatrick std::string thread_name;
2075061da546Spatrick std::string reason;
2076061da546Spatrick std::string description;
2077061da546Spatrick uint32_t exc_type = 0;
2078061da546Spatrick std::vector<addr_t> exc_data;
2079061da546Spatrick addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2080061da546Spatrick bool queue_vars_valid =
2081061da546Spatrick false; // says if locals below that start with "queue_" are valid
2082061da546Spatrick addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2083061da546Spatrick LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2084061da546Spatrick std::string queue_name;
2085061da546Spatrick QueueKind queue_kind = eQueueKindUnknown;
2086061da546Spatrick uint64_t queue_serial_number = 0;
2087061da546Spatrick ExpeditedRegisterMap expedited_register_map;
2088061da546Spatrick while (stop_packet.GetNameColonValue(key, value)) {
2089061da546Spatrick if (key.compare("metype") == 0) {
2090061da546Spatrick // exception type in big endian hex
2091061da546Spatrick value.getAsInteger(16, exc_type);
2092061da546Spatrick } else if (key.compare("medata") == 0) {
2093061da546Spatrick // exception data in big endian hex
2094061da546Spatrick uint64_t x;
2095061da546Spatrick value.getAsInteger(16, x);
2096061da546Spatrick exc_data.push_back(x);
2097061da546Spatrick } else if (key.compare("thread") == 0) {
2098be691f3bSpatrick // thread-id
2099be691f3bSpatrick StringExtractorGDBRemote thread_id{value};
2100be691f3bSpatrick auto pid_tid = thread_id.GetPidTid(pid);
2101be691f3bSpatrick if (pid_tid) {
2102be691f3bSpatrick stop_pid = pid_tid->first;
2103be691f3bSpatrick tid = pid_tid->second;
2104be691f3bSpatrick } else
2105061da546Spatrick tid = LLDB_INVALID_THREAD_ID;
2106061da546Spatrick } else if (key.compare("threads") == 0) {
2107061da546Spatrick std::lock_guard<std::recursive_mutex> guard(
2108061da546Spatrick m_thread_list_real.GetMutex());
2109be691f3bSpatrick UpdateThreadIDsFromStopReplyThreadsValue(value);
2110061da546Spatrick } else if (key.compare("thread-pcs") == 0) {
2111061da546Spatrick m_thread_pcs.clear();
2112061da546Spatrick // A comma separated list of all threads in the current
2113061da546Spatrick // process that includes the thread for this stop reply packet
2114061da546Spatrick lldb::addr_t pc;
2115061da546Spatrick while (!value.empty()) {
2116061da546Spatrick llvm::StringRef pc_str;
2117061da546Spatrick std::tie(pc_str, value) = value.split(',');
2118061da546Spatrick if (pc_str.getAsInteger(16, pc))
2119061da546Spatrick pc = LLDB_INVALID_ADDRESS;
2120061da546Spatrick m_thread_pcs.push_back(pc);
2121061da546Spatrick }
2122061da546Spatrick } else if (key.compare("jstopinfo") == 0) {
2123061da546Spatrick StringExtractor json_extractor(value);
2124061da546Spatrick std::string json;
2125061da546Spatrick // Now convert the HEX bytes into a string value
2126061da546Spatrick json_extractor.GetHexByteString(json);
2127061da546Spatrick
2128061da546Spatrick // This JSON contains thread IDs and thread stop info for all threads.
2129061da546Spatrick // It doesn't contain expedited registers, memory or queue info.
2130061da546Spatrick m_jstopinfo_sp = StructuredData::ParseJSON(json);
2131061da546Spatrick } else if (key.compare("hexname") == 0) {
2132061da546Spatrick StringExtractor name_extractor(value);
2133061da546Spatrick std::string name;
2134061da546Spatrick // Now convert the HEX bytes into a string value
2135061da546Spatrick name_extractor.GetHexByteString(thread_name);
2136061da546Spatrick } else if (key.compare("name") == 0) {
2137dda28197Spatrick thread_name = std::string(value);
2138061da546Spatrick } else if (key.compare("qaddr") == 0) {
2139061da546Spatrick value.getAsInteger(16, thread_dispatch_qaddr);
2140061da546Spatrick } else if (key.compare("dispatch_queue_t") == 0) {
2141061da546Spatrick queue_vars_valid = true;
2142061da546Spatrick value.getAsInteger(16, dispatch_queue_t);
2143061da546Spatrick } else if (key.compare("qname") == 0) {
2144061da546Spatrick queue_vars_valid = true;
2145061da546Spatrick StringExtractor name_extractor(value);
2146061da546Spatrick // Now convert the HEX bytes into a string value
2147061da546Spatrick name_extractor.GetHexByteString(queue_name);
2148061da546Spatrick } else if (key.compare("qkind") == 0) {
2149061da546Spatrick queue_kind = llvm::StringSwitch<QueueKind>(value)
2150061da546Spatrick .Case("serial", eQueueKindSerial)
2151061da546Spatrick .Case("concurrent", eQueueKindConcurrent)
2152061da546Spatrick .Default(eQueueKindUnknown);
2153061da546Spatrick queue_vars_valid = queue_kind != eQueueKindUnknown;
2154061da546Spatrick } else if (key.compare("qserialnum") == 0) {
2155061da546Spatrick if (!value.getAsInteger(0, queue_serial_number))
2156061da546Spatrick queue_vars_valid = true;
2157061da546Spatrick } else if (key.compare("reason") == 0) {
2158dda28197Spatrick reason = std::string(value);
2159061da546Spatrick } else if (key.compare("description") == 0) {
2160061da546Spatrick StringExtractor desc_extractor(value);
2161061da546Spatrick // Now convert the HEX bytes into a string value
2162061da546Spatrick desc_extractor.GetHexByteString(description);
2163061da546Spatrick } else if (key.compare("memory") == 0) {
2164061da546Spatrick // Expedited memory. GDB servers can choose to send back expedited
2165061da546Spatrick // memory that can populate the L1 memory cache in the process so that
2166061da546Spatrick // things like the frame pointer backchain can be expedited. This will
2167061da546Spatrick // help stack backtracing be more efficient by not having to send as
2168061da546Spatrick // many memory read requests down the remote GDB server.
2169061da546Spatrick
2170061da546Spatrick // Key/value pair format: memory:<addr>=<bytes>;
2171061da546Spatrick // <addr> is a number whose base will be interpreted by the prefix:
2172061da546Spatrick // "0x[0-9a-fA-F]+" for hex
2173061da546Spatrick // "0[0-7]+" for octal
2174061da546Spatrick // "[1-9]+" for decimal
2175061da546Spatrick // <bytes> is native endian ASCII hex bytes just like the register
2176061da546Spatrick // values
2177061da546Spatrick llvm::StringRef addr_str, bytes_str;
2178061da546Spatrick std::tie(addr_str, bytes_str) = value.split('=');
2179061da546Spatrick if (!addr_str.empty() && !bytes_str.empty()) {
2180061da546Spatrick lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2181061da546Spatrick if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2182061da546Spatrick StringExtractor bytes(bytes_str);
2183061da546Spatrick const size_t byte_size = bytes.GetBytesLeft() / 2;
2184*f6aab3d8Srobert WritableDataBufferSP data_buffer_sp(
2185*f6aab3d8Srobert new DataBufferHeap(byte_size, 0));
2186061da546Spatrick const size_t bytes_copied =
2187061da546Spatrick bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2188061da546Spatrick if (bytes_copied == byte_size)
2189061da546Spatrick m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2190061da546Spatrick }
2191061da546Spatrick }
2192061da546Spatrick } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2193061da546Spatrick key.compare("awatch") == 0) {
2194061da546Spatrick // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2195061da546Spatrick lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS;
2196061da546Spatrick value.getAsInteger(16, wp_addr);
2197061da546Spatrick
2198061da546Spatrick WatchpointSP wp_sp =
2199061da546Spatrick GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2200061da546Spatrick uint32_t wp_index = LLDB_INVALID_INDEX32;
2201061da546Spatrick
2202061da546Spatrick if (wp_sp)
2203061da546Spatrick wp_index = wp_sp->GetHardwareIndex();
2204061da546Spatrick
2205061da546Spatrick reason = "watchpoint";
2206061da546Spatrick StreamString ostr;
2207061da546Spatrick ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2208dda28197Spatrick description = std::string(ostr.GetString());
2209061da546Spatrick } else if (key.compare("library") == 0) {
2210061da546Spatrick auto error = LoadModules();
2211061da546Spatrick if (error) {
2212*f6aab3d8Srobert Log *log(GetLog(GDBRLog::Process));
2213061da546Spatrick LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2214061da546Spatrick }
2215*f6aab3d8Srobert } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2216*f6aab3d8Srobert // fork includes child pid/tid in thread-id format
2217*f6aab3d8Srobert StringExtractorGDBRemote thread_id{value};
2218*f6aab3d8Srobert auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2219*f6aab3d8Srobert if (!pid_tid) {
2220*f6aab3d8Srobert Log *log(GetLog(GDBRLog::Process));
2221*f6aab3d8Srobert LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2222*f6aab3d8Srobert pid_tid = {{LLDB_INVALID_PROCESS_ID, LLDB_INVALID_THREAD_ID}};
2223*f6aab3d8Srobert }
2224*f6aab3d8Srobert
2225*f6aab3d8Srobert reason = key.str();
2226*f6aab3d8Srobert StreamString ostr;
2227*f6aab3d8Srobert ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2228*f6aab3d8Srobert description = std::string(ostr.GetString());
2229061da546Spatrick } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2230061da546Spatrick uint32_t reg = UINT32_MAX;
2231061da546Spatrick if (!key.getAsInteger(16, reg))
2232dda28197Spatrick expedited_register_map[reg] = std::string(std::move(value));
2233061da546Spatrick }
2234061da546Spatrick }
2235061da546Spatrick
2236be691f3bSpatrick if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2237*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
2238be691f3bSpatrick LLDB_LOG(log,
2239be691f3bSpatrick "Received stop for incorrect PID = {0} (inferior PID = {1})",
2240be691f3bSpatrick stop_pid, pid);
2241be691f3bSpatrick return eStateInvalid;
2242be691f3bSpatrick }
2243be691f3bSpatrick
2244061da546Spatrick if (tid == LLDB_INVALID_THREAD_ID) {
2245061da546Spatrick // A thread id may be invalid if the response is old style 'S' packet
2246061da546Spatrick // which does not provide the
2247061da546Spatrick // thread information. So update the thread list and choose the first
2248061da546Spatrick // one.
2249061da546Spatrick UpdateThreadIDList();
2250061da546Spatrick
2251061da546Spatrick if (!m_thread_ids.empty()) {
2252061da546Spatrick tid = m_thread_ids.front();
2253061da546Spatrick }
2254061da546Spatrick }
2255061da546Spatrick
2256061da546Spatrick ThreadSP thread_sp = SetThreadStopInfo(
2257061da546Spatrick tid, expedited_register_map, signo, thread_name, reason, description,
2258061da546Spatrick exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2259061da546Spatrick associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2260061da546Spatrick queue_kind, queue_serial_number);
2261061da546Spatrick
2262061da546Spatrick return eStateStopped;
2263061da546Spatrick } break;
2264061da546Spatrick
2265061da546Spatrick case 'W':
2266061da546Spatrick case 'X':
2267061da546Spatrick // process exited
2268061da546Spatrick return eStateExited;
2269061da546Spatrick
2270061da546Spatrick default:
2271061da546Spatrick break;
2272061da546Spatrick }
2273061da546Spatrick return eStateInvalid;
2274061da546Spatrick }
2275061da546Spatrick
RefreshStateAfterStop()2276061da546Spatrick void ProcessGDBRemote::RefreshStateAfterStop() {
2277061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2278061da546Spatrick
2279061da546Spatrick m_thread_ids.clear();
2280061da546Spatrick m_thread_pcs.clear();
2281061da546Spatrick
2282061da546Spatrick // Set the thread stop info. It might have a "threads" key whose value is a
2283061da546Spatrick // list of all thread IDs in the current process, so m_thread_ids might get
2284061da546Spatrick // set.
2285061da546Spatrick // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2286061da546Spatrick if (m_thread_ids.empty()) {
2287061da546Spatrick // No, we need to fetch the thread list manually
2288061da546Spatrick UpdateThreadIDList();
2289061da546Spatrick }
2290061da546Spatrick
2291061da546Spatrick // We might set some stop info's so make sure the thread list is up to
2292061da546Spatrick // date before we do that or we might overwrite what was computed here.
2293061da546Spatrick UpdateThreadListIfNeeded();
2294061da546Spatrick
2295*f6aab3d8Srobert if (m_last_stop_packet)
2296*f6aab3d8Srobert SetThreadStopInfo(*m_last_stop_packet);
2297*f6aab3d8Srobert m_last_stop_packet.reset();
2298061da546Spatrick
2299061da546Spatrick // If we have queried for a default thread id
2300061da546Spatrick if (m_initial_tid != LLDB_INVALID_THREAD_ID) {
2301061da546Spatrick m_thread_list.SetSelectedThreadByID(m_initial_tid);
2302061da546Spatrick m_initial_tid = LLDB_INVALID_THREAD_ID;
2303061da546Spatrick }
2304061da546Spatrick
2305061da546Spatrick // Let all threads recover from stopping and do any clean up based on the
2306061da546Spatrick // previous thread state (if any).
2307061da546Spatrick m_thread_list_real.RefreshStateAfterStop();
2308061da546Spatrick }
2309061da546Spatrick
DoHalt(bool & caused_stop)2310061da546Spatrick Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2311061da546Spatrick Status error;
2312061da546Spatrick
2313061da546Spatrick if (m_public_state.GetValue() == eStateAttaching) {
2314061da546Spatrick // We are being asked to halt during an attach. We need to just close our
2315061da546Spatrick // file handle and debugserver will go away, and we can be done...
2316061da546Spatrick m_gdb_comm.Disconnect();
2317061da546Spatrick } else
2318be691f3bSpatrick caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2319061da546Spatrick return error;
2320061da546Spatrick }
2321061da546Spatrick
DoDetach(bool keep_stopped)2322061da546Spatrick Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2323061da546Spatrick Status error;
2324*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
2325061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2326061da546Spatrick
2327061da546Spatrick error = m_gdb_comm.Detach(keep_stopped);
2328061da546Spatrick if (log) {
2329061da546Spatrick if (error.Success())
2330061da546Spatrick log->PutCString(
2331061da546Spatrick "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2332061da546Spatrick else
2333061da546Spatrick LLDB_LOGF(log,
2334061da546Spatrick "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2335061da546Spatrick error.AsCString() ? error.AsCString() : "<unknown error>");
2336061da546Spatrick }
2337061da546Spatrick
2338061da546Spatrick if (!error.Success())
2339061da546Spatrick return error;
2340061da546Spatrick
2341061da546Spatrick // Sleep for one second to let the process get all detached...
2342061da546Spatrick StopAsyncThread();
2343061da546Spatrick
2344061da546Spatrick SetPrivateState(eStateDetached);
2345061da546Spatrick ResumePrivateStateThread();
2346061da546Spatrick
2347061da546Spatrick // KillDebugserverProcess ();
2348061da546Spatrick return error;
2349061da546Spatrick }
2350061da546Spatrick
DoDestroy()2351061da546Spatrick Status ProcessGDBRemote::DoDestroy() {
2352*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
2353061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2354061da546Spatrick
2355061da546Spatrick // Interrupt if our inferior is running...
2356061da546Spatrick int exit_status = SIGABRT;
2357061da546Spatrick std::string exit_string;
2358061da546Spatrick
2359061da546Spatrick if (m_gdb_comm.IsConnected()) {
2360061da546Spatrick if (m_public_state.GetValue() != eStateAttaching) {
2361*f6aab3d8Srobert llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2362061da546Spatrick
2363*f6aab3d8Srobert if (kill_res) {
2364*f6aab3d8Srobert exit_status = kill_res.get();
2365061da546Spatrick #if defined(__APPLE__)
2366061da546Spatrick // For Native processes on Mac OS X, we launch through the Host
2367061da546Spatrick // Platform, then hand the process off to debugserver, which becomes
2368061da546Spatrick // the parent process through "PT_ATTACH". Then when we go to kill
2369061da546Spatrick // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2370061da546Spatrick // we call waitpid which returns with no error and the correct
2371061da546Spatrick // status. But amusingly enough that doesn't seem to actually reap
2372061da546Spatrick // the process, but instead it is left around as a Zombie. Probably
2373061da546Spatrick // the kernel is in the process of switching ownership back to lldb
2374061da546Spatrick // which was the original parent, and gets confused in the handoff.
2375061da546Spatrick // Anyway, so call waitpid here to finally reap it.
2376061da546Spatrick PlatformSP platform_sp(GetTarget().GetPlatform());
2377061da546Spatrick if (platform_sp && platform_sp->IsHost()) {
2378061da546Spatrick int status;
2379061da546Spatrick ::pid_t reap_pid;
2380061da546Spatrick reap_pid = waitpid(GetID(), &status, WNOHANG);
2381061da546Spatrick LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2382061da546Spatrick }
2383061da546Spatrick #endif
2384061da546Spatrick ClearThreadIDList();
2385*f6aab3d8Srobert exit_string.assign("killed");
2386061da546Spatrick } else {
2387*f6aab3d8Srobert exit_string.assign(llvm::toString(kill_res.takeError()));
2388061da546Spatrick }
2389061da546Spatrick } else {
2390061da546Spatrick exit_string.assign("killed or interrupted while attaching.");
2391061da546Spatrick }
2392061da546Spatrick } else {
2393061da546Spatrick // If we missed setting the exit status on the way out, do it here.
2394061da546Spatrick // NB set exit status can be called multiple times, the first one sets the
2395061da546Spatrick // status.
2396061da546Spatrick exit_string.assign("destroying when not connected to debugserver");
2397061da546Spatrick }
2398061da546Spatrick
2399061da546Spatrick SetExitStatus(exit_status, exit_string.c_str());
2400061da546Spatrick
2401061da546Spatrick StopAsyncThread();
2402061da546Spatrick KillDebugserverProcess();
2403*f6aab3d8Srobert return Status();
2404061da546Spatrick }
2405061da546Spatrick
SetLastStopPacket(const StringExtractorGDBRemote & response)2406061da546Spatrick void ProcessGDBRemote::SetLastStopPacket(
2407061da546Spatrick const StringExtractorGDBRemote &response) {
2408061da546Spatrick const bool did_exec =
2409061da546Spatrick response.GetStringRef().find(";reason:exec;") != std::string::npos;
2410061da546Spatrick if (did_exec) {
2411*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
2412061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2413061da546Spatrick
2414061da546Spatrick m_thread_list_real.Clear();
2415061da546Spatrick m_thread_list.Clear();
2416061da546Spatrick BuildDynamicRegisterInfo(true);
2417061da546Spatrick m_gdb_comm.ResetDiscoverableSettings(did_exec);
2418061da546Spatrick }
2419061da546Spatrick
2420*f6aab3d8Srobert m_last_stop_packet = response;
2421061da546Spatrick }
2422061da546Spatrick
SetUnixSignals(const UnixSignalsSP & signals_sp)2423061da546Spatrick void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2424061da546Spatrick Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2425061da546Spatrick }
2426061da546Spatrick
2427061da546Spatrick // Process Queries
2428061da546Spatrick
IsAlive()2429061da546Spatrick bool ProcessGDBRemote::IsAlive() {
2430061da546Spatrick return m_gdb_comm.IsConnected() && Process::IsAlive();
2431061da546Spatrick }
2432061da546Spatrick
GetImageInfoAddress()2433061da546Spatrick addr_t ProcessGDBRemote::GetImageInfoAddress() {
2434061da546Spatrick // request the link map address via the $qShlibInfoAddr packet
2435061da546Spatrick lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2436061da546Spatrick
2437061da546Spatrick // the loaded module list can also provides a link map address
2438061da546Spatrick if (addr == LLDB_INVALID_ADDRESS) {
2439061da546Spatrick llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2440061da546Spatrick if (!list) {
2441*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
2442be691f3bSpatrick LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2443061da546Spatrick } else {
2444061da546Spatrick addr = list->m_link_map;
2445061da546Spatrick }
2446061da546Spatrick }
2447061da546Spatrick
2448061da546Spatrick return addr;
2449061da546Spatrick }
2450061da546Spatrick
WillPublicStop()2451061da546Spatrick void ProcessGDBRemote::WillPublicStop() {
2452061da546Spatrick // See if the GDB remote client supports the JSON threads info. If so, we
2453061da546Spatrick // gather stop info for all threads, expedited registers, expedited memory,
2454061da546Spatrick // runtime queue information (iOS and MacOSX only), and more. Expediting
2455061da546Spatrick // memory will help stack backtracing be much faster. Expediting registers
2456061da546Spatrick // will make sure we don't have to read the thread registers for GPRs.
2457061da546Spatrick m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2458061da546Spatrick
2459061da546Spatrick if (m_jthreadsinfo_sp) {
2460061da546Spatrick // Now set the stop info for each thread and also expedite any registers
2461061da546Spatrick // and memory that was in the jThreadsInfo response.
2462061da546Spatrick StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2463061da546Spatrick if (thread_infos) {
2464061da546Spatrick const size_t n = thread_infos->GetSize();
2465061da546Spatrick for (size_t i = 0; i < n; ++i) {
2466061da546Spatrick StructuredData::Dictionary *thread_dict =
2467061da546Spatrick thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2468061da546Spatrick if (thread_dict)
2469061da546Spatrick SetThreadStopInfo(thread_dict);
2470061da546Spatrick }
2471061da546Spatrick }
2472061da546Spatrick }
2473061da546Spatrick }
2474061da546Spatrick
2475061da546Spatrick // Process Memory
DoReadMemory(addr_t addr,void * buf,size_t size,Status & error)2476061da546Spatrick size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2477061da546Spatrick Status &error) {
2478061da546Spatrick GetMaxMemorySize();
2479061da546Spatrick bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2480061da546Spatrick // M and m packets take 2 bytes for 1 byte of memory
2481061da546Spatrick size_t max_memory_size =
2482061da546Spatrick binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2483061da546Spatrick if (size > max_memory_size) {
2484061da546Spatrick // Keep memory read sizes down to a sane limit. This function will be
2485061da546Spatrick // called multiple times in order to complete the task by
2486061da546Spatrick // lldb_private::Process so it is ok to do this.
2487061da546Spatrick size = max_memory_size;
2488061da546Spatrick }
2489061da546Spatrick
2490061da546Spatrick char packet[64];
2491061da546Spatrick int packet_len;
2492061da546Spatrick packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2493061da546Spatrick binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2494061da546Spatrick (uint64_t)size);
2495061da546Spatrick assert(packet_len + 1 < (int)sizeof(packet));
2496061da546Spatrick UNUSED_IF_ASSERT_DISABLED(packet_len);
2497061da546Spatrick StringExtractorGDBRemote response;
2498be691f3bSpatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2499be691f3bSpatrick GetInterruptTimeout()) ==
2500061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
2501061da546Spatrick if (response.IsNormalResponse()) {
2502061da546Spatrick error.Clear();
2503061da546Spatrick if (binary_memory_read) {
2504061da546Spatrick // The lower level GDBRemoteCommunication packet receive layer has
2505061da546Spatrick // already de-quoted any 0x7d character escaping that was present in
2506061da546Spatrick // the packet
2507061da546Spatrick
2508061da546Spatrick size_t data_received_size = response.GetBytesLeft();
2509061da546Spatrick if (data_received_size > size) {
2510061da546Spatrick // Don't write past the end of BUF if the remote debug server gave us
2511061da546Spatrick // too much data for some reason.
2512061da546Spatrick data_received_size = size;
2513061da546Spatrick }
2514061da546Spatrick memcpy(buf, response.GetStringRef().data(), data_received_size);
2515061da546Spatrick return data_received_size;
2516061da546Spatrick } else {
2517061da546Spatrick return response.GetHexBytes(
2518061da546Spatrick llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2519061da546Spatrick }
2520061da546Spatrick } else if (response.IsErrorResponse())
2521061da546Spatrick error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2522061da546Spatrick else if (response.IsUnsupportedResponse())
2523061da546Spatrick error.SetErrorStringWithFormat(
2524061da546Spatrick "GDB server does not support reading memory");
2525061da546Spatrick else
2526061da546Spatrick error.SetErrorStringWithFormat(
2527061da546Spatrick "unexpected response to GDB server memory read packet '%s': '%s'",
2528061da546Spatrick packet, response.GetStringRef().data());
2529061da546Spatrick } else {
2530061da546Spatrick error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2531061da546Spatrick }
2532061da546Spatrick return 0;
2533061da546Spatrick }
2534061da546Spatrick
SupportsMemoryTagging()2535be691f3bSpatrick bool ProcessGDBRemote::SupportsMemoryTagging() {
2536be691f3bSpatrick return m_gdb_comm.GetMemoryTaggingSupported();
2537be691f3bSpatrick }
2538be691f3bSpatrick
2539be691f3bSpatrick llvm::Expected<std::vector<uint8_t>>
DoReadMemoryTags(lldb::addr_t addr,size_t len,int32_t type)2540be691f3bSpatrick ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,
2541be691f3bSpatrick int32_t type) {
2542be691f3bSpatrick // By this point ReadMemoryTags has validated that tagging is enabled
2543be691f3bSpatrick // for this target/process/address.
2544be691f3bSpatrick DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2545be691f3bSpatrick if (!buffer_sp) {
2546be691f3bSpatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
2547be691f3bSpatrick "Error reading memory tags from remote");
2548be691f3bSpatrick }
2549be691f3bSpatrick
2550be691f3bSpatrick // Return the raw tag data
2551be691f3bSpatrick llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2552be691f3bSpatrick std::vector<uint8_t> got;
2553be691f3bSpatrick got.reserve(tag_data.size());
2554be691f3bSpatrick std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2555be691f3bSpatrick return got;
2556be691f3bSpatrick }
2557be691f3bSpatrick
DoWriteMemoryTags(lldb::addr_t addr,size_t len,int32_t type,const std::vector<uint8_t> & tags)2558be691f3bSpatrick Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,
2559be691f3bSpatrick int32_t type,
2560be691f3bSpatrick const std::vector<uint8_t> &tags) {
2561be691f3bSpatrick // By now WriteMemoryTags should have validated that tagging is enabled
2562be691f3bSpatrick // for this target/process.
2563be691f3bSpatrick return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2564be691f3bSpatrick }
2565be691f3bSpatrick
WriteObjectFile(std::vector<ObjectFile::LoadableData> entries)2566061da546Spatrick Status ProcessGDBRemote::WriteObjectFile(
2567061da546Spatrick std::vector<ObjectFile::LoadableData> entries) {
2568061da546Spatrick Status error;
2569061da546Spatrick // Sort the entries by address because some writes, like those to flash
2570061da546Spatrick // memory, must happen in order of increasing address.
2571061da546Spatrick std::stable_sort(
2572061da546Spatrick std::begin(entries), std::end(entries),
2573061da546Spatrick [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2574061da546Spatrick return a.Dest < b.Dest;
2575061da546Spatrick });
2576061da546Spatrick m_allow_flash_writes = true;
2577061da546Spatrick error = Process::WriteObjectFile(entries);
2578061da546Spatrick if (error.Success())
2579061da546Spatrick error = FlashDone();
2580061da546Spatrick else
2581061da546Spatrick // Even though some of the writing failed, try to send a flash done if some
2582061da546Spatrick // of the writing succeeded so the flash state is reset to normal, but
2583061da546Spatrick // don't stomp on the error status that was set in the write failure since
2584061da546Spatrick // that's the one we want to report back.
2585061da546Spatrick FlashDone();
2586061da546Spatrick m_allow_flash_writes = false;
2587061da546Spatrick return error;
2588061da546Spatrick }
2589061da546Spatrick
HasErased(FlashRange range)2590061da546Spatrick bool ProcessGDBRemote::HasErased(FlashRange range) {
2591061da546Spatrick auto size = m_erased_flash_ranges.GetSize();
2592061da546Spatrick for (size_t i = 0; i < size; ++i)
2593061da546Spatrick if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2594061da546Spatrick return true;
2595061da546Spatrick return false;
2596061da546Spatrick }
2597061da546Spatrick
FlashErase(lldb::addr_t addr,size_t size)2598061da546Spatrick Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2599061da546Spatrick Status status;
2600061da546Spatrick
2601061da546Spatrick MemoryRegionInfo region;
2602061da546Spatrick status = GetMemoryRegionInfo(addr, region);
2603061da546Spatrick if (!status.Success())
2604061da546Spatrick return status;
2605061da546Spatrick
2606061da546Spatrick // The gdb spec doesn't say if erasures are allowed across multiple regions,
2607061da546Spatrick // but we'll disallow it to be safe and to keep the logic simple by worring
2608061da546Spatrick // about only one region's block size. DoMemoryWrite is this function's
2609061da546Spatrick // primary user, and it can easily keep writes within a single memory region
2610061da546Spatrick if (addr + size > region.GetRange().GetRangeEnd()) {
2611061da546Spatrick status.SetErrorString("Unable to erase flash in multiple regions");
2612061da546Spatrick return status;
2613061da546Spatrick }
2614061da546Spatrick
2615061da546Spatrick uint64_t blocksize = region.GetBlocksize();
2616061da546Spatrick if (blocksize == 0) {
2617061da546Spatrick status.SetErrorString("Unable to erase flash because blocksize is 0");
2618061da546Spatrick return status;
2619061da546Spatrick }
2620061da546Spatrick
2621061da546Spatrick // Erasures can only be done on block boundary adresses, so round down addr
2622061da546Spatrick // and round up size
2623061da546Spatrick lldb::addr_t block_start_addr = addr - (addr % blocksize);
2624061da546Spatrick size += (addr - block_start_addr);
2625061da546Spatrick if ((size % blocksize) != 0)
2626061da546Spatrick size += (blocksize - size % blocksize);
2627061da546Spatrick
2628061da546Spatrick FlashRange range(block_start_addr, size);
2629061da546Spatrick
2630061da546Spatrick if (HasErased(range))
2631061da546Spatrick return status;
2632061da546Spatrick
2633061da546Spatrick // We haven't erased the entire range, but we may have erased part of it.
2634061da546Spatrick // (e.g., block A is already erased and range starts in A and ends in B). So,
2635061da546Spatrick // adjust range if necessary to exclude already erased blocks.
2636061da546Spatrick if (!m_erased_flash_ranges.IsEmpty()) {
2637061da546Spatrick // Assuming that writes and erasures are done in increasing addr order,
2638061da546Spatrick // because that is a requirement of the vFlashWrite command. Therefore, we
2639061da546Spatrick // only need to look at the last range in the list for overlap.
2640061da546Spatrick const auto &last_range = *m_erased_flash_ranges.Back();
2641061da546Spatrick if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2642061da546Spatrick auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2643061da546Spatrick // overlap will be less than range.GetByteSize() or else HasErased()
2644061da546Spatrick // would have been true
2645061da546Spatrick range.SetByteSize(range.GetByteSize() - overlap);
2646061da546Spatrick range.SetRangeBase(range.GetRangeBase() + overlap);
2647061da546Spatrick }
2648061da546Spatrick }
2649061da546Spatrick
2650061da546Spatrick StreamString packet;
2651061da546Spatrick packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2652061da546Spatrick (uint64_t)range.GetByteSize());
2653061da546Spatrick
2654061da546Spatrick StringExtractorGDBRemote response;
2655061da546Spatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2656be691f3bSpatrick GetInterruptTimeout()) ==
2657061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
2658061da546Spatrick if (response.IsOKResponse()) {
2659061da546Spatrick m_erased_flash_ranges.Insert(range, true);
2660061da546Spatrick } else {
2661061da546Spatrick if (response.IsErrorResponse())
2662061da546Spatrick status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2663061da546Spatrick addr);
2664061da546Spatrick else if (response.IsUnsupportedResponse())
2665061da546Spatrick status.SetErrorStringWithFormat("GDB server does not support flashing");
2666061da546Spatrick else
2667061da546Spatrick status.SetErrorStringWithFormat(
2668061da546Spatrick "unexpected response to GDB server flash erase packet '%s': '%s'",
2669061da546Spatrick packet.GetData(), response.GetStringRef().data());
2670061da546Spatrick }
2671061da546Spatrick } else {
2672061da546Spatrick status.SetErrorStringWithFormat("failed to send packet: '%s'",
2673061da546Spatrick packet.GetData());
2674061da546Spatrick }
2675061da546Spatrick return status;
2676061da546Spatrick }
2677061da546Spatrick
FlashDone()2678061da546Spatrick Status ProcessGDBRemote::FlashDone() {
2679061da546Spatrick Status status;
2680061da546Spatrick // If we haven't erased any blocks, then we must not have written anything
2681061da546Spatrick // either, so there is no need to actually send a vFlashDone command
2682061da546Spatrick if (m_erased_flash_ranges.IsEmpty())
2683061da546Spatrick return status;
2684061da546Spatrick StringExtractorGDBRemote response;
2685be691f3bSpatrick if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2686be691f3bSpatrick GetInterruptTimeout()) ==
2687061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
2688061da546Spatrick if (response.IsOKResponse()) {
2689061da546Spatrick m_erased_flash_ranges.Clear();
2690061da546Spatrick } else {
2691061da546Spatrick if (response.IsErrorResponse())
2692061da546Spatrick status.SetErrorStringWithFormat("flash done failed");
2693061da546Spatrick else if (response.IsUnsupportedResponse())
2694061da546Spatrick status.SetErrorStringWithFormat("GDB server does not support flashing");
2695061da546Spatrick else
2696061da546Spatrick status.SetErrorStringWithFormat(
2697061da546Spatrick "unexpected response to GDB server flash done packet: '%s'",
2698061da546Spatrick response.GetStringRef().data());
2699061da546Spatrick }
2700061da546Spatrick } else {
2701061da546Spatrick status.SetErrorStringWithFormat("failed to send flash done packet");
2702061da546Spatrick }
2703061da546Spatrick return status;
2704061da546Spatrick }
2705061da546Spatrick
DoWriteMemory(addr_t addr,const void * buf,size_t size,Status & error)2706061da546Spatrick size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2707061da546Spatrick size_t size, Status &error) {
2708061da546Spatrick GetMaxMemorySize();
2709061da546Spatrick // M and m packets take 2 bytes for 1 byte of memory
2710061da546Spatrick size_t max_memory_size = m_max_memory_size / 2;
2711061da546Spatrick if (size > max_memory_size) {
2712061da546Spatrick // Keep memory read sizes down to a sane limit. This function will be
2713061da546Spatrick // called multiple times in order to complete the task by
2714061da546Spatrick // lldb_private::Process so it is ok to do this.
2715061da546Spatrick size = max_memory_size;
2716061da546Spatrick }
2717061da546Spatrick
2718061da546Spatrick StreamGDBRemote packet;
2719061da546Spatrick
2720061da546Spatrick MemoryRegionInfo region;
2721061da546Spatrick Status region_status = GetMemoryRegionInfo(addr, region);
2722061da546Spatrick
2723061da546Spatrick bool is_flash =
2724061da546Spatrick region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2725061da546Spatrick
2726061da546Spatrick if (is_flash) {
2727061da546Spatrick if (!m_allow_flash_writes) {
2728061da546Spatrick error.SetErrorString("Writing to flash memory is not allowed");
2729061da546Spatrick return 0;
2730061da546Spatrick }
2731061da546Spatrick // Keep the write within a flash memory region
2732061da546Spatrick if (addr + size > region.GetRange().GetRangeEnd())
2733061da546Spatrick size = region.GetRange().GetRangeEnd() - addr;
2734061da546Spatrick // Flash memory must be erased before it can be written
2735061da546Spatrick error = FlashErase(addr, size);
2736061da546Spatrick if (!error.Success())
2737061da546Spatrick return 0;
2738061da546Spatrick packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2739061da546Spatrick packet.PutEscapedBytes(buf, size);
2740061da546Spatrick } else {
2741061da546Spatrick packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2742061da546Spatrick packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2743061da546Spatrick endian::InlHostByteOrder());
2744061da546Spatrick }
2745061da546Spatrick StringExtractorGDBRemote response;
2746061da546Spatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2747be691f3bSpatrick GetInterruptTimeout()) ==
2748061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
2749061da546Spatrick if (response.IsOKResponse()) {
2750061da546Spatrick error.Clear();
2751061da546Spatrick return size;
2752061da546Spatrick } else if (response.IsErrorResponse())
2753061da546Spatrick error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2754061da546Spatrick addr);
2755061da546Spatrick else if (response.IsUnsupportedResponse())
2756061da546Spatrick error.SetErrorStringWithFormat(
2757061da546Spatrick "GDB server does not support writing memory");
2758061da546Spatrick else
2759061da546Spatrick error.SetErrorStringWithFormat(
2760061da546Spatrick "unexpected response to GDB server memory write packet '%s': '%s'",
2761061da546Spatrick packet.GetData(), response.GetStringRef().data());
2762061da546Spatrick } else {
2763061da546Spatrick error.SetErrorStringWithFormat("failed to send packet: '%s'",
2764061da546Spatrick packet.GetData());
2765061da546Spatrick }
2766061da546Spatrick return 0;
2767061da546Spatrick }
2768061da546Spatrick
DoAllocateMemory(size_t size,uint32_t permissions,Status & error)2769061da546Spatrick lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2770061da546Spatrick uint32_t permissions,
2771061da546Spatrick Status &error) {
2772*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions);
2773061da546Spatrick addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2774061da546Spatrick
2775061da546Spatrick if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2776061da546Spatrick allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2777061da546Spatrick if (allocated_addr != LLDB_INVALID_ADDRESS ||
2778061da546Spatrick m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2779061da546Spatrick return allocated_addr;
2780061da546Spatrick }
2781061da546Spatrick
2782061da546Spatrick if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2783061da546Spatrick // Call mmap() to create memory in the inferior..
2784061da546Spatrick unsigned prot = 0;
2785061da546Spatrick if (permissions & lldb::ePermissionsReadable)
2786061da546Spatrick prot |= eMmapProtRead;
2787061da546Spatrick if (permissions & lldb::ePermissionsWritable)
2788061da546Spatrick prot |= eMmapProtWrite;
2789061da546Spatrick if (permissions & lldb::ePermissionsExecutable)
2790061da546Spatrick prot |= eMmapProtExec;
2791061da546Spatrick
2792061da546Spatrick if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2793061da546Spatrick eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2794061da546Spatrick m_addr_to_mmap_size[allocated_addr] = size;
2795061da546Spatrick else {
2796061da546Spatrick allocated_addr = LLDB_INVALID_ADDRESS;
2797061da546Spatrick LLDB_LOGF(log,
2798061da546Spatrick "ProcessGDBRemote::%s no direct stub support for memory "
2799061da546Spatrick "allocation, and InferiorCallMmap also failed - is stub "
2800061da546Spatrick "missing register context save/restore capability?",
2801061da546Spatrick __FUNCTION__);
2802061da546Spatrick }
2803061da546Spatrick }
2804061da546Spatrick
2805061da546Spatrick if (allocated_addr == LLDB_INVALID_ADDRESS)
2806061da546Spatrick error.SetErrorStringWithFormat(
2807061da546Spatrick "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2808061da546Spatrick (uint64_t)size, GetPermissionsAsCString(permissions));
2809061da546Spatrick else
2810061da546Spatrick error.Clear();
2811061da546Spatrick return allocated_addr;
2812061da546Spatrick }
2813061da546Spatrick
DoGetMemoryRegionInfo(addr_t load_addr,MemoryRegionInfo & region_info)2814*f6aab3d8Srobert Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr,
2815061da546Spatrick MemoryRegionInfo ®ion_info) {
2816061da546Spatrick
2817061da546Spatrick Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2818061da546Spatrick return error;
2819061da546Spatrick }
2820061da546Spatrick
GetWatchpointSupportInfo(uint32_t & num)2821061da546Spatrick Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2822061da546Spatrick
2823061da546Spatrick Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
2824061da546Spatrick return error;
2825061da546Spatrick }
2826061da546Spatrick
GetWatchpointSupportInfo(uint32_t & num,bool & after)2827061da546Spatrick Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2828061da546Spatrick Status error(m_gdb_comm.GetWatchpointSupportInfo(
2829061da546Spatrick num, after, GetTarget().GetArchitecture()));
2830061da546Spatrick return error;
2831061da546Spatrick }
2832061da546Spatrick
DoDeallocateMemory(lldb::addr_t addr)2833061da546Spatrick Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2834061da546Spatrick Status error;
2835061da546Spatrick LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2836061da546Spatrick
2837061da546Spatrick switch (supported) {
2838061da546Spatrick case eLazyBoolCalculate:
2839061da546Spatrick // We should never be deallocating memory without allocating memory first
2840061da546Spatrick // so we should never get eLazyBoolCalculate
2841061da546Spatrick error.SetErrorString(
2842061da546Spatrick "tried to deallocate memory without ever allocating memory");
2843061da546Spatrick break;
2844061da546Spatrick
2845061da546Spatrick case eLazyBoolYes:
2846061da546Spatrick if (!m_gdb_comm.DeallocateMemory(addr))
2847061da546Spatrick error.SetErrorStringWithFormat(
2848061da546Spatrick "unable to deallocate memory at 0x%" PRIx64, addr);
2849061da546Spatrick break;
2850061da546Spatrick
2851061da546Spatrick case eLazyBoolNo:
2852061da546Spatrick // Call munmap() to deallocate memory in the inferior..
2853061da546Spatrick {
2854061da546Spatrick MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2855061da546Spatrick if (pos != m_addr_to_mmap_size.end() &&
2856061da546Spatrick InferiorCallMunmap(this, addr, pos->second))
2857061da546Spatrick m_addr_to_mmap_size.erase(pos);
2858061da546Spatrick else
2859061da546Spatrick error.SetErrorStringWithFormat(
2860061da546Spatrick "unable to deallocate memory at 0x%" PRIx64, addr);
2861061da546Spatrick }
2862061da546Spatrick break;
2863061da546Spatrick }
2864061da546Spatrick
2865061da546Spatrick return error;
2866061da546Spatrick }
2867061da546Spatrick
2868061da546Spatrick // Process STDIO
PutSTDIN(const char * src,size_t src_len,Status & error)2869061da546Spatrick size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2870061da546Spatrick Status &error) {
2871061da546Spatrick if (m_stdio_communication.IsConnected()) {
2872061da546Spatrick ConnectionStatus status;
2873*f6aab3d8Srobert m_stdio_communication.WriteAll(src, src_len, status, nullptr);
2874061da546Spatrick } else if (m_stdin_forward) {
2875061da546Spatrick m_gdb_comm.SendStdinNotification(src, src_len);
2876061da546Spatrick }
2877061da546Spatrick return 0;
2878061da546Spatrick }
2879061da546Spatrick
EnableBreakpointSite(BreakpointSite * bp_site)2880061da546Spatrick Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2881061da546Spatrick Status error;
2882061da546Spatrick assert(bp_site != nullptr);
2883061da546Spatrick
2884061da546Spatrick // Get logging info
2885*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Breakpoints);
2886061da546Spatrick user_id_t site_id = bp_site->GetID();
2887061da546Spatrick
2888061da546Spatrick // Get the breakpoint address
2889061da546Spatrick const addr_t addr = bp_site->GetLoadAddress();
2890061da546Spatrick
2891061da546Spatrick // Log that a breakpoint was requested
2892061da546Spatrick LLDB_LOGF(log,
2893061da546Spatrick "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2894061da546Spatrick ") address = 0x%" PRIx64,
2895061da546Spatrick site_id, (uint64_t)addr);
2896061da546Spatrick
2897061da546Spatrick // Breakpoint already exists and is enabled
2898061da546Spatrick if (bp_site->IsEnabled()) {
2899061da546Spatrick LLDB_LOGF(log,
2900061da546Spatrick "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2901061da546Spatrick ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2902061da546Spatrick site_id, (uint64_t)addr);
2903061da546Spatrick return error;
2904061da546Spatrick }
2905061da546Spatrick
2906061da546Spatrick // Get the software breakpoint trap opcode size
2907061da546Spatrick const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2908061da546Spatrick
2909061da546Spatrick // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2910061da546Spatrick // breakpoint type is supported by the remote stub. These are set to true by
2911061da546Spatrick // default, and later set to false only after we receive an unimplemented
2912061da546Spatrick // response when sending a breakpoint packet. This means initially that
2913061da546Spatrick // unless we were specifically instructed to use a hardware breakpoint, LLDB
2914061da546Spatrick // will attempt to set a software breakpoint. HardwareRequired() also queries
2915061da546Spatrick // a boolean variable which indicates if the user specifically asked for
2916061da546Spatrick // hardware breakpoints. If true then we will skip over software
2917061da546Spatrick // breakpoints.
2918061da546Spatrick if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
2919061da546Spatrick (!bp_site->HardwareRequired())) {
2920061da546Spatrick // Try to send off a software breakpoint packet ($Z0)
2921061da546Spatrick uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2922be691f3bSpatrick eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
2923061da546Spatrick if (error_no == 0) {
2924061da546Spatrick // The breakpoint was placed successfully
2925061da546Spatrick bp_site->SetEnabled(true);
2926061da546Spatrick bp_site->SetType(BreakpointSite::eExternal);
2927061da546Spatrick return error;
2928061da546Spatrick }
2929061da546Spatrick
2930061da546Spatrick // SendGDBStoppointTypePacket() will return an error if it was unable to
2931061da546Spatrick // set this breakpoint. We need to differentiate between a error specific
2932061da546Spatrick // to placing this breakpoint or if we have learned that this breakpoint
2933061da546Spatrick // type is unsupported. To do this, we must test the support boolean for
2934061da546Spatrick // this breakpoint type to see if it now indicates that this breakpoint
2935061da546Spatrick // type is unsupported. If they are still supported then we should return
2936061da546Spatrick // with the error code. If they are now unsupported, then we would like to
2937061da546Spatrick // fall through and try another form of breakpoint.
2938061da546Spatrick if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
2939061da546Spatrick if (error_no != UINT8_MAX)
2940061da546Spatrick error.SetErrorStringWithFormat(
2941dda28197Spatrick "error: %d sending the breakpoint request", error_no);
2942061da546Spatrick else
2943061da546Spatrick error.SetErrorString("error sending the breakpoint request");
2944061da546Spatrick return error;
2945061da546Spatrick }
2946061da546Spatrick
2947061da546Spatrick // We reach here when software breakpoints have been found to be
2948061da546Spatrick // unsupported. For future calls to set a breakpoint, we will not attempt
2949061da546Spatrick // to set a breakpoint with a type that is known not to be supported.
2950061da546Spatrick LLDB_LOGF(log, "Software breakpoints are unsupported");
2951061da546Spatrick
2952061da546Spatrick // So we will fall through and try a hardware breakpoint
2953061da546Spatrick }
2954061da546Spatrick
2955061da546Spatrick // The process of setting a hardware breakpoint is much the same as above.
2956061da546Spatrick // We check the supported boolean for this breakpoint type, and if it is
2957061da546Spatrick // thought to be supported then we will try to set this breakpoint with a
2958061da546Spatrick // hardware breakpoint.
2959061da546Spatrick if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
2960061da546Spatrick // Try to send off a hardware breakpoint packet ($Z1)
2961061da546Spatrick uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2962be691f3bSpatrick eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
2963061da546Spatrick if (error_no == 0) {
2964061da546Spatrick // The breakpoint was placed successfully
2965061da546Spatrick bp_site->SetEnabled(true);
2966061da546Spatrick bp_site->SetType(BreakpointSite::eHardware);
2967061da546Spatrick return error;
2968061da546Spatrick }
2969061da546Spatrick
2970061da546Spatrick // Check if the error was something other then an unsupported breakpoint
2971061da546Spatrick // type
2972061da546Spatrick if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
2973061da546Spatrick // Unable to set this hardware breakpoint
2974061da546Spatrick if (error_no != UINT8_MAX)
2975061da546Spatrick error.SetErrorStringWithFormat(
2976061da546Spatrick "error: %d sending the hardware breakpoint request "
2977061da546Spatrick "(hardware breakpoint resources might be exhausted or unavailable)",
2978061da546Spatrick error_no);
2979061da546Spatrick else
2980061da546Spatrick error.SetErrorString("error sending the hardware breakpoint request "
2981061da546Spatrick "(hardware breakpoint resources "
2982061da546Spatrick "might be exhausted or unavailable)");
2983061da546Spatrick return error;
2984061da546Spatrick }
2985061da546Spatrick
2986061da546Spatrick // We will reach here when the stub gives an unsupported response to a
2987061da546Spatrick // hardware breakpoint
2988061da546Spatrick LLDB_LOGF(log, "Hardware breakpoints are unsupported");
2989061da546Spatrick
2990061da546Spatrick // Finally we will falling through to a #trap style breakpoint
2991061da546Spatrick }
2992061da546Spatrick
2993061da546Spatrick // Don't fall through when hardware breakpoints were specifically requested
2994061da546Spatrick if (bp_site->HardwareRequired()) {
2995061da546Spatrick error.SetErrorString("hardware breakpoints are not supported");
2996061da546Spatrick return error;
2997061da546Spatrick }
2998061da546Spatrick
2999061da546Spatrick // As a last resort we want to place a manual breakpoint. An instruction is
3000061da546Spatrick // placed into the process memory using memory write packets.
3001061da546Spatrick return EnableSoftwareBreakpoint(bp_site);
3002061da546Spatrick }
3003061da546Spatrick
DisableBreakpointSite(BreakpointSite * bp_site)3004061da546Spatrick Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3005061da546Spatrick Status error;
3006061da546Spatrick assert(bp_site != nullptr);
3007061da546Spatrick addr_t addr = bp_site->GetLoadAddress();
3008061da546Spatrick user_id_t site_id = bp_site->GetID();
3009*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Breakpoints);
3010061da546Spatrick LLDB_LOGF(log,
3011061da546Spatrick "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3012061da546Spatrick ") addr = 0x%8.8" PRIx64,
3013061da546Spatrick site_id, (uint64_t)addr);
3014061da546Spatrick
3015061da546Spatrick if (bp_site->IsEnabled()) {
3016061da546Spatrick const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3017061da546Spatrick
3018061da546Spatrick BreakpointSite::Type bp_type = bp_site->GetType();
3019061da546Spatrick switch (bp_type) {
3020061da546Spatrick case BreakpointSite::eSoftware:
3021061da546Spatrick error = DisableSoftwareBreakpoint(bp_site);
3022061da546Spatrick break;
3023061da546Spatrick
3024061da546Spatrick case BreakpointSite::eHardware:
3025061da546Spatrick if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3026be691f3bSpatrick addr, bp_op_size,
3027be691f3bSpatrick GetInterruptTimeout()))
3028061da546Spatrick error.SetErrorToGenericError();
3029061da546Spatrick break;
3030061da546Spatrick
3031061da546Spatrick case BreakpointSite::eExternal: {
3032be691f3bSpatrick if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3033be691f3bSpatrick addr, bp_op_size,
3034be691f3bSpatrick GetInterruptTimeout()))
3035061da546Spatrick error.SetErrorToGenericError();
3036061da546Spatrick } break;
3037061da546Spatrick }
3038061da546Spatrick if (error.Success())
3039061da546Spatrick bp_site->SetEnabled(false);
3040061da546Spatrick } else {
3041061da546Spatrick LLDB_LOGF(log,
3042061da546Spatrick "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3043061da546Spatrick ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3044061da546Spatrick site_id, (uint64_t)addr);
3045061da546Spatrick return error;
3046061da546Spatrick }
3047061da546Spatrick
3048061da546Spatrick if (error.Success())
3049061da546Spatrick error.SetErrorToGenericError();
3050061da546Spatrick return error;
3051061da546Spatrick }
3052061da546Spatrick
3053061da546Spatrick // Pre-requisite: wp != NULL.
GetGDBStoppointType(Watchpoint * wp)3054061da546Spatrick static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3055061da546Spatrick assert(wp);
3056061da546Spatrick bool watch_read = wp->WatchpointRead();
3057061da546Spatrick bool watch_write = wp->WatchpointWrite();
3058061da546Spatrick
3059061da546Spatrick // watch_read and watch_write cannot both be false.
3060061da546Spatrick assert(watch_read || watch_write);
3061061da546Spatrick if (watch_read && watch_write)
3062061da546Spatrick return eWatchpointReadWrite;
3063061da546Spatrick else if (watch_read)
3064061da546Spatrick return eWatchpointRead;
3065061da546Spatrick else // Must be watch_write, then.
3066061da546Spatrick return eWatchpointWrite;
3067061da546Spatrick }
3068061da546Spatrick
EnableWatchpoint(Watchpoint * wp,bool notify)3069061da546Spatrick Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3070061da546Spatrick Status error;
3071061da546Spatrick if (wp) {
3072061da546Spatrick user_id_t watchID = wp->GetID();
3073061da546Spatrick addr_t addr = wp->GetLoadAddress();
3074*f6aab3d8Srobert Log *log(GetLog(GDBRLog::Watchpoints));
3075061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3076061da546Spatrick watchID);
3077061da546Spatrick if (wp->IsEnabled()) {
3078061da546Spatrick LLDB_LOGF(log,
3079061da546Spatrick "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3080061da546Spatrick ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3081061da546Spatrick watchID, (uint64_t)addr);
3082061da546Spatrick return error;
3083061da546Spatrick }
3084061da546Spatrick
3085061da546Spatrick GDBStoppointType type = GetGDBStoppointType(wp);
3086061da546Spatrick // Pass down an appropriate z/Z packet...
3087061da546Spatrick if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3088061da546Spatrick if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3089be691f3bSpatrick wp->GetByteSize(),
3090be691f3bSpatrick GetInterruptTimeout()) == 0) {
3091061da546Spatrick wp->SetEnabled(true, notify);
3092061da546Spatrick return error;
3093061da546Spatrick } else
3094061da546Spatrick error.SetErrorString("sending gdb watchpoint packet failed");
3095061da546Spatrick } else
3096061da546Spatrick error.SetErrorString("watchpoints not supported");
3097061da546Spatrick } else {
3098061da546Spatrick error.SetErrorString("Watchpoint argument was NULL.");
3099061da546Spatrick }
3100061da546Spatrick if (error.Success())
3101061da546Spatrick error.SetErrorToGenericError();
3102061da546Spatrick return error;
3103061da546Spatrick }
3104061da546Spatrick
DisableWatchpoint(Watchpoint * wp,bool notify)3105061da546Spatrick Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3106061da546Spatrick Status error;
3107061da546Spatrick if (wp) {
3108061da546Spatrick user_id_t watchID = wp->GetID();
3109061da546Spatrick
3110*f6aab3d8Srobert Log *log(GetLog(GDBRLog::Watchpoints));
3111061da546Spatrick
3112061da546Spatrick addr_t addr = wp->GetLoadAddress();
3113061da546Spatrick
3114061da546Spatrick LLDB_LOGF(log,
3115061da546Spatrick "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3116061da546Spatrick ") addr = 0x%8.8" PRIx64,
3117061da546Spatrick watchID, (uint64_t)addr);
3118061da546Spatrick
3119061da546Spatrick if (!wp->IsEnabled()) {
3120061da546Spatrick LLDB_LOGF(log,
3121061da546Spatrick "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3122061da546Spatrick ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3123061da546Spatrick watchID, (uint64_t)addr);
3124061da546Spatrick // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3125061da546Spatrick // attempt might come from the user-supplied actions, we'll route it in
3126061da546Spatrick // order for the watchpoint object to intelligently process this action.
3127061da546Spatrick wp->SetEnabled(false, notify);
3128061da546Spatrick return error;
3129061da546Spatrick }
3130061da546Spatrick
3131061da546Spatrick if (wp->IsHardware()) {
3132061da546Spatrick GDBStoppointType type = GetGDBStoppointType(wp);
3133061da546Spatrick // Pass down an appropriate z/Z packet...
3134061da546Spatrick if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3135be691f3bSpatrick wp->GetByteSize(),
3136be691f3bSpatrick GetInterruptTimeout()) == 0) {
3137061da546Spatrick wp->SetEnabled(false, notify);
3138061da546Spatrick return error;
3139061da546Spatrick } else
3140061da546Spatrick error.SetErrorString("sending gdb watchpoint packet failed");
3141061da546Spatrick }
3142061da546Spatrick // TODO: clear software watchpoints if we implement them
3143061da546Spatrick } else {
3144061da546Spatrick error.SetErrorString("Watchpoint argument was NULL.");
3145061da546Spatrick }
3146061da546Spatrick if (error.Success())
3147061da546Spatrick error.SetErrorToGenericError();
3148061da546Spatrick return error;
3149061da546Spatrick }
3150061da546Spatrick
Clear()3151061da546Spatrick void ProcessGDBRemote::Clear() {
3152061da546Spatrick m_thread_list_real.Clear();
3153061da546Spatrick m_thread_list.Clear();
3154061da546Spatrick }
3155061da546Spatrick
DoSignal(int signo)3156061da546Spatrick Status ProcessGDBRemote::DoSignal(int signo) {
3157061da546Spatrick Status error;
3158*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
3159061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3160061da546Spatrick
3161be691f3bSpatrick if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3162061da546Spatrick error.SetErrorStringWithFormat("failed to send signal %i", signo);
3163061da546Spatrick return error;
3164061da546Spatrick }
3165061da546Spatrick
3166061da546Spatrick Status
EstablishConnectionIfNeeded(const ProcessInfo & process_info)3167061da546Spatrick ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3168061da546Spatrick // Make sure we aren't already connected?
3169061da546Spatrick if (m_gdb_comm.IsConnected())
3170061da546Spatrick return Status();
3171061da546Spatrick
3172061da546Spatrick PlatformSP platform_sp(GetTarget().GetPlatform());
3173061da546Spatrick if (platform_sp && !platform_sp->IsHost())
3174061da546Spatrick return Status("Lost debug server connection");
3175061da546Spatrick
3176061da546Spatrick auto error = LaunchAndConnectToDebugserver(process_info);
3177061da546Spatrick if (error.Fail()) {
3178061da546Spatrick const char *error_string = error.AsCString();
3179061da546Spatrick if (error_string == nullptr)
3180061da546Spatrick error_string = "unable to launch " DEBUGSERVER_BASENAME;
3181061da546Spatrick }
3182061da546Spatrick return error;
3183061da546Spatrick }
3184061da546Spatrick #if !defined(_WIN32)
3185061da546Spatrick #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3186061da546Spatrick #endif
3187061da546Spatrick
3188061da546Spatrick #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
SetCloexecFlag(int fd)3189061da546Spatrick static bool SetCloexecFlag(int fd) {
3190061da546Spatrick #if defined(FD_CLOEXEC)
3191061da546Spatrick int flags = ::fcntl(fd, F_GETFD);
3192061da546Spatrick if (flags == -1)
3193061da546Spatrick return false;
3194061da546Spatrick return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3195061da546Spatrick #else
3196061da546Spatrick return false;
3197061da546Spatrick #endif
3198061da546Spatrick }
3199061da546Spatrick #endif
3200061da546Spatrick
LaunchAndConnectToDebugserver(const ProcessInfo & process_info)3201061da546Spatrick Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3202061da546Spatrick const ProcessInfo &process_info) {
3203061da546Spatrick using namespace std::placeholders; // For _1, _2, etc.
3204061da546Spatrick
3205061da546Spatrick Status error;
3206061da546Spatrick if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) {
3207061da546Spatrick // If we locate debugserver, keep that located version around
3208061da546Spatrick static FileSpec g_debugserver_file_spec;
3209061da546Spatrick
3210061da546Spatrick ProcessLaunchInfo debugserver_launch_info;
3211061da546Spatrick // Make debugserver run in its own session so signals generated by special
3212061da546Spatrick // terminal key sequences (^C) don't affect debugserver.
3213061da546Spatrick debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3214061da546Spatrick
3215061da546Spatrick const std::weak_ptr<ProcessGDBRemote> this_wp =
3216061da546Spatrick std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3217061da546Spatrick debugserver_launch_info.SetMonitorProcessCallback(
3218*f6aab3d8Srobert std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3219061da546Spatrick debugserver_launch_info.SetUserID(process_info.GetUserID());
3220061da546Spatrick
3221dda28197Spatrick #if defined(__APPLE__)
3222dda28197Spatrick // On macOS 11, we need to support x86_64 applications translated to
3223dda28197Spatrick // arm64. We check whether a binary is translated and spawn the correct
3224dda28197Spatrick // debugserver accordingly.
3225dda28197Spatrick int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3226dda28197Spatrick static_cast<int>(process_info.GetProcessID()) };
3227dda28197Spatrick struct kinfo_proc processInfo;
3228dda28197Spatrick size_t bufsize = sizeof(processInfo);
3229dda28197Spatrick if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3230dda28197Spatrick &bufsize, NULL, 0) == 0 && bufsize > 0) {
3231dda28197Spatrick if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3232dda28197Spatrick FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3233dda28197Spatrick debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3234dda28197Spatrick }
3235dda28197Spatrick }
3236dda28197Spatrick #endif
3237dda28197Spatrick
3238061da546Spatrick int communication_fd = -1;
3239061da546Spatrick #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3240061da546Spatrick // Use a socketpair on non-Windows systems for security and performance
3241061da546Spatrick // reasons.
3242061da546Spatrick int sockets[2]; /* the pair of socket descriptors */
3243061da546Spatrick if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3244061da546Spatrick error.SetErrorToErrno();
3245061da546Spatrick return error;
3246061da546Spatrick }
3247061da546Spatrick
3248061da546Spatrick int our_socket = sockets[0];
3249061da546Spatrick int gdb_socket = sockets[1];
3250061da546Spatrick auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3251061da546Spatrick auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3252061da546Spatrick
3253061da546Spatrick // Don't let any child processes inherit our communication socket
3254061da546Spatrick SetCloexecFlag(our_socket);
3255061da546Spatrick communication_fd = gdb_socket;
3256061da546Spatrick #endif
3257061da546Spatrick
3258061da546Spatrick error = m_gdb_comm.StartDebugserverProcess(
3259061da546Spatrick nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3260061da546Spatrick nullptr, nullptr, communication_fd);
3261061da546Spatrick
3262061da546Spatrick if (error.Success())
3263061da546Spatrick m_debugserver_pid = debugserver_launch_info.GetProcessID();
3264061da546Spatrick else
3265061da546Spatrick m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3266061da546Spatrick
3267061da546Spatrick if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3268061da546Spatrick #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3269061da546Spatrick // Our process spawned correctly, we can now set our connection to use
3270061da546Spatrick // our end of the socket pair
3271061da546Spatrick cleanup_our.release();
3272dda28197Spatrick m_gdb_comm.SetConnection(
3273dda28197Spatrick std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3274061da546Spatrick #endif
3275061da546Spatrick StartAsyncThread();
3276061da546Spatrick }
3277061da546Spatrick
3278061da546Spatrick if (error.Fail()) {
3279*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
3280061da546Spatrick
3281061da546Spatrick LLDB_LOGF(log, "failed to start debugserver process: %s",
3282061da546Spatrick error.AsCString());
3283061da546Spatrick return error;
3284061da546Spatrick }
3285061da546Spatrick
3286061da546Spatrick if (m_gdb_comm.IsConnected()) {
3287061da546Spatrick // Finish the connection process by doing the handshake without
3288061da546Spatrick // connecting (send NULL URL)
3289061da546Spatrick error = ConnectToDebugserver("");
3290061da546Spatrick } else {
3291061da546Spatrick error.SetErrorString("connection failed");
3292061da546Spatrick }
3293061da546Spatrick }
3294061da546Spatrick return error;
3295061da546Spatrick }
3296061da546Spatrick
MonitorDebugserverProcess(std::weak_ptr<ProcessGDBRemote> process_wp,lldb::pid_t debugserver_pid,int signo,int exit_status)3297*f6aab3d8Srobert void ProcessGDBRemote::MonitorDebugserverProcess(
3298061da546Spatrick std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3299061da546Spatrick int signo, // Zero for no signal
3300061da546Spatrick int exit_status // Exit value of process if signal is zero
3301061da546Spatrick ) {
3302061da546Spatrick // "debugserver_pid" argument passed in is the process ID for debugserver
3303061da546Spatrick // that we are tracking...
3304*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
3305061da546Spatrick
3306061da546Spatrick LLDB_LOGF(log,
3307061da546Spatrick "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3308061da546Spatrick ", signo=%i (0x%x), exit_status=%i)",
3309061da546Spatrick __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3310061da546Spatrick
3311061da546Spatrick std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3312061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3313061da546Spatrick static_cast<void *>(process_sp.get()));
3314061da546Spatrick if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3315*f6aab3d8Srobert return;
3316061da546Spatrick
3317061da546Spatrick // Sleep for a half a second to make sure our inferior process has time to
3318061da546Spatrick // set its exit status before we set it incorrectly when both the debugserver
3319061da546Spatrick // and the inferior process shut down.
3320061da546Spatrick std::this_thread::sleep_for(std::chrono::milliseconds(500));
3321061da546Spatrick
3322061da546Spatrick // If our process hasn't yet exited, debugserver might have died. If the
3323061da546Spatrick // process did exit, then we are reaping it.
3324061da546Spatrick const StateType state = process_sp->GetState();
3325061da546Spatrick
3326061da546Spatrick if (state != eStateInvalid && state != eStateUnloaded &&
3327061da546Spatrick state != eStateExited && state != eStateDetached) {
3328061da546Spatrick char error_str[1024];
3329061da546Spatrick if (signo) {
3330061da546Spatrick const char *signal_cstr =
3331061da546Spatrick process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3332061da546Spatrick if (signal_cstr)
3333061da546Spatrick ::snprintf(error_str, sizeof(error_str),
3334061da546Spatrick DEBUGSERVER_BASENAME " died with signal %s", signal_cstr);
3335061da546Spatrick else
3336061da546Spatrick ::snprintf(error_str, sizeof(error_str),
3337061da546Spatrick DEBUGSERVER_BASENAME " died with signal %i", signo);
3338061da546Spatrick } else {
3339061da546Spatrick ::snprintf(error_str, sizeof(error_str),
3340061da546Spatrick DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x",
3341061da546Spatrick exit_status);
3342061da546Spatrick }
3343061da546Spatrick
3344061da546Spatrick process_sp->SetExitStatus(-1, error_str);
3345061da546Spatrick }
3346061da546Spatrick // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3347061da546Spatrick // longer has a debugserver instance
3348061da546Spatrick process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3349061da546Spatrick }
3350061da546Spatrick
KillDebugserverProcess()3351061da546Spatrick void ProcessGDBRemote::KillDebugserverProcess() {
3352061da546Spatrick m_gdb_comm.Disconnect();
3353061da546Spatrick if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) {
3354061da546Spatrick Host::Kill(m_debugserver_pid, SIGINT);
3355061da546Spatrick m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3356061da546Spatrick }
3357061da546Spatrick }
3358061da546Spatrick
Initialize()3359061da546Spatrick void ProcessGDBRemote::Initialize() {
3360061da546Spatrick static llvm::once_flag g_once_flag;
3361061da546Spatrick
3362061da546Spatrick llvm::call_once(g_once_flag, []() {
3363061da546Spatrick PluginManager::RegisterPlugin(GetPluginNameStatic(),
3364061da546Spatrick GetPluginDescriptionStatic(), CreateInstance,
3365061da546Spatrick DebuggerInitialize);
3366061da546Spatrick });
3367061da546Spatrick }
3368061da546Spatrick
DebuggerInitialize(Debugger & debugger)3369061da546Spatrick void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3370061da546Spatrick if (!PluginManager::GetSettingForProcessPlugin(
3371061da546Spatrick debugger, PluginProperties::GetSettingName())) {
3372061da546Spatrick const bool is_global_setting = true;
3373061da546Spatrick PluginManager::CreateSettingForProcessPlugin(
3374*f6aab3d8Srobert debugger, GetGlobalPluginProperties().GetValueProperties(),
3375061da546Spatrick ConstString("Properties for the gdb-remote process plug-in."),
3376061da546Spatrick is_global_setting);
3377061da546Spatrick }
3378061da546Spatrick }
3379061da546Spatrick
StartAsyncThread()3380061da546Spatrick bool ProcessGDBRemote::StartAsyncThread() {
3381*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
3382061da546Spatrick
3383061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3384061da546Spatrick
3385061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3386061da546Spatrick if (!m_async_thread.IsJoinable()) {
3387061da546Spatrick // Create a thread that watches our internal state and controls which
3388061da546Spatrick // events make it to clients (into the DCProcess event queue).
3389061da546Spatrick
3390*f6aab3d8Srobert llvm::Expected<HostThread> async_thread =
3391*f6aab3d8Srobert ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3392*f6aab3d8Srobert return ProcessGDBRemote::AsyncThread();
3393*f6aab3d8Srobert });
3394061da546Spatrick if (!async_thread) {
3395*f6aab3d8Srobert LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3396061da546Spatrick "failed to launch host thread: {}");
3397061da546Spatrick return false;
3398061da546Spatrick }
3399061da546Spatrick m_async_thread = *async_thread;
3400061da546Spatrick } else
3401061da546Spatrick LLDB_LOGF(log,
3402061da546Spatrick "ProcessGDBRemote::%s () - Called when Async thread was "
3403061da546Spatrick "already running.",
3404061da546Spatrick __FUNCTION__);
3405061da546Spatrick
3406061da546Spatrick return m_async_thread.IsJoinable();
3407061da546Spatrick }
3408061da546Spatrick
StopAsyncThread()3409061da546Spatrick void ProcessGDBRemote::StopAsyncThread() {
3410*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
3411061da546Spatrick
3412061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3413061da546Spatrick
3414061da546Spatrick std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3415061da546Spatrick if (m_async_thread.IsJoinable()) {
3416061da546Spatrick m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3417061da546Spatrick
3418061da546Spatrick // This will shut down the async thread.
3419061da546Spatrick m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3420061da546Spatrick
3421061da546Spatrick // Stop the stdio thread
3422061da546Spatrick m_async_thread.Join(nullptr);
3423061da546Spatrick m_async_thread.Reset();
3424061da546Spatrick } else
3425061da546Spatrick LLDB_LOGF(
3426061da546Spatrick log,
3427061da546Spatrick "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3428061da546Spatrick __FUNCTION__);
3429061da546Spatrick }
3430061da546Spatrick
AsyncThread()3431*f6aab3d8Srobert thread_result_t ProcessGDBRemote::AsyncThread() {
3432*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
3433*f6aab3d8Srobert LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3434*f6aab3d8Srobert __FUNCTION__, GetID());
3435061da546Spatrick
3436061da546Spatrick EventSP event_sp;
3437be691f3bSpatrick
3438be691f3bSpatrick // We need to ignore any packets that come in after we have
3439be691f3bSpatrick // have decided the process has exited. There are some
3440be691f3bSpatrick // situations, for instance when we try to interrupt a running
3441be691f3bSpatrick // process and the interrupt fails, where another packet might
3442be691f3bSpatrick // get delivered after we've decided to give up on the process.
3443be691f3bSpatrick // But once we've decided we are done with the process we will
3444be691f3bSpatrick // not be in a state to do anything useful with new packets.
3445be691f3bSpatrick // So it is safer to simply ignore any remaining packets by
3446be691f3bSpatrick // explicitly checking for eStateExited before reentering the
3447be691f3bSpatrick // fetch loop.
3448be691f3bSpatrick
3449061da546Spatrick bool done = false;
3450*f6aab3d8Srobert while (!done && GetPrivateState() != eStateExited) {
3451061da546Spatrick LLDB_LOGF(log,
3452*f6aab3d8Srobert "ProcessGDBRemote::%s(pid = %" PRIu64
3453061da546Spatrick ") listener.WaitForEvent (NULL, event_sp)...",
3454*f6aab3d8Srobert __FUNCTION__, GetID());
3455be691f3bSpatrick
3456*f6aab3d8Srobert if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
3457061da546Spatrick const uint32_t event_type = event_sp->GetType();
3458*f6aab3d8Srobert if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3459061da546Spatrick LLDB_LOGF(log,
3460*f6aab3d8Srobert "ProcessGDBRemote::%s(pid = %" PRIu64
3461061da546Spatrick ") Got an event of type: %d...",
3462*f6aab3d8Srobert __FUNCTION__, GetID(), event_type);
3463061da546Spatrick
3464061da546Spatrick switch (event_type) {
3465061da546Spatrick case eBroadcastBitAsyncContinue: {
3466061da546Spatrick const EventDataBytes *continue_packet =
3467061da546Spatrick EventDataBytes::GetEventDataFromEvent(event_sp.get());
3468061da546Spatrick
3469061da546Spatrick if (continue_packet) {
3470061da546Spatrick const char *continue_cstr =
3471061da546Spatrick (const char *)continue_packet->GetBytes();
3472061da546Spatrick const size_t continue_cstr_len = continue_packet->GetByteSize();
3473061da546Spatrick LLDB_LOGF(log,
3474*f6aab3d8Srobert "ProcessGDBRemote::%s(pid = %" PRIu64
3475061da546Spatrick ") got eBroadcastBitAsyncContinue: %s",
3476*f6aab3d8Srobert __FUNCTION__, GetID(), continue_cstr);
3477061da546Spatrick
3478061da546Spatrick if (::strstr(continue_cstr, "vAttach") == nullptr)
3479*f6aab3d8Srobert SetPrivateState(eStateRunning);
3480061da546Spatrick StringExtractorGDBRemote response;
3481061da546Spatrick
3482061da546Spatrick StateType stop_state =
3483*f6aab3d8Srobert GetGDBRemote().SendContinuePacketAndWaitForResponse(
3484*f6aab3d8Srobert *this, *GetUnixSignals(),
3485061da546Spatrick llvm::StringRef(continue_cstr, continue_cstr_len),
3486*f6aab3d8Srobert GetInterruptTimeout(), response);
3487061da546Spatrick
3488061da546Spatrick // We need to immediately clear the thread ID list so we are sure
3489061da546Spatrick // to get a valid list of threads. The thread ID list might be
3490061da546Spatrick // contained within the "response", or the stop reply packet that
3491061da546Spatrick // caused the stop. So clear it now before we give the stop reply
3492061da546Spatrick // packet to the process using the
3493*f6aab3d8Srobert // SetLastStopPacket()...
3494*f6aab3d8Srobert ClearThreadIDList();
3495061da546Spatrick
3496061da546Spatrick switch (stop_state) {
3497061da546Spatrick case eStateStopped:
3498061da546Spatrick case eStateCrashed:
3499061da546Spatrick case eStateSuspended:
3500*f6aab3d8Srobert SetLastStopPacket(response);
3501*f6aab3d8Srobert SetPrivateState(stop_state);
3502061da546Spatrick break;
3503061da546Spatrick
3504061da546Spatrick case eStateExited: {
3505*f6aab3d8Srobert SetLastStopPacket(response);
3506*f6aab3d8Srobert ClearThreadIDList();
3507061da546Spatrick response.SetFilePos(1);
3508061da546Spatrick
3509061da546Spatrick int exit_status = response.GetHexU8();
3510061da546Spatrick std::string desc_string;
3511*f6aab3d8Srobert if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3512061da546Spatrick llvm::StringRef desc_str;
3513061da546Spatrick llvm::StringRef desc_token;
3514061da546Spatrick while (response.GetNameColonValue(desc_token, desc_str)) {
3515061da546Spatrick if (desc_token != "description")
3516061da546Spatrick continue;
3517061da546Spatrick StringExtractor extractor(desc_str);
3518061da546Spatrick extractor.GetHexByteString(desc_string);
3519061da546Spatrick }
3520061da546Spatrick }
3521*f6aab3d8Srobert SetExitStatus(exit_status, desc_string.c_str());
3522061da546Spatrick done = true;
3523061da546Spatrick break;
3524061da546Spatrick }
3525061da546Spatrick case eStateInvalid: {
3526061da546Spatrick // Check to see if we were trying to attach and if we got back
3527061da546Spatrick // the "E87" error code from debugserver -- this indicates that
3528061da546Spatrick // the process is not debuggable. Return a slightly more
3529061da546Spatrick // helpful error message about why the attach failed.
3530061da546Spatrick if (::strstr(continue_cstr, "vAttach") != nullptr &&
3531061da546Spatrick response.GetError() == 0x87) {
3532*f6aab3d8Srobert SetExitStatus(-1, "cannot attach to process due to "
3533061da546Spatrick "System Integrity Protection");
3534061da546Spatrick } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3535061da546Spatrick response.GetStatus().Fail()) {
3536*f6aab3d8Srobert SetExitStatus(-1, response.GetStatus().AsCString());
3537061da546Spatrick } else {
3538*f6aab3d8Srobert SetExitStatus(-1, "lost connection");
3539061da546Spatrick }
3540be691f3bSpatrick done = true;
3541061da546Spatrick break;
3542061da546Spatrick }
3543061da546Spatrick
3544061da546Spatrick default:
3545*f6aab3d8Srobert SetPrivateState(stop_state);
3546061da546Spatrick break;
3547061da546Spatrick } // switch(stop_state)
3548061da546Spatrick } // if (continue_packet)
3549dda28197Spatrick } // case eBroadcastBitAsyncContinue
3550061da546Spatrick break;
3551061da546Spatrick
3552061da546Spatrick case eBroadcastBitAsyncThreadShouldExit:
3553061da546Spatrick LLDB_LOGF(log,
3554*f6aab3d8Srobert "ProcessGDBRemote::%s(pid = %" PRIu64
3555061da546Spatrick ") got eBroadcastBitAsyncThreadShouldExit...",
3556*f6aab3d8Srobert __FUNCTION__, GetID());
3557061da546Spatrick done = true;
3558061da546Spatrick break;
3559061da546Spatrick
3560061da546Spatrick default:
3561061da546Spatrick LLDB_LOGF(log,
3562*f6aab3d8Srobert "ProcessGDBRemote::%s(pid = %" PRIu64
3563061da546Spatrick ") got unknown event 0x%8.8x",
3564*f6aab3d8Srobert __FUNCTION__, GetID(), event_type);
3565061da546Spatrick done = true;
3566061da546Spatrick break;
3567061da546Spatrick }
3568061da546Spatrick }
3569061da546Spatrick } else {
3570061da546Spatrick LLDB_LOGF(log,
3571*f6aab3d8Srobert "ProcessGDBRemote::%s(pid = %" PRIu64
3572061da546Spatrick ") listener.WaitForEvent (NULL, event_sp) => false",
3573*f6aab3d8Srobert __FUNCTION__, GetID());
3574061da546Spatrick done = true;
3575061da546Spatrick }
3576061da546Spatrick }
3577061da546Spatrick
3578*f6aab3d8Srobert LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
3579*f6aab3d8Srobert __FUNCTION__, GetID());
3580061da546Spatrick
3581061da546Spatrick return {};
3582061da546Spatrick }
3583061da546Spatrick
3584061da546Spatrick // uint32_t
3585061da546Spatrick // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3586061da546Spatrick // &matches, std::vector<lldb::pid_t> &pids)
3587061da546Spatrick //{
3588061da546Spatrick // // If we are planning to launch the debugserver remotely, then we need to
3589061da546Spatrick // fire up a debugserver
3590061da546Spatrick // // process and ask it for the list of processes. But if we are local, we
3591061da546Spatrick // can let the Host do it.
3592061da546Spatrick // if (m_local_debugserver)
3593061da546Spatrick // {
3594061da546Spatrick // return Host::ListProcessesMatchingName (name, matches, pids);
3595061da546Spatrick // }
3596061da546Spatrick // else
3597061da546Spatrick // {
3598061da546Spatrick // // FIXME: Implement talking to the remote debugserver.
3599061da546Spatrick // return 0;
3600061da546Spatrick // }
3601061da546Spatrick //
3602061da546Spatrick //}
3603061da546Spatrick //
NewThreadNotifyBreakpointHit(void * baton,StoppointCallbackContext * context,lldb::user_id_t break_id,lldb::user_id_t break_loc_id)3604061da546Spatrick bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3605061da546Spatrick void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3606061da546Spatrick lldb::user_id_t break_loc_id) {
3607061da546Spatrick // I don't think I have to do anything here, just make sure I notice the new
3608061da546Spatrick // thread when it starts to
3609061da546Spatrick // run so I can stop it if that's what I want to do.
3610*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Step);
3611061da546Spatrick LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3612061da546Spatrick return false;
3613061da546Spatrick }
3614061da546Spatrick
UpdateAutomaticSignalFiltering()3615061da546Spatrick Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3616*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
3617061da546Spatrick LLDB_LOG(log, "Check if need to update ignored signals");
3618061da546Spatrick
3619061da546Spatrick // QPassSignals package is not supported by the server, there is no way we
3620061da546Spatrick // can ignore any signals on server side.
3621061da546Spatrick if (!m_gdb_comm.GetQPassSignalsSupported())
3622061da546Spatrick return Status();
3623061da546Spatrick
3624061da546Spatrick // No signals, nothing to send.
3625061da546Spatrick if (m_unix_signals_sp == nullptr)
3626061da546Spatrick return Status();
3627061da546Spatrick
3628061da546Spatrick // Signals' version hasn't changed, no need to send anything.
3629061da546Spatrick uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3630061da546Spatrick if (new_signals_version == m_last_signals_version) {
3631061da546Spatrick LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3632061da546Spatrick m_last_signals_version);
3633061da546Spatrick return Status();
3634061da546Spatrick }
3635061da546Spatrick
3636061da546Spatrick auto signals_to_ignore =
3637061da546Spatrick m_unix_signals_sp->GetFilteredSignals(false, false, false);
3638061da546Spatrick Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3639061da546Spatrick
3640061da546Spatrick LLDB_LOG(log,
3641061da546Spatrick "Signals' version changed. old version={0}, new version={1}, "
3642061da546Spatrick "signals ignored={2}, update result={3}",
3643061da546Spatrick m_last_signals_version, new_signals_version,
3644061da546Spatrick signals_to_ignore.size(), error);
3645061da546Spatrick
3646061da546Spatrick if (error.Success())
3647061da546Spatrick m_last_signals_version = new_signals_version;
3648061da546Spatrick
3649061da546Spatrick return error;
3650061da546Spatrick }
3651061da546Spatrick
StartNoticingNewThreads()3652061da546Spatrick bool ProcessGDBRemote::StartNoticingNewThreads() {
3653*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Step);
3654061da546Spatrick if (m_thread_create_bp_sp) {
3655061da546Spatrick if (log && log->GetVerbose())
3656061da546Spatrick LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3657061da546Spatrick m_thread_create_bp_sp->SetEnabled(true);
3658061da546Spatrick } else {
3659061da546Spatrick PlatformSP platform_sp(GetTarget().GetPlatform());
3660061da546Spatrick if (platform_sp) {
3661061da546Spatrick m_thread_create_bp_sp =
3662061da546Spatrick platform_sp->SetThreadCreationBreakpoint(GetTarget());
3663061da546Spatrick if (m_thread_create_bp_sp) {
3664061da546Spatrick if (log && log->GetVerbose())
3665061da546Spatrick LLDB_LOGF(
3666061da546Spatrick log, "Successfully created new thread notification breakpoint %i",
3667061da546Spatrick m_thread_create_bp_sp->GetID());
3668061da546Spatrick m_thread_create_bp_sp->SetCallback(
3669061da546Spatrick ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3670061da546Spatrick } else {
3671061da546Spatrick LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3672061da546Spatrick }
3673061da546Spatrick }
3674061da546Spatrick }
3675061da546Spatrick return m_thread_create_bp_sp.get() != nullptr;
3676061da546Spatrick }
3677061da546Spatrick
StopNoticingNewThreads()3678061da546Spatrick bool ProcessGDBRemote::StopNoticingNewThreads() {
3679*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Step);
3680061da546Spatrick if (log && log->GetVerbose())
3681061da546Spatrick LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3682061da546Spatrick
3683061da546Spatrick if (m_thread_create_bp_sp)
3684061da546Spatrick m_thread_create_bp_sp->SetEnabled(false);
3685061da546Spatrick
3686061da546Spatrick return true;
3687061da546Spatrick }
3688061da546Spatrick
GetDynamicLoader()3689061da546Spatrick DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3690061da546Spatrick if (m_dyld_up.get() == nullptr)
3691*f6aab3d8Srobert m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3692061da546Spatrick return m_dyld_up.get();
3693061da546Spatrick }
3694061da546Spatrick
SendEventData(const char * data)3695061da546Spatrick Status ProcessGDBRemote::SendEventData(const char *data) {
3696061da546Spatrick int return_value;
3697061da546Spatrick bool was_supported;
3698061da546Spatrick
3699061da546Spatrick Status error;
3700061da546Spatrick
3701061da546Spatrick return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3702061da546Spatrick if (return_value != 0) {
3703061da546Spatrick if (!was_supported)
3704061da546Spatrick error.SetErrorString("Sending events is not supported for this process.");
3705061da546Spatrick else
3706061da546Spatrick error.SetErrorStringWithFormat("Error sending event data: %d.",
3707061da546Spatrick return_value);
3708061da546Spatrick }
3709061da546Spatrick return error;
3710061da546Spatrick }
3711061da546Spatrick
GetAuxvData()3712061da546Spatrick DataExtractor ProcessGDBRemote::GetAuxvData() {
3713061da546Spatrick DataBufferSP buf;
3714061da546Spatrick if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3715*f6aab3d8Srobert llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3716*f6aab3d8Srobert if (response)
3717*f6aab3d8Srobert buf = std::make_shared<DataBufferHeap>(response->c_str(),
3718*f6aab3d8Srobert response->length());
3719*f6aab3d8Srobert else
3720*f6aab3d8Srobert LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
3721061da546Spatrick }
3722061da546Spatrick return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3723061da546Spatrick }
3724061da546Spatrick
3725061da546Spatrick StructuredData::ObjectSP
GetExtendedInfoForThread(lldb::tid_t tid)3726061da546Spatrick ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3727061da546Spatrick StructuredData::ObjectSP object_sp;
3728061da546Spatrick
3729061da546Spatrick if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3730061da546Spatrick StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3731061da546Spatrick SystemRuntime *runtime = GetSystemRuntime();
3732061da546Spatrick if (runtime) {
3733061da546Spatrick runtime->AddThreadExtendedInfoPacketHints(args_dict);
3734061da546Spatrick }
3735061da546Spatrick args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3736061da546Spatrick
3737061da546Spatrick StreamString packet;
3738061da546Spatrick packet << "jThreadExtendedInfo:";
3739061da546Spatrick args_dict->Dump(packet, false);
3740061da546Spatrick
3741061da546Spatrick // FIXME the final character of a JSON dictionary, '}', is the escape
3742061da546Spatrick // character in gdb-remote binary mode. lldb currently doesn't escape
3743061da546Spatrick // these characters in its packet output -- so we add the quoted version of
3744061da546Spatrick // the } character here manually in case we talk to a debugserver which un-
3745061da546Spatrick // escapes the characters at packet read time.
3746061da546Spatrick packet << (char)(0x7d ^ 0x20);
3747061da546Spatrick
3748061da546Spatrick StringExtractorGDBRemote response;
3749061da546Spatrick response.SetResponseValidatorToJSON();
3750be691f3bSpatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3751061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
3752061da546Spatrick StringExtractorGDBRemote::ResponseType response_type =
3753061da546Spatrick response.GetResponseType();
3754061da546Spatrick if (response_type == StringExtractorGDBRemote::eResponse) {
3755061da546Spatrick if (!response.Empty()) {
3756dda28197Spatrick object_sp =
3757dda28197Spatrick StructuredData::ParseJSON(std::string(response.GetStringRef()));
3758061da546Spatrick }
3759061da546Spatrick }
3760061da546Spatrick }
3761061da546Spatrick }
3762061da546Spatrick return object_sp;
3763061da546Spatrick }
3764061da546Spatrick
GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,lldb::addr_t image_count)3765061da546Spatrick StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3766061da546Spatrick lldb::addr_t image_list_address, lldb::addr_t image_count) {
3767061da546Spatrick
3768061da546Spatrick StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3769061da546Spatrick args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3770061da546Spatrick image_list_address);
3771061da546Spatrick args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3772061da546Spatrick
3773061da546Spatrick return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3774061da546Spatrick }
3775061da546Spatrick
GetLoadedDynamicLibrariesInfos()3776061da546Spatrick StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3777061da546Spatrick StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3778061da546Spatrick
3779061da546Spatrick args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3780061da546Spatrick
3781061da546Spatrick return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3782061da546Spatrick }
3783061da546Spatrick
GetLoadedDynamicLibrariesInfos(const std::vector<lldb::addr_t> & load_addresses)3784061da546Spatrick StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3785061da546Spatrick const std::vector<lldb::addr_t> &load_addresses) {
3786061da546Spatrick StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3787061da546Spatrick StructuredData::ArraySP addresses(new StructuredData::Array);
3788061da546Spatrick
3789061da546Spatrick for (auto addr : load_addresses) {
3790061da546Spatrick StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3791061da546Spatrick addresses->AddItem(addr_sp);
3792061da546Spatrick }
3793061da546Spatrick
3794061da546Spatrick args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3795061da546Spatrick
3796061da546Spatrick return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3797061da546Spatrick }
3798061da546Spatrick
3799061da546Spatrick StructuredData::ObjectSP
GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args_dict)3800061da546Spatrick ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3801061da546Spatrick StructuredData::ObjectSP args_dict) {
3802061da546Spatrick StructuredData::ObjectSP object_sp;
3803061da546Spatrick
3804061da546Spatrick if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3805061da546Spatrick // Scope for the scoped timeout object
3806061da546Spatrick GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3807061da546Spatrick std::chrono::seconds(10));
3808061da546Spatrick
3809061da546Spatrick StreamString packet;
3810061da546Spatrick packet << "jGetLoadedDynamicLibrariesInfos:";
3811061da546Spatrick args_dict->Dump(packet, false);
3812061da546Spatrick
3813061da546Spatrick // FIXME the final character of a JSON dictionary, '}', is the escape
3814061da546Spatrick // character in gdb-remote binary mode. lldb currently doesn't escape
3815061da546Spatrick // these characters in its packet output -- so we add the quoted version of
3816061da546Spatrick // the } character here manually in case we talk to a debugserver which un-
3817061da546Spatrick // escapes the characters at packet read time.
3818061da546Spatrick packet << (char)(0x7d ^ 0x20);
3819061da546Spatrick
3820061da546Spatrick StringExtractorGDBRemote response;
3821061da546Spatrick response.SetResponseValidatorToJSON();
3822be691f3bSpatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3823061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
3824061da546Spatrick StringExtractorGDBRemote::ResponseType response_type =
3825061da546Spatrick response.GetResponseType();
3826061da546Spatrick if (response_type == StringExtractorGDBRemote::eResponse) {
3827061da546Spatrick if (!response.Empty()) {
3828dda28197Spatrick object_sp =
3829dda28197Spatrick StructuredData::ParseJSON(std::string(response.GetStringRef()));
3830061da546Spatrick }
3831061da546Spatrick }
3832061da546Spatrick }
3833061da546Spatrick }
3834061da546Spatrick return object_sp;
3835061da546Spatrick }
3836061da546Spatrick
GetDynamicLoaderProcessState()3837*f6aab3d8Srobert StructuredData::ObjectSP ProcessGDBRemote::GetDynamicLoaderProcessState() {
3838*f6aab3d8Srobert StructuredData::ObjectSP object_sp;
3839*f6aab3d8Srobert StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3840*f6aab3d8Srobert
3841*f6aab3d8Srobert if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
3842*f6aab3d8Srobert StringExtractorGDBRemote response;
3843*f6aab3d8Srobert response.SetResponseValidatorToJSON();
3844*f6aab3d8Srobert if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
3845*f6aab3d8Srobert response) ==
3846*f6aab3d8Srobert GDBRemoteCommunication::PacketResult::Success) {
3847*f6aab3d8Srobert StringExtractorGDBRemote::ResponseType response_type =
3848*f6aab3d8Srobert response.GetResponseType();
3849*f6aab3d8Srobert if (response_type == StringExtractorGDBRemote::eResponse) {
3850*f6aab3d8Srobert if (!response.Empty()) {
3851*f6aab3d8Srobert object_sp =
3852*f6aab3d8Srobert StructuredData::ParseJSON(std::string(response.GetStringRef()));
3853*f6aab3d8Srobert }
3854*f6aab3d8Srobert }
3855*f6aab3d8Srobert }
3856*f6aab3d8Srobert }
3857*f6aab3d8Srobert return object_sp;
3858*f6aab3d8Srobert }
3859*f6aab3d8Srobert
GetSharedCacheInfo()3860061da546Spatrick StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3861061da546Spatrick StructuredData::ObjectSP object_sp;
3862061da546Spatrick StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3863061da546Spatrick
3864061da546Spatrick if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3865061da546Spatrick StreamString packet;
3866061da546Spatrick packet << "jGetSharedCacheInfo:";
3867061da546Spatrick args_dict->Dump(packet, false);
3868061da546Spatrick
3869061da546Spatrick // FIXME the final character of a JSON dictionary, '}', is the escape
3870061da546Spatrick // character in gdb-remote binary mode. lldb currently doesn't escape
3871061da546Spatrick // these characters in its packet output -- so we add the quoted version of
3872061da546Spatrick // the } character here manually in case we talk to a debugserver which un-
3873061da546Spatrick // escapes the characters at packet read time.
3874061da546Spatrick packet << (char)(0x7d ^ 0x20);
3875061da546Spatrick
3876061da546Spatrick StringExtractorGDBRemote response;
3877061da546Spatrick response.SetResponseValidatorToJSON();
3878be691f3bSpatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3879061da546Spatrick GDBRemoteCommunication::PacketResult::Success) {
3880061da546Spatrick StringExtractorGDBRemote::ResponseType response_type =
3881061da546Spatrick response.GetResponseType();
3882061da546Spatrick if (response_type == StringExtractorGDBRemote::eResponse) {
3883061da546Spatrick if (!response.Empty()) {
3884dda28197Spatrick object_sp =
3885dda28197Spatrick StructuredData::ParseJSON(std::string(response.GetStringRef()));
3886061da546Spatrick }
3887061da546Spatrick }
3888061da546Spatrick }
3889061da546Spatrick }
3890061da546Spatrick return object_sp;
3891061da546Spatrick }
3892061da546Spatrick
ConfigureStructuredData(ConstString type_name,const StructuredData::ObjectSP & config_sp)3893061da546Spatrick Status ProcessGDBRemote::ConfigureStructuredData(
3894061da546Spatrick ConstString type_name, const StructuredData::ObjectSP &config_sp) {
3895061da546Spatrick return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3896061da546Spatrick }
3897061da546Spatrick
3898061da546Spatrick // Establish the largest memory read/write payloads we should use. If the
3899061da546Spatrick // remote stub has a max packet size, stay under that size.
3900061da546Spatrick //
3901061da546Spatrick // If the remote stub's max packet size is crazy large, use a reasonable
3902061da546Spatrick // largeish default.
3903061da546Spatrick //
3904061da546Spatrick // If the remote stub doesn't advertise a max packet size, use a conservative
3905061da546Spatrick // default.
3906061da546Spatrick
GetMaxMemorySize()3907061da546Spatrick void ProcessGDBRemote::GetMaxMemorySize() {
3908061da546Spatrick const uint64_t reasonable_largeish_default = 128 * 1024;
3909061da546Spatrick const uint64_t conservative_default = 512;
3910061da546Spatrick
3911061da546Spatrick if (m_max_memory_size == 0) {
3912061da546Spatrick uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3913061da546Spatrick if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
3914061da546Spatrick // Save the stub's claimed maximum packet size
3915061da546Spatrick m_remote_stub_max_memory_size = stub_max_size;
3916061da546Spatrick
3917061da546Spatrick // Even if the stub says it can support ginormous packets, don't exceed
3918061da546Spatrick // our reasonable largeish default packet size.
3919061da546Spatrick if (stub_max_size > reasonable_largeish_default) {
3920061da546Spatrick stub_max_size = reasonable_largeish_default;
3921061da546Spatrick }
3922061da546Spatrick
3923061da546Spatrick // Memory packet have other overheads too like Maddr,size:#NN Instead of
3924061da546Spatrick // calculating the bytes taken by size and addr every time, we take a
3925061da546Spatrick // maximum guess here.
3926061da546Spatrick if (stub_max_size > 70)
3927061da546Spatrick stub_max_size -= 32 + 32 + 6;
3928061da546Spatrick else {
3929061da546Spatrick // In unlikely scenario that max packet size is less then 70, we will
3930061da546Spatrick // hope that data being written is small enough to fit.
3931*f6aab3d8Srobert Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory));
3932061da546Spatrick if (log)
3933061da546Spatrick log->Warning("Packet size is too small. "
3934061da546Spatrick "LLDB may face problems while writing memory");
3935061da546Spatrick }
3936061da546Spatrick
3937061da546Spatrick m_max_memory_size = stub_max_size;
3938061da546Spatrick } else {
3939061da546Spatrick m_max_memory_size = conservative_default;
3940061da546Spatrick }
3941061da546Spatrick }
3942061da546Spatrick }
3943061da546Spatrick
SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max)3944061da546Spatrick void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
3945061da546Spatrick uint64_t user_specified_max) {
3946061da546Spatrick if (user_specified_max != 0) {
3947061da546Spatrick GetMaxMemorySize();
3948061da546Spatrick
3949061da546Spatrick if (m_remote_stub_max_memory_size != 0) {
3950061da546Spatrick if (m_remote_stub_max_memory_size < user_specified_max) {
3951061da546Spatrick m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
3952061da546Spatrick // packet size too
3953061da546Spatrick // big, go as big
3954061da546Spatrick // as the remote stub says we can go.
3955061da546Spatrick } else {
3956061da546Spatrick m_max_memory_size = user_specified_max; // user's packet size is good
3957061da546Spatrick }
3958061da546Spatrick } else {
3959061da546Spatrick m_max_memory_size =
3960061da546Spatrick user_specified_max; // user's packet size is probably fine
3961061da546Spatrick }
3962061da546Spatrick }
3963061da546Spatrick }
3964061da546Spatrick
GetModuleSpec(const FileSpec & module_file_spec,const ArchSpec & arch,ModuleSpec & module_spec)3965061da546Spatrick bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
3966061da546Spatrick const ArchSpec &arch,
3967061da546Spatrick ModuleSpec &module_spec) {
3968*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Platform);
3969061da546Spatrick
3970061da546Spatrick const ModuleCacheKey key(module_file_spec.GetPath(),
3971061da546Spatrick arch.GetTriple().getTriple());
3972061da546Spatrick auto cached = m_cached_module_specs.find(key);
3973061da546Spatrick if (cached != m_cached_module_specs.end()) {
3974061da546Spatrick module_spec = cached->second;
3975061da546Spatrick return bool(module_spec);
3976061da546Spatrick }
3977061da546Spatrick
3978061da546Spatrick if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
3979061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
3980061da546Spatrick __FUNCTION__, module_file_spec.GetPath().c_str(),
3981061da546Spatrick arch.GetTriple().getTriple().c_str());
3982061da546Spatrick return false;
3983061da546Spatrick }
3984061da546Spatrick
3985061da546Spatrick if (log) {
3986061da546Spatrick StreamString stream;
3987061da546Spatrick module_spec.Dump(stream);
3988061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
3989061da546Spatrick __FUNCTION__, module_file_spec.GetPath().c_str(),
3990061da546Spatrick arch.GetTriple().getTriple().c_str(), stream.GetData());
3991061da546Spatrick }
3992061da546Spatrick
3993061da546Spatrick m_cached_module_specs[key] = module_spec;
3994061da546Spatrick return true;
3995061da546Spatrick }
3996061da546Spatrick
PrefetchModuleSpecs(llvm::ArrayRef<FileSpec> module_file_specs,const llvm::Triple & triple)3997061da546Spatrick void ProcessGDBRemote::PrefetchModuleSpecs(
3998061da546Spatrick llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
3999061da546Spatrick auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4000061da546Spatrick if (module_specs) {
4001061da546Spatrick for (const FileSpec &spec : module_file_specs)
4002061da546Spatrick m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4003061da546Spatrick triple.getTriple())] = ModuleSpec();
4004061da546Spatrick for (const ModuleSpec &spec : *module_specs)
4005061da546Spatrick m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4006061da546Spatrick triple.getTriple())] = spec;
4007061da546Spatrick }
4008061da546Spatrick }
4009061da546Spatrick
GetHostOSVersion()4010061da546Spatrick llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4011061da546Spatrick return m_gdb_comm.GetOSVersion();
4012061da546Spatrick }
4013061da546Spatrick
GetHostMacCatalystVersion()4014061da546Spatrick llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4015061da546Spatrick return m_gdb_comm.GetMacCatalystVersion();
4016061da546Spatrick }
4017061da546Spatrick
4018061da546Spatrick namespace {
4019061da546Spatrick
4020061da546Spatrick typedef std::vector<std::string> stringVec;
4021061da546Spatrick
4022061da546Spatrick typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4023061da546Spatrick struct RegisterSetInfo {
4024061da546Spatrick ConstString name;
4025061da546Spatrick };
4026061da546Spatrick
4027061da546Spatrick typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4028061da546Spatrick
4029061da546Spatrick struct GdbServerTargetInfo {
4030061da546Spatrick std::string arch;
4031061da546Spatrick std::string osabi;
4032061da546Spatrick stringVec includes;
4033061da546Spatrick RegisterSetMap reg_set_map;
4034061da546Spatrick };
4035061da546Spatrick
ParseRegisters(XMLNode feature_node,GdbServerTargetInfo & target_info,std::vector<DynamicRegisterInfo::Register> & registers)4036061da546Spatrick bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4037*f6aab3d8Srobert std::vector<DynamicRegisterInfo::Register> ®isters) {
4038061da546Spatrick if (!feature_node)
4039061da546Spatrick return false;
4040061da546Spatrick
4041*f6aab3d8Srobert Log *log(GetLog(GDBRLog::Process));
4042*f6aab3d8Srobert
4043061da546Spatrick feature_node.ForEachChildElementWithName(
4044*f6aab3d8Srobert "reg", [&target_info, ®isters, log](const XMLNode ®_node) -> bool {
4045061da546Spatrick std::string gdb_group;
4046061da546Spatrick std::string gdb_type;
4047*f6aab3d8Srobert DynamicRegisterInfo::Register reg_info;
4048061da546Spatrick bool encoding_set = false;
4049061da546Spatrick bool format_set = false;
4050061da546Spatrick
4051*f6aab3d8Srobert // FIXME: we're silently ignoring invalid data here
4052061da546Spatrick reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4053*f6aab3d8Srobert &encoding_set, &format_set, ®_info,
4054*f6aab3d8Srobert log](const llvm::StringRef &name,
4055061da546Spatrick const llvm::StringRef &value) -> bool {
4056061da546Spatrick if (name == "name") {
4057*f6aab3d8Srobert reg_info.name.SetString(value);
4058061da546Spatrick } else if (name == "bitsize") {
4059*f6aab3d8Srobert if (llvm::to_integer(value, reg_info.byte_size))
4060061da546Spatrick reg_info.byte_size =
4061*f6aab3d8Srobert llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4062061da546Spatrick } else if (name == "type") {
4063061da546Spatrick gdb_type = value.str();
4064061da546Spatrick } else if (name == "group") {
4065061da546Spatrick gdb_group = value.str();
4066061da546Spatrick } else if (name == "regnum") {
4067*f6aab3d8Srobert llvm::to_integer(value, reg_info.regnum_remote);
4068061da546Spatrick } else if (name == "offset") {
4069*f6aab3d8Srobert llvm::to_integer(value, reg_info.byte_offset);
4070061da546Spatrick } else if (name == "altname") {
4071*f6aab3d8Srobert reg_info.alt_name.SetString(value);
4072061da546Spatrick } else if (name == "encoding") {
4073061da546Spatrick encoding_set = true;
4074061da546Spatrick reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4075061da546Spatrick } else if (name == "format") {
4076061da546Spatrick format_set = true;
4077*f6aab3d8Srobert if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4078*f6aab3d8Srobert nullptr)
4079061da546Spatrick .Success())
4080*f6aab3d8Srobert reg_info.format =
4081*f6aab3d8Srobert llvm::StringSwitch<lldb::Format>(value)
4082*f6aab3d8Srobert .Case("vector-sint8", eFormatVectorOfSInt8)
4083*f6aab3d8Srobert .Case("vector-uint8", eFormatVectorOfUInt8)
4084*f6aab3d8Srobert .Case("vector-sint16", eFormatVectorOfSInt16)
4085*f6aab3d8Srobert .Case("vector-uint16", eFormatVectorOfUInt16)
4086*f6aab3d8Srobert .Case("vector-sint32", eFormatVectorOfSInt32)
4087*f6aab3d8Srobert .Case("vector-uint32", eFormatVectorOfUInt32)
4088*f6aab3d8Srobert .Case("vector-float32", eFormatVectorOfFloat32)
4089*f6aab3d8Srobert .Case("vector-uint64", eFormatVectorOfUInt64)
4090*f6aab3d8Srobert .Case("vector-uint128", eFormatVectorOfUInt128)
4091*f6aab3d8Srobert .Default(eFormatInvalid);
4092061da546Spatrick } else if (name == "group_id") {
4093*f6aab3d8Srobert uint32_t set_id = UINT32_MAX;
4094*f6aab3d8Srobert llvm::to_integer(value, set_id);
4095061da546Spatrick RegisterSetMap::const_iterator pos =
4096061da546Spatrick target_info.reg_set_map.find(set_id);
4097061da546Spatrick if (pos != target_info.reg_set_map.end())
4098*f6aab3d8Srobert reg_info.set_name = pos->second.name;
4099061da546Spatrick } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4100*f6aab3d8Srobert llvm::to_integer(value, reg_info.regnum_ehframe);
4101061da546Spatrick } else if (name == "dwarf_regnum") {
4102*f6aab3d8Srobert llvm::to_integer(value, reg_info.regnum_dwarf);
4103061da546Spatrick } else if (name == "generic") {
4104*f6aab3d8Srobert reg_info.regnum_generic = Args::StringToGenericRegister(value);
4105061da546Spatrick } else if (name == "value_regnums") {
4106*f6aab3d8Srobert SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,
4107*f6aab3d8Srobert 0);
4108061da546Spatrick } else if (name == "invalidate_regnums") {
4109*f6aab3d8Srobert SplitCommaSeparatedRegisterNumberString(
4110*f6aab3d8Srobert value, reg_info.invalidate_regs, 0);
4111061da546Spatrick } else {
4112*f6aab3d8Srobert LLDB_LOGF(log,
4113*f6aab3d8Srobert "ProcessGDBRemote::ParseRegisters unhandled reg "
4114*f6aab3d8Srobert "attribute %s = %s",
4115*f6aab3d8Srobert name.data(), value.data());
4116061da546Spatrick }
4117061da546Spatrick return true; // Keep iterating through all attributes
4118061da546Spatrick });
4119061da546Spatrick
4120061da546Spatrick if (!gdb_type.empty() && !(encoding_set || format_set)) {
4121dda28197Spatrick if (llvm::StringRef(gdb_type).startswith("int")) {
4122061da546Spatrick reg_info.format = eFormatHex;
4123061da546Spatrick reg_info.encoding = eEncodingUint;
4124061da546Spatrick } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4125061da546Spatrick reg_info.format = eFormatAddressInfo;
4126061da546Spatrick reg_info.encoding = eEncodingUint;
4127*f6aab3d8Srobert } else if (gdb_type == "float") {
4128061da546Spatrick reg_info.format = eFormatFloat;
4129061da546Spatrick reg_info.encoding = eEncodingIEEE754;
4130*f6aab3d8Srobert } else if (gdb_type == "aarch64v" ||
4131*f6aab3d8Srobert llvm::StringRef(gdb_type).startswith("vec") ||
4132*f6aab3d8Srobert gdb_type == "i387_ext" || gdb_type == "uint128") {
4133*f6aab3d8Srobert // lldb doesn't handle 128-bit uints correctly (for ymm*h), so treat
4134*f6aab3d8Srobert // them as vector (similarly to xmm/ymm)
4135*f6aab3d8Srobert reg_info.format = eFormatVectorOfUInt8;
4136*f6aab3d8Srobert reg_info.encoding = eEncodingVector;
4137*f6aab3d8Srobert } else {
4138*f6aab3d8Srobert LLDB_LOGF(
4139*f6aab3d8Srobert log,
4140*f6aab3d8Srobert "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4141*f6aab3d8Srobert "format and encoding for gdb type %s",
4142*f6aab3d8Srobert gdb_type.c_str());
4143061da546Spatrick }
4144061da546Spatrick }
4145061da546Spatrick
4146061da546Spatrick // Only update the register set name if we didn't get a "reg_set"
4147061da546Spatrick // attribute. "set_name" will be empty if we didn't have a "reg_set"
4148061da546Spatrick // attribute.
4149*f6aab3d8Srobert if (!reg_info.set_name) {
4150061da546Spatrick if (!gdb_group.empty()) {
4151*f6aab3d8Srobert reg_info.set_name.SetCString(gdb_group.c_str());
4152061da546Spatrick } else {
4153061da546Spatrick // If no register group name provided anywhere,
4154061da546Spatrick // we'll create a 'general' register set
4155*f6aab3d8Srobert reg_info.set_name.SetCString("general");
4156061da546Spatrick }
4157061da546Spatrick }
4158061da546Spatrick
4159*f6aab3d8Srobert if (reg_info.byte_size == 0) {
4160*f6aab3d8Srobert LLDB_LOGF(log,
4161*f6aab3d8Srobert "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4162*f6aab3d8Srobert __FUNCTION__, reg_info.name.AsCString());
4163*f6aab3d8Srobert } else
4164*f6aab3d8Srobert registers.push_back(reg_info);
4165061da546Spatrick
4166061da546Spatrick return true; // Keep iterating through all "reg" elements
4167061da546Spatrick });
4168061da546Spatrick return true;
4169061da546Spatrick }
4170061da546Spatrick
4171061da546Spatrick } // namespace
4172061da546Spatrick
4173061da546Spatrick // This method fetches a register description feature xml file from
4174061da546Spatrick // the remote stub and adds registers/register groupsets/architecture
4175061da546Spatrick // information to the current process. It will call itself recursively
4176061da546Spatrick // for nested register definition files. It returns true if it was able
4177061da546Spatrick // to fetch and parse an xml file.
GetGDBServerRegisterInfoXMLAndProcess(ArchSpec & arch_to_use,std::string xml_filename,std::vector<DynamicRegisterInfo::Register> & registers)4178061da546Spatrick bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4179*f6aab3d8Srobert ArchSpec &arch_to_use, std::string xml_filename,
4180*f6aab3d8Srobert std::vector<DynamicRegisterInfo::Register> ®isters) {
4181061da546Spatrick // request the target xml file
4182*f6aab3d8Srobert llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4183*f6aab3d8Srobert if (errorToBool(raw.takeError()))
4184061da546Spatrick return false;
4185061da546Spatrick
4186061da546Spatrick XMLDocument xml_document;
4187061da546Spatrick
4188*f6aab3d8Srobert if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4189*f6aab3d8Srobert xml_filename.c_str())) {
4190061da546Spatrick GdbServerTargetInfo target_info;
4191061da546Spatrick std::vector<XMLNode> feature_nodes;
4192061da546Spatrick
4193061da546Spatrick // The top level feature XML file will start with a <target> tag.
4194061da546Spatrick XMLNode target_node = xml_document.GetRootElement("target");
4195061da546Spatrick if (target_node) {
4196061da546Spatrick target_node.ForEachChildElement([&target_info, &feature_nodes](
4197061da546Spatrick const XMLNode &node) -> bool {
4198061da546Spatrick llvm::StringRef name = node.GetName();
4199061da546Spatrick if (name == "architecture") {
4200061da546Spatrick node.GetElementText(target_info.arch);
4201061da546Spatrick } else if (name == "osabi") {
4202061da546Spatrick node.GetElementText(target_info.osabi);
4203061da546Spatrick } else if (name == "xi:include" || name == "include") {
4204*f6aab3d8Srobert std::string href = node.GetAttributeValue("href");
4205061da546Spatrick if (!href.empty())
4206*f6aab3d8Srobert target_info.includes.push_back(href);
4207061da546Spatrick } else if (name == "feature") {
4208061da546Spatrick feature_nodes.push_back(node);
4209061da546Spatrick } else if (name == "groups") {
4210061da546Spatrick node.ForEachChildElementWithName(
4211061da546Spatrick "group", [&target_info](const XMLNode &node) -> bool {
4212061da546Spatrick uint32_t set_id = UINT32_MAX;
4213061da546Spatrick RegisterSetInfo set_info;
4214061da546Spatrick
4215061da546Spatrick node.ForEachAttribute(
4216061da546Spatrick [&set_id, &set_info](const llvm::StringRef &name,
4217061da546Spatrick const llvm::StringRef &value) -> bool {
4218*f6aab3d8Srobert // FIXME: we're silently ignoring invalid data here
4219061da546Spatrick if (name == "id")
4220*f6aab3d8Srobert llvm::to_integer(value, set_id);
4221061da546Spatrick if (name == "name")
4222061da546Spatrick set_info.name = ConstString(value);
4223061da546Spatrick return true; // Keep iterating through all attributes
4224061da546Spatrick });
4225061da546Spatrick
4226061da546Spatrick if (set_id != UINT32_MAX)
4227061da546Spatrick target_info.reg_set_map[set_id] = set_info;
4228061da546Spatrick return true; // Keep iterating through all "group" elements
4229061da546Spatrick });
4230061da546Spatrick }
4231061da546Spatrick return true; // Keep iterating through all children of the target_node
4232061da546Spatrick });
4233061da546Spatrick } else {
4234061da546Spatrick // In an included XML feature file, we're already "inside" the <target>
4235061da546Spatrick // tag of the initial XML file; this included file will likely only have
4236061da546Spatrick // a <feature> tag. Need to check for any more included files in this
4237061da546Spatrick // <feature> element.
4238061da546Spatrick XMLNode feature_node = xml_document.GetRootElement("feature");
4239061da546Spatrick if (feature_node) {
4240061da546Spatrick feature_nodes.push_back(feature_node);
4241061da546Spatrick feature_node.ForEachChildElement([&target_info](
4242061da546Spatrick const XMLNode &node) -> bool {
4243061da546Spatrick llvm::StringRef name = node.GetName();
4244061da546Spatrick if (name == "xi:include" || name == "include") {
4245*f6aab3d8Srobert std::string href = node.GetAttributeValue("href");
4246061da546Spatrick if (!href.empty())
4247*f6aab3d8Srobert target_info.includes.push_back(href);
4248061da546Spatrick }
4249061da546Spatrick return true;
4250061da546Spatrick });
4251061da546Spatrick }
4252061da546Spatrick }
4253061da546Spatrick
4254*f6aab3d8Srobert // gdbserver does not implement the LLDB packets used to determine host
4255*f6aab3d8Srobert // or process architecture. If that is the case, attempt to use
4256*f6aab3d8Srobert // the <architecture/> field from target.xml, e.g.:
4257*f6aab3d8Srobert //
4258061da546Spatrick // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4259*f6aab3d8Srobert // <architecture>arm</architecture> (seen from Segger JLink on unspecified
4260*f6aab3d8Srobert // arm board)
4261061da546Spatrick if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4262061da546Spatrick // We don't have any information about vendor or OS.
4263*f6aab3d8Srobert arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4264*f6aab3d8Srobert .Case("i386:x86-64", "x86_64")
4265*f6aab3d8Srobert .Default(target_info.arch) +
4266*f6aab3d8Srobert "--");
4267061da546Spatrick
4268*f6aab3d8Srobert if (arch_to_use.IsValid())
4269061da546Spatrick GetTarget().MergeArchitecture(arch_to_use);
4270061da546Spatrick }
4271061da546Spatrick
4272061da546Spatrick if (arch_to_use.IsValid()) {
4273061da546Spatrick for (auto &feature_node : feature_nodes) {
4274*f6aab3d8Srobert ParseRegisters(feature_node, target_info,
4275*f6aab3d8Srobert registers);
4276061da546Spatrick }
4277061da546Spatrick
4278061da546Spatrick for (const auto &include : target_info.includes) {
4279be691f3bSpatrick GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4280*f6aab3d8Srobert registers);
4281061da546Spatrick }
4282061da546Spatrick }
4283061da546Spatrick } else {
4284061da546Spatrick return false;
4285061da546Spatrick }
4286061da546Spatrick return true;
4287061da546Spatrick }
4288061da546Spatrick
AddRemoteRegisters(std::vector<DynamicRegisterInfo::Register> & registers,const ArchSpec & arch_to_use)4289*f6aab3d8Srobert void ProcessGDBRemote::AddRemoteRegisters(
4290*f6aab3d8Srobert std::vector<DynamicRegisterInfo::Register> ®isters,
4291*f6aab3d8Srobert const ArchSpec &arch_to_use) {
4292*f6aab3d8Srobert std::map<uint32_t, uint32_t> remote_to_local_map;
4293*f6aab3d8Srobert uint32_t remote_regnum = 0;
4294*f6aab3d8Srobert for (auto it : llvm::enumerate(registers)) {
4295*f6aab3d8Srobert DynamicRegisterInfo::Register &remote_reg_info = it.value();
4296*f6aab3d8Srobert
4297*f6aab3d8Srobert // Assign successive remote regnums if missing.
4298*f6aab3d8Srobert if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4299*f6aab3d8Srobert remote_reg_info.regnum_remote = remote_regnum;
4300*f6aab3d8Srobert
4301*f6aab3d8Srobert // Create a mapping from remote to local regnos.
4302*f6aab3d8Srobert remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4303*f6aab3d8Srobert
4304*f6aab3d8Srobert remote_regnum = remote_reg_info.regnum_remote + 1;
4305*f6aab3d8Srobert }
4306*f6aab3d8Srobert
4307*f6aab3d8Srobert for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4308*f6aab3d8Srobert auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4309*f6aab3d8Srobert auto lldb_regit = remote_to_local_map.find(process_regnum);
4310*f6aab3d8Srobert return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4311*f6aab3d8Srobert : LLDB_INVALID_REGNUM;
4312*f6aab3d8Srobert };
4313*f6aab3d8Srobert
4314*f6aab3d8Srobert llvm::transform(remote_reg_info.value_regs,
4315*f6aab3d8Srobert remote_reg_info.value_regs.begin(), proc_to_lldb);
4316*f6aab3d8Srobert llvm::transform(remote_reg_info.invalidate_regs,
4317*f6aab3d8Srobert remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4318*f6aab3d8Srobert }
4319*f6aab3d8Srobert
4320*f6aab3d8Srobert // Don't use Process::GetABI, this code gets called from DidAttach, and
4321*f6aab3d8Srobert // in that context we haven't set the Target's architecture yet, so the
4322*f6aab3d8Srobert // ABI is also potentially incorrect.
4323*f6aab3d8Srobert if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4324*f6aab3d8Srobert abi_sp->AugmentRegisterInfo(registers);
4325*f6aab3d8Srobert
4326*f6aab3d8Srobert m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4327*f6aab3d8Srobert }
4328*f6aab3d8Srobert
4329061da546Spatrick // query the target of gdb-remote for extended target information returns
4330061da546Spatrick // true on success (got register definitions), false on failure (did not).
GetGDBServerRegisterInfo(ArchSpec & arch_to_use)4331061da546Spatrick bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4332061da546Spatrick // Make sure LLDB has an XML parser it can use first
4333061da546Spatrick if (!XMLDocument::XMLEnabled())
4334061da546Spatrick return false;
4335061da546Spatrick
4336061da546Spatrick // check that we have extended feature read support
4337061da546Spatrick if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4338061da546Spatrick return false;
4339061da546Spatrick
4340*f6aab3d8Srobert std::vector<DynamicRegisterInfo::Register> registers;
4341be691f3bSpatrick if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4342*f6aab3d8Srobert registers))
4343*f6aab3d8Srobert AddRemoteRegisters(registers, arch_to_use);
4344061da546Spatrick
4345be691f3bSpatrick return m_register_info_sp->GetNumRegisters() > 0;
4346061da546Spatrick }
4347061da546Spatrick
GetLoadedModuleList()4348061da546Spatrick llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4349061da546Spatrick // Make sure LLDB has an XML parser it can use first
4350061da546Spatrick if (!XMLDocument::XMLEnabled())
4351061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
4352061da546Spatrick "XML parsing not available");
4353061da546Spatrick
4354*f6aab3d8Srobert Log *log = GetLog(LLDBLog::Process);
4355061da546Spatrick LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4356061da546Spatrick
4357061da546Spatrick LoadedModuleInfoList list;
4358061da546Spatrick GDBRemoteCommunicationClient &comm = m_gdb_comm;
4359*f6aab3d8Srobert bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
4360061da546Spatrick
4361061da546Spatrick // check that we have extended feature read support
4362061da546Spatrick if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4363061da546Spatrick // request the loaded library list
4364*f6aab3d8Srobert llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4365*f6aab3d8Srobert if (!raw)
4366*f6aab3d8Srobert return raw.takeError();
4367061da546Spatrick
4368061da546Spatrick // parse the xml file in memory
4369*f6aab3d8Srobert LLDB_LOGF(log, "parsing: %s", raw->c_str());
4370061da546Spatrick XMLDocument doc;
4371061da546Spatrick
4372*f6aab3d8Srobert if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4373061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
4374061da546Spatrick "Error reading noname.xml");
4375061da546Spatrick
4376061da546Spatrick XMLNode root_element = doc.GetRootElement("library-list-svr4");
4377061da546Spatrick if (!root_element)
4378061da546Spatrick return llvm::createStringError(
4379061da546Spatrick llvm::inconvertibleErrorCode(),
4380061da546Spatrick "Error finding library-list-svr4 xml element");
4381061da546Spatrick
4382061da546Spatrick // main link map structure
4383*f6aab3d8Srobert std::string main_lm = root_element.GetAttributeValue("main-lm");
4384*f6aab3d8Srobert // FIXME: we're silently ignoring invalid data here
4385*f6aab3d8Srobert if (!main_lm.empty())
4386*f6aab3d8Srobert llvm::to_integer(main_lm, list.m_link_map);
4387061da546Spatrick
4388061da546Spatrick root_element.ForEachChildElementWithName(
4389061da546Spatrick "library", [log, &list](const XMLNode &library) -> bool {
4390061da546Spatrick LoadedModuleInfoList::LoadedModuleInfo module;
4391061da546Spatrick
4392*f6aab3d8Srobert // FIXME: we're silently ignoring invalid data here
4393061da546Spatrick library.ForEachAttribute(
4394061da546Spatrick [&module](const llvm::StringRef &name,
4395061da546Spatrick const llvm::StringRef &value) -> bool {
4396*f6aab3d8Srobert uint64_t uint_value = LLDB_INVALID_ADDRESS;
4397061da546Spatrick if (name == "name")
4398061da546Spatrick module.set_name(value.str());
4399061da546Spatrick else if (name == "lm") {
4400061da546Spatrick // the address of the link_map struct.
4401*f6aab3d8Srobert llvm::to_integer(value, uint_value);
4402*f6aab3d8Srobert module.set_link_map(uint_value);
4403061da546Spatrick } else if (name == "l_addr") {
4404061da546Spatrick // the displacement as read from the field 'l_addr' of the
4405061da546Spatrick // link_map struct.
4406*f6aab3d8Srobert llvm::to_integer(value, uint_value);
4407*f6aab3d8Srobert module.set_base(uint_value);
4408061da546Spatrick // base address is always a displacement, not an absolute
4409061da546Spatrick // value.
4410061da546Spatrick module.set_base_is_offset(true);
4411061da546Spatrick } else if (name == "l_ld") {
4412dda28197Spatrick // the memory address of the libraries PT_DYNAMIC section.
4413*f6aab3d8Srobert llvm::to_integer(value, uint_value);
4414*f6aab3d8Srobert module.set_dynamic(uint_value);
4415061da546Spatrick }
4416061da546Spatrick
4417061da546Spatrick return true; // Keep iterating over all properties of "library"
4418061da546Spatrick });
4419061da546Spatrick
4420061da546Spatrick if (log) {
4421061da546Spatrick std::string name;
4422061da546Spatrick lldb::addr_t lm = 0, base = 0, ld = 0;
4423061da546Spatrick bool base_is_offset;
4424061da546Spatrick
4425061da546Spatrick module.get_name(name);
4426061da546Spatrick module.get_link_map(lm);
4427061da546Spatrick module.get_base(base);
4428061da546Spatrick module.get_base_is_offset(base_is_offset);
4429061da546Spatrick module.get_dynamic(ld);
4430061da546Spatrick
4431061da546Spatrick LLDB_LOGF(log,
4432061da546Spatrick "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4433061da546Spatrick "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4434061da546Spatrick lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4435061da546Spatrick name.c_str());
4436061da546Spatrick }
4437061da546Spatrick
4438061da546Spatrick list.add(module);
4439061da546Spatrick return true; // Keep iterating over all "library" elements in the root
4440061da546Spatrick // node
4441061da546Spatrick });
4442061da546Spatrick
4443061da546Spatrick if (log)
4444061da546Spatrick LLDB_LOGF(log, "found %" PRId32 " modules in total",
4445061da546Spatrick (int)list.m_list.size());
4446061da546Spatrick return list;
4447061da546Spatrick } else if (comm.GetQXferLibrariesReadSupported()) {
4448061da546Spatrick // request the loaded library list
4449*f6aab3d8Srobert llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
4450061da546Spatrick
4451*f6aab3d8Srobert if (!raw)
4452*f6aab3d8Srobert return raw.takeError();
4453061da546Spatrick
4454*f6aab3d8Srobert LLDB_LOGF(log, "parsing: %s", raw->c_str());
4455061da546Spatrick XMLDocument doc;
4456061da546Spatrick
4457*f6aab3d8Srobert if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4458061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
4459061da546Spatrick "Error reading noname.xml");
4460061da546Spatrick
4461061da546Spatrick XMLNode root_element = doc.GetRootElement("library-list");
4462061da546Spatrick if (!root_element)
4463061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
4464061da546Spatrick "Error finding library-list xml element");
4465061da546Spatrick
4466*f6aab3d8Srobert // FIXME: we're silently ignoring invalid data here
4467061da546Spatrick root_element.ForEachChildElementWithName(
4468061da546Spatrick "library", [log, &list](const XMLNode &library) -> bool {
4469061da546Spatrick LoadedModuleInfoList::LoadedModuleInfo module;
4470061da546Spatrick
4471*f6aab3d8Srobert std::string name = library.GetAttributeValue("name");
4472*f6aab3d8Srobert module.set_name(name);
4473061da546Spatrick
4474061da546Spatrick // The base address of a given library will be the address of its
4475061da546Spatrick // first section. Most remotes send only one section for Windows
4476061da546Spatrick // targets for example.
4477061da546Spatrick const XMLNode §ion =
4478061da546Spatrick library.FindFirstChildElementWithName("section");
4479*f6aab3d8Srobert std::string address = section.GetAttributeValue("address");
4480*f6aab3d8Srobert uint64_t address_value = LLDB_INVALID_ADDRESS;
4481*f6aab3d8Srobert llvm::to_integer(address, address_value);
4482*f6aab3d8Srobert module.set_base(address_value);
4483061da546Spatrick // These addresses are absolute values.
4484061da546Spatrick module.set_base_is_offset(false);
4485061da546Spatrick
4486061da546Spatrick if (log) {
4487061da546Spatrick std::string name;
4488061da546Spatrick lldb::addr_t base = 0;
4489061da546Spatrick bool base_is_offset;
4490061da546Spatrick module.get_name(name);
4491061da546Spatrick module.get_base(base);
4492061da546Spatrick module.get_base_is_offset(base_is_offset);
4493061da546Spatrick
4494061da546Spatrick LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4495061da546Spatrick (base_is_offset ? "offset" : "absolute"), name.c_str());
4496061da546Spatrick }
4497061da546Spatrick
4498061da546Spatrick list.add(module);
4499061da546Spatrick return true; // Keep iterating over all "library" elements in the root
4500061da546Spatrick // node
4501061da546Spatrick });
4502061da546Spatrick
4503061da546Spatrick if (log)
4504061da546Spatrick LLDB_LOGF(log, "found %" PRId32 " modules in total",
4505061da546Spatrick (int)list.m_list.size());
4506061da546Spatrick return list;
4507061da546Spatrick } else {
4508061da546Spatrick return llvm::createStringError(llvm::inconvertibleErrorCode(),
4509061da546Spatrick "Remote libraries not supported");
4510061da546Spatrick }
4511061da546Spatrick }
4512061da546Spatrick
LoadModuleAtAddress(const FileSpec & file,lldb::addr_t link_map,lldb::addr_t base_addr,bool value_is_offset)4513061da546Spatrick lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4514061da546Spatrick lldb::addr_t link_map,
4515061da546Spatrick lldb::addr_t base_addr,
4516061da546Spatrick bool value_is_offset) {
4517061da546Spatrick DynamicLoader *loader = GetDynamicLoader();
4518061da546Spatrick if (!loader)
4519061da546Spatrick return nullptr;
4520061da546Spatrick
4521061da546Spatrick return loader->LoadModuleAtAddress(file, link_map, base_addr,
4522061da546Spatrick value_is_offset);
4523061da546Spatrick }
4524061da546Spatrick
LoadModules()4525061da546Spatrick llvm::Error ProcessGDBRemote::LoadModules() {
4526061da546Spatrick using lldb_private::process_gdb_remote::ProcessGDBRemote;
4527061da546Spatrick
4528061da546Spatrick // request a list of loaded libraries from GDBServer
4529061da546Spatrick llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4530061da546Spatrick if (!module_list)
4531061da546Spatrick return module_list.takeError();
4532061da546Spatrick
4533061da546Spatrick // get a list of all the modules
4534061da546Spatrick ModuleList new_modules;
4535061da546Spatrick
4536061da546Spatrick for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4537061da546Spatrick std::string mod_name;
4538061da546Spatrick lldb::addr_t mod_base;
4539061da546Spatrick lldb::addr_t link_map;
4540061da546Spatrick bool mod_base_is_offset;
4541061da546Spatrick
4542061da546Spatrick bool valid = true;
4543061da546Spatrick valid &= modInfo.get_name(mod_name);
4544061da546Spatrick valid &= modInfo.get_base(mod_base);
4545061da546Spatrick valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4546061da546Spatrick if (!valid)
4547061da546Spatrick continue;
4548061da546Spatrick
4549061da546Spatrick if (!modInfo.get_link_map(link_map))
4550061da546Spatrick link_map = LLDB_INVALID_ADDRESS;
4551061da546Spatrick
4552061da546Spatrick FileSpec file(mod_name);
4553061da546Spatrick FileSystem::Instance().Resolve(file);
4554061da546Spatrick lldb::ModuleSP module_sp =
4555061da546Spatrick LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4556061da546Spatrick
4557061da546Spatrick if (module_sp.get())
4558061da546Spatrick new_modules.Append(module_sp);
4559061da546Spatrick }
4560061da546Spatrick
4561061da546Spatrick if (new_modules.GetSize() > 0) {
4562061da546Spatrick ModuleList removed_modules;
4563061da546Spatrick Target &target = GetTarget();
4564061da546Spatrick ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4565061da546Spatrick
4566061da546Spatrick for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4567061da546Spatrick const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4568061da546Spatrick
4569061da546Spatrick bool found = false;
4570061da546Spatrick for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4571061da546Spatrick if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4572061da546Spatrick found = true;
4573061da546Spatrick }
4574061da546Spatrick
4575061da546Spatrick // The main executable will never be included in libraries-svr4, don't
4576061da546Spatrick // remove it
4577061da546Spatrick if (!found &&
4578061da546Spatrick loaded_module.get() != target.GetExecutableModulePointer()) {
4579061da546Spatrick removed_modules.Append(loaded_module);
4580061da546Spatrick }
4581061da546Spatrick }
4582061da546Spatrick
4583061da546Spatrick loaded_modules.Remove(removed_modules);
4584061da546Spatrick m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4585061da546Spatrick
4586061da546Spatrick new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4587061da546Spatrick lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4588061da546Spatrick if (!obj)
4589061da546Spatrick return true;
4590061da546Spatrick
4591061da546Spatrick if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4592061da546Spatrick return true;
4593061da546Spatrick
4594061da546Spatrick lldb::ModuleSP module_copy_sp = module_sp;
4595061da546Spatrick target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4596061da546Spatrick return false;
4597061da546Spatrick });
4598061da546Spatrick
4599061da546Spatrick loaded_modules.AppendIfNeeded(new_modules);
4600061da546Spatrick m_process->GetTarget().ModulesDidLoad(new_modules);
4601061da546Spatrick }
4602061da546Spatrick
4603061da546Spatrick return llvm::ErrorSuccess();
4604061da546Spatrick }
4605061da546Spatrick
GetFileLoadAddress(const FileSpec & file,bool & is_loaded,lldb::addr_t & load_addr)4606061da546Spatrick Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4607061da546Spatrick bool &is_loaded,
4608061da546Spatrick lldb::addr_t &load_addr) {
4609061da546Spatrick is_loaded = false;
4610061da546Spatrick load_addr = LLDB_INVALID_ADDRESS;
4611061da546Spatrick
4612061da546Spatrick std::string file_path = file.GetPath(false);
4613061da546Spatrick if (file_path.empty())
4614061da546Spatrick return Status("Empty file name specified");
4615061da546Spatrick
4616061da546Spatrick StreamString packet;
4617061da546Spatrick packet.PutCString("qFileLoadAddress:");
4618061da546Spatrick packet.PutStringAsRawHex8(file_path);
4619061da546Spatrick
4620061da546Spatrick StringExtractorGDBRemote response;
4621be691f3bSpatrick if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
4622061da546Spatrick GDBRemoteCommunication::PacketResult::Success)
4623061da546Spatrick return Status("Sending qFileLoadAddress packet failed");
4624061da546Spatrick
4625061da546Spatrick if (response.IsErrorResponse()) {
4626061da546Spatrick if (response.GetError() == 1) {
4627061da546Spatrick // The file is not loaded into the inferior
4628061da546Spatrick is_loaded = false;
4629061da546Spatrick load_addr = LLDB_INVALID_ADDRESS;
4630061da546Spatrick return Status();
4631061da546Spatrick }
4632061da546Spatrick
4633061da546Spatrick return Status(
4634061da546Spatrick "Fetching file load address from remote server returned an error");
4635061da546Spatrick }
4636061da546Spatrick
4637061da546Spatrick if (response.IsNormalResponse()) {
4638061da546Spatrick is_loaded = true;
4639061da546Spatrick load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
4640061da546Spatrick return Status();
4641061da546Spatrick }
4642061da546Spatrick
4643061da546Spatrick return Status(
4644061da546Spatrick "Unknown error happened during sending the load address packet");
4645061da546Spatrick }
4646061da546Spatrick
ModulesDidLoad(ModuleList & module_list)4647061da546Spatrick void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4648061da546Spatrick // We must call the lldb_private::Process::ModulesDidLoad () first before we
4649061da546Spatrick // do anything
4650061da546Spatrick Process::ModulesDidLoad(module_list);
4651061da546Spatrick
4652061da546Spatrick // After loading shared libraries, we can ask our remote GDB server if it
4653061da546Spatrick // needs any symbols.
4654061da546Spatrick m_gdb_comm.ServeSymbolLookups(this);
4655061da546Spatrick }
4656061da546Spatrick
HandleAsyncStdout(llvm::StringRef out)4657061da546Spatrick void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4658061da546Spatrick AppendSTDOUT(out.data(), out.size());
4659061da546Spatrick }
4660061da546Spatrick
4661061da546Spatrick static const char *end_delimiter = "--end--;";
4662061da546Spatrick static const int end_delimiter_len = 8;
4663061da546Spatrick
HandleAsyncMisc(llvm::StringRef data)4664061da546Spatrick void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4665061da546Spatrick std::string input = data.str(); // '1' to move beyond 'A'
4666061da546Spatrick if (m_partial_profile_data.length() > 0) {
4667061da546Spatrick m_partial_profile_data.append(input);
4668061da546Spatrick input = m_partial_profile_data;
4669061da546Spatrick m_partial_profile_data.clear();
4670061da546Spatrick }
4671061da546Spatrick
4672061da546Spatrick size_t found, pos = 0, len = input.length();
4673061da546Spatrick while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4674061da546Spatrick StringExtractorGDBRemote profileDataExtractor(
4675061da546Spatrick input.substr(pos, found).c_str());
4676061da546Spatrick std::string profile_data =
4677061da546Spatrick HarmonizeThreadIdsForProfileData(profileDataExtractor);
4678061da546Spatrick BroadcastAsyncProfileData(profile_data);
4679061da546Spatrick
4680061da546Spatrick pos = found + end_delimiter_len;
4681061da546Spatrick }
4682061da546Spatrick
4683061da546Spatrick if (pos < len) {
4684061da546Spatrick // Last incomplete chunk.
4685061da546Spatrick m_partial_profile_data = input.substr(pos);
4686061da546Spatrick }
4687061da546Spatrick }
4688061da546Spatrick
HarmonizeThreadIdsForProfileData(StringExtractorGDBRemote & profileDataExtractor)4689061da546Spatrick std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4690061da546Spatrick StringExtractorGDBRemote &profileDataExtractor) {
4691061da546Spatrick std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4692061da546Spatrick std::string output;
4693061da546Spatrick llvm::raw_string_ostream output_stream(output);
4694061da546Spatrick llvm::StringRef name, value;
4695061da546Spatrick
4696061da546Spatrick // Going to assuming thread_used_usec comes first, else bail out.
4697061da546Spatrick while (profileDataExtractor.GetNameColonValue(name, value)) {
4698061da546Spatrick if (name.compare("thread_used_id") == 0) {
4699061da546Spatrick StringExtractor threadIDHexExtractor(value);
4700061da546Spatrick uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4701061da546Spatrick
4702061da546Spatrick bool has_used_usec = false;
4703061da546Spatrick uint32_t curr_used_usec = 0;
4704061da546Spatrick llvm::StringRef usec_name, usec_value;
4705061da546Spatrick uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4706061da546Spatrick if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4707061da546Spatrick if (usec_name.equals("thread_used_usec")) {
4708061da546Spatrick has_used_usec = true;
4709061da546Spatrick usec_value.getAsInteger(0, curr_used_usec);
4710061da546Spatrick } else {
4711061da546Spatrick // We didn't find what we want, it is probably an older version. Bail
4712061da546Spatrick // out.
4713061da546Spatrick profileDataExtractor.SetFilePos(input_file_pos);
4714061da546Spatrick }
4715061da546Spatrick }
4716061da546Spatrick
4717061da546Spatrick if (has_used_usec) {
4718061da546Spatrick uint32_t prev_used_usec = 0;
4719061da546Spatrick std::map<uint64_t, uint32_t>::iterator iterator =
4720061da546Spatrick m_thread_id_to_used_usec_map.find(thread_id);
4721061da546Spatrick if (iterator != m_thread_id_to_used_usec_map.end()) {
4722061da546Spatrick prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4723061da546Spatrick }
4724061da546Spatrick
4725061da546Spatrick uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4726061da546Spatrick // A good first time record is one that runs for at least 0.25 sec
4727061da546Spatrick bool good_first_time =
4728061da546Spatrick (prev_used_usec == 0) && (real_used_usec > 250000);
4729061da546Spatrick bool good_subsequent_time =
4730061da546Spatrick (prev_used_usec > 0) &&
4731061da546Spatrick ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4732061da546Spatrick
4733061da546Spatrick if (good_first_time || good_subsequent_time) {
4734061da546Spatrick // We try to avoid doing too many index id reservation, resulting in
4735061da546Spatrick // fast increase of index ids.
4736061da546Spatrick
4737061da546Spatrick output_stream << name << ":";
4738061da546Spatrick int32_t index_id = AssignIndexIDToThread(thread_id);
4739061da546Spatrick output_stream << index_id << ";";
4740061da546Spatrick
4741061da546Spatrick output_stream << usec_name << ":" << usec_value << ";";
4742061da546Spatrick } else {
4743061da546Spatrick // Skip past 'thread_used_name'.
4744061da546Spatrick llvm::StringRef local_name, local_value;
4745061da546Spatrick profileDataExtractor.GetNameColonValue(local_name, local_value);
4746061da546Spatrick }
4747061da546Spatrick
4748061da546Spatrick // Store current time as previous time so that they can be compared
4749061da546Spatrick // later.
4750061da546Spatrick new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4751061da546Spatrick } else {
4752061da546Spatrick // Bail out and use old string.
4753061da546Spatrick output_stream << name << ":" << value << ";";
4754061da546Spatrick }
4755061da546Spatrick } else {
4756061da546Spatrick output_stream << name << ":" << value << ";";
4757061da546Spatrick }
4758061da546Spatrick }
4759061da546Spatrick output_stream << end_delimiter;
4760061da546Spatrick m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4761061da546Spatrick
4762061da546Spatrick return output_stream.str();
4763061da546Spatrick }
4764061da546Spatrick
HandleStopReply()4765061da546Spatrick void ProcessGDBRemote::HandleStopReply() {
4766061da546Spatrick if (GetStopID() != 0)
4767061da546Spatrick return;
4768061da546Spatrick
4769061da546Spatrick if (GetID() == LLDB_INVALID_PROCESS_ID) {
4770061da546Spatrick lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4771061da546Spatrick if (pid != LLDB_INVALID_PROCESS_ID)
4772061da546Spatrick SetID(pid);
4773061da546Spatrick }
4774061da546Spatrick BuildDynamicRegisterInfo(true);
4775061da546Spatrick }
4776061da546Spatrick
SaveCore(llvm::StringRef outfile)4777*f6aab3d8Srobert llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
4778*f6aab3d8Srobert if (!m_gdb_comm.GetSaveCoreSupported())
4779*f6aab3d8Srobert return false;
4780*f6aab3d8Srobert
4781*f6aab3d8Srobert StreamString packet;
4782*f6aab3d8Srobert packet.PutCString("qSaveCore;path-hint:");
4783*f6aab3d8Srobert packet.PutStringAsRawHex8(outfile);
4784*f6aab3d8Srobert
4785*f6aab3d8Srobert StringExtractorGDBRemote response;
4786*f6aab3d8Srobert if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4787*f6aab3d8Srobert GDBRemoteCommunication::PacketResult::Success) {
4788*f6aab3d8Srobert // TODO: grab error message from the packet? StringExtractor seems to
4789*f6aab3d8Srobert // be missing a method for that
4790*f6aab3d8Srobert if (response.IsErrorResponse())
4791*f6aab3d8Srobert return llvm::createStringError(
4792*f6aab3d8Srobert llvm::inconvertibleErrorCode(),
4793*f6aab3d8Srobert llvm::formatv("qSaveCore returned an error"));
4794*f6aab3d8Srobert
4795*f6aab3d8Srobert std::string path;
4796*f6aab3d8Srobert
4797*f6aab3d8Srobert // process the response
4798*f6aab3d8Srobert for (auto x : llvm::split(response.GetStringRef(), ';')) {
4799*f6aab3d8Srobert if (x.consume_front("core-path:"))
4800*f6aab3d8Srobert StringExtractor(x).GetHexByteString(path);
4801*f6aab3d8Srobert }
4802*f6aab3d8Srobert
4803*f6aab3d8Srobert // verify that we've gotten what we need
4804*f6aab3d8Srobert if (path.empty())
4805*f6aab3d8Srobert return llvm::createStringError(llvm::inconvertibleErrorCode(),
4806*f6aab3d8Srobert "qSaveCore returned no core path");
4807*f6aab3d8Srobert
4808*f6aab3d8Srobert // now transfer the core file
4809*f6aab3d8Srobert FileSpec remote_core{llvm::StringRef(path)};
4810*f6aab3d8Srobert Platform &platform = *GetTarget().GetPlatform();
4811*f6aab3d8Srobert Status error = platform.GetFile(remote_core, FileSpec(outfile));
4812*f6aab3d8Srobert
4813*f6aab3d8Srobert if (platform.IsRemote()) {
4814*f6aab3d8Srobert // NB: we unlink the file on error too
4815*f6aab3d8Srobert platform.Unlink(remote_core);
4816*f6aab3d8Srobert if (error.Fail())
4817*f6aab3d8Srobert return error.ToError();
4818*f6aab3d8Srobert }
4819*f6aab3d8Srobert
4820*f6aab3d8Srobert return true;
4821*f6aab3d8Srobert }
4822*f6aab3d8Srobert
4823*f6aab3d8Srobert return llvm::createStringError(llvm::inconvertibleErrorCode(),
4824*f6aab3d8Srobert "Unable to send qSaveCore");
4825*f6aab3d8Srobert }
4826*f6aab3d8Srobert
4827061da546Spatrick static const char *const s_async_json_packet_prefix = "JSON-async:";
4828061da546Spatrick
4829061da546Spatrick static StructuredData::ObjectSP
ParseStructuredDataPacket(llvm::StringRef packet)4830061da546Spatrick ParseStructuredDataPacket(llvm::StringRef packet) {
4831*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
4832061da546Spatrick
4833061da546Spatrick if (!packet.consume_front(s_async_json_packet_prefix)) {
4834061da546Spatrick if (log) {
4835061da546Spatrick LLDB_LOGF(
4836061da546Spatrick log,
4837061da546Spatrick "GDBRemoteCommunicationClientBase::%s() received $J packet "
4838061da546Spatrick "but was not a StructuredData packet: packet starts with "
4839061da546Spatrick "%s",
4840061da546Spatrick __FUNCTION__,
4841061da546Spatrick packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
4842061da546Spatrick }
4843061da546Spatrick return StructuredData::ObjectSP();
4844061da546Spatrick }
4845061da546Spatrick
4846061da546Spatrick // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
4847dda28197Spatrick StructuredData::ObjectSP json_sp =
4848dda28197Spatrick StructuredData::ParseJSON(std::string(packet));
4849061da546Spatrick if (log) {
4850061da546Spatrick if (json_sp) {
4851061da546Spatrick StreamString json_str;
4852061da546Spatrick json_sp->Dump(json_str, true);
4853061da546Spatrick json_str.Flush();
4854061da546Spatrick LLDB_LOGF(log,
4855061da546Spatrick "ProcessGDBRemote::%s() "
4856061da546Spatrick "received Async StructuredData packet: %s",
4857061da546Spatrick __FUNCTION__, json_str.GetData());
4858061da546Spatrick } else {
4859061da546Spatrick LLDB_LOGF(log,
4860061da546Spatrick "ProcessGDBRemote::%s"
4861061da546Spatrick "() received StructuredData packet:"
4862061da546Spatrick " parse failure",
4863061da546Spatrick __FUNCTION__);
4864061da546Spatrick }
4865061da546Spatrick }
4866061da546Spatrick return json_sp;
4867061da546Spatrick }
4868061da546Spatrick
HandleAsyncStructuredDataPacket(llvm::StringRef data)4869061da546Spatrick void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4870061da546Spatrick auto structured_data_sp = ParseStructuredDataPacket(data);
4871061da546Spatrick if (structured_data_sp)
4872061da546Spatrick RouteAsyncStructuredData(structured_data_sp);
4873061da546Spatrick }
4874061da546Spatrick
4875061da546Spatrick class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
4876061da546Spatrick public:
CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter & interpreter)4877061da546Spatrick CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
4878061da546Spatrick : CommandObjectParsed(interpreter, "process plugin packet speed-test",
4879061da546Spatrick "Tests packet speeds of various sizes to determine "
4880061da546Spatrick "the performance characteristics of the GDB remote "
4881061da546Spatrick "connection. ",
4882061da546Spatrick nullptr),
4883061da546Spatrick m_option_group(),
4884061da546Spatrick m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
4885061da546Spatrick "The number of packets to send of each varying size "
4886061da546Spatrick "(default is 1000).",
4887061da546Spatrick 1000),
4888061da546Spatrick m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
4889061da546Spatrick "The maximum number of bytes to send in a packet. Sizes "
4890061da546Spatrick "increase in powers of 2 while the size is less than or "
4891061da546Spatrick "equal to this option value. (default 1024).",
4892061da546Spatrick 1024),
4893061da546Spatrick m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
4894061da546Spatrick "The maximum number of bytes to receive in a packet. Sizes "
4895061da546Spatrick "increase in powers of 2 while the size is less than or "
4896061da546Spatrick "equal to this option value. (default 1024).",
4897061da546Spatrick 1024),
4898061da546Spatrick m_json(LLDB_OPT_SET_1, false, "json", 'j',
4899061da546Spatrick "Print the output as JSON data for easy parsing.", false, true) {
4900061da546Spatrick m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4901061da546Spatrick m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4902061da546Spatrick m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4903061da546Spatrick m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
4904061da546Spatrick m_option_group.Finalize();
4905061da546Spatrick }
4906061da546Spatrick
4907be691f3bSpatrick ~CommandObjectProcessGDBRemoteSpeedTest() override = default;
4908061da546Spatrick
GetOptions()4909061da546Spatrick Options *GetOptions() override { return &m_option_group; }
4910061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4911061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4912061da546Spatrick const size_t argc = command.GetArgumentCount();
4913061da546Spatrick if (argc == 0) {
4914061da546Spatrick ProcessGDBRemote *process =
4915061da546Spatrick (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4916061da546Spatrick .GetProcessPtr();
4917061da546Spatrick if (process) {
4918061da546Spatrick StreamSP output_stream_sp(
4919061da546Spatrick m_interpreter.GetDebugger().GetAsyncOutputStream());
4920061da546Spatrick result.SetImmediateOutputStream(output_stream_sp);
4921061da546Spatrick
4922061da546Spatrick const uint32_t num_packets =
4923061da546Spatrick (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4924061da546Spatrick const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4925061da546Spatrick const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4926061da546Spatrick const bool json = m_json.GetOptionValue().GetCurrentValue();
4927061da546Spatrick const uint64_t k_recv_amount =
4928061da546Spatrick 4 * 1024 * 1024; // Receive amount in bytes
4929061da546Spatrick process->GetGDBRemote().TestPacketSpeed(
4930061da546Spatrick num_packets, max_send, max_recv, k_recv_amount, json,
4931061da546Spatrick output_stream_sp ? *output_stream_sp : result.GetOutputStream());
4932061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4933061da546Spatrick return true;
4934061da546Spatrick }
4935061da546Spatrick } else {
4936061da546Spatrick result.AppendErrorWithFormat("'%s' takes no arguments",
4937061da546Spatrick m_cmd_name.c_str());
4938061da546Spatrick }
4939061da546Spatrick result.SetStatus(eReturnStatusFailed);
4940061da546Spatrick return false;
4941061da546Spatrick }
4942061da546Spatrick
4943061da546Spatrick protected:
4944061da546Spatrick OptionGroupOptions m_option_group;
4945061da546Spatrick OptionGroupUInt64 m_num_packets;
4946061da546Spatrick OptionGroupUInt64 m_max_send;
4947061da546Spatrick OptionGroupUInt64 m_max_recv;
4948061da546Spatrick OptionGroupBoolean m_json;
4949061da546Spatrick };
4950061da546Spatrick
4951061da546Spatrick class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
4952061da546Spatrick private:
4953061da546Spatrick public:
CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter & interpreter)4954061da546Spatrick CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
4955061da546Spatrick : CommandObjectParsed(interpreter, "process plugin packet history",
4956061da546Spatrick "Dumps the packet history buffer. ", nullptr) {}
4957061da546Spatrick
4958be691f3bSpatrick ~CommandObjectProcessGDBRemotePacketHistory() override = default;
4959061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4960061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4961061da546Spatrick ProcessGDBRemote *process =
4962*f6aab3d8Srobert (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4963061da546Spatrick if (process) {
4964061da546Spatrick process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4965061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
4966061da546Spatrick return true;
4967061da546Spatrick }
4968061da546Spatrick result.SetStatus(eReturnStatusFailed);
4969061da546Spatrick return false;
4970061da546Spatrick }
4971061da546Spatrick };
4972061da546Spatrick
4973061da546Spatrick class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
4974061da546Spatrick private:
4975061da546Spatrick public:
CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter & interpreter)4976061da546Spatrick CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
4977061da546Spatrick : CommandObjectParsed(
4978061da546Spatrick interpreter, "process plugin packet xfer-size",
4979061da546Spatrick "Maximum size that lldb will try to read/write one one chunk.",
4980*f6aab3d8Srobert nullptr) {
4981*f6aab3d8Srobert CommandArgumentData max_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4982*f6aab3d8Srobert m_arguments.push_back({max_arg});
4983*f6aab3d8Srobert }
4984061da546Spatrick
4985be691f3bSpatrick ~CommandObjectProcessGDBRemotePacketXferSize() override = default;
4986061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)4987061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
4988061da546Spatrick const size_t argc = command.GetArgumentCount();
4989061da546Spatrick if (argc == 0) {
4990061da546Spatrick result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
4991061da546Spatrick "amount to be transferred when "
4992061da546Spatrick "reading/writing",
4993061da546Spatrick m_cmd_name.c_str());
4994061da546Spatrick return false;
4995061da546Spatrick }
4996061da546Spatrick
4997061da546Spatrick ProcessGDBRemote *process =
4998061da546Spatrick (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4999061da546Spatrick if (process) {
5000061da546Spatrick const char *packet_size = command.GetArgumentAtIndex(0);
5001061da546Spatrick errno = 0;
5002061da546Spatrick uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5003061da546Spatrick if (errno == 0 && user_specified_max != 0) {
5004061da546Spatrick process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5005061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
5006061da546Spatrick return true;
5007061da546Spatrick }
5008061da546Spatrick }
5009061da546Spatrick result.SetStatus(eReturnStatusFailed);
5010061da546Spatrick return false;
5011061da546Spatrick }
5012061da546Spatrick };
5013061da546Spatrick
5014061da546Spatrick class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5015061da546Spatrick private:
5016061da546Spatrick public:
CommandObjectProcessGDBRemotePacketSend(CommandInterpreter & interpreter)5017061da546Spatrick CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5018061da546Spatrick : CommandObjectParsed(interpreter, "process plugin packet send",
5019061da546Spatrick "Send a custom packet through the GDB remote "
5020061da546Spatrick "protocol and print the answer. "
5021061da546Spatrick "The packet header and footer will automatically "
5022061da546Spatrick "be added to the packet prior to sending and "
5023061da546Spatrick "stripped from the result.",
5024*f6aab3d8Srobert nullptr) {
5025*f6aab3d8Srobert CommandArgumentData packet_arg{eArgTypeNone, eArgRepeatStar};
5026*f6aab3d8Srobert m_arguments.push_back({packet_arg});
5027*f6aab3d8Srobert }
5028061da546Spatrick
5029be691f3bSpatrick ~CommandObjectProcessGDBRemotePacketSend() override = default;
5030061da546Spatrick
DoExecute(Args & command,CommandReturnObject & result)5031061da546Spatrick bool DoExecute(Args &command, CommandReturnObject &result) override {
5032061da546Spatrick const size_t argc = command.GetArgumentCount();
5033061da546Spatrick if (argc == 0) {
5034061da546Spatrick result.AppendErrorWithFormat(
5035061da546Spatrick "'%s' takes a one or more packet content arguments",
5036061da546Spatrick m_cmd_name.c_str());
5037061da546Spatrick return false;
5038061da546Spatrick }
5039061da546Spatrick
5040061da546Spatrick ProcessGDBRemote *process =
5041061da546Spatrick (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5042061da546Spatrick if (process) {
5043061da546Spatrick for (size_t i = 0; i < argc; ++i) {
5044061da546Spatrick const char *packet_cstr = command.GetArgumentAtIndex(0);
5045061da546Spatrick StringExtractorGDBRemote response;
5046061da546Spatrick process->GetGDBRemote().SendPacketAndWaitForResponse(
5047be691f3bSpatrick packet_cstr, response, process->GetInterruptTimeout());
5048061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
5049061da546Spatrick Stream &output_strm = result.GetOutputStream();
5050061da546Spatrick output_strm.Printf(" packet: %s\n", packet_cstr);
5051dda28197Spatrick std::string response_str = std::string(response.GetStringRef());
5052061da546Spatrick
5053061da546Spatrick if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5054061da546Spatrick response_str = process->HarmonizeThreadIdsForProfileData(response);
5055061da546Spatrick }
5056061da546Spatrick
5057061da546Spatrick if (response_str.empty())
5058061da546Spatrick output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5059061da546Spatrick else
5060061da546Spatrick output_strm.Printf("response: %s\n", response.GetStringRef().data());
5061061da546Spatrick }
5062061da546Spatrick }
5063061da546Spatrick return true;
5064061da546Spatrick }
5065061da546Spatrick };
5066061da546Spatrick
5067061da546Spatrick class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5068061da546Spatrick private:
5069061da546Spatrick public:
CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter & interpreter)5070061da546Spatrick CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5071061da546Spatrick : CommandObjectRaw(interpreter, "process plugin packet monitor",
5072061da546Spatrick "Send a qRcmd packet through the GDB remote protocol "
5073061da546Spatrick "and print the response."
5074061da546Spatrick "The argument passed to this command will be hex "
5075061da546Spatrick "encoded into a valid 'qRcmd' packet, sent and the "
5076061da546Spatrick "response will be printed.") {}
5077061da546Spatrick
5078be691f3bSpatrick ~CommandObjectProcessGDBRemotePacketMonitor() override = default;
5079061da546Spatrick
DoExecute(llvm::StringRef command,CommandReturnObject & result)5080061da546Spatrick bool DoExecute(llvm::StringRef command,
5081061da546Spatrick CommandReturnObject &result) override {
5082061da546Spatrick if (command.empty()) {
5083061da546Spatrick result.AppendErrorWithFormat("'%s' takes a command string argument",
5084061da546Spatrick m_cmd_name.c_str());
5085061da546Spatrick return false;
5086061da546Spatrick }
5087061da546Spatrick
5088061da546Spatrick ProcessGDBRemote *process =
5089061da546Spatrick (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5090061da546Spatrick if (process) {
5091061da546Spatrick StreamString packet;
5092061da546Spatrick packet.PutCString("qRcmd,");
5093061da546Spatrick packet.PutBytesAsRawHex8(command.data(), command.size());
5094061da546Spatrick
5095061da546Spatrick StringExtractorGDBRemote response;
5096061da546Spatrick Stream &output_strm = result.GetOutputStream();
5097061da546Spatrick process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5098be691f3bSpatrick packet.GetString(), response, process->GetInterruptTimeout(),
5099061da546Spatrick [&output_strm](llvm::StringRef output) { output_strm << output; });
5100061da546Spatrick result.SetStatus(eReturnStatusSuccessFinishResult);
5101061da546Spatrick output_strm.Printf(" packet: %s\n", packet.GetData());
5102dda28197Spatrick const std::string &response_str = std::string(response.GetStringRef());
5103061da546Spatrick
5104061da546Spatrick if (response_str.empty())
5105061da546Spatrick output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5106061da546Spatrick else
5107061da546Spatrick output_strm.Printf("response: %s\n", response.GetStringRef().data());
5108061da546Spatrick }
5109061da546Spatrick return true;
5110061da546Spatrick }
5111061da546Spatrick };
5112061da546Spatrick
5113061da546Spatrick class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5114061da546Spatrick private:
5115061da546Spatrick public:
CommandObjectProcessGDBRemotePacket(CommandInterpreter & interpreter)5116061da546Spatrick CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5117061da546Spatrick : CommandObjectMultiword(interpreter, "process plugin packet",
5118061da546Spatrick "Commands that deal with GDB remote packets.",
5119061da546Spatrick nullptr) {
5120061da546Spatrick LoadSubCommand(
5121061da546Spatrick "history",
5122061da546Spatrick CommandObjectSP(
5123061da546Spatrick new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5124061da546Spatrick LoadSubCommand(
5125061da546Spatrick "send", CommandObjectSP(
5126061da546Spatrick new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5127061da546Spatrick LoadSubCommand(
5128061da546Spatrick "monitor",
5129061da546Spatrick CommandObjectSP(
5130061da546Spatrick new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5131061da546Spatrick LoadSubCommand(
5132061da546Spatrick "xfer-size",
5133061da546Spatrick CommandObjectSP(
5134061da546Spatrick new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5135061da546Spatrick LoadSubCommand("speed-test",
5136061da546Spatrick CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5137061da546Spatrick interpreter)));
5138061da546Spatrick }
5139061da546Spatrick
5140be691f3bSpatrick ~CommandObjectProcessGDBRemotePacket() override = default;
5141061da546Spatrick };
5142061da546Spatrick
5143061da546Spatrick class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5144061da546Spatrick public:
CommandObjectMultiwordProcessGDBRemote(CommandInterpreter & interpreter)5145061da546Spatrick CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5146061da546Spatrick : CommandObjectMultiword(
5147061da546Spatrick interpreter, "process plugin",
5148061da546Spatrick "Commands for operating on a ProcessGDBRemote process.",
5149061da546Spatrick "process plugin <subcommand> [<subcommand-options>]") {
5150061da546Spatrick LoadSubCommand(
5151061da546Spatrick "packet",
5152061da546Spatrick CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5153061da546Spatrick }
5154061da546Spatrick
5155be691f3bSpatrick ~CommandObjectMultiwordProcessGDBRemote() override = default;
5156061da546Spatrick };
5157061da546Spatrick
GetPluginCommandObject()5158061da546Spatrick CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5159061da546Spatrick if (!m_command_sp)
5160061da546Spatrick m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5161061da546Spatrick GetTarget().GetDebugger().GetCommandInterpreter());
5162061da546Spatrick return m_command_sp.get();
5163061da546Spatrick }
5164*f6aab3d8Srobert
DidForkSwitchSoftwareBreakpoints(bool enable)5165*f6aab3d8Srobert void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {
5166*f6aab3d8Srobert GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5167*f6aab3d8Srobert if (bp_site->IsEnabled() &&
5168*f6aab3d8Srobert (bp_site->GetType() == BreakpointSite::eSoftware ||
5169*f6aab3d8Srobert bp_site->GetType() == BreakpointSite::eExternal)) {
5170*f6aab3d8Srobert m_gdb_comm.SendGDBStoppointTypePacket(
5171*f6aab3d8Srobert eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5172*f6aab3d8Srobert GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5173*f6aab3d8Srobert }
5174*f6aab3d8Srobert });
5175*f6aab3d8Srobert }
5176*f6aab3d8Srobert
DidForkSwitchHardwareTraps(bool enable)5177*f6aab3d8Srobert void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {
5178*f6aab3d8Srobert if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
5179*f6aab3d8Srobert GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5180*f6aab3d8Srobert if (bp_site->IsEnabled() &&
5181*f6aab3d8Srobert bp_site->GetType() == BreakpointSite::eHardware) {
5182*f6aab3d8Srobert m_gdb_comm.SendGDBStoppointTypePacket(
5183*f6aab3d8Srobert eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5184*f6aab3d8Srobert GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5185*f6aab3d8Srobert }
5186*f6aab3d8Srobert });
5187*f6aab3d8Srobert }
5188*f6aab3d8Srobert
5189*f6aab3d8Srobert WatchpointList &wps = GetTarget().GetWatchpointList();
5190*f6aab3d8Srobert size_t wp_count = wps.GetSize();
5191*f6aab3d8Srobert for (size_t i = 0; i < wp_count; ++i) {
5192*f6aab3d8Srobert WatchpointSP wp = wps.GetByIndex(i);
5193*f6aab3d8Srobert if (wp->IsEnabled()) {
5194*f6aab3d8Srobert GDBStoppointType type = GetGDBStoppointType(wp.get());
5195*f6aab3d8Srobert m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5196*f6aab3d8Srobert wp->GetByteSize(),
5197*f6aab3d8Srobert GetInterruptTimeout());
5198*f6aab3d8Srobert }
5199*f6aab3d8Srobert }
5200*f6aab3d8Srobert }
5201*f6aab3d8Srobert
DidFork(lldb::pid_t child_pid,lldb::tid_t child_tid)5202*f6aab3d8Srobert void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5203*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
5204*f6aab3d8Srobert
5205*f6aab3d8Srobert lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5206*f6aab3d8Srobert // Any valid TID will suffice, thread-relevant actions will set a proper TID
5207*f6aab3d8Srobert // anyway.
5208*f6aab3d8Srobert lldb::tid_t parent_tid = m_thread_ids.front();
5209*f6aab3d8Srobert
5210*f6aab3d8Srobert lldb::pid_t follow_pid, detach_pid;
5211*f6aab3d8Srobert lldb::tid_t follow_tid, detach_tid;
5212*f6aab3d8Srobert
5213*f6aab3d8Srobert switch (GetFollowForkMode()) {
5214*f6aab3d8Srobert case eFollowParent:
5215*f6aab3d8Srobert follow_pid = parent_pid;
5216*f6aab3d8Srobert follow_tid = parent_tid;
5217*f6aab3d8Srobert detach_pid = child_pid;
5218*f6aab3d8Srobert detach_tid = child_tid;
5219*f6aab3d8Srobert break;
5220*f6aab3d8Srobert case eFollowChild:
5221*f6aab3d8Srobert follow_pid = child_pid;
5222*f6aab3d8Srobert follow_tid = child_tid;
5223*f6aab3d8Srobert detach_pid = parent_pid;
5224*f6aab3d8Srobert detach_tid = parent_tid;
5225*f6aab3d8Srobert break;
5226*f6aab3d8Srobert }
5227*f6aab3d8Srobert
5228*f6aab3d8Srobert // Switch to the process that is going to be detached.
5229*f6aab3d8Srobert if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5230*f6aab3d8Srobert LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5231*f6aab3d8Srobert return;
5232*f6aab3d8Srobert }
5233*f6aab3d8Srobert
5234*f6aab3d8Srobert // Disable all software breakpoints in the forked process.
5235*f6aab3d8Srobert if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5236*f6aab3d8Srobert DidForkSwitchSoftwareBreakpoints(false);
5237*f6aab3d8Srobert
5238*f6aab3d8Srobert // Remove hardware breakpoints / watchpoints from parent process if we're
5239*f6aab3d8Srobert // following child.
5240*f6aab3d8Srobert if (GetFollowForkMode() == eFollowChild)
5241*f6aab3d8Srobert DidForkSwitchHardwareTraps(false);
5242*f6aab3d8Srobert
5243*f6aab3d8Srobert // Switch to the process that is going to be followed
5244*f6aab3d8Srobert if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5245*f6aab3d8Srobert !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5246*f6aab3d8Srobert LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5247*f6aab3d8Srobert return;
5248*f6aab3d8Srobert }
5249*f6aab3d8Srobert
5250*f6aab3d8Srobert LLDB_LOG(log, "Detaching process {0}", detach_pid);
5251*f6aab3d8Srobert Status error = m_gdb_comm.Detach(false, detach_pid);
5252*f6aab3d8Srobert if (error.Fail()) {
5253*f6aab3d8Srobert LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5254*f6aab3d8Srobert error.AsCString() ? error.AsCString() : "<unknown error>");
5255*f6aab3d8Srobert return;
5256*f6aab3d8Srobert }
5257*f6aab3d8Srobert
5258*f6aab3d8Srobert // Hardware breakpoints/watchpoints are not inherited implicitly,
5259*f6aab3d8Srobert // so we need to readd them if we're following child.
5260*f6aab3d8Srobert if (GetFollowForkMode() == eFollowChild) {
5261*f6aab3d8Srobert DidForkSwitchHardwareTraps(true);
5262*f6aab3d8Srobert // Update our PID
5263*f6aab3d8Srobert SetID(child_pid);
5264*f6aab3d8Srobert }
5265*f6aab3d8Srobert }
5266*f6aab3d8Srobert
DidVFork(lldb::pid_t child_pid,lldb::tid_t child_tid)5267*f6aab3d8Srobert void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5268*f6aab3d8Srobert Log *log = GetLog(GDBRLog::Process);
5269*f6aab3d8Srobert
5270*f6aab3d8Srobert assert(!m_vfork_in_progress);
5271*f6aab3d8Srobert m_vfork_in_progress = true;
5272*f6aab3d8Srobert
5273*f6aab3d8Srobert // Disable all software breakpoints for the duration of vfork.
5274*f6aab3d8Srobert if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5275*f6aab3d8Srobert DidForkSwitchSoftwareBreakpoints(false);
5276*f6aab3d8Srobert
5277*f6aab3d8Srobert lldb::pid_t detach_pid;
5278*f6aab3d8Srobert lldb::tid_t detach_tid;
5279*f6aab3d8Srobert
5280*f6aab3d8Srobert switch (GetFollowForkMode()) {
5281*f6aab3d8Srobert case eFollowParent:
5282*f6aab3d8Srobert detach_pid = child_pid;
5283*f6aab3d8Srobert detach_tid = child_tid;
5284*f6aab3d8Srobert break;
5285*f6aab3d8Srobert case eFollowChild:
5286*f6aab3d8Srobert detach_pid = m_gdb_comm.GetCurrentProcessID();
5287*f6aab3d8Srobert // Any valid TID will suffice, thread-relevant actions will set a proper TID
5288*f6aab3d8Srobert // anyway.
5289*f6aab3d8Srobert detach_tid = m_thread_ids.front();
5290*f6aab3d8Srobert
5291*f6aab3d8Srobert // Switch to the parent process before detaching it.
5292*f6aab3d8Srobert if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5293*f6aab3d8Srobert LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5294*f6aab3d8Srobert return;
5295*f6aab3d8Srobert }
5296*f6aab3d8Srobert
5297*f6aab3d8Srobert // Remove hardware breakpoints / watchpoints from the parent process.
5298*f6aab3d8Srobert DidForkSwitchHardwareTraps(false);
5299*f6aab3d8Srobert
5300*f6aab3d8Srobert // Switch to the child process.
5301*f6aab3d8Srobert if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5302*f6aab3d8Srobert !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5303*f6aab3d8Srobert LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5304*f6aab3d8Srobert return;
5305*f6aab3d8Srobert }
5306*f6aab3d8Srobert break;
5307*f6aab3d8Srobert }
5308*f6aab3d8Srobert
5309*f6aab3d8Srobert LLDB_LOG(log, "Detaching process {0}", detach_pid);
5310*f6aab3d8Srobert Status error = m_gdb_comm.Detach(false, detach_pid);
5311*f6aab3d8Srobert if (error.Fail()) {
5312*f6aab3d8Srobert LLDB_LOG(log,
5313*f6aab3d8Srobert "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5314*f6aab3d8Srobert error.AsCString() ? error.AsCString() : "<unknown error>");
5315*f6aab3d8Srobert return;
5316*f6aab3d8Srobert }
5317*f6aab3d8Srobert
5318*f6aab3d8Srobert if (GetFollowForkMode() == eFollowChild) {
5319*f6aab3d8Srobert // Update our PID
5320*f6aab3d8Srobert SetID(child_pid);
5321*f6aab3d8Srobert }
5322*f6aab3d8Srobert }
5323*f6aab3d8Srobert
DidVForkDone()5324*f6aab3d8Srobert void ProcessGDBRemote::DidVForkDone() {
5325*f6aab3d8Srobert assert(m_vfork_in_progress);
5326*f6aab3d8Srobert m_vfork_in_progress = false;
5327*f6aab3d8Srobert
5328*f6aab3d8Srobert // Reenable all software breakpoints that were enabled before vfork.
5329*f6aab3d8Srobert if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5330*f6aab3d8Srobert DidForkSwitchSoftwareBreakpoints(true);
5331*f6aab3d8Srobert }
5332*f6aab3d8Srobert
DidExec()5333*f6aab3d8Srobert void ProcessGDBRemote::DidExec() {
5334*f6aab3d8Srobert // If we are following children, vfork is finished by exec (rather than
5335*f6aab3d8Srobert // vforkdone that is submitted for parent).
5336*f6aab3d8Srobert if (GetFollowForkMode() == eFollowChild)
5337*f6aab3d8Srobert m_vfork_in_progress = false;
5338*f6aab3d8Srobert Process::DidExec();
5339*f6aab3d8Srobert }
5340