Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
Warning:line 3190, column 7
Value stored to 'error_string' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ProcessGDBRemote.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm/tools/clang/stage2-bins -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -isystem /usr/include/libxml2 -D HAVE_ROUND -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/lldb/source/Plugins/Process/gdb-remote -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lldb/source/Plugins/Process/gdb-remote -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lldb/include -I tools/lldb/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -I /usr/include/python3.9 -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/lldb/../clang/include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lldb/source -I tools/lldb/source -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O2 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -Wno-deprecated-declarations -Wno-unknown-pragmas -Wno-strict-aliasing -Wno-stringop-truncation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm/tools/clang/stage2-bins=build-llvm/tools/clang/stage2-bins -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp
1//===-- ProcessGDBRemote.cpp ----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Host/Config.h"
10
11#include <cerrno>
12#include <cstdlib>
13#if LLDB_ENABLE_POSIX1
14#include <netinet/in.h>
15#include <sys/mman.h>
16#include <sys/socket.h>
17#include <unistd.h>
18#endif
19#include <sys/stat.h>
20#if defined(__APPLE__)
21#include <sys/sysctl.h>
22#endif
23#include <ctime>
24#include <sys/types.h>
25
26#include "lldb/Breakpoint/Watchpoint.h"
27#include "lldb/Core/Debugger.h"
28#include "lldb/Core/Module.h"
29#include "lldb/Core/ModuleSpec.h"
30#include "lldb/Core/PluginManager.h"
31#include "lldb/Core/StreamFile.h"
32#include "lldb/Core/Value.h"
33#include "lldb/DataFormatters/FormatManager.h"
34#include "lldb/Host/ConnectionFileDescriptor.h"
35#include "lldb/Host/FileSystem.h"
36#include "lldb/Host/HostThread.h"
37#include "lldb/Host/PosixApi.h"
38#include "lldb/Host/PseudoTerminal.h"
39#include "lldb/Host/ThreadLauncher.h"
40#include "lldb/Host/XML.h"
41#include "lldb/Interpreter/CommandInterpreter.h"
42#include "lldb/Interpreter/CommandObject.h"
43#include "lldb/Interpreter/CommandObjectMultiword.h"
44#include "lldb/Interpreter/CommandReturnObject.h"
45#include "lldb/Interpreter/OptionArgParser.h"
46#include "lldb/Interpreter/OptionGroupBoolean.h"
47#include "lldb/Interpreter/OptionGroupUInt64.h"
48#include "lldb/Interpreter/OptionValueProperties.h"
49#include "lldb/Interpreter/Options.h"
50#include "lldb/Interpreter/Property.h"
51#include "lldb/Symbol/LocateSymbolFile.h"
52#include "lldb/Symbol/ObjectFile.h"
53#include "lldb/Target/ABI.h"
54#include "lldb/Target/DynamicLoader.h"
55#include "lldb/Target/MemoryRegionInfo.h"
56#include "lldb/Target/SystemRuntime.h"
57#include "lldb/Target/Target.h"
58#include "lldb/Target/TargetList.h"
59#include "lldb/Target/ThreadPlanCallFunction.h"
60#include "lldb/Utility/Args.h"
61#include "lldb/Utility/FileSpec.h"
62#include "lldb/Utility/LLDBLog.h"
63#include "lldb/Utility/Reproducer.h"
64#include "lldb/Utility/State.h"
65#include "lldb/Utility/StreamString.h"
66#include "lldb/Utility/Timer.h"
67#include <algorithm>
68#include <csignal>
69#include <map>
70#include <memory>
71#include <mutex>
72#include <sstream>
73#include <thread>
74
75#include "GDBRemoteRegisterContext.h"
76#include "GDBRemoteRegisterFallback.h"
77#include "Plugins/Process/Utility/GDBRemoteSignals.h"
78#include "Plugins/Process/Utility/InferiorCallPOSIX.h"
79#include "Plugins/Process/Utility/StopInfoMachException.h"
80#include "ProcessGDBRemote.h"
81#include "ProcessGDBRemoteLog.h"
82#include "ThreadGDBRemote.h"
83#include "lldb/Host/Host.h"
84#include "lldb/Utility/StringExtractorGDBRemote.h"
85
86#include "llvm/ADT/ScopeExit.h"
87#include "llvm/ADT/StringSwitch.h"
88#include "llvm/Support/Threading.h"
89#include "llvm/Support/raw_ostream.h"
90
91#define DEBUGSERVER_BASENAME"debugserver" "debugserver"
92using namespace lldb;
93using namespace lldb_private;
94using namespace lldb_private::process_gdb_remote;
95
96LLDB_PLUGIN_DEFINE(ProcessGDBRemote)namespace lldb_private { void lldb_initialize_ProcessGDBRemote
() { ProcessGDBRemote::Initialize(); } void lldb_terminate_ProcessGDBRemote
() { ProcessGDBRemote::Terminate(); } }
97
98namespace lldb {
99// Provide a function that can easily dump the packet history if we know a
100// ProcessGDBRemote * value (which we can get from logs or from debugging). We
101// need the function in the lldb namespace so it makes it into the final
102// executable since the LLDB shared library only exports stuff in the lldb
103// namespace. This allows you to attach with a debugger and call this function
104// and get the packet history dumped to a file.
105void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
106 auto file = FileSystem::Instance().Open(
107 FileSpec(path), File::eOpenOptionWriteOnly | File::eOpenOptionCanCreate);
108 if (!file) {
109 llvm::consumeError(file.takeError());
110 return;
111 }
112 StreamFile stream(std::move(file.get()));
113 ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream);
114}
115} // namespace lldb
116
117namespace {
118
119#define LLDB_PROPERTIES_processgdbremote
120#include "ProcessGDBRemoteProperties.inc"
121
122enum {
123#define LLDB_PROPERTIES_processgdbremote
124#include "ProcessGDBRemotePropertiesEnum.inc"
125};
126
127class PluginProperties : public Properties {
128public:
129 static ConstString GetSettingName() {
130 return ConstString(ProcessGDBRemote::GetPluginNameStatic());
131 }
132
133 PluginProperties() : Properties() {
134 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
135 m_collection_sp->Initialize(g_processgdbremote_properties);
136 }
137
138 ~PluginProperties() override = default;
139
140 uint64_t GetPacketTimeout() {
141 const uint32_t idx = ePropertyPacketTimeout;
142 return m_collection_sp->GetPropertyAtIndexAsUInt64(
143 nullptr, idx, g_processgdbremote_properties[idx].default_uint_value);
144 }
145
146 bool SetPacketTimeout(uint64_t timeout) {
147 const uint32_t idx = ePropertyPacketTimeout;
148 return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout);
149 }
150
151 FileSpec GetTargetDefinitionFile() const {
152 const uint32_t idx = ePropertyTargetDefinitionFile;
153 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
154 }
155
156 bool GetUseSVR4() const {
157 const uint32_t idx = ePropertyUseSVR4;
158 return m_collection_sp->GetPropertyAtIndexAsBoolean(
159 nullptr, idx,
160 g_processgdbremote_properties[idx].default_uint_value != 0);
161 }
162
163 bool GetUseGPacketForReading() const {
164 const uint32_t idx = ePropertyUseGPacketForReading;
165 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true);
166 }
167};
168
169static PluginProperties &GetGlobalPluginProperties() {
170 static PluginProperties g_settings;
171 return g_settings;
172}
173
174} // namespace
175
176// TODO Randomly assigning a port is unsafe. We should get an unused
177// ephemeral port from the kernel and make sure we reserve it before passing it
178// to debugserver.
179
180#if defined(__APPLE__)
181#define LOW_PORT(1024u) (IPPORT_RESERVED1024)
182#define HIGH_PORT(49151u) (IPPORT_HIFIRSTAUTO)
183#else
184#define LOW_PORT(1024u) (1024u)
185#define HIGH_PORT(49151u) (49151u)
186#endif
187
188llvm::StringRef ProcessGDBRemote::GetPluginDescriptionStatic() {
189 return "GDB Remote protocol based debugging plug-in.";
190}
191
192void ProcessGDBRemote::Terminate() {
193 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance);
194}
195
196lldb::ProcessSP ProcessGDBRemote::CreateInstance(
197 lldb::TargetSP target_sp, ListenerSP listener_sp,
198 const FileSpec *crash_file_path, bool can_connect) {
199 lldb::ProcessSP process_sp;
200 if (crash_file_path == nullptr)
201 process_sp = std::shared_ptr<ProcessGDBRemote>(
202 new ProcessGDBRemote(target_sp, listener_sp));
203 return process_sp;
204}
205
206std::chrono::seconds ProcessGDBRemote::GetPacketTimeout() {
207 return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
208}
209
210ArchSpec ProcessGDBRemote::GetSystemArchitecture() {
211 return m_gdb_comm.GetHostArchitecture();
212}
213
214bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp,
215 bool plugin_specified_by_name) {
216 if (plugin_specified_by_name)
217 return true;
218
219 // For now we are just making sure the file exists for a given module
220 Module *exe_module = target_sp->GetExecutableModulePointer();
221 if (exe_module) {
222 ObjectFile *exe_objfile = exe_module->GetObjectFile();
223 // We can't debug core files...
224 switch (exe_objfile->GetType()) {
225 case ObjectFile::eTypeInvalid:
226 case ObjectFile::eTypeCoreFile:
227 case ObjectFile::eTypeDebugInfo:
228 case ObjectFile::eTypeObjectFile:
229 case ObjectFile::eTypeSharedLibrary:
230 case ObjectFile::eTypeStubLibrary:
231 case ObjectFile::eTypeJIT:
232 return false;
233 case ObjectFile::eTypeExecutable:
234 case ObjectFile::eTypeDynamicLinker:
235 case ObjectFile::eTypeUnknown:
236 break;
237 }
238 return FileSystem::Instance().Exists(exe_module->GetFileSpec());
239 }
240 // However, if there is no executable module, we return true since we might
241 // be preparing to attach.
242 return true;
243}
244
245// ProcessGDBRemote constructor
246ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp,
247 ListenerSP listener_sp)
248 : Process(target_sp, listener_sp),
249 m_debugserver_pid(LLDB_INVALID_PROCESS_ID0), m_register_info_sp(nullptr),
250 m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
251 m_async_listener_sp(
252 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
253 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
254 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
255 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
256 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
257 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
258 m_waiting_for_attach(false),
259 m_command_sp(), m_breakpoint_pc_offset(0),
260 m_initial_tid(LLDB_INVALID_THREAD_ID0), m_allow_flash_writes(false),
261 m_erased_flash_ranges(), m_vfork_in_progress(false) {
262 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit,
263 "async thread should exit");
264 m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue,
265 "async thread continue");
266 m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit,
267 "async thread did exit");
268
269 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
270 repro::GDBRemoteProvider &provider =
271 g->GetOrCreate<repro::GDBRemoteProvider>();
272 m_gdb_comm.SetPacketRecorder(provider.GetNewPacketRecorder());
273 }
274
275 Log *log = GetLog(GDBRLog::Async);
276
277 const uint32_t async_event_mask =
278 eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit;
279
280 if (m_async_listener_sp->StartListeningForEvents(
281 &m_async_broadcaster, async_event_mask) != async_event_mask) {
282 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s failed to listen for "
"m_async_broadcaster events", __FUNCTION__); } while (0)
283 "ProcessGDBRemote::%s failed to listen for "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s failed to listen for "
"m_async_broadcaster events", __FUNCTION__); } while (0)
284 "m_async_broadcaster events",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s failed to listen for "
"m_async_broadcaster events", __FUNCTION__); } while (0)
285 __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s failed to listen for "
"m_async_broadcaster events", __FUNCTION__); } while (0)
;
286 }
287
288 const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit;
289 if (m_async_listener_sp->StartListeningForEvents(
290 &m_gdb_comm, gdb_event_mask) != gdb_event_mask) {
291 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events"
, __FUNCTION__); } while (0)
292 "ProcessGDBRemote::%s failed to listen for m_gdb_comm events",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events"
, __FUNCTION__); } while (0)
293 __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s failed to listen for m_gdb_comm events"
, __FUNCTION__); } while (0)
;
294 }
295
296 const uint64_t timeout_seconds =
297 GetGlobalPluginProperties().GetPacketTimeout();
298 if (timeout_seconds > 0)
299 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
300
301 m_use_g_packet_for_reading =
302 GetGlobalPluginProperties().GetUseGPacketForReading();
303}
304
305// Destructor
306ProcessGDBRemote::~ProcessGDBRemote() {
307 // m_mach_process.UnregisterNotificationCallbacks (this);
308 Clear();
309 // We need to call finalize on the process before destroying ourselves to
310 // make sure all of the broadcaster cleanup goes as planned. If we destruct
311 // this class, then Process::~Process() might have problems trying to fully
312 // destroy the broadcaster.
313 Finalize();
314
315 // The general Finalize is going to try to destroy the process and that
316 // SHOULD shut down the async thread. However, if we don't kill it it will
317 // get stranded and its connection will go away so when it wakes up it will
318 // crash. So kill it for sure here.
319 StopAsyncThread();
320 KillDebugserverProcess();
321}
322
323bool ProcessGDBRemote::ParsePythonTargetDefinition(
324 const FileSpec &target_definition_fspec) {
325 ScriptInterpreter *interpreter =
326 GetTarget().GetDebugger().GetScriptInterpreter();
327 Status error;
328 StructuredData::ObjectSP module_object_sp(
329 interpreter->LoadPluginModule(target_definition_fspec, error));
330 if (module_object_sp) {
331 StructuredData::DictionarySP target_definition_sp(
332 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
333 "gdb-server-target-definition", error));
334
335 if (target_definition_sp) {
336 StructuredData::ObjectSP target_object(
337 target_definition_sp->GetValueForKey("host-info"));
338 if (target_object) {
339 if (auto host_info_dict = target_object->GetAsDictionary()) {
340 StructuredData::ObjectSP triple_value =
341 host_info_dict->GetValueForKey("triple");
342 if (auto triple_string_value = triple_value->GetAsString()) {
343 std::string triple_string =
344 std::string(triple_string_value->GetValue());
345 ArchSpec host_arch(triple_string.c_str());
346 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
347 GetTarget().SetArchitecture(host_arch);
348 }
349 }
350 }
351 }
352 m_breakpoint_pc_offset = 0;
353 StructuredData::ObjectSP breakpoint_pc_offset_value =
354 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
355 if (breakpoint_pc_offset_value) {
356 if (auto breakpoint_pc_int_value =
357 breakpoint_pc_offset_value->GetAsInteger())
358 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
359 }
360
361 if (m_register_info_sp->SetRegisterInfo(
362 *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
363 return true;
364 }
365 }
366 }
367 return false;
368}
369
370static size_t SplitCommaSeparatedRegisterNumberString(
371 const llvm::StringRef &comma_separated_register_numbers,
372 std::vector<uint32_t> &regnums, int base) {
373 regnums.clear();
374 for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
375 uint32_t reg;
376 if (llvm::to_integer(x, reg, base))
377 regnums.push_back(reg);
378 }
379 return regnums.size();
380}
381
382void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) {
383 if (!force && m_register_info_sp)
384 return;
385
386 m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
387
388 // Check if qHostInfo specified a specific packet timeout for this
389 // connection. If so then lets update our setting so the user knows what the
390 // timeout is and can see it.
391 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
392 if (host_packet_timeout > std::chrono::seconds(0)) {
393 GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
394 }
395
396 // Register info search order:
397 // 1 - Use the target definition python file if one is specified.
398 // 2 - If the target definition doesn't have any of the info from the
399 // target.xml (registers) then proceed to read the target.xml.
400 // 3 - Fall back on the qRegisterInfo packets.
401 // 4 - Use hardcoded defaults if available.
402
403 FileSpec target_definition_fspec =
404 GetGlobalPluginProperties().GetTargetDefinitionFile();
405 if (!FileSystem::Instance().Exists(target_definition_fspec)) {
406 // If the filename doesn't exist, it may be a ~ not having been expanded -
407 // try to resolve it.
408 FileSystem::Instance().Resolve(target_definition_fspec);
409 }
410 if (target_definition_fspec) {
411 // See if we can get register definitions from a python file
412 if (ParsePythonTargetDefinition(target_definition_fspec))
413 return;
414
415 Debugger::ReportError("target description file " +
416 target_definition_fspec.GetPath() +
417 " failed to parse",
418 GetTarget().GetDebugger().GetID());
419 }
420
421 const ArchSpec &target_arch = GetTarget().GetArchitecture();
422 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
423 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
424
425 // Use the process' architecture instead of the host arch, if available
426 ArchSpec arch_to_use;
427 if (remote_process_arch.IsValid())
428 arch_to_use = remote_process_arch;
429 else
430 arch_to_use = remote_host_arch;
431
432 if (!arch_to_use.IsValid())
433 arch_to_use = target_arch;
434
435 if (GetGDBServerRegisterInfo(arch_to_use))
436 return;
437
438 char packet[128];
439 std::vector<DynamicRegisterInfo::Register> registers;
440 uint32_t reg_num = 0;
441 for (StringExtractorGDBRemote::ResponseType response_type =
442 StringExtractorGDBRemote::eResponse;
443 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
444 const int packet_len =
445 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
446 assert(packet_len < (int)sizeof(packet))(static_cast <bool> (packet_len < (int)sizeof(packet
)) ? void (0) : __assert_fail ("packet_len < (int)sizeof(packet)"
, "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 446, __extension__ __PRETTY_FUNCTION__))
;
447 UNUSED_IF_ASSERT_DISABLED(packet_len)((void)(packet_len));
448 StringExtractorGDBRemote response;
449 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
450 GDBRemoteCommunication::PacketResult::Success) {
451 response_type = response.GetResponseType();
452 if (response_type == StringExtractorGDBRemote::eResponse) {
453 llvm::StringRef name;
454 llvm::StringRef value;
455 DynamicRegisterInfo::Register reg_info;
456
457 while (response.GetNameColonValue(name, value)) {
458 if (name.equals("name")) {
459 reg_info.name.SetString(value);
460 } else if (name.equals("alt-name")) {
461 reg_info.alt_name.SetString(value);
462 } else if (name.equals("bitsize")) {
463 if (!value.getAsInteger(0, reg_info.byte_size))
464 reg_info.byte_size /= CHAR_BIT8;
465 } else if (name.equals("offset")) {
466 value.getAsInteger(0, reg_info.byte_offset);
467 } else if (name.equals("encoding")) {
468 const Encoding encoding = Args::StringToEncoding(value);
469 if (encoding != eEncodingInvalid)
470 reg_info.encoding = encoding;
471 } else if (name.equals("format")) {
472 if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
473 .Success())
474 reg_info.format =
475 llvm::StringSwitch<Format>(value)
476 .Case("binary", eFormatBinary)
477 .Case("decimal", eFormatDecimal)
478 .Case("hex", eFormatHex)
479 .Case("float", eFormatFloat)
480 .Case("vector-sint8", eFormatVectorOfSInt8)
481 .Case("vector-uint8", eFormatVectorOfUInt8)
482 .Case("vector-sint16", eFormatVectorOfSInt16)
483 .Case("vector-uint16", eFormatVectorOfUInt16)
484 .Case("vector-sint32", eFormatVectorOfSInt32)
485 .Case("vector-uint32", eFormatVectorOfUInt32)
486 .Case("vector-float32", eFormatVectorOfFloat32)
487 .Case("vector-uint64", eFormatVectorOfUInt64)
488 .Case("vector-uint128", eFormatVectorOfUInt128)
489 .Default(eFormatInvalid);
490 } else if (name.equals("set")) {
491 reg_info.set_name.SetString(value);
492 } else if (name.equals("gcc") || name.equals("ehframe")) {
493 value.getAsInteger(0, reg_info.regnum_ehframe);
494 } else if (name.equals("dwarf")) {
495 value.getAsInteger(0, reg_info.regnum_dwarf);
496 } else if (name.equals("generic")) {
497 reg_info.regnum_generic = Args::StringToGenericRegister(value);
498 } else if (name.equals("container-regs")) {
499 SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs, 16);
500 } else if (name.equals("invalidate-regs")) {
501 SplitCommaSeparatedRegisterNumberString(value, reg_info.invalidate_regs, 16);
502 }
503 }
504
505 assert(reg_info.byte_size != 0)(static_cast <bool> (reg_info.byte_size != 0) ? void (0
) : __assert_fail ("reg_info.byte_size != 0", "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 505, __extension__ __PRETTY_FUNCTION__))
;
506 registers.push_back(reg_info);
507 } else {
508 break; // ensure exit before reg_num is incremented
509 }
510 } else {
511 break;
512 }
513 }
514
515 if (registers.empty())
516 registers = GetFallbackRegisters(arch_to_use);
517
518 AddRemoteRegisters(registers, arch_to_use);
519}
520
521Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) {
522 return WillLaunchOrAttach();
523}
524
525Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) {
526 return WillLaunchOrAttach();
527}
528
529Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name,
530 bool wait_for_launch) {
531 return WillLaunchOrAttach();
532}
533
534Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
535 Log *log = GetLog(GDBRLog::Process);
536
537 Status error(WillLaunchOrAttach());
538 if (error.Fail())
539 return error;
540
541 error = ConnectToDebugserver(remote_url);
542 if (error.Fail())
543 return error;
544
545 StartAsyncThread();
546
547 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
548 if (pid == LLDB_INVALID_PROCESS_ID0) {
549 // We don't have a valid process ID, so note that we are connected and
550 // could now request to launch or attach, or get remote process listings...
551 SetPrivateState(eStateConnected);
552 } else {
553 // We have a valid process
554 SetID(pid);
555 GetThreadList();
556 StringExtractorGDBRemote response;
557 if (m_gdb_comm.GetStopReply(response)) {
558 SetLastStopPacket(response);
559
560 Target &target = GetTarget();
561 if (!target.GetArchitecture().IsValid()) {
562 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
563 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
564 } else {
565 if (m_gdb_comm.GetHostArchitecture().IsValid()) {
566 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
567 }
568 }
569 }
570
571 // The remote stub may know about the "main binary" in
572 // the context of a firmware debug session, and can
573 // give us a UUID and an address/slide of where the
574 // binary is loaded in memory.
575 UUID standalone_uuid;
576 addr_t standalone_value;
577 bool standalone_value_is_offset;
578 if (m_gdb_comm.GetProcessStandaloneBinary(
579 standalone_uuid, standalone_value, standalone_value_is_offset)) {
580 ModuleSP module_sp;
581
582 if (standalone_uuid.IsValid()) {
583 const bool force_symbol_search = true;
584 const bool notify = true;
585 DynamicLoader::LoadBinaryWithUUIDAndAddress(
586 this, standalone_uuid, standalone_value,
587 standalone_value_is_offset, force_symbol_search, notify);
588 }
589 }
590
591 // The remote stub may know about a list of binaries to
592 // force load into the process -- a firmware type situation
593 // where multiple binaries are present in virtual memory,
594 // and we are only given the addresses of the binaries.
595 // Not intended for use with userland debugging when we
596 // a DynamicLoader plugin that knows how to find the loaded
597 // binaries and will track updates as binaries are added.
598
599 std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
600 if (bin_addrs.size()) {
601 UUID uuid;
602 const bool value_is_slide = false;
603 for (addr_t addr : bin_addrs) {
604 const bool force_symbol_search = true;
605 const bool notify = true;
606 DynamicLoader::LoadBinaryWithUUIDAndAddress(
607 this, uuid, addr, value_is_slide, force_symbol_search, notify);
608 }
609 }
610
611 const StateType state = SetThreadStopInfo(response);
612 if (state != eStateInvalid) {
613 SetPrivateState(state);
614 } else
615 error.SetErrorStringWithFormat(
616 "Process %" PRIu64"l" "u" " was reported after connecting to "
617 "'%s', but state was not stopped: %s",
618 pid, remote_url.str().c_str(), StateAsCString(state));
619 } else
620 error.SetErrorStringWithFormat("Process %" PRIu64"l" "u"
621 " was reported after connecting to '%s', "
622 "but no stop reply packet was received",
623 pid, remote_url.str().c_str());
624 }
625
626 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
627 "ProcessGDBRemote::%s pid %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
628 ": normalizing target architecture initial triple: %s "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
629 "(GetTarget().GetArchitecture().IsValid() %s, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
630 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
631 __FUNCTION__, GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
632 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
633 GetTarget().GetArchitecture().IsValid() ? "true" : "false",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
634 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, "
"m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__
, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" :
"false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true"
: "false"); } while (0)
;
635
636 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
637 m_gdb_comm.GetHostArchitecture().IsValid()) {
638 // Prefer the *process'* architecture over that of the *host*, if
639 // available.
640 if (m_gdb_comm.GetProcessArchitecture().IsValid())
641 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
642 else
643 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
644 }
645
646 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalized target architecture triple: %s", __FUNCTION__,
GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str()); } while (0)
647 "ProcessGDBRemote::%s pid %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalized target architecture triple: %s", __FUNCTION__,
GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str()); } while (0)
648 ": normalized target architecture triple: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalized target architecture triple: %s", __FUNCTION__,
GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str()); } while (0)
649 __FUNCTION__, GetID(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalized target architecture triple: %s", __FUNCTION__,
GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str()); } while (0)
650 GetTarget().GetArchitecture().GetTriple().getTriple().c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s pid %" "l" "u"
": normalized target architecture triple: %s", __FUNCTION__,
GetID(), GetTarget().GetArchitecture().GetTriple().getTriple
().c_str()); } while (0)
;
651
652 return error;
653}
654
655Status ProcessGDBRemote::WillLaunchOrAttach() {
656 Status error;
657 m_stdio_communication.Clear();
658 return error;
659}
660
661// Process Control
662Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module,
663 ProcessLaunchInfo &launch_info) {
664 Log *log = GetLog(GDBRLog::Process);
665 Status error;
666
667 LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s() entered", __FUNCTION__
); } while (0)
;
668
669 uint32_t launch_flags = launch_info.GetFlags().Get();
670 FileSpec stdin_file_spec{};
671 FileSpec stdout_file_spec{};
672 FileSpec stderr_file_spec{};
673 FileSpec working_dir = launch_info.GetWorkingDirectory();
674
675 const FileAction *file_action;
676 file_action = launch_info.GetFileActionForFD(STDIN_FILENO0);
677 if (file_action) {
678 if (file_action->GetAction() == FileAction::eFileActionOpen)
679 stdin_file_spec = file_action->GetFileSpec();
680 }
681 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO1);
682 if (file_action) {
683 if (file_action->GetAction() == FileAction::eFileActionOpen)
684 stdout_file_spec = file_action->GetFileSpec();
685 }
686 file_action = launch_info.GetFileActionForFD(STDERR_FILENO2);
687 if (file_action) {
688 if (file_action->GetAction() == FileAction::eFileActionOpen)
689 stderr_file_spec = file_action->GetFileSpec();
690 }
691
692 if (log) {
693 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
694 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
695 "ProcessGDBRemote::%s provided with STDIO paths via "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
696 "launch_info: stdin=%s, stdout=%s, stderr=%s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
697 __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
698 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
699 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
700 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s provided with STDIO paths via "
"launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
;
701 else
702 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info"
, __FUNCTION__); } while (0)
703 "ProcessGDBRemote::%s no STDIO paths given via launch_info",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info"
, __FUNCTION__); } while (0)
704 __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no STDIO paths given via launch_info"
, __FUNCTION__); } while (0)
;
705 }
706
707 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
708 if (stdin_file_spec || disable_stdio) {
709 // the inferior will be reading stdin from the specified file or stdio is
710 // completely disabled
711 m_stdin_forward = false;
712 } else {
713 m_stdin_forward = true;
714 }
715
716 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
717 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
718 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
719 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
720 // ::LogSetLogFile ("/dev/stdout");
721
722 error = EstablishConnectionIfNeeded(launch_info);
723 if (error.Success()) {
724 PseudoTerminal pty;
725 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
726
727 PlatformSP platform_sp(GetTarget().GetPlatform());
728 if (disable_stdio) {
729 // set to /dev/null unless redirected to a file above
730 if (!stdin_file_spec)
731 stdin_file_spec.SetFile(FileSystem::DEV_NULL,
732 FileSpec::Style::native);
733 if (!stdout_file_spec)
734 stdout_file_spec.SetFile(FileSystem::DEV_NULL,
735 FileSpec::Style::native);
736 if (!stderr_file_spec)
737 stderr_file_spec.SetFile(FileSystem::DEV_NULL,
738 FileSpec::Style::native);
739 } else if (platform_sp && platform_sp->IsHost()) {
740 // If the debugserver is local and we aren't disabling STDIO, lets use
741 // a pseudo terminal to instead of relying on the 'O' packets for stdio
742 // since 'O' packets can really slow down debugging if the inferior
743 // does a lot of output.
744 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
745 !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR02 | O_NOCTTY0400))) {
746 FileSpec secondary_name(pty.GetSecondaryName());
747
748 if (!stdin_file_spec)
749 stdin_file_spec = secondary_name;
750
751 if (!stdout_file_spec)
752 stdout_file_spec = secondary_name;
753
754 if (!stderr_file_spec)
755 stderr_file_spec = secondary_name;
756 }
757 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
758 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
759 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
760 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
761 "stderr=%s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
762 __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
763 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
764 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
765 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s adjusted STDIO paths for local platform "
"(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s"
, __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetPath().c_str
() : "<null>", stdout_file_spec ? stdout_file_spec.GetPath
().c_str() : "<null>", stderr_file_spec ? stderr_file_spec
.GetPath().c_str() : "<null>"); } while (0)
;
766 }
767
768 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
769 "ProcessGDBRemote::%s final STDIO paths after all "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
770 "adjustments: stdin=%s, stdout=%s, stderr=%s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
771 __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
772 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
773 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
774 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s final STDIO paths after all "
"adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__,
stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>"
, stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>"
, stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>"
); } while (0)
;
775
776 if (stdin_file_spec)
777 m_gdb_comm.SetSTDIN(stdin_file_spec);
778 if (stdout_file_spec)
779 m_gdb_comm.SetSTDOUT(stdout_file_spec);
780 if (stderr_file_spec)
781 m_gdb_comm.SetSTDERR(stderr_file_spec);
782
783 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
784 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
785
786 m_gdb_comm.SendLaunchArchPacket(
787 GetTarget().GetArchitecture().GetArchitectureName());
788
789 const char *launch_event_data = launch_info.GetLaunchEventData();
790 if (launch_event_data != nullptr && *launch_event_data != '\0')
791 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
792
793 if (working_dir) {
794 m_gdb_comm.SetWorkingDir(working_dir);
795 }
796
797 // Send the environment and the program + arguments after we connect
798 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
799
800 {
801 // Scope for the scoped timeout object
802 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
803 std::chrono::seconds(10));
804
805 int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info);
806 if (arg_packet_err == 0) {
807 std::string error_str;
808 if (m_gdb_comm.GetLaunchSuccess(error_str)) {
809 SetID(m_gdb_comm.GetCurrentProcessID());
810 } else {
811 error.SetErrorString(error_str.c_str());
812 }
813 } else {
814 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
815 arg_packet_err);
816 }
817 }
818
819 if (GetID() == LLDB_INVALID_PROCESS_ID0) {
820 LLDB_LOGF(log, "failed to connect to debugserver: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("failed to connect to debugserver: %s"
, error.AsCString()); } while (0)
821 error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("failed to connect to debugserver: %s"
, error.AsCString()); } while (0)
;
822 KillDebugserverProcess();
823 return error;
824 }
825
826 StringExtractorGDBRemote response;
827 if (m_gdb_comm.GetStopReply(response)) {
828 SetLastStopPacket(response);
829
830 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
831
832 if (process_arch.IsValid()) {
833 GetTarget().MergeArchitecture(process_arch);
834 } else {
835 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
836 if (host_arch.IsValid())
837 GetTarget().MergeArchitecture(host_arch);
838 }
839
840 SetPrivateState(SetThreadStopInfo(response));
841
842 if (!disable_stdio) {
843 if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd)
844 SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor());
845 }
846 }
847 } else {
848 LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("failed to connect to debugserver: %s"
, error.AsCString()); } while (0)
;
849 }
850 return error;
851}
852
853Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
854 Status error;
855 // Only connect if we have a valid connect URL
856 Log *log = GetLog(GDBRLog::Process);
857
858 if (!connect_url.empty()) {
859 LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s Connecting to %s"
, __FUNCTION__, connect_url.str().c_str()); } while (0)
860 connect_url.str().c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s Connecting to %s"
, __FUNCTION__, connect_url.str().c_str()); } while (0)
;
861 std::unique_ptr<ConnectionFileDescriptor> conn_up(
862 new ConnectionFileDescriptor());
863 if (conn_up) {
864 const uint32_t max_retry_count = 50;
865 uint32_t retry_count = 0;
866 while (!m_gdb_comm.IsConnected()) {
867 if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
868 m_gdb_comm.SetConnection(std::move(conn_up));
869 break;
870 }
871
872 retry_count++;
873
874 if (retry_count >= max_retry_count)
875 break;
876
877 std::this_thread::sleep_for(std::chrono::milliseconds(100));
878 }
879 }
880 }
881
882 if (!m_gdb_comm.IsConnected()) {
883 if (error.Success())
884 error.SetErrorString("not connected to remote gdb server");
885 return error;
886 }
887
888 // We always seem to be able to open a connection to a local port so we need
889 // to make sure we can then send data to it. If we can't then we aren't
890 // actually connected to anything, so try and do the handshake with the
891 // remote GDB server and make sure that goes alright.
892 if (!m_gdb_comm.HandshakeWithServer(&error)) {
893 m_gdb_comm.Disconnect();
894 if (error.Success())
895 error.SetErrorString("not connected to remote gdb server");
896 return error;
897 }
898
899 m_gdb_comm.GetEchoSupported();
900 m_gdb_comm.GetThreadSuffixSupported();
901 m_gdb_comm.GetListThreadsInStopReplySupported();
902 m_gdb_comm.GetHostInfo();
903 m_gdb_comm.GetVContSupported('c');
904 m_gdb_comm.GetVAttachOrWaitSupported();
905 m_gdb_comm.EnableErrorStringInPacket();
906
907 // First dispatch any commands from the platform:
908 auto handle_cmds = [&] (const Args &args) -> void {
909 for (const Args::ArgEntry &entry : args) {
910 StringExtractorGDBRemote response;
911 m_gdb_comm.SendPacketAndWaitForResponse(
912 entry.c_str(), response);
913 }
914 };
915
916 PlatformSP platform_sp = GetTarget().GetPlatform();
917 if (platform_sp) {
918 handle_cmds(platform_sp->GetExtraStartupCommands());
919 }
920
921 // Then dispatch any process commands:
922 handle_cmds(GetExtraStartupCommands());
923
924 return error;
925}
926
927void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) {
928 Log *log = GetLog(GDBRLog::Process);
929 BuildDynamicRegisterInfo(false);
930
931 // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
932 // qProcessInfo as it will be more specific to our process.
933
934 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
935 if (remote_process_arch.IsValid()) {
936 process_arch = remote_process_arch;
937 LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote had process architecture, using {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
938 process_arch.GetArchitectureName(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote had process architecture, using {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
939 process_arch.GetTriple().getTriple())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote had process architecture, using {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
;
940 } else {
941 process_arch = m_gdb_comm.GetHostArchitecture();
942 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote did not have process architecture, using gdb-remote "
"host architecture {0} {1}", process_arch.GetArchitectureName
(), process_arch.GetTriple().getTriple()); } while (0)
943 "gdb-remote did not have process architecture, using gdb-remote "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote did not have process architecture, using gdb-remote "
"host architecture {0} {1}", process_arch.GetArchitectureName
(), process_arch.GetTriple().getTriple()); } while (0)
944 "host architecture {0} {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote did not have process architecture, using gdb-remote "
"host architecture {0} {1}", process_arch.GetArchitectureName
(), process_arch.GetTriple().getTriple()); } while (0)
945 process_arch.GetArchitectureName(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote did not have process architecture, using gdb-remote "
"host architecture {0} {1}", process_arch.GetArchitectureName
(), process_arch.GetTriple().getTriple()); } while (0)
946 process_arch.GetTriple().getTriple())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "gdb-remote did not have process architecture, using gdb-remote "
"host architecture {0} {1}", process_arch.GetArchitectureName
(), process_arch.GetTriple().getTriple()); } while (0)
;
947 }
948
949 if (int addresssable_bits = m_gdb_comm.GetAddressingBits()) {
950 lldb::addr_t address_mask = ~((1ULL << addresssable_bits) - 1);
951 SetCodeAddressMask(address_mask);
952 SetDataAddressMask(address_mask);
953 }
954
955 if (process_arch.IsValid()) {
956 const ArchSpec &target_arch = GetTarget().GetArchitecture();
957 if (target_arch.IsValid()) {
958 LLDB_LOG(log, "analyzing target arch, currently {0} {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "analyzing target arch, currently {0} {1}", target_arch
.GetArchitectureName(), target_arch.GetTriple().getTriple());
} while (0)
959 target_arch.GetArchitectureName(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "analyzing target arch, currently {0} {1}", target_arch
.GetArchitectureName(), target_arch.GetTriple().getTriple());
} while (0)
960 target_arch.GetTriple().getTriple())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "analyzing target arch, currently {0} {1}", target_arch
.GetArchitectureName(), target_arch.GetTriple().getTriple());
} while (0)
;
961
962 // If the remote host is ARM and we have apple as the vendor, then
963 // ARM executables and shared libraries can have mixed ARM
964 // architectures.
965 // You can have an armv6 executable, and if the host is armv7, then the
966 // system will load the best possible architecture for all shared
967 // libraries it has, so we really need to take the remote host
968 // architecture as our defacto architecture in this case.
969
970 if ((process_arch.GetMachine() == llvm::Triple::arm ||
971 process_arch.GetMachine() == llvm::Triple::thumb) &&
972 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
973 GetTarget().SetArchitecture(process_arch);
974 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "remote process is ARM/Apple, " "setting target arch to {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
975 "remote process is ARM/Apple, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "remote process is ARM/Apple, " "setting target arch to {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
976 "setting target arch to {0} {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "remote process is ARM/Apple, " "setting target arch to {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
977 process_arch.GetArchitectureName(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "remote process is ARM/Apple, " "setting target arch to {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
978 process_arch.GetTriple().getTriple())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "remote process is ARM/Apple, " "setting target arch to {0} {1}"
, process_arch.GetArchitectureName(), process_arch.GetTriple(
).getTriple()); } while (0)
;
979 } else {
980 // Fill in what is missing in the triple
981 const llvm::Triple &remote_triple = process_arch.GetTriple();
982 llvm::Triple new_target_triple = target_arch.GetTriple();
983 if (new_target_triple.getVendorName().size() == 0) {
984 new_target_triple.setVendor(remote_triple.getVendor());
985
986 if (new_target_triple.getOSName().size() == 0) {
987 new_target_triple.setOS(remote_triple.getOS());
988
989 if (new_target_triple.getEnvironmentName().size() == 0)
990 new_target_triple.setEnvironment(remote_triple.getEnvironment());
991 }
992
993 ArchSpec new_target_arch = target_arch;
994 new_target_arch.SetTriple(new_target_triple);
995 GetTarget().SetArchitecture(new_target_arch);
996 }
997 }
998
999 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "final target arch after adjustments for remote architecture: "
"{0} {1}", target_arch.GetArchitectureName(), target_arch.GetTriple
().getTriple()); } while (0)
1000 "final target arch after adjustments for remote architecture: "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "final target arch after adjustments for remote architecture: "
"{0} {1}", target_arch.GetArchitectureName(), target_arch.GetTriple
().getTriple()); } while (0)
1001 "{0} {1}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "final target arch after adjustments for remote architecture: "
"{0} {1}", target_arch.GetArchitectureName(), target_arch.GetTriple
().getTriple()); } while (0)
1002 target_arch.GetArchitectureName(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "final target arch after adjustments for remote architecture: "
"{0} {1}", target_arch.GetArchitectureName(), target_arch.GetTriple
().getTriple()); } while (0)
1003 target_arch.GetTriple().getTriple())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "final target arch after adjustments for remote architecture: "
"{0} {1}", target_arch.GetArchitectureName(), target_arch.GetTriple
().getTriple()); } while (0)
;
1004 } else {
1005 // The target doesn't have a valid architecture yet, set it from the
1006 // architecture we got from the remote GDB server
1007 GetTarget().SetArchitecture(process_arch);
1008 }
1009 }
1010
1011 MaybeLoadExecutableModule();
1012
1013 // Find out which StructuredDataPlugins are supported by the debug monitor.
1014 // These plugins transmit data over async $J packets.
1015 if (StructuredData::Array *supported_packets =
1016 m_gdb_comm.GetSupportedStructuredDataPlugins())
1017 MapSupportedStructuredDataPlugins(*supported_packets);
1018
1019 // If connected to LLDB ("native-signals+"), use signal defs for
1020 // the remote platform. If connected to GDB, just use the standard set.
1021 if (!m_gdb_comm.UsesNativeSignals()) {
1022 SetUnixSignals(std::make_shared<GDBRemoteSignals>());
1023 } else {
1024 PlatformSP platform_sp = GetTarget().GetPlatform();
1025 if (platform_sp && platform_sp->IsConnected())
1026 SetUnixSignals(platform_sp->GetUnixSignals());
1027 else
1028 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
1029 }
1030}
1031
1032void ProcessGDBRemote::MaybeLoadExecutableModule() {
1033 ModuleSP module_sp = GetTarget().GetExecutableModule();
1034 if (!module_sp)
1035 return;
1036
1037 llvm::Optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1038 if (!offsets)
1039 return;
1040
1041 bool is_uniform =
1042 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1043 offsets->offsets.size();
1044 if (!is_uniform)
1045 return; // TODO: Handle non-uniform responses.
1046
1047 bool changed = false;
1048 module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1049 /*value_is_offset=*/true, changed);
1050 if (changed) {
1051 ModuleList list;
1052 list.Append(module_sp);
1053 m_process->GetTarget().ModulesDidLoad(list);
1054 }
1055}
1056
1057void ProcessGDBRemote::DidLaunch() {
1058 ArchSpec process_arch;
1059 DidLaunchOrAttach(process_arch);
1060}
1061
1062Status ProcessGDBRemote::DoAttachToProcessWithID(
1063 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1064 Log *log = GetLog(GDBRLog::Process);
1065 Status error;
1066
1067 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s()", __FUNCTION__
); } while (0)
;
1068
1069 // Clear out and clean up from any current state
1070 Clear();
1071 if (attach_pid != LLDB_INVALID_PROCESS_ID0) {
1072 error = EstablishConnectionIfNeeded(attach_info);
1073 if (error.Success()) {
1074 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1075
1076 char packet[64];
1077 const int packet_len =
1078 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64"l" "x", attach_pid);
1079 SetID(attach_pid);
1080 m_async_broadcaster.BroadcastEvent(
1081 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1082 } else
1083 SetExitStatus(-1, error.AsCString());
1084 }
1085
1086 return error;
1087}
1088
1089Status ProcessGDBRemote::DoAttachToProcessWithName(
1090 const char *process_name, const ProcessAttachInfo &attach_info) {
1091 Status error;
1092 // Clear out and clean up from any current state
1093 Clear();
1094
1095 if (process_name && process_name[0]) {
1096 error = EstablishConnectionIfNeeded(attach_info);
1097 if (error.Success()) {
1098 StreamString packet;
1099
1100 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1101
1102 if (attach_info.GetWaitForLaunch()) {
1103 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1104 packet.PutCString("vAttachWait");
1105 } else {
1106 if (attach_info.GetIgnoreExisting())
1107 packet.PutCString("vAttachWait");
1108 else
1109 packet.PutCString("vAttachOrWait");
1110 }
1111 } else
1112 packet.PutCString("vAttachName");
1113 packet.PutChar(';');
1114 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1115 endian::InlHostByteOrder(),
1116 endian::InlHostByteOrder());
1117
1118 m_async_broadcaster.BroadcastEvent(
1119 eBroadcastBitAsyncContinue,
1120 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
1121
1122 } else
1123 SetExitStatus(-1, error.AsCString());
1124 }
1125 return error;
1126}
1127
1128llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1129 return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
1130}
1131
1132llvm::Error ProcessGDBRemote::TraceStop(const TraceStopRequest &request) {
1133 return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1134}
1135
1136llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1137 return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1138}
1139
1140llvm::Expected<std::string>
1141ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1142 return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
1143}
1144
1145llvm::Expected<std::vector<uint8_t>>
1146ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest &request) {
1147 return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1148}
1149
1150void ProcessGDBRemote::DidExit() {
1151 // When we exit, disconnect from the GDB server communications
1152 m_gdb_comm.Disconnect();
1153}
1154
1155void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) {
1156 // If you can figure out what the architecture is, fill it in here.
1157 process_arch.Clear();
1158 DidLaunchOrAttach(process_arch);
1159}
1160
1161Status ProcessGDBRemote::WillResume() {
1162 m_continue_c_tids.clear();
1163 m_continue_C_tids.clear();
1164 m_continue_s_tids.clear();
1165 m_continue_S_tids.clear();
1166 m_jstopinfo_sp.reset();
1167 m_jthreadsinfo_sp.reset();
1168 return Status();
1169}
1170
1171Status ProcessGDBRemote::DoResume() {
1172 Status error;
1173 Log *log = GetLog(GDBRLog::Process);
1174 LLDB_LOGF(log, "ProcessGDBRemote::Resume()")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::Resume()"); } while
(0)
;
1175
1176 ListenerSP listener_sp(
1177 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1178 if (listener_sp->StartListeningForEvents(
1179 &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) {
1180 listener_sp->StartListeningForEvents(
1181 &m_async_broadcaster,
1182 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit);
1183
1184 const size_t num_threads = GetThreadList().GetSize();
1185
1186 StreamString continue_packet;
1187 bool continue_packet_error = false;
1188 if (m_gdb_comm.HasAnyVContSupport()) {
1189 std::string pid_prefix;
1190 if (m_gdb_comm.GetMultiprocessSupported())
1191 pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1192
1193 if (m_continue_c_tids.size() == num_threads ||
1194 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1195 m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1196 // All threads are continuing
1197 if (m_gdb_comm.GetMultiprocessSupported())
1198 continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1199 else
1200 continue_packet.PutCString("c");
1201 } else {
1202 continue_packet.PutCString("vCont");
1203
1204 if (!m_continue_c_tids.empty()) {
1205 if (m_gdb_comm.GetVContSupported('c')) {
1206 for (tid_collection::const_iterator
1207 t_pos = m_continue_c_tids.begin(),
1208 t_end = m_continue_c_tids.end();
1209 t_pos != t_end; ++t_pos)
1210 continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1211 } else
1212 continue_packet_error = true;
1213 }
1214
1215 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1216 if (m_gdb_comm.GetVContSupported('C')) {
1217 for (tid_sig_collection::const_iterator
1218 s_pos = m_continue_C_tids.begin(),
1219 s_end = m_continue_C_tids.end();
1220 s_pos != s_end; ++s_pos)
1221 continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1222 pid_prefix, s_pos->first);
1223 } else
1224 continue_packet_error = true;
1225 }
1226
1227 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1228 if (m_gdb_comm.GetVContSupported('s')) {
1229 for (tid_collection::const_iterator
1230 t_pos = m_continue_s_tids.begin(),
1231 t_end = m_continue_s_tids.end();
1232 t_pos != t_end; ++t_pos)
1233 continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1234 } else
1235 continue_packet_error = true;
1236 }
1237
1238 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1239 if (m_gdb_comm.GetVContSupported('S')) {
1240 for (tid_sig_collection::const_iterator
1241 s_pos = m_continue_S_tids.begin(),
1242 s_end = m_continue_S_tids.end();
1243 s_pos != s_end; ++s_pos)
1244 continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1245 pid_prefix, s_pos->first);
1246 } else
1247 continue_packet_error = true;
1248 }
1249
1250 if (continue_packet_error)
1251 continue_packet.Clear();
1252 }
1253 } else
1254 continue_packet_error = true;
1255
1256 if (continue_packet_error) {
1257 // Either no vCont support, or we tried to use part of the vCont packet
1258 // that wasn't supported by the remote GDB server. We need to try and
1259 // make a simple packet that can do our continue
1260 const size_t num_continue_c_tids = m_continue_c_tids.size();
1261 const size_t num_continue_C_tids = m_continue_C_tids.size();
1262 const size_t num_continue_s_tids = m_continue_s_tids.size();
1263 const size_t num_continue_S_tids = m_continue_S_tids.size();
1264 if (num_continue_c_tids > 0) {
1265 if (num_continue_c_tids == num_threads) {
1266 // All threads are resuming...
1267 m_gdb_comm.SetCurrentThreadForRun(-1);
1268 continue_packet.PutChar('c');
1269 continue_packet_error = false;
1270 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1271 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1272 // Only one thread is continuing
1273 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1274 continue_packet.PutChar('c');
1275 continue_packet_error = false;
1276 }
1277 }
1278
1279 if (continue_packet_error && num_continue_C_tids > 0) {
1280 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1281 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1282 num_continue_S_tids == 0) {
1283 const int continue_signo = m_continue_C_tids.front().second;
1284 // Only one thread is continuing
1285 if (num_continue_C_tids > 1) {
1286 // More that one thread with a signal, yet we don't have vCont
1287 // support and we are being asked to resume each thread with a
1288 // signal, we need to make sure they are all the same signal, or we
1289 // can't issue the continue accurately with the current support...
1290 if (num_continue_C_tids > 1) {
1291 continue_packet_error = false;
1292 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1293 if (m_continue_C_tids[i].second != continue_signo)
1294 continue_packet_error = true;
1295 }
1296 }
1297 if (!continue_packet_error)
1298 m_gdb_comm.SetCurrentThreadForRun(-1);
1299 } else {
1300 // Set the continue thread ID
1301 continue_packet_error = false;
1302 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1303 }
1304 if (!continue_packet_error) {
1305 // Add threads continuing with the same signo...
1306 continue_packet.Printf("C%2.2x", continue_signo);
1307 }
1308 }
1309 }
1310
1311 if (continue_packet_error && num_continue_s_tids > 0) {
1312 if (num_continue_s_tids == num_threads) {
1313 // All threads are resuming...
1314 m_gdb_comm.SetCurrentThreadForRun(-1);
1315
1316 continue_packet.PutChar('s');
1317
1318 continue_packet_error = false;
1319 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1320 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1321 // Only one thread is stepping
1322 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1323 continue_packet.PutChar('s');
1324 continue_packet_error = false;
1325 }
1326 }
1327
1328 if (!continue_packet_error && num_continue_S_tids > 0) {
1329 if (num_continue_S_tids == num_threads) {
1330 const int step_signo = m_continue_S_tids.front().second;
1331 // Are all threads trying to step with the same signal?
1332 continue_packet_error = false;
1333 if (num_continue_S_tids > 1) {
1334 for (size_t i = 1; i < num_threads; ++i) {
1335 if (m_continue_S_tids[i].second != step_signo)
1336 continue_packet_error = true;
1337 }
1338 }
1339 if (!continue_packet_error) {
1340 // Add threads stepping with the same signo...
1341 m_gdb_comm.SetCurrentThreadForRun(-1);
1342 continue_packet.Printf("S%2.2x", step_signo);
1343 }
1344 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1345 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1346 // Only one thread is stepping with signal
1347 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1348 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1349 continue_packet_error = false;
1350 }
1351 }
1352 }
1353
1354 if (continue_packet_error) {
1355 error.SetErrorString("can't make continue packet for this resume");
1356 } else {
1357 EventSP event_sp;
1358 if (!m_async_thread.IsJoinable()) {
1359 error.SetErrorString("Trying to resume but the async thread is dead.");
1360 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
"async thread is dead."); } while (0)
1361 "async thread is dead.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoResume: Trying to resume but the "
"async thread is dead."); } while (0)
;
1362 return error;
1363 }
1364
1365 m_async_broadcaster.BroadcastEvent(
1366 eBroadcastBitAsyncContinue,
1367 new EventDataBytes(continue_packet.GetString().data(),
1368 continue_packet.GetSize()));
1369
1370 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1371 error.SetErrorString("Resume timed out.");
1372 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoResume: Resume timed out."
); } while (0)
;
1373 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1374 error.SetErrorString("Broadcast continue, but the async thread was "
1375 "killed before we got an ack back.");
1376 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
"async thread was killed before we got an ack back."); } while
(0)
1377 "ProcessGDBRemote::DoResume: Broadcast continue, but the "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
"async thread was killed before we got an ack back."); } while
(0)
1378 "async thread was killed before we got an ack back.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoResume: Broadcast continue, but the "
"async thread was killed before we got an ack back."); } while
(0)
;
1379 return error;
1380 }
1381 }
1382 }
1383
1384 return error;
1385}
1386
1387void ProcessGDBRemote::ClearThreadIDList() {
1388 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1389 m_thread_ids.clear();
1390 m_thread_pcs.clear();
1391}
1392
1393size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(
1394 llvm::StringRef value) {
1395 m_thread_ids.clear();
1396 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1397 StringExtractorGDBRemote thread_ids{value};
1398
1399 do {
1400 auto pid_tid = thread_ids.GetPidTid(pid);
1401 if (pid_tid && pid_tid->first == pid) {
1402 lldb::tid_t tid = pid_tid->second;
1403 if (tid != LLDB_INVALID_THREAD_ID0 &&
1404 tid != StringExtractorGDBRemote::AllProcesses)
1405 m_thread_ids.push_back(tid);
1406 }
1407 } while (thread_ids.GetChar() == ',');
1408
1409 return m_thread_ids.size();
1410}
1411
1412size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(
1413 llvm::StringRef value) {
1414 m_thread_pcs.clear();
1415 for (llvm::StringRef x : llvm::split(value, ',')) {
1416 lldb::addr_t pc;
1417 if (llvm::to_integer(x, pc, 16))
1418 m_thread_pcs.push_back(pc);
1419 }
1420 return m_thread_pcs.size();
1421}
1422
1423bool ProcessGDBRemote::UpdateThreadIDList() {
1424 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1425
1426 if (m_jthreadsinfo_sp) {
1427 // If we have the JSON threads info, we can get the thread list from that
1428 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1429 if (thread_infos && thread_infos->GetSize() > 0) {
1430 m_thread_ids.clear();
1431 m_thread_pcs.clear();
1432 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1433 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1434 if (thread_dict) {
1435 // Set the thread stop info from the JSON dictionary
1436 SetThreadStopInfo(thread_dict);
1437 lldb::tid_t tid = LLDB_INVALID_THREAD_ID0;
1438 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1439 m_thread_ids.push_back(tid);
1440 }
1441 return true; // Keep iterating through all thread_info objects
1442 });
1443 }
1444 if (!m_thread_ids.empty())
1445 return true;
1446 } else {
1447 // See if we can get the thread IDs from the current stop reply packets
1448 // that might contain a "threads" key/value pair
1449
1450 if (m_last_stop_packet) {
1451 // Get the thread stop info
1452 StringExtractorGDBRemote &stop_info = *m_last_stop_packet;
1453 const std::string &stop_info_str = std::string(stop_info.GetStringRef());
1454
1455 m_thread_pcs.clear();
1456 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1457 if (thread_pcs_pos != std::string::npos) {
1458 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1459 const size_t end = stop_info_str.find(';', start);
1460 if (end != std::string::npos) {
1461 std::string value = stop_info_str.substr(start, end - start);
1462 UpdateThreadPCsFromStopReplyThreadsValue(value);
1463 }
1464 }
1465
1466 const size_t threads_pos = stop_info_str.find(";threads:");
1467 if (threads_pos != std::string::npos) {
1468 const size_t start = threads_pos + strlen(";threads:");
1469 const size_t end = stop_info_str.find(';', start);
1470 if (end != std::string::npos) {
1471 std::string value = stop_info_str.substr(start, end - start);
1472 if (UpdateThreadIDsFromStopReplyThreadsValue(value))
1473 return true;
1474 }
1475 }
1476 }
1477 }
1478
1479 bool sequence_mutex_unavailable = false;
1480 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1481 if (sequence_mutex_unavailable) {
1482 return false; // We just didn't get the list
1483 }
1484 return true;
1485}
1486
1487bool ProcessGDBRemote::DoUpdateThreadList(ThreadList &old_thread_list,
1488 ThreadList &new_thread_list) {
1489 // locker will keep a mutex locked until it goes out of scope
1490 Log *log = GetLog(GDBRLog::Thread);
1491 LLDB_LOGV(log, "pid = {0}", GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "pid = {0}", GetID()); } while (0)
;
1492
1493 size_t num_thread_ids = m_thread_ids.size();
1494 // The "m_thread_ids" thread ID list should always be updated after each stop
1495 // reply packet, but in case it isn't, update it here.
1496 if (num_thread_ids == 0) {
1497 if (!UpdateThreadIDList())
1498 return false;
1499 num_thread_ids = m_thread_ids.size();
1500 }
1501
1502 ThreadList old_thread_list_copy(old_thread_list);
1503 if (num_thread_ids > 0) {
1504 for (size_t i = 0; i < num_thread_ids; ++i) {
1505 tid_t tid = m_thread_ids[i];
1506 ThreadSP thread_sp(
1507 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1508 if (!thread_sp) {
1509 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1510 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Making new thread: {0} for thread ID: {1:x}.", thread_sp
.get(), thread_sp->GetID()); } while (0)
1511 thread_sp.get(), thread_sp->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Making new thread: {0} for thread ID: {1:x}.", thread_sp
.get(), thread_sp->GetID()); } while (0)
;
1512 } else {
1513 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Found old thread: {0} for thread ID: {1:x}.", thread_sp
.get(), thread_sp->GetID()); } while (0)
1514 thread_sp.get(), thread_sp->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
&& log_private->GetVerbose()) log_private->Format
("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Found old thread: {0} for thread ID: {1:x}.", thread_sp
.get(), thread_sp->GetID()); } while (0)
;
1515 }
1516
1517 SetThreadPc(thread_sp, i);
1518 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1519 }
1520 }
1521
1522 // Whatever that is left in old_thread_list_copy are not present in
1523 // new_thread_list. Remove non-existent threads from internal id table.
1524 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1525 for (size_t i = 0; i < old_num_thread_ids; i++) {
1526 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1527 if (old_thread_sp) {
1528 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1529 m_thread_id_to_index_id_map.erase(old_thread_id);
1530 }
1531 }
1532
1533 return true;
1534}
1535
1536void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1537 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1538 GetByteOrder() != eByteOrderInvalid) {
1539 ThreadGDBRemote *gdb_thread =
1540 static_cast<ThreadGDBRemote *>(thread_sp.get());
1541 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1542 if (reg_ctx_sp) {
1543 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1544 eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC0);
1545 if (pc_regnum != LLDB_INVALID_REGNUM(4294967295U)) {
1546 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1547 }
1548 }
1549 }
1550}
1551
1552bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1553 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1554 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1555 // packet
1556 if (thread_infos_sp) {
1557 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1558 if (thread_infos) {
1559 lldb::tid_t tid;
1560 const size_t n = thread_infos->GetSize();
1561 for (size_t i = 0; i < n; ++i) {
1562 StructuredData::Dictionary *thread_dict =
1563 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1564 if (thread_dict) {
1565 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1566 "tid", tid, LLDB_INVALID_THREAD_ID0)) {
1567 if (tid == thread->GetID())
1568 return (bool)SetThreadStopInfo(thread_dict);
1569 }
1570 }
1571 }
1572 }
1573 }
1574 return false;
1575}
1576
1577bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) {
1578 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1579 // packet
1580 if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp))
1581 return true;
1582
1583 // See if we got thread stop info for any threads valid stop info reasons
1584 // threads via the "jstopinfo" packet stop reply packet key/value pair?
1585 if (m_jstopinfo_sp) {
1586 // If we have "jstopinfo" then we have stop descriptions for all threads
1587 // that have stop reasons, and if there is no entry for a thread, then it
1588 // has no stop reason.
1589 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1590 if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) {
1591 thread->SetStopInfo(StopInfoSP());
1592 }
1593 return true;
1594 }
1595
1596 // Fall back to using the qThreadStopInfo packet
1597 StringExtractorGDBRemote stop_packet;
1598 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1599 return SetThreadStopInfo(stop_packet) == eStateStopped;
1600 return false;
1601}
1602
1603ThreadSP ProcessGDBRemote::SetThreadStopInfo(
1604 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1605 uint8_t signo, const std::string &thread_name, const std::string &reason,
1606 const std::string &description, uint32_t exc_type,
1607 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1608 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1609 // queue_serial are valid
1610 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1611 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1612 ThreadSP thread_sp;
1613 if (tid != LLDB_INVALID_THREAD_ID0) {
1614 // Scope for "locker" below
1615 {
1616 // m_thread_list_real does have its own mutex, but we need to hold onto
1617 // the mutex between the call to m_thread_list_real.FindThreadByID(...)
1618 // and the m_thread_list_real.AddThread(...) so it doesn't change on us
1619 std::lock_guard<std::recursive_mutex> guard(
1620 m_thread_list_real.GetMutex());
1621 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1622
1623 if (!thread_sp) {
1624 // Create the thread if we need to
1625 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1626 m_thread_list_real.AddThread(thread_sp);
1627 }
1628 }
1629
1630 if (thread_sp) {
1631 ThreadGDBRemote *gdb_thread =
1632 static_cast<ThreadGDBRemote *>(thread_sp.get());
1633 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1634
1635 gdb_reg_ctx_sp->InvalidateIfNeeded(true);
1636
1637 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1638 if (iter != m_thread_ids.end()) {
1639 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1640 }
1641
1642 for (const auto &pair : expedited_register_map) {
1643 StringExtractor reg_value_extractor(pair.second);
1644 WritableDataBufferSP buffer_sp(new DataBufferHeap(
1645 reg_value_extractor.GetStringRef().size() / 2, 0));
1646 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1647 uint32_t lldb_regnum =
1648 gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1649 eRegisterKindProcessPlugin, pair.first);
1650 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1651 }
1652
1653 // AArch64 SVE specific code below calls AArch64SVEReconfigure to update
1654 // SVE register sizes and offsets if value of VG register has changed
1655 // since last stop.
1656 const ArchSpec &arch = GetTarget().GetArchitecture();
1657 if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1658 GDBRemoteRegisterContext *reg_ctx_sp =
1659 static_cast<GDBRemoteRegisterContext *>(
1660 gdb_thread->GetRegisterContext().get());
1661
1662 if (reg_ctx_sp)
1663 reg_ctx_sp->AArch64SVEReconfigure();
1664 }
1665
1666 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1667
1668 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1669 // Check if the GDB server was able to provide the queue name, kind and
1670 // serial number
1671 if (queue_vars_valid)
1672 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind,
1673 queue_serial, dispatch_queue_t,
1674 associated_with_dispatch_queue);
1675 else
1676 gdb_thread->ClearQueueInfo();
1677
1678 gdb_thread->SetAssociatedWithLibdispatchQueue(
1679 associated_with_dispatch_queue);
1680
1681 if (dispatch_queue_t != LLDB_INVALID_ADDRESS(18446744073709551615UL))
1682 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1683
1684 // Make sure we update our thread stop reason just once, but don't
1685 // overwrite the stop info for threads that haven't moved:
1686 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1687 if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1688 current_stop_info_sp) {
1689 thread_sp->SetStopInfo(current_stop_info_sp);
1690 return thread_sp;
1691 }
1692
1693 if (!thread_sp->StopInfoIsUpToDate()) {
1694 thread_sp->SetStopInfo(StopInfoSP());
1695 // If there's a memory thread backed by this thread, we need to use it
1696 // to calculate StopInfo.
1697 if (ThreadSP memory_thread_sp =
1698 m_thread_list.GetBackingThread(thread_sp))
1699 thread_sp = memory_thread_sp;
1700
1701 if (exc_type != 0) {
1702 const size_t exc_data_size = exc_data.size();
1703
1704 thread_sp->SetStopInfo(
1705 StopInfoMachException::CreateStopReasonWithMachException(
1706 *thread_sp, exc_type, exc_data_size,
1707 exc_data_size >= 1 ? exc_data[0] : 0,
1708 exc_data_size >= 2 ? exc_data[1] : 0,
1709 exc_data_size >= 3 ? exc_data[2] : 0));
1710 } else {
1711 bool handled = false;
1712 bool did_exec = false;
1713 if (!reason.empty()) {
1714 if (reason == "trace") {
1715 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1716 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1717 ->GetBreakpointSiteList()
1718 .FindByAddress(pc);
1719
1720 // If the current pc is a breakpoint site then the StopInfo
1721 // should be set to Breakpoint Otherwise, it will be set to
1722 // Trace.
1723 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1724 thread_sp->SetStopInfo(
1725 StopInfo::CreateStopReasonWithBreakpointSiteID(
1726 *thread_sp, bp_site_sp->GetID()));
1727 } else
1728 thread_sp->SetStopInfo(
1729 StopInfo::CreateStopReasonToTrace(*thread_sp));
1730 handled = true;
1731 } else if (reason == "breakpoint") {
1732 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1733 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1734 ->GetBreakpointSiteList()
1735 .FindByAddress(pc);
1736 if (bp_site_sp) {
1737 // If the breakpoint is for this thread, then we'll report the
1738 // hit, but if it is for another thread, we can just report no
1739 // reason. We don't need to worry about stepping over the
1740 // breakpoint here, that will be taken care of when the thread
1741 // resumes and notices that there's a breakpoint under the pc.
1742 handled = true;
1743 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1744 thread_sp->SetStopInfo(
1745 StopInfo::CreateStopReasonWithBreakpointSiteID(
1746 *thread_sp, bp_site_sp->GetID()));
1747 } else {
1748 StopInfoSP invalid_stop_info_sp;
1749 thread_sp->SetStopInfo(invalid_stop_info_sp);
1750 }
1751 }
1752 } else if (reason == "trap") {
1753 // Let the trap just use the standard signal stop reason below...
1754 } else if (reason == "watchpoint") {
1755 StringExtractor desc_extractor(description.c_str());
1756 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1757 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32(4294967295U));
1758 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1759 watch_id_t watch_id = LLDB_INVALID_WATCH_ID0;
1760 if (wp_addr != LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
1761 WatchpointSP wp_sp;
1762 ArchSpec::Core core = GetTarget().GetArchitecture().GetCore();
1763 if ((core >= ArchSpec::kCore_mips_first &&
1764 core <= ArchSpec::kCore_mips_last) ||
1765 (core >= ArchSpec::eCore_arm_generic &&
1766 core <= ArchSpec::eCore_arm_aarch64))
1767 wp_sp = GetTarget().GetWatchpointList().FindByAddress(
1768 wp_hit_addr);
1769 if (!wp_sp)
1770 wp_sp =
1771 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1772 if (wp_sp) {
1773 wp_sp->SetHardwareIndex(wp_index);
1774 watch_id = wp_sp->GetID();
1775 }
1776 }
1777 if (watch_id == LLDB_INVALID_WATCH_ID0) {
1778 Log *log(GetLog(GDBRLog::Watchpoints));
1779 LLDB_LOGF(log, "failed to find watchpoint")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("failed to find watchpoint"); } while
(0)
;
1780 }
1781 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1782 *thread_sp, watch_id, wp_hit_addr));
1783 handled = true;
1784 } else if (reason == "exception") {
1785 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1786 *thread_sp, description.c_str()));
1787 handled = true;
1788 } else if (reason == "exec") {
1789 did_exec = true;
1790 thread_sp->SetStopInfo(
1791 StopInfo::CreateStopReasonWithExec(*thread_sp));
1792 handled = true;
1793 } else if (reason == "processor trace") {
1794 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1795 *thread_sp, description.c_str()));
1796 } else if (reason == "fork") {
1797 StringExtractor desc_extractor(description.c_str());
1798 lldb::pid_t child_pid = desc_extractor.GetU64(
1799 LLDB_INVALID_PROCESS_ID0);
1800 lldb::tid_t child_tid = desc_extractor.GetU64(
1801 LLDB_INVALID_THREAD_ID0);
1802 thread_sp->SetStopInfo(StopInfo::CreateStopReasonFork(
1803 *thread_sp, child_pid, child_tid));
1804 handled = true;
1805 } else if (reason == "vfork") {
1806 StringExtractor desc_extractor(description.c_str());
1807 lldb::pid_t child_pid = desc_extractor.GetU64(
1808 LLDB_INVALID_PROCESS_ID0);
1809 lldb::tid_t child_tid = desc_extractor.GetU64(
1810 LLDB_INVALID_THREAD_ID0);
1811 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1812 *thread_sp, child_pid, child_tid));
1813 handled = true;
1814 } else if (reason == "vforkdone") {
1815 thread_sp->SetStopInfo(
1816 StopInfo::CreateStopReasonVForkDone(*thread_sp));
1817 handled = true;
1818 }
1819 } else if (!signo) {
1820 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1821 lldb::BreakpointSiteSP bp_site_sp =
1822 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1823 pc);
1824
1825 // If the current pc is a breakpoint site then the StopInfo should
1826 // be set to Breakpoint even though the remote stub did not set it
1827 // as such. This can happen when the thread is involuntarily
1828 // interrupted (e.g. due to stops on other threads) just as it is
1829 // about to execute the breakpoint instruction.
1830 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1831 thread_sp->SetStopInfo(
1832 StopInfo::CreateStopReasonWithBreakpointSiteID(
1833 *thread_sp, bp_site_sp->GetID()));
1834 handled = true;
1835 }
1836 }
1837
1838 if (!handled && signo && !did_exec) {
1839 if (signo == SIGTRAP5) {
1840 // Currently we are going to assume SIGTRAP means we are either
1841 // hitting a breakpoint or hardware single stepping.
1842 handled = true;
1843 addr_t pc = thread_sp->GetRegisterContext()->GetPC() +
1844 m_breakpoint_pc_offset;
1845 lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()
1846 ->GetBreakpointSiteList()
1847 .FindByAddress(pc);
1848
1849 if (bp_site_sp) {
1850 // If the breakpoint is for this thread, then we'll report the
1851 // hit, but if it is for another thread, we can just report no
1852 // reason. We don't need to worry about stepping over the
1853 // breakpoint here, that will be taken care of when the thread
1854 // resumes and notices that there's a breakpoint under the pc.
1855 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1856 if (m_breakpoint_pc_offset != 0)
1857 thread_sp->GetRegisterContext()->SetPC(pc);
1858 thread_sp->SetStopInfo(
1859 StopInfo::CreateStopReasonWithBreakpointSiteID(
1860 *thread_sp, bp_site_sp->GetID()));
1861 } else {
1862 StopInfoSP invalid_stop_info_sp;
1863 thread_sp->SetStopInfo(invalid_stop_info_sp);
1864 }
1865 } else {
1866 // If we were stepping then assume the stop was the result of
1867 // the trace. If we were not stepping then report the SIGTRAP.
1868 // FIXME: We are still missing the case where we single step
1869 // over a trap instruction.
1870 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1871 thread_sp->SetStopInfo(
1872 StopInfo::CreateStopReasonToTrace(*thread_sp));
1873 else
1874 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1875 *thread_sp, signo, description.c_str()));
1876 }
1877 }
1878 if (!handled)
1879 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1880 *thread_sp, signo, description.c_str()));
1881 }
1882
1883 if (!description.empty()) {
1884 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1885 if (stop_info_sp) {
1886 const char *stop_info_desc = stop_info_sp->GetDescription();
1887 if (!stop_info_desc || !stop_info_desc[0])
1888 stop_info_sp->SetDescription(description.c_str());
1889 } else {
1890 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1891 *thread_sp, description.c_str()));
1892 }
1893 }
1894 }
1895 }
1896 }
1897 }
1898 return thread_sp;
1899}
1900
1901lldb::ThreadSP
1902ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) {
1903 static ConstString g_key_tid("tid");
1904 static ConstString g_key_name("name");
1905 static ConstString g_key_reason("reason");
1906 static ConstString g_key_metype("metype");
1907 static ConstString g_key_medata("medata");
1908 static ConstString g_key_qaddr("qaddr");
1909 static ConstString g_key_dispatch_queue_t("dispatch_queue_t");
1910 static ConstString g_key_associated_with_dispatch_queue(
1911 "associated_with_dispatch_queue");
1912 static ConstString g_key_queue_name("qname");
1913 static ConstString g_key_queue_kind("qkind");
1914 static ConstString g_key_queue_serial_number("qserialnum");
1915 static ConstString g_key_registers("registers");
1916 static ConstString g_key_memory("memory");
1917 static ConstString g_key_address("address");
1918 static ConstString g_key_bytes("bytes");
1919 static ConstString g_key_description("description");
1920 static ConstString g_key_signal("signal");
1921
1922 // Stop with signal and thread info
1923 lldb::tid_t tid = LLDB_INVALID_THREAD_ID0;
1924 uint8_t signo = 0;
1925 std::string value;
1926 std::string thread_name;
1927 std::string reason;
1928 std::string description;
1929 uint32_t exc_type = 0;
1930 std::vector<addr_t> exc_data;
1931 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1932 ExpeditedRegisterMap expedited_register_map;
1933 bool queue_vars_valid = false;
1934 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS(18446744073709551615UL);
1935 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
1936 std::string queue_name;
1937 QueueKind queue_kind = eQueueKindUnknown;
1938 uint64_t queue_serial_number = 0;
1939 // Iterate through all of the thread dictionary key/value pairs from the
1940 // structured data dictionary
1941
1942 // FIXME: we're silently ignoring invalid data here
1943 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
1944 &signo, &reason, &description, &exc_type, &exc_data,
1945 &thread_dispatch_qaddr, &queue_vars_valid,
1946 &associated_with_dispatch_queue, &dispatch_queue_t,
1947 &queue_name, &queue_kind, &queue_serial_number](
1948 ConstString key,
1949 StructuredData::Object *object) -> bool {
1950 if (key == g_key_tid) {
1951 // thread in big endian hex
1952 tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID0);
1953 } else if (key == g_key_metype) {
1954 // exception type in big endian hex
1955 exc_type = object->GetIntegerValue(0);
1956 } else if (key == g_key_medata) {
1957 // exception data in big endian hex
1958 StructuredData::Array *array = object->GetAsArray();
1959 if (array) {
1960 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
1961 exc_data.push_back(object->GetIntegerValue());
1962 return true; // Keep iterating through all array items
1963 });
1964 }
1965 } else if (key == g_key_name) {
1966 thread_name = std::string(object->GetStringValue());
1967 } else if (key == g_key_qaddr) {
1968 thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS(18446744073709551615UL));
1969 } else if (key == g_key_queue_name) {
1970 queue_vars_valid = true;
1971 queue_name = std::string(object->GetStringValue());
1972 } else if (key == g_key_queue_kind) {
1973 std::string queue_kind_str = std::string(object->GetStringValue());
1974 if (queue_kind_str == "serial") {
1975 queue_vars_valid = true;
1976 queue_kind = eQueueKindSerial;
1977 } else if (queue_kind_str == "concurrent") {
1978 queue_vars_valid = true;
1979 queue_kind = eQueueKindConcurrent;
1980 }
1981 } else if (key == g_key_queue_serial_number) {
1982 queue_serial_number = object->GetIntegerValue(0);
1983 if (queue_serial_number != 0)
1984 queue_vars_valid = true;
1985 } else if (key == g_key_dispatch_queue_t) {
1986 dispatch_queue_t = object->GetIntegerValue(0);
1987 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS(18446744073709551615UL))
1988 queue_vars_valid = true;
1989 } else if (key == g_key_associated_with_dispatch_queue) {
1990 queue_vars_valid = true;
1991 bool associated = object->GetBooleanValue();
1992 if (associated)
1993 associated_with_dispatch_queue = eLazyBoolYes;
1994 else
1995 associated_with_dispatch_queue = eLazyBoolNo;
1996 } else if (key == g_key_reason) {
1997 reason = std::string(object->GetStringValue());
1998 } else if (key == g_key_description) {
1999 description = std::string(object->GetStringValue());
2000 } else if (key == g_key_registers) {
2001 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2002
2003 if (registers_dict) {
2004 registers_dict->ForEach(
2005 [&expedited_register_map](ConstString key,
2006 StructuredData::Object *object) -> bool {
2007 uint32_t reg;
2008 if (llvm::to_integer(key.AsCString(), reg))
2009 expedited_register_map[reg] =
2010 std::string(object->GetStringValue());
2011 return true; // Keep iterating through all array items
2012 });
2013 }
2014 } else if (key == g_key_memory) {
2015 StructuredData::Array *array = object->GetAsArray();
2016 if (array) {
2017 array->ForEach([this](StructuredData::Object *object) -> bool {
2018 StructuredData::Dictionary *mem_cache_dict =
2019 object->GetAsDictionary();
2020 if (mem_cache_dict) {
2021 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2022 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2023 "address", mem_cache_addr)) {
2024 if (mem_cache_addr != LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
2025 llvm::StringRef str;
2026 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2027 StringExtractor bytes(str);
2028 bytes.SetFilePos(0);
2029
2030 const size_t byte_size = bytes.GetStringRef().size() / 2;
2031 WritableDataBufferSP data_buffer_sp(
2032 new DataBufferHeap(byte_size, 0));
2033 const size_t bytes_copied =
2034 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2035 if (bytes_copied == byte_size)
2036 m_memory_cache.AddL1CacheData(mem_cache_addr,
2037 data_buffer_sp);
2038 }
2039 }
2040 }
2041 }
2042 return true; // Keep iterating through all array items
2043 });
2044 }
2045
2046 } else if (key == g_key_signal)
2047 signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER(2147483647));
2048 return true; // Keep iterating through all dictionary key/value pairs
2049 });
2050
2051 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2052 reason, description, exc_type, exc_data,
2053 thread_dispatch_qaddr, queue_vars_valid,
2054 associated_with_dispatch_queue, dispatch_queue_t,
2055 queue_name, queue_kind, queue_serial_number);
2056}
2057
2058StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) {
2059 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2060 stop_packet.SetFilePos(0);
2061 const char stop_type = stop_packet.GetChar();
2062 switch (stop_type) {
2063 case 'T':
2064 case 'S': {
2065 // This is a bit of a hack, but is is required. If we did exec, we need to
2066 // clear our thread lists and also know to rebuild our dynamic register
2067 // info before we lookup and threads and populate the expedited register
2068 // values so we need to know this right away so we can cleanup and update
2069 // our registers.
2070 const uint32_t stop_id = GetStopID();
2071 if (stop_id == 0) {
2072 // Our first stop, make sure we have a process ID, and also make sure we
2073 // know about our registers
2074 if (GetID() == LLDB_INVALID_PROCESS_ID0 && pid != LLDB_INVALID_PROCESS_ID0)
2075 SetID(pid);
2076 BuildDynamicRegisterInfo(true);
2077 }
2078 // Stop with signal and thread info
2079 lldb::pid_t stop_pid = LLDB_INVALID_PROCESS_ID0;
2080 lldb::tid_t tid = LLDB_INVALID_THREAD_ID0;
2081 const uint8_t signo = stop_packet.GetHexU8();
2082 llvm::StringRef key;
2083 llvm::StringRef value;
2084 std::string thread_name;
2085 std::string reason;
2086 std::string description;
2087 uint32_t exc_type = 0;
2088 std::vector<addr_t> exc_data;
2089 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2090 bool queue_vars_valid =
2091 false; // says if locals below that start with "queue_" are valid
2092 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2093 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2094 std::string queue_name;
2095 QueueKind queue_kind = eQueueKindUnknown;
2096 uint64_t queue_serial_number = 0;
2097 ExpeditedRegisterMap expedited_register_map;
2098 while (stop_packet.GetNameColonValue(key, value)) {
2099 if (key.compare("metype") == 0) {
2100 // exception type in big endian hex
2101 value.getAsInteger(16, exc_type);
2102 } else if (key.compare("medata") == 0) {
2103 // exception data in big endian hex
2104 uint64_t x;
2105 value.getAsInteger(16, x);
2106 exc_data.push_back(x);
2107 } else if (key.compare("thread") == 0) {
2108 // thread-id
2109 StringExtractorGDBRemote thread_id{value};
2110 auto pid_tid = thread_id.GetPidTid(pid);
2111 if (pid_tid) {
2112 stop_pid = pid_tid->first;
2113 tid = pid_tid->second;
2114 } else
2115 tid = LLDB_INVALID_THREAD_ID0;
2116 } else if (key.compare("threads") == 0) {
2117 std::lock_guard<std::recursive_mutex> guard(
2118 m_thread_list_real.GetMutex());
2119 UpdateThreadIDsFromStopReplyThreadsValue(value);
2120 } else if (key.compare("thread-pcs") == 0) {
2121 m_thread_pcs.clear();
2122 // A comma separated list of all threads in the current
2123 // process that includes the thread for this stop reply packet
2124 lldb::addr_t pc;
2125 while (!value.empty()) {
2126 llvm::StringRef pc_str;
2127 std::tie(pc_str, value) = value.split(',');
2128 if (pc_str.getAsInteger(16, pc))
2129 pc = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2130 m_thread_pcs.push_back(pc);
2131 }
2132 } else if (key.compare("jstopinfo") == 0) {
2133 StringExtractor json_extractor(value);
2134 std::string json;
2135 // Now convert the HEX bytes into a string value
2136 json_extractor.GetHexByteString(json);
2137
2138 // This JSON contains thread IDs and thread stop info for all threads.
2139 // It doesn't contain expedited registers, memory or queue info.
2140 m_jstopinfo_sp = StructuredData::ParseJSON(json);
2141 } else if (key.compare("hexname") == 0) {
2142 StringExtractor name_extractor(value);
2143 std::string name;
2144 // Now convert the HEX bytes into a string value
2145 name_extractor.GetHexByteString(thread_name);
2146 } else if (key.compare("name") == 0) {
2147 thread_name = std::string(value);
2148 } else if (key.compare("qaddr") == 0) {
2149 value.getAsInteger(16, thread_dispatch_qaddr);
2150 } else if (key.compare("dispatch_queue_t") == 0) {
2151 queue_vars_valid = true;
2152 value.getAsInteger(16, dispatch_queue_t);
2153 } else if (key.compare("qname") == 0) {
2154 queue_vars_valid = true;
2155 StringExtractor name_extractor(value);
2156 // Now convert the HEX bytes into a string value
2157 name_extractor.GetHexByteString(queue_name);
2158 } else if (key.compare("qkind") == 0) {
2159 queue_kind = llvm::StringSwitch<QueueKind>(value)
2160 .Case("serial", eQueueKindSerial)
2161 .Case("concurrent", eQueueKindConcurrent)
2162 .Default(eQueueKindUnknown);
2163 queue_vars_valid = queue_kind != eQueueKindUnknown;
2164 } else if (key.compare("qserialnum") == 0) {
2165 if (!value.getAsInteger(0, queue_serial_number))
2166 queue_vars_valid = true;
2167 } else if (key.compare("reason") == 0) {
2168 reason = std::string(value);
2169 } else if (key.compare("description") == 0) {
2170 StringExtractor desc_extractor(value);
2171 // Now convert the HEX bytes into a string value
2172 desc_extractor.GetHexByteString(description);
2173 } else if (key.compare("memory") == 0) {
2174 // Expedited memory. GDB servers can choose to send back expedited
2175 // memory that can populate the L1 memory cache in the process so that
2176 // things like the frame pointer backchain can be expedited. This will
2177 // help stack backtracing be more efficient by not having to send as
2178 // many memory read requests down the remote GDB server.
2179
2180 // Key/value pair format: memory:<addr>=<bytes>;
2181 // <addr> is a number whose base will be interpreted by the prefix:
2182 // "0x[0-9a-fA-F]+" for hex
2183 // "0[0-7]+" for octal
2184 // "[1-9]+" for decimal
2185 // <bytes> is native endian ASCII hex bytes just like the register
2186 // values
2187 llvm::StringRef addr_str, bytes_str;
2188 std::tie(addr_str, bytes_str) = value.split('=');
2189 if (!addr_str.empty() && !bytes_str.empty()) {
2190 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2191 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2192 StringExtractor bytes(bytes_str);
2193 const size_t byte_size = bytes.GetBytesLeft() / 2;
2194 WritableDataBufferSP data_buffer_sp(
2195 new DataBufferHeap(byte_size, 0));
2196 const size_t bytes_copied =
2197 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2198 if (bytes_copied == byte_size)
2199 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2200 }
2201 }
2202 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2203 key.compare("awatch") == 0) {
2204 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2205 lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2206 value.getAsInteger(16, wp_addr);
2207
2208 WatchpointSP wp_sp =
2209 GetTarget().GetWatchpointList().FindByAddress(wp_addr);
2210 uint32_t wp_index = LLDB_INVALID_INDEX32(4294967295U);
2211
2212 if (wp_sp)
2213 wp_index = wp_sp->GetHardwareIndex();
2214
2215 reason = "watchpoint";
2216 StreamString ostr;
2217 ostr.Printf("%" PRIu64"l" "u" " %" PRIu32"u", wp_addr, wp_index);
2218 description = std::string(ostr.GetString());
2219 } else if (key.compare("library") == 0) {
2220 auto error = LoadModules();
2221 if (error) {
2222 Log *log(GetLog(GDBRLog::Process));
2223 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (std::move(error)); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Failed to load modules: {0}"); } else ::llvm::consumeError
(::std::move(error_private)); } while (0)
;
2224 }
2225 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2226 // fork includes child pid/tid in thread-id format
2227 StringExtractorGDBRemote thread_id{value};
2228 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID0);
2229 if (!pid_tid) {
2230 Log *log(GetLog(GDBRLog::Process));
2231 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Invalid PID/TID to fork: {0}", value); } while (
0)
;
2232 pid_tid = {{LLDB_INVALID_PROCESS_ID0, LLDB_INVALID_THREAD_ID0}};
2233 }
2234
2235 reason = key.str();
2236 StreamString ostr;
2237 ostr.Printf("%" PRIu64"l" "u" " %" PRIu64"l" "u", pid_tid->first, pid_tid->second);
2238 description = std::string(ostr.GetString());
2239 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2240 uint32_t reg = UINT32_MAX(4294967295U);
2241 if (!key.getAsInteger(16, reg))
2242 expedited_register_map[reg] = std::string(std::move(value));
2243 }
2244 }
2245
2246 if (stop_pid != LLDB_INVALID_PROCESS_ID0 && stop_pid != pid) {
2247 Log *log = GetLog(GDBRLog::Process);
2248 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Received stop for incorrect PID = {0} (inferior PID = {1})"
, stop_pid, pid); } while (0)
2249 "Received stop for incorrect PID = {0} (inferior PID = {1})",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Received stop for incorrect PID = {0} (inferior PID = {1})"
, stop_pid, pid); } while (0)
2250 stop_pid, pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Received stop for incorrect PID = {0} (inferior PID = {1})"
, stop_pid, pid); } while (0)
;
2251 return eStateInvalid;
2252 }
2253
2254 if (tid == LLDB_INVALID_THREAD_ID0) {
2255 // A thread id may be invalid if the response is old style 'S' packet
2256 // which does not provide the
2257 // thread information. So update the thread list and choose the first
2258 // one.
2259 UpdateThreadIDList();
2260
2261 if (!m_thread_ids.empty()) {
2262 tid = m_thread_ids.front();
2263 }
2264 }
2265
2266 ThreadSP thread_sp = SetThreadStopInfo(
2267 tid, expedited_register_map, signo, thread_name, reason, description,
2268 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2269 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2270 queue_kind, queue_serial_number);
2271
2272 return eStateStopped;
2273 } break;
2274
2275 case 'W':
2276 case 'X':
2277 // process exited
2278 return eStateExited;
2279
2280 default:
2281 break;
2282 }
2283 return eStateInvalid;
2284}
2285
2286void ProcessGDBRemote::RefreshStateAfterStop() {
2287 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2288
2289 m_thread_ids.clear();
2290 m_thread_pcs.clear();
2291
2292 // Set the thread stop info. It might have a "threads" key whose value is a
2293 // list of all thread IDs in the current process, so m_thread_ids might get
2294 // set.
2295 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2296 if (m_thread_ids.empty()) {
2297 // No, we need to fetch the thread list manually
2298 UpdateThreadIDList();
2299 }
2300
2301 // We might set some stop info's so make sure the thread list is up to
2302 // date before we do that or we might overwrite what was computed here.
2303 UpdateThreadListIfNeeded();
2304
2305 if (m_last_stop_packet)
2306 SetThreadStopInfo(*m_last_stop_packet);
2307 m_last_stop_packet.reset();
2308
2309 // If we have queried for a default thread id
2310 if (m_initial_tid != LLDB_INVALID_THREAD_ID0) {
2311 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2312 m_initial_tid = LLDB_INVALID_THREAD_ID0;
2313 }
2314
2315 // Let all threads recover from stopping and do any clean up based on the
2316 // previous thread state (if any).
2317 m_thread_list_real.RefreshStateAfterStop();
2318}
2319
2320Status ProcessGDBRemote::DoHalt(bool &caused_stop) {
2321 Status error;
2322
2323 if (m_public_state.GetValue() == eStateAttaching) {
2324 // We are being asked to halt during an attach. We need to just close our
2325 // file handle and debugserver will go away, and we can be done...
2326 m_gdb_comm.Disconnect();
2327 } else
2328 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2329 return error;
2330}
2331
2332Status ProcessGDBRemote::DoDetach(bool keep_stopped) {
2333 Status error;
2334 Log *log = GetLog(GDBRLog::Process);
2335 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoDetach(keep_stopped: %i)"
, keep_stopped); } while (0)
;
2336
2337 error = m_gdb_comm.Detach(keep_stopped);
2338 if (log) {
2339 if (error.Success())
2340 log->PutCString(
2341 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2342 else
2343 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
2344 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
2345 error.AsCString() ? error.AsCString() : "<unknown error>")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoDetach() detach packet send failed: %s"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
;
2346 }
2347
2348 if (!error.Success())
2349 return error;
2350
2351 // Sleep for one second to let the process get all detached...
2352 StopAsyncThread();
2353
2354 SetPrivateState(eStateDetached);
2355 ResumePrivateStateThread();
2356
2357 // KillDebugserverProcess ();
2358 return error;
2359}
2360
2361Status ProcessGDBRemote::DoDestroy() {
2362 Log *log = GetLog(GDBRLog::Process);
2363 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoDestroy()"); } while
(0)
;
2364
2365 // Interrupt if our inferior is running...
2366 int exit_status = SIGABRT6;
2367 std::string exit_string;
2368
2369 if (m_gdb_comm.IsConnected()) {
2370 if (m_public_state.GetValue() != eStateAttaching) {
2371 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2372
2373 if (kill_res) {
2374 exit_status = kill_res.get();
2375#if defined(__APPLE__)
2376 // For Native processes on Mac OS X, we launch through the Host
2377 // Platform, then hand the process off to debugserver, which becomes
2378 // the parent process through "PT_ATTACH". Then when we go to kill
2379 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2380 // we call waitpid which returns with no error and the correct
2381 // status. But amusingly enough that doesn't seem to actually reap
2382 // the process, but instead it is left around as a Zombie. Probably
2383 // the kernel is in the process of switching ownership back to lldb
2384 // which was the original parent, and gets confused in the handoff.
2385 // Anyway, so call waitpid here to finally reap it.
2386 PlatformSP platform_sp(GetTarget().GetPlatform());
2387 if (platform_sp && platform_sp->IsHost()) {
2388 int status;
2389 ::pid_t reap_pid;
2390 reap_pid = waitpid(GetID(), &status, WNOHANG1);
2391 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Reaped pid: %d, status: %d.\n", reap_pid
, status); } while (0)
;
2392 }
2393#endif
2394 ClearThreadIDList();
2395 exit_string.assign("killed");
2396 } else {
2397 exit_string.assign(llvm::toString(kill_res.takeError()));
2398 }
2399 } else {
2400 exit_string.assign("killed or interrupted while attaching.");
2401 }
2402 } else {
2403 // If we missed setting the exit status on the way out, do it here.
2404 // NB set exit status can be called multiple times, the first one sets the
2405 // status.
2406 exit_string.assign("destroying when not connected to debugserver");
2407 }
2408
2409 SetExitStatus(exit_status, exit_string.c_str());
2410
2411 StopAsyncThread();
2412 KillDebugserverProcess();
2413 return Status();
2414}
2415
2416void ProcessGDBRemote::SetLastStopPacket(
2417 const StringExtractorGDBRemote &response) {
2418 const bool did_exec =
2419 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2420 if (did_exec) {
2421 Log *log = GetLog(GDBRLog::Process);
2422 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::SetLastStopPacket () - detected exec"
); } while (0)
;
2423
2424 m_thread_list_real.Clear();
2425 m_thread_list.Clear();
2426 BuildDynamicRegisterInfo(true);
2427 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2428 }
2429
2430 m_last_stop_packet = response;
2431}
2432
2433void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) {
2434 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2435}
2436
2437// Process Queries
2438
2439bool ProcessGDBRemote::IsAlive() {
2440 return m_gdb_comm.IsConnected() && Process::IsAlive();
2441}
2442
2443addr_t ProcessGDBRemote::GetImageInfoAddress() {
2444 // request the link map address via the $qShlibInfoAddr packet
2445 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2446
2447 // the loaded module list can also provides a link map address
2448 if (addr == LLDB_INVALID_ADDRESS(18446744073709551615UL)) {
2449 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2450 if (!list) {
2451 Log *log = GetLog(GDBRLog::Process);
2452 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.")do { ::lldb_private::Log *log_private = (log); ::llvm::Error error_private
= (list.takeError()); if (log_private && error_private
) { log_private->FormatError(::std::move(error_private), "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Failed to read module list: {0}."); } else ::llvm
::consumeError(::std::move(error_private)); } while (0)
;
2453 } else {
2454 addr = list->m_link_map;
2455 }
2456 }
2457
2458 return addr;
2459}
2460
2461void ProcessGDBRemote::WillPublicStop() {
2462 // See if the GDB remote client supports the JSON threads info. If so, we
2463 // gather stop info for all threads, expedited registers, expedited memory,
2464 // runtime queue information (iOS and MacOSX only), and more. Expediting
2465 // memory will help stack backtracing be much faster. Expediting registers
2466 // will make sure we don't have to read the thread registers for GPRs.
2467 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2468
2469 if (m_jthreadsinfo_sp) {
2470 // Now set the stop info for each thread and also expedite any registers
2471 // and memory that was in the jThreadsInfo response.
2472 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2473 if (thread_infos) {
2474 const size_t n = thread_infos->GetSize();
2475 for (size_t i = 0; i < n; ++i) {
2476 StructuredData::Dictionary *thread_dict =
2477 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2478 if (thread_dict)
2479 SetThreadStopInfo(thread_dict);
2480 }
2481 }
2482 }
2483}
2484
2485// Process Memory
2486size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2487 Status &error) {
2488 GetMaxMemorySize();
2489 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2490 // M and m packets take 2 bytes for 1 byte of memory
2491 size_t max_memory_size =
2492 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2493 if (size > max_memory_size) {
2494 // Keep memory read sizes down to a sane limit. This function will be
2495 // called multiple times in order to complete the task by
2496 // lldb_private::Process so it is ok to do this.
2497 size = max_memory_size;
2498 }
2499
2500 char packet[64];
2501 int packet_len;
2502 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64"l" "x" ",%" PRIx64"l" "x",
2503 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2504 (uint64_t)size);
2505 assert(packet_len + 1 < (int)sizeof(packet))(static_cast <bool> (packet_len + 1 < (int)sizeof(packet
)) ? void (0) : __assert_fail ("packet_len + 1 < (int)sizeof(packet)"
, "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 2505, __extension__ __PRETTY_FUNCTION__))
;
2506 UNUSED_IF_ASSERT_DISABLED(packet_len)((void)(packet_len));
2507 StringExtractorGDBRemote response;
2508 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2509 GetInterruptTimeout()) ==
2510 GDBRemoteCommunication::PacketResult::Success) {
2511 if (response.IsNormalResponse()) {
2512 error.Clear();
2513 if (binary_memory_read) {
2514 // The lower level GDBRemoteCommunication packet receive layer has
2515 // already de-quoted any 0x7d character escaping that was present in
2516 // the packet
2517
2518 size_t data_received_size = response.GetBytesLeft();
2519 if (data_received_size > size) {
2520 // Don't write past the end of BUF if the remote debug server gave us
2521 // too much data for some reason.
2522 data_received_size = size;
2523 }
2524 memcpy(buf, response.GetStringRef().data(), data_received_size);
2525 return data_received_size;
2526 } else {
2527 return response.GetHexBytes(
2528 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2529 }
2530 } else if (response.IsErrorResponse())
2531 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64"l" "x", addr);
2532 else if (response.IsUnsupportedResponse())
2533 error.SetErrorStringWithFormat(
2534 "GDB server does not support reading memory");
2535 else
2536 error.SetErrorStringWithFormat(
2537 "unexpected response to GDB server memory read packet '%s': '%s'",
2538 packet, response.GetStringRef().data());
2539 } else {
2540 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2541 }
2542 return 0;
2543}
2544
2545bool ProcessGDBRemote::SupportsMemoryTagging() {
2546 return m_gdb_comm.GetMemoryTaggingSupported();
2547}
2548
2549llvm::Expected<std::vector<uint8_t>>
2550ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr, size_t len,
2551 int32_t type) {
2552 // By this point ReadMemoryTags has validated that tagging is enabled
2553 // for this target/process/address.
2554 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2555 if (!buffer_sp) {
2556 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2557 "Error reading memory tags from remote");
2558 }
2559
2560 // Return the raw tag data
2561 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2562 std::vector<uint8_t> got;
2563 got.reserve(tag_data.size());
2564 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2565 return got;
2566}
2567
2568Status ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr, size_t len,
2569 int32_t type,
2570 const std::vector<uint8_t> &tags) {
2571 // By now WriteMemoryTags should have validated that tagging is enabled
2572 // for this target/process.
2573 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2574}
2575
2576Status ProcessGDBRemote::WriteObjectFile(
2577 std::vector<ObjectFile::LoadableData> entries) {
2578 Status error;
2579 // Sort the entries by address because some writes, like those to flash
2580 // memory, must happen in order of increasing address.
2581 std::stable_sort(
2582 std::begin(entries), std::end(entries),
2583 [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) {
2584 return a.Dest < b.Dest;
2585 });
2586 m_allow_flash_writes = true;
2587 error = Process::WriteObjectFile(entries);
2588 if (error.Success())
2589 error = FlashDone();
2590 else
2591 // Even though some of the writing failed, try to send a flash done if some
2592 // of the writing succeeded so the flash state is reset to normal, but
2593 // don't stomp on the error status that was set in the write failure since
2594 // that's the one we want to report back.
2595 FlashDone();
2596 m_allow_flash_writes = false;
2597 return error;
2598}
2599
2600bool ProcessGDBRemote::HasErased(FlashRange range) {
2601 auto size = m_erased_flash_ranges.GetSize();
2602 for (size_t i = 0; i < size; ++i)
2603 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2604 return true;
2605 return false;
2606}
2607
2608Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) {
2609 Status status;
2610
2611 MemoryRegionInfo region;
2612 status = GetMemoryRegionInfo(addr, region);
2613 if (!status.Success())
2614 return status;
2615
2616 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2617 // but we'll disallow it to be safe and to keep the logic simple by worring
2618 // about only one region's block size. DoMemoryWrite is this function's
2619 // primary user, and it can easily keep writes within a single memory region
2620 if (addr + size > region.GetRange().GetRangeEnd()) {
2621 status.SetErrorString("Unable to erase flash in multiple regions");
2622 return status;
2623 }
2624
2625 uint64_t blocksize = region.GetBlocksize();
2626 if (blocksize == 0) {
2627 status.SetErrorString("Unable to erase flash because blocksize is 0");
2628 return status;
2629 }
2630
2631 // Erasures can only be done on block boundary adresses, so round down addr
2632 // and round up size
2633 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2634 size += (addr - block_start_addr);
2635 if ((size % blocksize) != 0)
2636 size += (blocksize - size % blocksize);
2637
2638 FlashRange range(block_start_addr, size);
2639
2640 if (HasErased(range))
2641 return status;
2642
2643 // We haven't erased the entire range, but we may have erased part of it.
2644 // (e.g., block A is already erased and range starts in A and ends in B). So,
2645 // adjust range if necessary to exclude already erased blocks.
2646 if (!m_erased_flash_ranges.IsEmpty()) {
2647 // Assuming that writes and erasures are done in increasing addr order,
2648 // because that is a requirement of the vFlashWrite command. Therefore, we
2649 // only need to look at the last range in the list for overlap.
2650 const auto &last_range = *m_erased_flash_ranges.Back();
2651 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2652 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2653 // overlap will be less than range.GetByteSize() or else HasErased()
2654 // would have been true
2655 range.SetByteSize(range.GetByteSize() - overlap);
2656 range.SetRangeBase(range.GetRangeBase() + overlap);
2657 }
2658 }
2659
2660 StreamString packet;
2661 packet.Printf("vFlashErase:%" PRIx64"l" "x" ",%" PRIx64"l" "x", range.GetRangeBase(),
2662 (uint64_t)range.GetByteSize());
2663
2664 StringExtractorGDBRemote response;
2665 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2666 GetInterruptTimeout()) ==
2667 GDBRemoteCommunication::PacketResult::Success) {
2668 if (response.IsOKResponse()) {
2669 m_erased_flash_ranges.Insert(range, true);
2670 } else {
2671 if (response.IsErrorResponse())
2672 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64"l" "x",
2673 addr);
2674 else if (response.IsUnsupportedResponse())
2675 status.SetErrorStringWithFormat("GDB server does not support flashing");
2676 else
2677 status.SetErrorStringWithFormat(
2678 "unexpected response to GDB server flash erase packet '%s': '%s'",
2679 packet.GetData(), response.GetStringRef().data());
2680 }
2681 } else {
2682 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2683 packet.GetData());
2684 }
2685 return status;
2686}
2687
2688Status ProcessGDBRemote::FlashDone() {
2689 Status status;
2690 // If we haven't erased any blocks, then we must not have written anything
2691 // either, so there is no need to actually send a vFlashDone command
2692 if (m_erased_flash_ranges.IsEmpty())
2693 return status;
2694 StringExtractorGDBRemote response;
2695 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2696 GetInterruptTimeout()) ==
2697 GDBRemoteCommunication::PacketResult::Success) {
2698 if (response.IsOKResponse()) {
2699 m_erased_flash_ranges.Clear();
2700 } else {
2701 if (response.IsErrorResponse())
2702 status.SetErrorStringWithFormat("flash done failed");
2703 else if (response.IsUnsupportedResponse())
2704 status.SetErrorStringWithFormat("GDB server does not support flashing");
2705 else
2706 status.SetErrorStringWithFormat(
2707 "unexpected response to GDB server flash done packet: '%s'",
2708 response.GetStringRef().data());
2709 }
2710 } else {
2711 status.SetErrorStringWithFormat("failed to send flash done packet");
2712 }
2713 return status;
2714}
2715
2716size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2717 size_t size, Status &error) {
2718 GetMaxMemorySize();
2719 // M and m packets take 2 bytes for 1 byte of memory
2720 size_t max_memory_size = m_max_memory_size / 2;
2721 if (size > max_memory_size) {
2722 // Keep memory read sizes down to a sane limit. This function will be
2723 // called multiple times in order to complete the task by
2724 // lldb_private::Process so it is ok to do this.
2725 size = max_memory_size;
2726 }
2727
2728 StreamGDBRemote packet;
2729
2730 MemoryRegionInfo region;
2731 Status region_status = GetMemoryRegionInfo(addr, region);
2732
2733 bool is_flash =
2734 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2735
2736 if (is_flash) {
2737 if (!m_allow_flash_writes) {
2738 error.SetErrorString("Writing to flash memory is not allowed");
2739 return 0;
2740 }
2741 // Keep the write within a flash memory region
2742 if (addr + size > region.GetRange().GetRangeEnd())
2743 size = region.GetRange().GetRangeEnd() - addr;
2744 // Flash memory must be erased before it can be written
2745 error = FlashErase(addr, size);
2746 if (!error.Success())
2747 return 0;
2748 packet.Printf("vFlashWrite:%" PRIx64"l" "x" ":", addr);
2749 packet.PutEscapedBytes(buf, size);
2750 } else {
2751 packet.Printf("M%" PRIx64"l" "x" ",%" PRIx64"l" "x" ":", addr, (uint64_t)size);
2752 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2753 endian::InlHostByteOrder());
2754 }
2755 StringExtractorGDBRemote response;
2756 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2757 GetInterruptTimeout()) ==
2758 GDBRemoteCommunication::PacketResult::Success) {
2759 if (response.IsOKResponse()) {
2760 error.Clear();
2761 return size;
2762 } else if (response.IsErrorResponse())
2763 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64"l" "x",
2764 addr);
2765 else if (response.IsUnsupportedResponse())
2766 error.SetErrorStringWithFormat(
2767 "GDB server does not support writing memory");
2768 else
2769 error.SetErrorStringWithFormat(
2770 "unexpected response to GDB server memory write packet '%s': '%s'",
2771 packet.GetData(), response.GetStringRef().data());
2772 } else {
2773 error.SetErrorStringWithFormat("failed to send packet: '%s'",
2774 packet.GetData());
2775 }
2776 return 0;
2777}
2778
2779lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size,
2780 uint32_t permissions,
2781 Status &error) {
2782 Log *log = GetLog(LLDBLog::Process | LLDBLog::Expressions);
2783 addr_t allocated_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2784
2785 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
2786 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2787 if (allocated_addr != LLDB_INVALID_ADDRESS(18446744073709551615UL) ||
2788 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
2789 return allocated_addr;
2790 }
2791
2792 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
2793 // Call mmap() to create memory in the inferior..
2794 unsigned prot = 0;
2795 if (permissions & lldb::ePermissionsReadable)
2796 prot |= eMmapProtRead;
2797 if (permissions & lldb::ePermissionsWritable)
2798 prot |= eMmapProtWrite;
2799 if (permissions & lldb::ePermissionsExecutable)
2800 prot |= eMmapProtExec;
2801
2802 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2803 eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0))
2804 m_addr_to_mmap_size[allocated_addr] = size;
2805 else {
2806 allocated_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
2807 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no direct stub support for memory "
"allocation, and InferiorCallMmap also failed - is stub " "missing register context save/restore capability?"
, __FUNCTION__); } while (0)
2808 "ProcessGDBRemote::%s no direct stub support for memory "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no direct stub support for memory "
"allocation, and InferiorCallMmap also failed - is stub " "missing register context save/restore capability?"
, __FUNCTION__); } while (0)
2809 "allocation, and InferiorCallMmap also failed - is stub "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no direct stub support for memory "
"allocation, and InferiorCallMmap also failed - is stub " "missing register context save/restore capability?"
, __FUNCTION__); } while (0)
2810 "missing register context save/restore capability?",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no direct stub support for memory "
"allocation, and InferiorCallMmap also failed - is stub " "missing register context save/restore capability?"
, __FUNCTION__); } while (0)
2811 __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s no direct stub support for memory "
"allocation, and InferiorCallMmap also failed - is stub " "missing register context save/restore capability?"
, __FUNCTION__); } while (0)
;
2812 }
2813 }
2814
2815 if (allocated_addr == LLDB_INVALID_ADDRESS(18446744073709551615UL))
2816 error.SetErrorStringWithFormat(
2817 "unable to allocate %" PRIu64"l" "u" " bytes of memory with permissions %s",
2818 (uint64_t)size, GetPermissionsAsCString(permissions));
2819 else
2820 error.Clear();
2821 return allocated_addr;
2822}
2823
2824Status ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr,
2825 MemoryRegionInfo &region_info) {
2826
2827 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2828 return error;
2829}
2830
2831Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) {
2832
2833 Status error(m_gdb_comm.GetWatchpointSupportInfo(num));
2834 return error;
2835}
2836
2837Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) {
2838 Status error(m_gdb_comm.GetWatchpointSupportInfo(
2839 num, after, GetTarget().GetArchitecture()));
2840 return error;
2841}
2842
2843Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) {
2844 Status error;
2845 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
2846
2847 switch (supported) {
2848 case eLazyBoolCalculate:
2849 // We should never be deallocating memory without allocating memory first
2850 // so we should never get eLazyBoolCalculate
2851 error.SetErrorString(
2852 "tried to deallocate memory without ever allocating memory");
2853 break;
2854
2855 case eLazyBoolYes:
2856 if (!m_gdb_comm.DeallocateMemory(addr))
2857 error.SetErrorStringWithFormat(
2858 "unable to deallocate memory at 0x%" PRIx64"l" "x", addr);
2859 break;
2860
2861 case eLazyBoolNo:
2862 // Call munmap() to deallocate memory in the inferior..
2863 {
2864 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2865 if (pos != m_addr_to_mmap_size.end() &&
2866 InferiorCallMunmap(this, addr, pos->second))
2867 m_addr_to_mmap_size.erase(pos);
2868 else
2869 error.SetErrorStringWithFormat(
2870 "unable to deallocate memory at 0x%" PRIx64"l" "x", addr);
2871 }
2872 break;
2873 }
2874
2875 return error;
2876}
2877
2878// Process STDIO
2879size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2880 Status &error) {
2881 if (m_stdio_communication.IsConnected()) {
2882 ConnectionStatus status;
2883 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
2884 } else if (m_stdin_forward) {
2885 m_gdb_comm.SendStdinNotification(src, src_len);
2886 }
2887 return 0;
2888}
2889
2890Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) {
2891 Status error;
2892 assert(bp_site != nullptr)(static_cast <bool> (bp_site != nullptr) ? void (0) : __assert_fail
("bp_site != nullptr", "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 2892, __extension__ __PRETTY_FUNCTION__))
;
2893
2894 // Get logging info
2895 Log *log = GetLog(GDBRLog::Breakpoints);
2896 user_id_t site_id = bp_site->GetID();
2897
2898 // Get the breakpoint address
2899 const addr_t addr = bp_site->GetLoadAddress();
2900
2901 // Log that a breakpoint was requested
2902 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x", site_id, (uint64_t)addr);
} while (0)
2903 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x", site_id, (uint64_t)addr);
} while (0)
2904 ") address = 0x%" PRIx64,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x", site_id, (uint64_t)addr);
} while (0)
2905 site_id, (uint64_t)addr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x", site_id, (uint64_t)addr);
} while (0)
;
2906
2907 // Breakpoint already exists and is enabled
2908 if (bp_site->IsEnabled()) {
2909 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x" " -- SUCCESS (already enabled)"
, site_id, (uint64_t)addr); } while (0)
2910 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x" " -- SUCCESS (already enabled)"
, site_id, (uint64_t)addr); } while (0)
2911 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x" " -- SUCCESS (already enabled)"
, site_id, (uint64_t)addr); } while (0)
2912 site_id, (uint64_t)addr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableBreakpointSite (size_id = %"
"l" "u" ") address = 0x%" "l" "x" " -- SUCCESS (already enabled)"
, site_id, (uint64_t)addr); } while (0)
;
2913 return error;
2914 }
2915
2916 // Get the software breakpoint trap opcode size
2917 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2918
2919 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2920 // breakpoint type is supported by the remote stub. These are set to true by
2921 // default, and later set to false only after we receive an unimplemented
2922 // response when sending a breakpoint packet. This means initially that
2923 // unless we were specifically instructed to use a hardware breakpoint, LLDB
2924 // will attempt to set a software breakpoint. HardwareRequired() also queries
2925 // a boolean variable which indicates if the user specifically asked for
2926 // hardware breakpoints. If true then we will skip over software
2927 // breakpoints.
2928 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
2929 (!bp_site->HardwareRequired())) {
2930 // Try to send off a software breakpoint packet ($Z0)
2931 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2932 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
2933 if (error_no == 0) {
2934 // The breakpoint was placed successfully
2935 bp_site->SetEnabled(true);
2936 bp_site->SetType(BreakpointSite::eExternal);
2937 return error;
2938 }
2939
2940 // SendGDBStoppointTypePacket() will return an error if it was unable to
2941 // set this breakpoint. We need to differentiate between a error specific
2942 // to placing this breakpoint or if we have learned that this breakpoint
2943 // type is unsupported. To do this, we must test the support boolean for
2944 // this breakpoint type to see if it now indicates that this breakpoint
2945 // type is unsupported. If they are still supported then we should return
2946 // with the error code. If they are now unsupported, then we would like to
2947 // fall through and try another form of breakpoint.
2948 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
2949 if (error_no != UINT8_MAX(255))
2950 error.SetErrorStringWithFormat(
2951 "error: %d sending the breakpoint request", error_no);
2952 else
2953 error.SetErrorString("error sending the breakpoint request");
2954 return error;
2955 }
2956
2957 // We reach here when software breakpoints have been found to be
2958 // unsupported. For future calls to set a breakpoint, we will not attempt
2959 // to set a breakpoint with a type that is known not to be supported.
2960 LLDB_LOGF(log, "Software breakpoints are unsupported")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Software breakpoints are unsupported"
); } while (0)
;
2961
2962 // So we will fall through and try a hardware breakpoint
2963 }
2964
2965 // The process of setting a hardware breakpoint is much the same as above.
2966 // We check the supported boolean for this breakpoint type, and if it is
2967 // thought to be supported then we will try to set this breakpoint with a
2968 // hardware breakpoint.
2969 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
2970 // Try to send off a hardware breakpoint packet ($Z1)
2971 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2972 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
2973 if (error_no == 0) {
2974 // The breakpoint was placed successfully
2975 bp_site->SetEnabled(true);
2976 bp_site->SetType(BreakpointSite::eHardware);
2977 return error;
2978 }
2979
2980 // Check if the error was something other then an unsupported breakpoint
2981 // type
2982 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
2983 // Unable to set this hardware breakpoint
2984 if (error_no != UINT8_MAX(255))
2985 error.SetErrorStringWithFormat(
2986 "error: %d sending the hardware breakpoint request "
2987 "(hardware breakpoint resources might be exhausted or unavailable)",
2988 error_no);
2989 else
2990 error.SetErrorString("error sending the hardware breakpoint request "
2991 "(hardware breakpoint resources "
2992 "might be exhausted or unavailable)");
2993 return error;
2994 }
2995
2996 // We will reach here when the stub gives an unsupported response to a
2997 // hardware breakpoint
2998 LLDB_LOGF(log, "Hardware breakpoints are unsupported")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Hardware breakpoints are unsupported"
); } while (0)
;
2999
3000 // Finally we will falling through to a #trap style breakpoint
3001 }
3002
3003 // Don't fall through when hardware breakpoints were specifically requested
3004 if (bp_site->HardwareRequired()) {
3005 error.SetErrorString("hardware breakpoints are not supported");
3006 return error;
3007 }
3008
3009 // As a last resort we want to place a manual breakpoint. An instruction is
3010 // placed into the process memory using memory write packets.
3011 return EnableSoftwareBreakpoint(bp_site);
3012}
3013
3014Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) {
3015 Status error;
3016 assert(bp_site != nullptr)(static_cast <bool> (bp_site != nullptr) ? void (0) : __assert_fail
("bp_site != nullptr", "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 3016, __extension__ __PRETTY_FUNCTION__))
;
3017 addr_t addr = bp_site->GetLoadAddress();
3018 user_id_t site_id = bp_site->GetID();
3019 Log *log = GetLog(GDBRLog::Breakpoints);
3020 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x", site_id, (uint64_t)addr);
} while (0)
3021 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x", site_id, (uint64_t)addr);
} while (0)
3022 ") addr = 0x%8.8" PRIx64,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x", site_id, (uint64_t)addr);
} while (0)
3023 site_id, (uint64_t)addr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x", site_id, (uint64_t)addr);
} while (0)
;
3024
3025 if (bp_site->IsEnabled()) {
3026 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3027
3028 BreakpointSite::Type bp_type = bp_site->GetType();
3029 switch (bp_type) {
3030 case BreakpointSite::eSoftware:
3031 error = DisableSoftwareBreakpoint(bp_site);
3032 break;
3033
3034 case BreakpointSite::eHardware:
3035 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3036 addr, bp_op_size,
3037 GetInterruptTimeout()))
3038 error.SetErrorToGenericError();
3039 break;
3040
3041 case BreakpointSite::eExternal: {
3042 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3043 addr, bp_op_size,
3044 GetInterruptTimeout()))
3045 error.SetErrorToGenericError();
3046 } break;
3047 }
3048 if (error.Success())
3049 bp_site->SetEnabled(false);
3050 } else {
3051 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, site_id, (uint64_t)addr); } while (0)
3052 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, site_id, (uint64_t)addr); } while (0)
3053 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, site_id, (uint64_t)addr); } while (0)
3054 site_id, (uint64_t)addr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableBreakpointSite (site_id = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, site_id, (uint64_t)addr); } while (0)
;
3055 return error;
3056 }
3057
3058 if (error.Success())
3059 error.SetErrorToGenericError();
3060 return error;
3061}
3062
3063// Pre-requisite: wp != NULL.
3064static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) {
3065 assert(wp)(static_cast <bool> (wp) ? void (0) : __assert_fail ("wp"
, "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 3065, __extension__ __PRETTY_FUNCTION__))
;
3066 bool watch_read = wp->WatchpointRead();
3067 bool watch_write = wp->WatchpointWrite();
3068
3069 // watch_read and watch_write cannot both be false.
3070 assert(watch_read || watch_write)(static_cast <bool> (watch_read || watch_write) ? void (
0) : __assert_fail ("watch_read || watch_write", "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 3070, __extension__ __PRETTY_FUNCTION__))
;
3071 if (watch_read && watch_write)
3072 return eWatchpointReadWrite;
3073 else if (watch_read)
3074 return eWatchpointRead;
3075 else // Must be watch_write, then.
3076 return eWatchpointWrite;
3077}
3078
3079Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) {
3080 Status error;
3081 if (wp) {
3082 user_id_t watchID = wp->GetID();
3083 addr_t addr = wp->GetLoadAddress();
3084 Log *log(GetLog(GDBRLog::Watchpoints));
3085 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %"
"l" "u" ")", watchID); } while (0)
3086 watchID)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %"
"l" "u" ")", watchID); } while (0)
;
3087 if (wp->IsEnabled()) {
3088 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" ": watchpoint already enabled."
, watchID, (uint64_t)addr); } while (0)
3089 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" ": watchpoint already enabled."
, watchID, (uint64_t)addr); } while (0)
3090 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" ": watchpoint already enabled."
, watchID, (uint64_t)addr); } while (0)
3091 watchID, (uint64_t)addr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::EnableWatchpoint(watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" ": watchpoint already enabled."
, watchID, (uint64_t)addr); } while (0)
;
3092 return error;
3093 }
3094
3095 GDBStoppointType type = GetGDBStoppointType(wp);
3096 // Pass down an appropriate z/Z packet...
3097 if (m_gdb_comm.SupportsGDBStoppointPacket(type)) {
3098 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3099 wp->GetByteSize(),
3100 GetInterruptTimeout()) == 0) {
3101 wp->SetEnabled(true, notify);
3102 return error;
3103 } else
3104 error.SetErrorString("sending gdb watchpoint packet failed");
3105 } else
3106 error.SetErrorString("watchpoints not supported");
3107 } else {
3108 error.SetErrorString("Watchpoint argument was NULL.");
3109 }
3110 if (error.Success())
3111 error.SetErrorToGenericError();
3112 return error;
3113}
3114
3115Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) {
3116 Status error;
3117 if (wp) {
3118 user_id_t watchID = wp->GetID();
3119
3120 Log *log(GetLog(GDBRLog::Watchpoints));
3121
3122 addr_t addr = wp->GetLoadAddress();
3123
3124 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x", watchID, (uint64_t)addr);
} while (0)
3125 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x", watchID, (uint64_t)addr);
} while (0)
3126 ") addr = 0x%8.8" PRIx64,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x", watchID, (uint64_t)addr);
} while (0)
3127 watchID, (uint64_t)addr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x", watchID, (uint64_t)addr);
} while (0)
;
3128
3129 if (!wp->IsEnabled()) {
3130 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, watchID, (uint64_t)addr); } while (0)
3131 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, watchID, (uint64_t)addr); } while (0)
3132 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, watchID, (uint64_t)addr); } while (0)
3133 watchID, (uint64_t)addr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DisableWatchpoint (watchID = %"
"l" "u" ") addr = 0x%8.8" "l" "x" " -- SUCCESS (already disabled)"
, watchID, (uint64_t)addr); } while (0)
;
3134 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3135 // attempt might come from the user-supplied actions, we'll route it in
3136 // order for the watchpoint object to intelligently process this action.
3137 wp->SetEnabled(false, notify);
3138 return error;
3139 }
3140
3141 if (wp->IsHardware()) {
3142 GDBStoppointType type = GetGDBStoppointType(wp);
3143 // Pass down an appropriate z/Z packet...
3144 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3145 wp->GetByteSize(),
3146 GetInterruptTimeout()) == 0) {
3147 wp->SetEnabled(false, notify);
3148 return error;
3149 } else
3150 error.SetErrorString("sending gdb watchpoint packet failed");
3151 }
3152 // TODO: clear software watchpoints if we implement them
3153 } else {
3154 error.SetErrorString("Watchpoint argument was NULL.");
3155 }
3156 if (error.Success())
3157 error.SetErrorToGenericError();
3158 return error;
3159}
3160
3161void ProcessGDBRemote::Clear() {
3162 m_thread_list_real.Clear();
3163 m_thread_list.Clear();
3164}
3165
3166Status ProcessGDBRemote::DoSignal(int signo) {
3167 Status error;
3168 Log *log = GetLog(GDBRLog::Process);
3169 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::DoSignal (signal = %d)"
, signo); } while (0)
;
3170
3171 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3172 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3173 return error;
3174}
3175
3176Status
3177ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) {
3178 // Make sure we aren't already connected?
3179 if (m_gdb_comm.IsConnected())
3180 return Status();
3181
3182 PlatformSP platform_sp(GetTarget().GetPlatform());
3183 if (platform_sp && !platform_sp->IsHost())
3184 return Status("Lost debug server connection");
3185
3186 auto error = LaunchAndConnectToDebugserver(process_info);
3187 if (error.Fail()) {
3188 const char *error_string = error.AsCString();
3189 if (error_string == nullptr)
3190 error_string = "unable to launch " DEBUGSERVER_BASENAME"debugserver";
Value stored to 'error_string' is never read
3191 }
3192 return error;
3193}
3194#if !defined(_WIN32)
3195#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1 1
3196#endif
3197
3198#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1
3199static bool SetCloexecFlag(int fd) {
3200#if defined(FD_CLOEXEC1)
3201 int flags = ::fcntl(fd, F_GETFD1);
3202 if (flags == -1)
3203 return false;
3204 return (::fcntl(fd, F_SETFD2, flags | FD_CLOEXEC1) == 0);
3205#else
3206 return false;
3207#endif
3208}
3209#endif
3210
3211Status ProcessGDBRemote::LaunchAndConnectToDebugserver(
3212 const ProcessInfo &process_info) {
3213 using namespace std::placeholders; // For _1, _2, etc.
3214
3215 Status error;
3216 if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID0) {
3217 // If we locate debugserver, keep that located version around
3218 static FileSpec g_debugserver_file_spec;
3219
3220 ProcessLaunchInfo debugserver_launch_info;
3221 // Make debugserver run in its own session so signals generated by special
3222 // terminal key sequences (^C) don't affect debugserver.
3223 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3224
3225 const std::weak_ptr<ProcessGDBRemote> this_wp =
3226 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3227 debugserver_launch_info.SetMonitorProcessCallback(
3228 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3229 debugserver_launch_info.SetUserID(process_info.GetUserID());
3230
3231#if defined(__APPLE__)
3232 // On macOS 11, we need to support x86_64 applications translated to
3233 // arm64. We check whether a binary is translated and spawn the correct
3234 // debugserver accordingly.
3235 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3236 static_cast<int>(process_info.GetProcessID()) };
3237 struct kinfo_proc processInfo;
3238 size_t bufsize = sizeof(processInfo);
3239 if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3240 &bufsize, NULL__null, 0) == 0 && bufsize > 0) {
3241 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3242 FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3243 debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3244 }
3245 }
3246#endif
3247
3248 int communication_fd = -1;
3249#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1
3250 // Use a socketpair on non-Windows systems for security and performance
3251 // reasons.
3252 int sockets[2]; /* the pair of socket descriptors */
3253 if (socketpair(AF_UNIX1, SOCK_STREAMSOCK_STREAM, 0, sockets) == -1) {
3254 error.SetErrorToErrno();
3255 return error;
3256 }
3257
3258 int our_socket = sockets[0];
3259 int gdb_socket = sockets[1];
3260 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3261 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3262
3263 // Don't let any child processes inherit our communication socket
3264 SetCloexecFlag(our_socket);
3265 communication_fd = gdb_socket;
3266#endif
3267
3268 error = m_gdb_comm.StartDebugserverProcess(
3269 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3270 nullptr, nullptr, communication_fd);
3271
3272 if (error.Success())
3273 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3274 else
3275 m_debugserver_pid = LLDB_INVALID_PROCESS_ID0;
3276
3277 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID0) {
3278#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION1
3279 // Our process spawned correctly, we can now set our connection to use
3280 // our end of the socket pair
3281 cleanup_our.release();
3282 m_gdb_comm.SetConnection(
3283 std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3284#endif
3285 StartAsyncThread();
3286 }
3287
3288 if (error.Fail()) {
3289 Log *log = GetLog(GDBRLog::Process);
3290
3291 LLDB_LOGF(log, "failed to start debugserver process: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("failed to start debugserver process: %s"
, error.AsCString()); } while (0)
3292 error.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("failed to start debugserver process: %s"
, error.AsCString()); } while (0)
;
3293 return error;
3294 }
3295
3296 if (m_gdb_comm.IsConnected()) {
3297 // Finish the connection process by doing the handshake without
3298 // connecting (send NULL URL)
3299 error = ConnectToDebugserver("");
3300 } else {
3301 error.SetErrorString("connection failed");
3302 }
3303 }
3304 return error;
3305}
3306
3307void ProcessGDBRemote::MonitorDebugserverProcess(
3308 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3309 int signo, // Zero for no signal
3310 int exit_status // Exit value of process if signal is zero
3311) {
3312 // "debugserver_pid" argument passed in is the process ID for debugserver
3313 // that we are tracking...
3314 Log *log = GetLog(GDBRLog::Process);
3315
3316 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(process_wp, pid=%"
"l" "u" ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__, debugserver_pid
, signo, signo, exit_status); } while (0)
3317 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(process_wp, pid=%"
"l" "u" ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__, debugserver_pid
, signo, signo, exit_status); } while (0)
3318 ", signo=%i (0x%x), exit_status=%i)",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(process_wp, pid=%"
"l" "u" ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__, debugserver_pid
, signo, signo, exit_status); } while (0)
3319 __FUNCTION__, debugserver_pid, signo, signo, exit_status)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(process_wp, pid=%"
"l" "u" ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__, debugserver_pid
, signo, signo, exit_status); } while (0)
;
3320
3321 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3322 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(process = %p)"
, __FUNCTION__, static_cast<void *>(process_sp.get()));
} while (0)
3323 static_cast<void *>(process_sp.get()))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(process = %p)"
, __FUNCTION__, static_cast<void *>(process_sp.get()));
} while (0)
;
3324 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3325 return;
3326
3327 // Sleep for a half a second to make sure our inferior process has time to
3328 // set its exit status before we set it incorrectly when both the debugserver
3329 // and the inferior process shut down.
3330 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3331
3332 // If our process hasn't yet exited, debugserver might have died. If the
3333 // process did exit, then we are reaping it.
3334 const StateType state = process_sp->GetState();
3335
3336 if (state != eStateInvalid && state != eStateUnloaded &&
3337 state != eStateExited && state != eStateDetached) {
3338 char error_str[1024];
3339 if (signo) {
3340 const char *signal_cstr =
3341 process_sp->GetUnixSignals()->GetSignalAsCString(signo);
3342 if (signal_cstr)
3343 ::snprintf(error_str, sizeof(error_str),
3344 DEBUGSERVER_BASENAME"debugserver" " died with signal %s", signal_cstr);
3345 else
3346 ::snprintf(error_str, sizeof(error_str),
3347 DEBUGSERVER_BASENAME"debugserver" " died with signal %i", signo);
3348 } else {
3349 ::snprintf(error_str, sizeof(error_str),
3350 DEBUGSERVER_BASENAME"debugserver" " died with an exit status of 0x%8.8x",
3351 exit_status);
3352 }
3353
3354 process_sp->SetExitStatus(-1, error_str);
3355 }
3356 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3357 // longer has a debugserver instance
3358 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID0;
3359}
3360
3361void ProcessGDBRemote::KillDebugserverProcess() {
3362 m_gdb_comm.Disconnect();
3363 if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID0) {
3364 Host::Kill(m_debugserver_pid, SIGINT2);
3365 m_debugserver_pid = LLDB_INVALID_PROCESS_ID0;
3366 }
3367}
3368
3369void ProcessGDBRemote::Initialize() {
3370 static llvm::once_flag g_once_flag;
3371
3372 llvm::call_once(g_once_flag, []() {
3373 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3374 GetPluginDescriptionStatic(), CreateInstance,
3375 DebuggerInitialize);
3376 });
3377}
3378
3379void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) {
3380 if (!PluginManager::GetSettingForProcessPlugin(
3381 debugger, PluginProperties::GetSettingName())) {
3382 const bool is_global_setting = true;
3383 PluginManager::CreateSettingForProcessPlugin(
3384 debugger, GetGlobalPluginProperties().GetValueProperties(),
3385 ConstString("Properties for the gdb-remote process plug-in."),
3386 is_global_setting);
3387 }
3388}
3389
3390bool ProcessGDBRemote::StartAsyncThread() {
3391 Log *log = GetLog(GDBRLog::Process);
3392
3393 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s ()", __FUNCTION__
); } while (0)
;
3394
3395 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3396 if (!m_async_thread.IsJoinable()) {
3397 // Create a thread that watches our internal state and controls which
3398 // events make it to clients (into the DCProcess event queue).
3399
3400 llvm::Expected<HostThread> async_thread =
3401 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3402 return ProcessGDBRemote::AsyncThread();
3403 });
3404 if (!async_thread) {
3405 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),do { ::lldb_private::Log *log_private = (GetLog(LLDBLog::Host
)); ::llvm::Error error_private = (async_thread.takeError());
if (log_private && error_private) { log_private->
FormatError(::std::move(error_private), "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "failed to launch host thread: {}"); } else ::llvm
::consumeError(::std::move(error_private)); } while (0)
3406 "failed to launch host thread: {}")do { ::lldb_private::Log *log_private = (GetLog(LLDBLog::Host
)); ::llvm::Error error_private = (async_thread.takeError());
if (log_private && error_private) { log_private->
FormatError(::std::move(error_private), "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "failed to launch host thread: {}"); } else ::llvm
::consumeError(::std::move(error_private)); } while (0)
;
3407 return false;
3408 }
3409 m_async_thread = *async_thread;
3410 } else
3411 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
"already running.", __FUNCTION__); } while (0)
3412 "ProcessGDBRemote::%s () - Called when Async thread was "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
"already running.", __FUNCTION__); } while (0)
3413 "already running.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
"already running.", __FUNCTION__); } while (0)
3414 __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was "
"already running.", __FUNCTION__); } while (0)
;
3415
3416 return m_async_thread.IsJoinable();
3417}
3418
3419void ProcessGDBRemote::StopAsyncThread() {
3420 Log *log = GetLog(GDBRLog::Process);
3421
3422 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s ()", __FUNCTION__
); } while (0)
;
3423
3424 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3425 if (m_async_thread.IsJoinable()) {
3426 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit);
3427
3428 // This will shut down the async thread.
3429 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3430
3431 // Stop the stdio thread
3432 m_async_thread.Join(nullptr);
3433 m_async_thread.Reset();
3434 } else
3435 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running."
, __FUNCTION__); } while (0)
3436 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running."
, __FUNCTION__); } while (0)
3437 "ProcessGDBRemote::%s () - Called when Async thread was not running.",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running."
, __FUNCTION__); } while (0)
3438 __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s () - Called when Async thread was not running."
, __FUNCTION__); } while (0)
;
3439}
3440
3441thread_result_t ProcessGDBRemote::AsyncThread() {
3442 Log *log = GetLog(GDBRLog::Process);
3443 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") thread starting...", __FUNCTION__, GetID()); } while (0)
3444 __FUNCTION__, GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") thread starting...", __FUNCTION__, GetID()); } while (0)
;
3445
3446 EventSP event_sp;
3447
3448 // We need to ignore any packets that come in after we have
3449 // have decided the process has exited. There are some
3450 // situations, for instance when we try to interrupt a running
3451 // process and the interrupt fails, where another packet might
3452 // get delivered after we've decided to give up on the process.
3453 // But once we've decided we are done with the process we will
3454 // not be in a state to do anything useful with new packets.
3455 // So it is safer to simply ignore any remaining packets by
3456 // explicitly checking for eStateExited before reentering the
3457 // fetch loop.
3458
3459 bool done = false;
3460 while (!done && GetPrivateState() != eStateExited) {
3461 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__,
GetID()); } while (0)
3462 "ProcessGDBRemote::%s(pid = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__,
GetID()); } while (0)
3463 ") listener.WaitForEvent (NULL, event_sp)...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__,
GetID()); } while (0)
3464 __FUNCTION__, GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__,
GetID()); } while (0)
;
3465
3466 if (m_async_listener_sp->GetEvent(event_sp, llvm::None)) {
3467 const uint32_t event_type = event_sp->GetType();
3468 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3469 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") Got an event of type: %d...", __FUNCTION__, GetID(), event_type
); } while (0)
3470 "ProcessGDBRemote::%s(pid = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") Got an event of type: %d...", __FUNCTION__, GetID(), event_type
); } while (0)
3471 ") Got an event of type: %d...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") Got an event of type: %d...", __FUNCTION__, GetID(), event_type
); } while (0)
3472 __FUNCTION__, GetID(), event_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") Got an event of type: %d...", __FUNCTION__, GetID(), event_type
); } while (0)
;
3473
3474 switch (event_type) {
3475 case eBroadcastBitAsyncContinue: {
3476 const EventDataBytes *continue_packet =
3477 EventDataBytes::GetEventDataFromEvent(event_sp.get());
3478
3479 if (continue_packet) {
3480 const char *continue_cstr =
3481 (const char *)continue_packet->GetBytes();
3482 const size_t continue_cstr_len = continue_packet->GetByteSize();
3483 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, GetID(
), continue_cstr); } while (0)
3484 "ProcessGDBRemote::%s(pid = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, GetID(
), continue_cstr); } while (0)
3485 ") got eBroadcastBitAsyncContinue: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, GetID(
), continue_cstr); } while (0)
3486 __FUNCTION__, GetID(), continue_cstr)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, GetID(
), continue_cstr); } while (0)
;
3487
3488 if (::strstr(continue_cstr, "vAttach") == nullptr)
3489 SetPrivateState(eStateRunning);
3490 StringExtractorGDBRemote response;
3491
3492 StateType stop_state =
3493 GetGDBRemote().SendContinuePacketAndWaitForResponse(
3494 *this, *GetUnixSignals(),
3495 llvm::StringRef(continue_cstr, continue_cstr_len),
3496 GetInterruptTimeout(), response);
3497
3498 // We need to immediately clear the thread ID list so we are sure
3499 // to get a valid list of threads. The thread ID list might be
3500 // contained within the "response", or the stop reply packet that
3501 // caused the stop. So clear it now before we give the stop reply
3502 // packet to the process using the
3503 // SetLastStopPacket()...
3504 ClearThreadIDList();
3505
3506 switch (stop_state) {
3507 case eStateStopped:
3508 case eStateCrashed:
3509 case eStateSuspended:
3510 SetLastStopPacket(response);
3511 SetPrivateState(stop_state);
3512 break;
3513
3514 case eStateExited: {
3515 SetLastStopPacket(response);
3516 ClearThreadIDList();
3517 response.SetFilePos(1);
3518
3519 int exit_status = response.GetHexU8();
3520 std::string desc_string;
3521 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3522 llvm::StringRef desc_str;
3523 llvm::StringRef desc_token;
3524 while (response.GetNameColonValue(desc_token, desc_str)) {
3525 if (desc_token != "description")
3526 continue;
3527 StringExtractor extractor(desc_str);
3528 extractor.GetHexByteString(desc_string);
3529 }
3530 }
3531 SetExitStatus(exit_status, desc_string.c_str());
3532 done = true;
3533 break;
3534 }
3535 case eStateInvalid: {
3536 // Check to see if we were trying to attach and if we got back
3537 // the "E87" error code from debugserver -- this indicates that
3538 // the process is not debuggable. Return a slightly more
3539 // helpful error message about why the attach failed.
3540 if (::strstr(continue_cstr, "vAttach") != nullptr &&
3541 response.GetError() == 0x87) {
3542 SetExitStatus(-1, "cannot attach to process due to "
3543 "System Integrity Protection");
3544 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3545 response.GetStatus().Fail()) {
3546 SetExitStatus(-1, response.GetStatus().AsCString());
3547 } else {
3548 SetExitStatus(-1, "lost connection");
3549 }
3550 done = true;
3551 break;
3552 }
3553
3554 default:
3555 SetPrivateState(stop_state);
3556 break;
3557 } // switch(stop_state)
3558 } // if (continue_packet)
3559 } // case eBroadcastBitAsyncContinue
3560 break;
3561
3562 case eBroadcastBitAsyncThreadShouldExit:
3563 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__,
GetID()); } while (0)
3564 "ProcessGDBRemote::%s(pid = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__,
GetID()); } while (0)
3565 ") got eBroadcastBitAsyncThreadShouldExit...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__,
GetID()); } while (0)
3566 __FUNCTION__, GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__,
GetID()); } while (0)
;
3567 done = true;
3568 break;
3569
3570 default:
3571 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
3572 "ProcessGDBRemote::%s(pid = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
3573 ") got unknown event 0x%8.8x",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
3574 __FUNCTION__, GetID(), event_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
;
3575 done = true;
3576 break;
3577 }
3578 } else if (event_sp->BroadcasterIs(&m_gdb_comm)) {
3579 switch (event_type) {
3580 case Communication::eBroadcastBitReadThreadDidExit:
3581 SetExitStatus(-1, "lost connection");
3582 done = true;
3583 break;
3584
3585 default:
3586 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
3587 "ProcessGDBRemote::%s(pid = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
3588 ") got unknown event 0x%8.8x",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
3589 __FUNCTION__, GetID(), event_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") got unknown event 0x%8.8x", __FUNCTION__, GetID(), event_type
); } while (0)
;
3590 done = true;
3591 break;
3592 }
3593 }
3594 } else {
3595 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__
, GetID()); } while (0)
3596 "ProcessGDBRemote::%s(pid = %" PRIu64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__
, GetID()); } while (0)
3597 ") listener.WaitForEvent (NULL, event_sp) => false",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__
, GetID()); } while (0)
3598 __FUNCTION__, GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__
, GetID()); } while (0)
;
3599 done = true;
3600 }
3601 }
3602
3603 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") thread exiting...", __FUNCTION__, GetID()); } while (0)
3604 __FUNCTION__, GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s(pid = %" "l" "u"
") thread exiting...", __FUNCTION__, GetID()); } while (0)
;
3605
3606 return {};
3607}
3608
3609// uint32_t
3610// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3611// &matches, std::vector<lldb::pid_t> &pids)
3612//{
3613// // If we are planning to launch the debugserver remotely, then we need to
3614// fire up a debugserver
3615// // process and ask it for the list of processes. But if we are local, we
3616// can let the Host do it.
3617// if (m_local_debugserver)
3618// {
3619// return Host::ListProcessesMatchingName (name, matches, pids);
3620// }
3621// else
3622// {
3623// // FIXME: Implement talking to the remote debugserver.
3624// return 0;
3625// }
3626//
3627//}
3628//
3629bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3630 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3631 lldb::user_id_t break_loc_id) {
3632 // I don't think I have to do anything here, just make sure I notice the new
3633 // thread when it starts to
3634 // run so I can stop it if that's what I want to do.
3635 Log *log = GetLog(LLDBLog::Step);
3636 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Hit New Thread Notification breakpoint."
); } while (0)
;
3637 return false;
3638}
3639
3640Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3641 Log *log = GetLog(GDBRLog::Process);
3642 LLDB_LOG(log, "Check if need to update ignored signals")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Check if need to update ignored signals"); } while
(0)
;
3643
3644 // QPassSignals package is not supported by the server, there is no way we
3645 // can ignore any signals on server side.
3646 if (!m_gdb_comm.GetQPassSignalsSupported())
3647 return Status();
3648
3649 // No signals, nothing to send.
3650 if (m_unix_signals_sp == nullptr)
3651 return Status();
3652
3653 // Signals' version hasn't changed, no need to send anything.
3654 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3655 if (new_signals_version == m_last_signals_version) {
3656 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Signals' version hasn't changed. version={0}", m_last_signals_version
); } while (0)
3657 m_last_signals_version)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Signals' version hasn't changed. version={0}", m_last_signals_version
); } while (0)
;
3658 return Status();
3659 }
3660
3661 auto signals_to_ignore =
3662 m_unix_signals_sp->GetFilteredSignals(false, false, false);
3663 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3664
3665 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3666 "Signals' version changed. old version={0}, new version={1}, "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3667 "signals ignored={2}, update result={3}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3668 m_last_signals_version, new_signals_version,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
3669 signals_to_ignore.size(), error)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Signals' version changed. old version={0}, new version={1}, "
"signals ignored={2}, update result={3}", m_last_signals_version
, new_signals_version, signals_to_ignore.size(), error); } while
(0)
;
3670
3671 if (error.Success())
3672 m_last_signals_version = new_signals_version;
3673
3674 return error;
3675}
3676
3677bool ProcessGDBRemote::StartNoticingNewThreads() {
3678 Log *log = GetLog(LLDBLog::Step);
3679 if (m_thread_create_bp_sp) {
3680 if (log && log->GetVerbose())
3681 LLDB_LOGF(log, "Enabled noticing new thread breakpoint.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Enabled noticing new thread breakpoint."
); } while (0)
;
3682 m_thread_create_bp_sp->SetEnabled(true);
3683 } else {
3684 PlatformSP platform_sp(GetTarget().GetPlatform());
3685 if (platform_sp) {
3686 m_thread_create_bp_sp =
3687 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3688 if (m_thread_create_bp_sp) {
3689 if (log && log->GetVerbose())
3690 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Successfully created new thread notification breakpoint %i"
, m_thread_create_bp_sp->GetID()); } while (0)
3691 log, "Successfully created new thread notification breakpoint %i",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Successfully created new thread notification breakpoint %i"
, m_thread_create_bp_sp->GetID()); } while (0)
3692 m_thread_create_bp_sp->GetID())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Successfully created new thread notification breakpoint %i"
, m_thread_create_bp_sp->GetID()); } while (0)
;
3693 m_thread_create_bp_sp->SetCallback(
3694 ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true);
3695 } else {
3696 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Failed to create new thread notification breakpoint."
); } while (0)
;
3697 }
3698 }
3699 }
3700 return m_thread_create_bp_sp.get() != nullptr;
3701}
3702
3703bool ProcessGDBRemote::StopNoticingNewThreads() {
3704 Log *log = GetLog(LLDBLog::Step);
3705 if (log && log->GetVerbose())
3706 LLDB_LOGF(log, "Disabling new thread notification breakpoint.")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("Disabling new thread notification breakpoint."
); } while (0)
;
3707
3708 if (m_thread_create_bp_sp)
3709 m_thread_create_bp_sp->SetEnabled(false);
3710
3711 return true;
3712}
3713
3714DynamicLoader *ProcessGDBRemote::GetDynamicLoader() {
3715 if (m_dyld_up.get() == nullptr)
3716 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3717 return m_dyld_up.get();
3718}
3719
3720Status ProcessGDBRemote::SendEventData(const char *data) {
3721 int return_value;
3722 bool was_supported;
3723
3724 Status error;
3725
3726 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3727 if (return_value != 0) {
3728 if (!was_supported)
3729 error.SetErrorString("Sending events is not supported for this process.");
3730 else
3731 error.SetErrorStringWithFormat("Error sending event data: %d.",
3732 return_value);
3733 }
3734 return error;
3735}
3736
3737DataExtractor ProcessGDBRemote::GetAuxvData() {
3738 DataBufferSP buf;
3739 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
3740 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3741 if (response)
3742 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3743 response->length());
3744 else
3745 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}")do { ::lldb_private::Log *log_private = (GetLog(GDBRLog::Process
)); ::llvm::Error error_private = (response.takeError()); if (
log_private && error_private) { log_private->FormatError
(::std::move(error_private), "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "{0}"); } else ::llvm::consumeError(::std::move(error_private
)); } while (0)
;
3746 }
3747 return DataExtractor(buf, GetByteOrder(), GetAddressByteSize());
3748}
3749
3750StructuredData::ObjectSP
3751ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) {
3752 StructuredData::ObjectSP object_sp;
3753
3754 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
3755 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3756 SystemRuntime *runtime = GetSystemRuntime();
3757 if (runtime) {
3758 runtime->AddThreadExtendedInfoPacketHints(args_dict);
3759 }
3760 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3761
3762 StreamString packet;
3763 packet << "jThreadExtendedInfo:";
3764 args_dict->Dump(packet, false);
3765
3766 // FIXME the final character of a JSON dictionary, '}', is the escape
3767 // character in gdb-remote binary mode. lldb currently doesn't escape
3768 // these characters in its packet output -- so we add the quoted version of
3769 // the } character here manually in case we talk to a debugserver which un-
3770 // escapes the characters at packet read time.
3771 packet << (char)(0x7d ^ 0x20);
3772
3773 StringExtractorGDBRemote response;
3774 response.SetResponseValidatorToJSON();
3775 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3776 GDBRemoteCommunication::PacketResult::Success) {
3777 StringExtractorGDBRemote::ResponseType response_type =
3778 response.GetResponseType();
3779 if (response_type == StringExtractorGDBRemote::eResponse) {
3780 if (!response.Empty()) {
3781 object_sp =
3782 StructuredData::ParseJSON(std::string(response.GetStringRef()));
3783 }
3784 }
3785 }
3786 }
3787 return object_sp;
3788}
3789
3790StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3791 lldb::addr_t image_list_address, lldb::addr_t image_count) {
3792
3793 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3794 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3795 image_list_address);
3796 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3797
3798 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3799}
3800
3801StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3802 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3803
3804 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3805
3806 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3807}
3808
3809StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3810 const std::vector<lldb::addr_t> &load_addresses) {
3811 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3812 StructuredData::ArraySP addresses(new StructuredData::Array);
3813
3814 for (auto addr : load_addresses) {
3815 StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr));
3816 addresses->AddItem(addr_sp);
3817 }
3818
3819 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3820
3821 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3822}
3823
3824StructuredData::ObjectSP
3825ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
3826 StructuredData::ObjectSP args_dict) {
3827 StructuredData::ObjectSP object_sp;
3828
3829 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
3830 // Scope for the scoped timeout object
3831 GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm,
3832 std::chrono::seconds(10));
3833
3834 StreamString packet;
3835 packet << "jGetLoadedDynamicLibrariesInfos:";
3836 args_dict->Dump(packet, false);
3837
3838 // FIXME the final character of a JSON dictionary, '}', is the escape
3839 // character in gdb-remote binary mode. lldb currently doesn't escape
3840 // these characters in its packet output -- so we add the quoted version of
3841 // the } character here manually in case we talk to a debugserver which un-
3842 // escapes the characters at packet read time.
3843 packet << (char)(0x7d ^ 0x20);
3844
3845 StringExtractorGDBRemote response;
3846 response.SetResponseValidatorToJSON();
3847 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3848 GDBRemoteCommunication::PacketResult::Success) {
3849 StringExtractorGDBRemote::ResponseType response_type =
3850 response.GetResponseType();
3851 if (response_type == StringExtractorGDBRemote::eResponse) {
3852 if (!response.Empty()) {
3853 object_sp =
3854 StructuredData::ParseJSON(std::string(response.GetStringRef()));
3855 }
3856 }
3857 }
3858 }
3859 return object_sp;
3860}
3861
3862StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() {
3863 StructuredData::ObjectSP object_sp;
3864 StructuredData::ObjectSP args_dict(new StructuredData::Dictionary());
3865
3866 if (m_gdb_comm.GetSharedCacheInfoSupported()) {
3867 StreamString packet;
3868 packet << "jGetSharedCacheInfo:";
3869 args_dict->Dump(packet, false);
3870
3871 // FIXME the final character of a JSON dictionary, '}', is the escape
3872 // character in gdb-remote binary mode. lldb currently doesn't escape
3873 // these characters in its packet output -- so we add the quoted version of
3874 // the } character here manually in case we talk to a debugserver which un-
3875 // escapes the characters at packet read time.
3876 packet << (char)(0x7d ^ 0x20);
3877
3878 StringExtractorGDBRemote response;
3879 response.SetResponseValidatorToJSON();
3880 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3881 GDBRemoteCommunication::PacketResult::Success) {
3882 StringExtractorGDBRemote::ResponseType response_type =
3883 response.GetResponseType();
3884 if (response_type == StringExtractorGDBRemote::eResponse) {
3885 if (!response.Empty()) {
3886 object_sp =
3887 StructuredData::ParseJSON(std::string(response.GetStringRef()));
3888 }
3889 }
3890 }
3891 }
3892 return object_sp;
3893}
3894
3895Status ProcessGDBRemote::ConfigureStructuredData(
3896 ConstString type_name, const StructuredData::ObjectSP &config_sp) {
3897 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3898}
3899
3900// Establish the largest memory read/write payloads we should use. If the
3901// remote stub has a max packet size, stay under that size.
3902//
3903// If the remote stub's max packet size is crazy large, use a reasonable
3904// largeish default.
3905//
3906// If the remote stub doesn't advertise a max packet size, use a conservative
3907// default.
3908
3909void ProcessGDBRemote::GetMaxMemorySize() {
3910 const uint64_t reasonable_largeish_default = 128 * 1024;
3911 const uint64_t conservative_default = 512;
3912
3913 if (m_max_memory_size == 0) {
3914 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3915 if (stub_max_size != UINT64_MAX(18446744073709551615UL) && stub_max_size != 0) {
3916 // Save the stub's claimed maximum packet size
3917 m_remote_stub_max_memory_size = stub_max_size;
3918
3919 // Even if the stub says it can support ginormous packets, don't exceed
3920 // our reasonable largeish default packet size.
3921 if (stub_max_size > reasonable_largeish_default) {
3922 stub_max_size = reasonable_largeish_default;
3923 }
3924
3925 // Memory packet have other overheads too like Maddr,size:#NN Instead of
3926 // calculating the bytes taken by size and addr every time, we take a
3927 // maximum guess here.
3928 if (stub_max_size > 70)
3929 stub_max_size -= 32 + 32 + 6;
3930 else {
3931 // In unlikely scenario that max packet size is less then 70, we will
3932 // hope that data being written is small enough to fit.
3933 Log *log(GetLog(GDBRLog::Comm | GDBRLog::Memory));
3934 if (log)
3935 log->Warning("Packet size is too small. "
3936 "LLDB may face problems while writing memory");
3937 }
3938
3939 m_max_memory_size = stub_max_size;
3940 } else {
3941 m_max_memory_size = conservative_default;
3942 }
3943 }
3944}
3945
3946void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
3947 uint64_t user_specified_max) {
3948 if (user_specified_max != 0) {
3949 GetMaxMemorySize();
3950
3951 if (m_remote_stub_max_memory_size != 0) {
3952 if (m_remote_stub_max_memory_size < user_specified_max) {
3953 m_max_memory_size = m_remote_stub_max_memory_size; // user specified a
3954 // packet size too
3955 // big, go as big
3956 // as the remote stub says we can go.
3957 } else {
3958 m_max_memory_size = user_specified_max; // user's packet size is good
3959 }
3960 } else {
3961 m_max_memory_size =
3962 user_specified_max; // user's packet size is probably fine
3963 }
3964 }
3965}
3966
3967bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
3968 const ArchSpec &arch,
3969 ModuleSpec &module_spec) {
3970 Log *log = GetLog(LLDBLog::Platform);
3971
3972 const ModuleCacheKey key(module_file_spec.GetPath(),
3973 arch.GetTriple().getTriple());
3974 auto cached = m_cached_module_specs.find(key);
3975 if (cached != m_cached_module_specs.end()) {
3976 module_spec = cached->second;
3977 return bool(module_spec);
3978 }
3979
3980 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
3981 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s"
, __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple
().getTriple().c_str()); } while (0)
3982 __FUNCTION__, module_file_spec.GetPath().c_str(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s"
, __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple
().getTriple().c_str()); } while (0)
3983 arch.GetTriple().getTriple().c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s - failed to get module info for %s:%s"
, __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple
().getTriple().c_str()); } while (0)
;
3984 return false;
3985 }
3986
3987 if (log) {
3988 StreamString stream;
3989 module_spec.Dump(stream);
3990 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s"
, __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple
().getTriple().c_str(), stream.GetData()); } while (0)
3991 __FUNCTION__, module_file_spec.GetPath().c_str(),do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s"
, __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple
().getTriple().c_str(), stream.GetData()); } while (0)
3992 arch.GetTriple().getTriple().c_str(), stream.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s - got module info for (%s:%s) : %s"
, __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple
().getTriple().c_str(), stream.GetData()); } while (0)
;
3993 }
3994
3995 m_cached_module_specs[key] = module_spec;
3996 return true;
3997}
3998
3999void ProcessGDBRemote::PrefetchModuleSpecs(
4000 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4001 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4002 if (module_specs) {
4003 for (const FileSpec &spec : module_file_specs)
4004 m_cached_module_specs[ModuleCacheKey(spec.GetPath(),
4005 triple.getTriple())] = ModuleSpec();
4006 for (const ModuleSpec &spec : *module_specs)
4007 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4008 triple.getTriple())] = spec;
4009 }
4010}
4011
4012llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() {
4013 return m_gdb_comm.GetOSVersion();
4014}
4015
4016llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() {
4017 return m_gdb_comm.GetMacCatalystVersion();
4018}
4019
4020namespace {
4021
4022typedef std::vector<std::string> stringVec;
4023
4024typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4025struct RegisterSetInfo {
4026 ConstString name;
4027};
4028
4029typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4030
4031struct GdbServerTargetInfo {
4032 std::string arch;
4033 std::string osabi;
4034 stringVec includes;
4035 RegisterSetMap reg_set_map;
4036};
4037
4038bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info,
4039 std::vector<DynamicRegisterInfo::Register> &registers) {
4040 if (!feature_node)
4041 return false;
4042
4043 feature_node.ForEachChildElementWithName(
4044 "reg", [&target_info, &registers](const XMLNode &reg_node) -> bool {
4045 std::string gdb_group;
4046 std::string gdb_type;
4047 DynamicRegisterInfo::Register reg_info;
4048 bool encoding_set = false;
4049 bool format_set = false;
4050
4051 // FIXME: we're silently ignoring invalid data here
4052 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4053 &encoding_set, &format_set, &reg_info](
4054 const llvm::StringRef &name,
4055 const llvm::StringRef &value) -> bool {
4056 if (name == "name") {
4057 reg_info.name.SetString(value);
4058 } else if (name == "bitsize") {
4059 if (llvm::to_integer(value, reg_info.byte_size))
4060 reg_info.byte_size =
4061 llvm::divideCeil(reg_info.byte_size, CHAR_BIT8);
4062 } else if (name == "type") {
4063 gdb_type = value.str();
4064 } else if (name == "group") {
4065 gdb_group = value.str();
4066 } else if (name == "regnum") {
4067 llvm::to_integer(value, reg_info.regnum_remote);
4068 } else if (name == "offset") {
4069 llvm::to_integer(value, reg_info.byte_offset);
4070 } else if (name == "altname") {
4071 reg_info.alt_name.SetString(value);
4072 } else if (name == "encoding") {
4073 encoding_set = true;
4074 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4075 } else if (name == "format") {
4076 format_set = true;
4077 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4078 nullptr)
4079 .Success())
4080 reg_info.format =
4081 llvm::StringSwitch<lldb::Format>(value)
4082 .Case("vector-sint8", eFormatVectorOfSInt8)
4083 .Case("vector-uint8", eFormatVectorOfUInt8)
4084 .Case("vector-sint16", eFormatVectorOfSInt16)
4085 .Case("vector-uint16", eFormatVectorOfUInt16)
4086 .Case("vector-sint32", eFormatVectorOfSInt32)
4087 .Case("vector-uint32", eFormatVectorOfUInt32)
4088 .Case("vector-float32", eFormatVectorOfFloat32)
4089 .Case("vector-uint64", eFormatVectorOfUInt64)
4090 .Case("vector-uint128", eFormatVectorOfUInt128)
4091 .Default(eFormatInvalid);
4092 } else if (name == "group_id") {
4093 uint32_t set_id = UINT32_MAX(4294967295U);
4094 llvm::to_integer(value, set_id);
4095 RegisterSetMap::const_iterator pos =
4096 target_info.reg_set_map.find(set_id);
4097 if (pos != target_info.reg_set_map.end())
4098 reg_info.set_name = pos->second.name;
4099 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4100 llvm::to_integer(value, reg_info.regnum_ehframe);
4101 } else if (name == "dwarf_regnum") {
4102 llvm::to_integer(value, reg_info.regnum_dwarf);
4103 } else if (name == "generic") {
4104 reg_info.regnum_generic = Args::StringToGenericRegister(value);
4105 } else if (name == "value_regnums") {
4106 SplitCommaSeparatedRegisterNumberString(value, reg_info.value_regs,
4107 0);
4108 } else if (name == "invalidate_regnums") {
4109 SplitCommaSeparatedRegisterNumberString(
4110 value, reg_info.invalidate_regs, 0);
4111 } else {
4112 Log *log(GetLog(GDBRLog::Process));
4113 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s unhandled reg attribute %s = %s"
, __FUNCTION__, name.data(), value.data()); } while (0)
4114 "ProcessGDBRemote::%s unhandled reg attribute %s = %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s unhandled reg attribute %s = %s"
, __FUNCTION__, name.data(), value.data()); } while (0)
4115 __FUNCTION__, name.data(), value.data())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s unhandled reg attribute %s = %s"
, __FUNCTION__, name.data(), value.data()); } while (0)
;
4116 }
4117 return true; // Keep iterating through all attributes
4118 });
4119
4120 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4121 if (llvm::StringRef(gdb_type).startswith("int")) {
4122 reg_info.format = eFormatHex;
4123 reg_info.encoding = eEncodingUint;
4124 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4125 reg_info.format = eFormatAddressInfo;
4126 reg_info.encoding = eEncodingUint;
4127 } else if (gdb_type == "float") {
4128 reg_info.format = eFormatFloat;
4129 reg_info.encoding = eEncodingIEEE754;
4130 } else if (gdb_type == "aarch64v" ||
4131 llvm::StringRef(gdb_type).startswith("vec") ||
4132 gdb_type == "i387_ext" || gdb_type == "uint128") {
4133 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so treat
4134 // them as vector (similarly to xmm/ymm)
4135 reg_info.format = eFormatVectorOfUInt8;
4136 reg_info.encoding = eEncodingVector;
4137 }
4138 }
4139
4140 // Only update the register set name if we didn't get a "reg_set"
4141 // attribute. "set_name" will be empty if we didn't have a "reg_set"
4142 // attribute.
4143 if (!reg_info.set_name) {
4144 if (!gdb_group.empty()) {
4145 reg_info.set_name.SetCString(gdb_group.c_str());
4146 } else {
4147 // If no register group name provided anywhere,
4148 // we'll create a 'general' register set
4149 reg_info.set_name.SetCString("general");
4150 }
4151 }
4152
4153 if (reg_info.byte_size == 0) {
4154 Log *log(GetLog(GDBRLog::Process));
4155 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s Skipping zero bitsize register %s"
, __FUNCTION__, reg_info.name.AsCString()); } while (0)
4156 "ProcessGDBRemote::%s Skipping zero bitsize register %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s Skipping zero bitsize register %s"
, __FUNCTION__, reg_info.name.AsCString()); } while (0)
4157 __FUNCTION__, reg_info.name.AsCString())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s Skipping zero bitsize register %s"
, __FUNCTION__, reg_info.name.AsCString()); } while (0)
;
4158 } else
4159 registers.push_back(reg_info);
4160
4161 return true; // Keep iterating through all "reg" elements
4162 });
4163 return true;
4164}
4165
4166} // namespace
4167
4168// This method fetches a register description feature xml file from
4169// the remote stub and adds registers/register groupsets/architecture
4170// information to the current process. It will call itself recursively
4171// for nested register definition files. It returns true if it was able
4172// to fetch and parse an xml file.
4173bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4174 ArchSpec &arch_to_use, std::string xml_filename,
4175 std::vector<DynamicRegisterInfo::Register> &registers) {
4176 // request the target xml file
4177 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4178 if (errorToBool(raw.takeError()))
4179 return false;
4180
4181 XMLDocument xml_document;
4182
4183 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4184 xml_filename.c_str())) {
4185 GdbServerTargetInfo target_info;
4186 std::vector<XMLNode> feature_nodes;
4187
4188 // The top level feature XML file will start with a <target> tag.
4189 XMLNode target_node = xml_document.GetRootElement("target");
4190 if (target_node) {
4191 target_node.ForEachChildElement([&target_info, &feature_nodes](
4192 const XMLNode &node) -> bool {
4193 llvm::StringRef name = node.GetName();
4194 if (name == "architecture") {
4195 node.GetElementText(target_info.arch);
4196 } else if (name == "osabi") {
4197 node.GetElementText(target_info.osabi);
4198 } else if (name == "xi:include" || name == "include") {
4199 std::string href = node.GetAttributeValue("href");
4200 if (!href.empty())
4201 target_info.includes.push_back(href);
4202 } else if (name == "feature") {
4203 feature_nodes.push_back(node);
4204 } else if (name == "groups") {
4205 node.ForEachChildElementWithName(
4206 "group", [&target_info](const XMLNode &node) -> bool {
4207 uint32_t set_id = UINT32_MAX(4294967295U);
4208 RegisterSetInfo set_info;
4209
4210 node.ForEachAttribute(
4211 [&set_id, &set_info](const llvm::StringRef &name,
4212 const llvm::StringRef &value) -> bool {
4213 // FIXME: we're silently ignoring invalid data here
4214 if (name == "id")
4215 llvm::to_integer(value, set_id);
4216 if (name == "name")
4217 set_info.name = ConstString(value);
4218 return true; // Keep iterating through all attributes
4219 });
4220
4221 if (set_id != UINT32_MAX(4294967295U))
4222 target_info.reg_set_map[set_id] = set_info;
4223 return true; // Keep iterating through all "group" elements
4224 });
4225 }
4226 return true; // Keep iterating through all children of the target_node
4227 });
4228 } else {
4229 // In an included XML feature file, we're already "inside" the <target>
4230 // tag of the initial XML file; this included file will likely only have
4231 // a <feature> tag. Need to check for any more included files in this
4232 // <feature> element.
4233 XMLNode feature_node = xml_document.GetRootElement("feature");
4234 if (feature_node) {
4235 feature_nodes.push_back(feature_node);
4236 feature_node.ForEachChildElement([&target_info](
4237 const XMLNode &node) -> bool {
4238 llvm::StringRef name = node.GetName();
4239 if (name == "xi:include" || name == "include") {
4240 std::string href = node.GetAttributeValue("href");
4241 if (!href.empty())
4242 target_info.includes.push_back(href);
4243 }
4244 return true;
4245 });
4246 }
4247 }
4248
4249 // gdbserver does not implement the LLDB packets used to determine host
4250 // or process architecture. If that is the case, attempt to use
4251 // the <architecture/> field from target.xml, e.g.:
4252 //
4253 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4254 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
4255 // arm board)
4256 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4257 // We don't have any information about vendor or OS.
4258 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4259 .Case("i386:x86-64", "x86_64")
4260 .Default(target_info.arch) +
4261 "--");
4262
4263 if (arch_to_use.IsValid())
4264 GetTarget().MergeArchitecture(arch_to_use);
4265 }
4266
4267 if (arch_to_use.IsValid()) {
4268 for (auto &feature_node : feature_nodes) {
4269 ParseRegisters(feature_node, target_info,
4270 registers);
4271 }
4272
4273 for (const auto &include : target_info.includes) {
4274 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4275 registers);
4276 }
4277 }
4278 } else {
4279 return false;
4280 }
4281 return true;
4282}
4283
4284void ProcessGDBRemote::AddRemoteRegisters(
4285 std::vector<DynamicRegisterInfo::Register> &registers,
4286 const ArchSpec &arch_to_use) {
4287 std::map<uint32_t, uint32_t> remote_to_local_map;
4288 uint32_t remote_regnum = 0;
4289 for (auto it : llvm::enumerate(registers)) {
4290 DynamicRegisterInfo::Register &remote_reg_info = it.value();
4291
4292 // Assign successive remote regnums if missing.
4293 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM(4294967295U))
4294 remote_reg_info.regnum_remote = remote_regnum;
4295
4296 // Create a mapping from remote to local regnos.
4297 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4298
4299 remote_regnum = remote_reg_info.regnum_remote + 1;
4300 }
4301
4302 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4303 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4304 auto lldb_regit = remote_to_local_map.find(process_regnum);
4305 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4306 : LLDB_INVALID_REGNUM(4294967295U);
4307 };
4308
4309 llvm::transform(remote_reg_info.value_regs,
4310 remote_reg_info.value_regs.begin(), proc_to_lldb);
4311 llvm::transform(remote_reg_info.invalidate_regs,
4312 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4313 }
4314
4315 // Don't use Process::GetABI, this code gets called from DidAttach, and
4316 // in that context we haven't set the Target's architecture yet, so the
4317 // ABI is also potentially incorrect.
4318 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4319 abi_sp->AugmentRegisterInfo(registers);
4320
4321 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4322}
4323
4324// query the target of gdb-remote for extended target information returns
4325// true on success (got register definitions), false on failure (did not).
4326bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec &arch_to_use) {
4327 // Make sure LLDB has an XML parser it can use first
4328 if (!XMLDocument::XMLEnabled())
4329 return false;
4330
4331 // check that we have extended feature read support
4332 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
4333 return false;
4334
4335 std::vector<DynamicRegisterInfo::Register> registers;
4336 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4337 registers))
4338 AddRemoteRegisters(registers, arch_to_use);
4339
4340 return m_register_info_sp->GetNumRegisters() > 0;
4341}
4342
4343llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4344 // Make sure LLDB has an XML parser it can use first
4345 if (!XMLDocument::XMLEnabled())
4346 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4347 "XML parsing not available");
4348
4349 Log *log = GetLog(LLDBLog::Process);
4350 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s", __FUNCTION__
); } while (0)
;
4351
4352 LoadedModuleInfoList list;
4353 GDBRemoteCommunicationClient &comm = m_gdb_comm;
4354 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
4355
4356 // check that we have extended feature read support
4357 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4358 // request the loaded library list
4359 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4360 if (!raw)
4361 return raw.takeError();
4362
4363 // parse the xml file in memory
4364 LLDB_LOGF(log, "parsing: %s", raw->c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("parsing: %s", raw->c_str()); } while
(0)
;
4365 XMLDocument doc;
4366
4367 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4368 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4369 "Error reading noname.xml");
4370
4371 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4372 if (!root_element)
4373 return llvm::createStringError(
4374 llvm::inconvertibleErrorCode(),
4375 "Error finding library-list-svr4 xml element");
4376
4377 // main link map structure
4378 std::string main_lm = root_element.GetAttributeValue("main-lm");
4379 // FIXME: we're silently ignoring invalid data here
4380 if (!main_lm.empty())
4381 llvm::to_integer(main_lm, list.m_link_map);
4382
4383 root_element.ForEachChildElementWithName(
4384 "library", [log, &list](const XMLNode &library) -> bool {
4385 LoadedModuleInfoList::LoadedModuleInfo module;
4386
4387 // FIXME: we're silently ignoring invalid data here
4388 library.ForEachAttribute(
4389 [&module](const llvm::StringRef &name,
4390 const llvm::StringRef &value) -> bool {
4391 uint64_t uint_value = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4392 if (name == "name")
4393 module.set_name(value.str());
4394 else if (name == "lm") {
4395 // the address of the link_map struct.
4396 llvm::to_integer(value, uint_value);
4397 module.set_link_map(uint_value);
4398 } else if (name == "l_addr") {
4399 // the displacement as read from the field 'l_addr' of the
4400 // link_map struct.
4401 llvm::to_integer(value, uint_value);
4402 module.set_base(uint_value);
4403 // base address is always a displacement, not an absolute
4404 // value.
4405 module.set_base_is_offset(true);
4406 } else if (name == "l_ld") {
4407 // the memory address of the libraries PT_DYNAMIC section.
4408 llvm::to_integer(value, uint_value);
4409 module.set_dynamic(uint_value);
4410 }
4411
4412 return true; // Keep iterating over all properties of "library"
4413 });
4414
4415 if (log) {
4416 std::string name;
4417 lldb::addr_t lm = 0, base = 0, ld = 0;
4418 bool base_is_offset;
4419
4420 module.get_name(name);
4421 module.get_link_map(lm);
4422 module.get_base(base);
4423 module.get_base_is_offset(base_is_offset);
4424 module.get_dynamic(ld);
4425
4426 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found (link_map:0x%08" "l" "x" ", base:0x%08"
"l" "x" "[%s], ld:0x%08" "l" "x" ", name:'%s')", lm, base, (
base_is_offset ? "offset" : "absolute"), ld, name.c_str()); }
while (0)
4427 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found (link_map:0x%08" "l" "x" ", base:0x%08"
"l" "x" "[%s], ld:0x%08" "l" "x" ", name:'%s')", lm, base, (
base_is_offset ? "offset" : "absolute"), ld, name.c_str()); }
while (0)
4428 "[%s], ld:0x%08" PRIx64 ", name:'%s')",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found (link_map:0x%08" "l" "x" ", base:0x%08"
"l" "x" "[%s], ld:0x%08" "l" "x" ", name:'%s')", lm, base, (
base_is_offset ? "offset" : "absolute"), ld, name.c_str()); }
while (0)
4429 lm, base, (base_is_offset ? "offset" : "absolute"), ld,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found (link_map:0x%08" "l" "x" ", base:0x%08"
"l" "x" "[%s], ld:0x%08" "l" "x" ", name:'%s')", lm, base, (
base_is_offset ? "offset" : "absolute"), ld, name.c_str()); }
while (0)
4430 name.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found (link_map:0x%08" "l" "x" ", base:0x%08"
"l" "x" "[%s], ld:0x%08" "l" "x" ", name:'%s')", lm, base, (
base_is_offset ? "offset" : "absolute"), ld, name.c_str()); }
while (0)
;
4431 }
4432
4433 list.add(module);
4434 return true; // Keep iterating over all "library" elements in the root
4435 // node
4436 });
4437
4438 if (log)
4439 LLDB_LOGF(log, "found %" PRId32 " modules in total",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found %" "d" " modules in total", (
int)list.m_list.size()); } while (0)
4440 (int)list.m_list.size())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found %" "d" " modules in total", (
int)list.m_list.size()); } while (0)
;
4441 return list;
4442 } else if (comm.GetQXferLibrariesReadSupported()) {
4443 // request the loaded library list
4444 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
4445
4446 if (!raw)
4447 return raw.takeError();
4448
4449 LLDB_LOGF(log, "parsing: %s", raw->c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("parsing: %s", raw->c_str()); } while
(0)
;
4450 XMLDocument doc;
4451
4452 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4453 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4454 "Error reading noname.xml");
4455
4456 XMLNode root_element = doc.GetRootElement("library-list");
4457 if (!root_element)
4458 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4459 "Error finding library-list xml element");
4460
4461 // FIXME: we're silently ignoring invalid data here
4462 root_element.ForEachChildElementWithName(
4463 "library", [log, &list](const XMLNode &library) -> bool {
4464 LoadedModuleInfoList::LoadedModuleInfo module;
4465
4466 std::string name = library.GetAttributeValue("name");
4467 module.set_name(name);
4468
4469 // The base address of a given library will be the address of its
4470 // first section. Most remotes send only one section for Windows
4471 // targets for example.
4472 const XMLNode &section =
4473 library.FindFirstChildElementWithName("section");
4474 std::string address = section.GetAttributeValue("address");
4475 uint64_t address_value = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4476 llvm::to_integer(address, address_value);
4477 module.set_base(address_value);
4478 // These addresses are absolute values.
4479 module.set_base_is_offset(false);
4480
4481 if (log) {
4482 std::string name;
4483 lldb::addr_t base = 0;
4484 bool base_is_offset;
4485 module.get_name(name);
4486 module.get_base(base);
4487 module.get_base_is_offset(base_is_offset);
4488
4489 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found (base:0x%08" "l" "x" "[%s], name:'%s')"
, base, (base_is_offset ? "offset" : "absolute"), name.c_str(
)); } while (0)
4490 (base_is_offset ? "offset" : "absolute"), name.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found (base:0x%08" "l" "x" "[%s], name:'%s')"
, base, (base_is_offset ? "offset" : "absolute"), name.c_str(
)); } while (0)
;
4491 }
4492
4493 list.add(module);
4494 return true; // Keep iterating over all "library" elements in the root
4495 // node
4496 });
4497
4498 if (log)
4499 LLDB_LOGF(log, "found %" PRId32 " modules in total",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found %" "d" " modules in total", (
int)list.m_list.size()); } while (0)
4500 (int)list.m_list.size())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("found %" "d" " modules in total", (
int)list.m_list.size()); } while (0)
;
4501 return list;
4502 } else {
4503 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4504 "Remote libraries not supported");
4505 }
4506}
4507
4508lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file,
4509 lldb::addr_t link_map,
4510 lldb::addr_t base_addr,
4511 bool value_is_offset) {
4512 DynamicLoader *loader = GetDynamicLoader();
4513 if (!loader)
4514 return nullptr;
4515
4516 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4517 value_is_offset);
4518}
4519
4520llvm::Error ProcessGDBRemote::LoadModules() {
4521 using lldb_private::process_gdb_remote::ProcessGDBRemote;
4522
4523 // request a list of loaded libraries from GDBServer
4524 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4525 if (!module_list)
4526 return module_list.takeError();
4527
4528 // get a list of all the modules
4529 ModuleList new_modules;
4530
4531 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4532 std::string mod_name;
4533 lldb::addr_t mod_base;
4534 lldb::addr_t link_map;
4535 bool mod_base_is_offset;
4536
4537 bool valid = true;
4538 valid &= modInfo.get_name(mod_name);
4539 valid &= modInfo.get_base(mod_base);
4540 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4541 if (!valid)
4542 continue;
4543
4544 if (!modInfo.get_link_map(link_map))
4545 link_map = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4546
4547 FileSpec file(mod_name);
4548 FileSystem::Instance().Resolve(file);
4549 lldb::ModuleSP module_sp =
4550 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4551
4552 if (module_sp.get())
4553 new_modules.Append(module_sp);
4554 }
4555
4556 if (new_modules.GetSize() > 0) {
4557 ModuleList removed_modules;
4558 Target &target = GetTarget();
4559 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4560
4561 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4562 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4563
4564 bool found = false;
4565 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4566 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4567 found = true;
4568 }
4569
4570 // The main executable will never be included in libraries-svr4, don't
4571 // remove it
4572 if (!found &&
4573 loaded_module.get() != target.GetExecutableModulePointer()) {
4574 removed_modules.Append(loaded_module);
4575 }
4576 }
4577
4578 loaded_modules.Remove(removed_modules);
4579 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4580
4581 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4582 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4583 if (!obj)
4584 return true;
4585
4586 if (obj->GetType() != ObjectFile::Type::eTypeExecutable)
4587 return true;
4588
4589 lldb::ModuleSP module_copy_sp = module_sp;
4590 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4591 return false;
4592 });
4593
4594 loaded_modules.AppendIfNeeded(new_modules);
4595 m_process->GetTarget().ModulesDidLoad(new_modules);
4596 }
4597
4598 return llvm::ErrorSuccess();
4599}
4600
4601Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file,
4602 bool &is_loaded,
4603 lldb::addr_t &load_addr) {
4604 is_loaded = false;
4605 load_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4606
4607 std::string file_path = file.GetPath(false);
4608 if (file_path.empty())
4609 return Status("Empty file name specified");
4610
4611 StreamString packet;
4612 packet.PutCString("qFileLoadAddress:");
4613 packet.PutStringAsRawHex8(file_path);
4614
4615 StringExtractorGDBRemote response;
4616 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
4617 GDBRemoteCommunication::PacketResult::Success)
4618 return Status("Sending qFileLoadAddress packet failed");
4619
4620 if (response.IsErrorResponse()) {
4621 if (response.GetError() == 1) {
4622 // The file is not loaded into the inferior
4623 is_loaded = false;
4624 load_addr = LLDB_INVALID_ADDRESS(18446744073709551615UL);
4625 return Status();
4626 }
4627
4628 return Status(
4629 "Fetching file load address from remote server returned an error");
4630 }
4631
4632 if (response.IsNormalResponse()) {
4633 is_loaded = true;
4634 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS(18446744073709551615UL));
4635 return Status();
4636 }
4637
4638 return Status(
4639 "Unknown error happened during sending the load address packet");
4640}
4641
4642void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) {
4643 // We must call the lldb_private::Process::ModulesDidLoad () first before we
4644 // do anything
4645 Process::ModulesDidLoad(module_list);
4646
4647 // After loading shared libraries, we can ask our remote GDB server if it
4648 // needs any symbols.
4649 m_gdb_comm.ServeSymbolLookups(this);
4650}
4651
4652void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
4653 AppendSTDOUT(out.data(), out.size());
4654}
4655
4656static const char *end_delimiter = "--end--;";
4657static const int end_delimiter_len = 8;
4658
4659void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
4660 std::string input = data.str(); // '1' to move beyond 'A'
4661 if (m_partial_profile_data.length() > 0) {
4662 m_partial_profile_data.append(input);
4663 input = m_partial_profile_data;
4664 m_partial_profile_data.clear();
4665 }
4666
4667 size_t found, pos = 0, len = input.length();
4668 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
4669 StringExtractorGDBRemote profileDataExtractor(
4670 input.substr(pos, found).c_str());
4671 std::string profile_data =
4672 HarmonizeThreadIdsForProfileData(profileDataExtractor);
4673 BroadcastAsyncProfileData(profile_data);
4674
4675 pos = found + end_delimiter_len;
4676 }
4677
4678 if (pos < len) {
4679 // Last incomplete chunk.
4680 m_partial_profile_data = input.substr(pos);
4681 }
4682}
4683
4684std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
4685 StringExtractorGDBRemote &profileDataExtractor) {
4686 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
4687 std::string output;
4688 llvm::raw_string_ostream output_stream(output);
4689 llvm::StringRef name, value;
4690
4691 // Going to assuming thread_used_usec comes first, else bail out.
4692 while (profileDataExtractor.GetNameColonValue(name, value)) {
4693 if (name.compare("thread_used_id") == 0) {
4694 StringExtractor threadIDHexExtractor(value);
4695 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
4696
4697 bool has_used_usec = false;
4698 uint32_t curr_used_usec = 0;
4699 llvm::StringRef usec_name, usec_value;
4700 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
4701 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
4702 if (usec_name.equals("thread_used_usec")) {
4703 has_used_usec = true;
4704 usec_value.getAsInteger(0, curr_used_usec);
4705 } else {
4706 // We didn't find what we want, it is probably an older version. Bail
4707 // out.
4708 profileDataExtractor.SetFilePos(input_file_pos);
4709 }
4710 }
4711
4712 if (has_used_usec) {
4713 uint32_t prev_used_usec = 0;
4714 std::map<uint64_t, uint32_t>::iterator iterator =
4715 m_thread_id_to_used_usec_map.find(thread_id);
4716 if (iterator != m_thread_id_to_used_usec_map.end()) {
4717 prev_used_usec = m_thread_id_to_used_usec_map[thread_id];
4718 }
4719
4720 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
4721 // A good first time record is one that runs for at least 0.25 sec
4722 bool good_first_time =
4723 (prev_used_usec == 0) && (real_used_usec > 250000);
4724 bool good_subsequent_time =
4725 (prev_used_usec > 0) &&
4726 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
4727
4728 if (good_first_time || good_subsequent_time) {
4729 // We try to avoid doing too many index id reservation, resulting in
4730 // fast increase of index ids.
4731
4732 output_stream << name << ":";
4733 int32_t index_id = AssignIndexIDToThread(thread_id);
4734 output_stream << index_id << ";";
4735
4736 output_stream << usec_name << ":" << usec_value << ";";
4737 } else {
4738 // Skip past 'thread_used_name'.
4739 llvm::StringRef local_name, local_value;
4740 profileDataExtractor.GetNameColonValue(local_name, local_value);
4741 }
4742
4743 // Store current time as previous time so that they can be compared
4744 // later.
4745 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
4746 } else {
4747 // Bail out and use old string.
4748 output_stream << name << ":" << value << ";";
4749 }
4750 } else {
4751 output_stream << name << ":" << value << ";";
4752 }
4753 }
4754 output_stream << end_delimiter;
4755 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
4756
4757 return output_stream.str();
4758}
4759
4760void ProcessGDBRemote::HandleStopReply() {
4761 if (GetStopID() != 0)
4762 return;
4763
4764 if (GetID() == LLDB_INVALID_PROCESS_ID0) {
4765 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
4766 if (pid != LLDB_INVALID_PROCESS_ID0)
4767 SetID(pid);
4768 }
4769 BuildDynamicRegisterInfo(true);
4770}
4771
4772llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
4773 if (!m_gdb_comm.GetSaveCoreSupported())
4774 return false;
4775
4776 StreamString packet;
4777 packet.PutCString("qSaveCore;path-hint:");
4778 packet.PutStringAsRawHex8(outfile);
4779
4780 StringExtractorGDBRemote response;
4781 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4782 GDBRemoteCommunication::PacketResult::Success) {
4783 // TODO: grab error message from the packet? StringExtractor seems to
4784 // be missing a method for that
4785 if (response.IsErrorResponse())
4786 return llvm::createStringError(
4787 llvm::inconvertibleErrorCode(),
4788 llvm::formatv("qSaveCore returned an error"));
4789
4790 std::string path;
4791
4792 // process the response
4793 for (auto x : llvm::split(response.GetStringRef(), ';')) {
4794 if (x.consume_front("core-path:"))
4795 StringExtractor(x).GetHexByteString(path);
4796 }
4797
4798 // verify that we've gotten what we need
4799 if (path.empty())
4800 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4801 "qSaveCore returned no core path");
4802
4803 // now transfer the core file
4804 FileSpec remote_core{llvm::StringRef(path)};
4805 Platform &platform = *GetTarget().GetPlatform();
4806 Status error = platform.GetFile(remote_core, FileSpec(outfile));
4807
4808 if (platform.IsRemote()) {
4809 // NB: we unlink the file on error too
4810 platform.Unlink(remote_core);
4811 if (error.Fail())
4812 return error.ToError();
4813 }
4814
4815 return true;
4816 }
4817
4818 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4819 "Unable to send qSaveCore");
4820}
4821
4822static const char *const s_async_json_packet_prefix = "JSON-async:";
4823
4824static StructuredData::ObjectSP
4825ParseStructuredDataPacket(llvm::StringRef packet) {
4826 Log *log = GetLog(GDBRLog::Process);
4827
4828 if (!packet.consume_front(s_async_json_packet_prefix)) {
4829 if (log) {
4830 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunicationClientBase::%s() received $J packet "
"but was not a StructuredData packet: packet starts with " "%s"
, __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str()); } while (0)
4831 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunicationClientBase::%s() received $J packet "
"but was not a StructuredData packet: packet starts with " "%s"
, __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str()); } while (0)
4832 "GDBRemoteCommunicationClientBase::%s() received $J packet "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunicationClientBase::%s() received $J packet "
"but was not a StructuredData packet: packet starts with " "%s"
, __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str()); } while (0)
4833 "but was not a StructuredData packet: packet starts with "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunicationClientBase::%s() received $J packet "
"but was not a StructuredData packet: packet starts with " "%s"
, __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str()); } while (0)
4834 "%s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunicationClientBase::%s() received $J packet "
"but was not a StructuredData packet: packet starts with " "%s"
, __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str()); } while (0)
4835 __FUNCTION__,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunicationClientBase::%s() received $J packet "
"but was not a StructuredData packet: packet starts with " "%s"
, __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str()); } while (0)
4836 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("GDBRemoteCommunicationClientBase::%s() received $J packet "
"but was not a StructuredData packet: packet starts with " "%s"
, __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str()); } while (0)
;
4837 }
4838 return StructuredData::ObjectSP();
4839 }
4840
4841 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
4842 StructuredData::ObjectSP json_sp =
4843 StructuredData::ParseJSON(std::string(packet));
4844 if (log) {
4845 if (json_sp) {
4846 StreamString json_str;
4847 json_sp->Dump(json_str, true);
4848 json_str.Flush();
4849 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s() " "received Async StructuredData packet: %s"
, __FUNCTION__, json_str.GetData()); } while (0)
4850 "ProcessGDBRemote::%s() "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s() " "received Async StructuredData packet: %s"
, __FUNCTION__, json_str.GetData()); } while (0)
4851 "received Async StructuredData packet: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s() " "received Async StructuredData packet: %s"
, __FUNCTION__, json_str.GetData()); } while (0)
4852 __FUNCTION__, json_str.GetData())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s() " "received Async StructuredData packet: %s"
, __FUNCTION__, json_str.GetData()); } while (0)
;
4853 } else {
4854 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s" "() received StructuredData packet:"
" parse failure", __FUNCTION__); } while (0)
4855 "ProcessGDBRemote::%s"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s" "() received StructuredData packet:"
" parse failure", __FUNCTION__); } while (0)
4856 "() received StructuredData packet:"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s" "() received StructuredData packet:"
" parse failure", __FUNCTION__); } while (0)
4857 " parse failure",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s" "() received StructuredData packet:"
" parse failure", __FUNCTION__); } while (0)
4858 __FUNCTION__)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("ProcessGDBRemote::%s" "() received StructuredData packet:"
" parse failure", __FUNCTION__); } while (0)
;
4859 }
4860 }
4861 return json_sp;
4862}
4863
4864void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) {
4865 auto structured_data_sp = ParseStructuredDataPacket(data);
4866 if (structured_data_sp)
4867 RouteAsyncStructuredData(structured_data_sp);
4868}
4869
4870class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed {
4871public:
4872 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
4873 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
4874 "Tests packet speeds of various sizes to determine "
4875 "the performance characteristics of the GDB remote "
4876 "connection. ",
4877 nullptr),
4878 m_option_group(),
4879 m_num_packets(LLDB_OPT_SET_1(1U << 0), false, "count", 'c', 0, eArgTypeCount,
4880 "The number of packets to send of each varying size "
4881 "(default is 1000).",
4882 1000),
4883 m_max_send(LLDB_OPT_SET_1(1U << 0), false, "max-send", 's', 0, eArgTypeCount,
4884 "The maximum number of bytes to send in a packet. Sizes "
4885 "increase in powers of 2 while the size is less than or "
4886 "equal to this option value. (default 1024).",
4887 1024),
4888 m_max_recv(LLDB_OPT_SET_1(1U << 0), false, "max-receive", 'r', 0, eArgTypeCount,
4889 "The maximum number of bytes to receive in a packet. Sizes "
4890 "increase in powers of 2 while the size is less than or "
4891 "equal to this option value. (default 1024).",
4892 1024),
4893 m_json(LLDB_OPT_SET_1(1U << 0), false, "json", 'j',
4894 "Print the output as JSON data for easy parsing.", false, true) {
4895 m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4896 m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4897 m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4898 m_option_group.Append(&m_json, LLDB_OPT_SET_ALL0xFFFFFFFFU, LLDB_OPT_SET_1(1U << 0));
4899 m_option_group.Finalize();
4900 }
4901
4902 ~CommandObjectProcessGDBRemoteSpeedTest() override = default;
4903
4904 Options *GetOptions() override { return &m_option_group; }
4905
4906 bool DoExecute(Args &command, CommandReturnObject &result) override {
4907 const size_t argc = command.GetArgumentCount();
4908 if (argc == 0) {
4909 ProcessGDBRemote *process =
4910 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
4911 .GetProcessPtr();
4912 if (process) {
4913 StreamSP output_stream_sp(
4914 m_interpreter.GetDebugger().GetAsyncOutputStream());
4915 result.SetImmediateOutputStream(output_stream_sp);
4916
4917 const uint32_t num_packets =
4918 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
4919 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
4920 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
4921 const bool json = m_json.GetOptionValue().GetCurrentValue();
4922 const uint64_t k_recv_amount =
4923 4 * 1024 * 1024; // Receive amount in bytes
4924 process->GetGDBRemote().TestPacketSpeed(
4925 num_packets, max_send, max_recv, k_recv_amount, json,
4926 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
4927 result.SetStatus(eReturnStatusSuccessFinishResult);
4928 return true;
4929 }
4930 } else {
4931 result.AppendErrorWithFormat("'%s' takes no arguments",
4932 m_cmd_name.c_str());
4933 }
4934 result.SetStatus(eReturnStatusFailed);
4935 return false;
4936 }
4937
4938protected:
4939 OptionGroupOptions m_option_group;
4940 OptionGroupUInt64 m_num_packets;
4941 OptionGroupUInt64 m_max_send;
4942 OptionGroupUInt64 m_max_recv;
4943 OptionGroupBoolean m_json;
4944};
4945
4946class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed {
4947private:
4948public:
4949 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
4950 : CommandObjectParsed(interpreter, "process plugin packet history",
4951 "Dumps the packet history buffer. ", nullptr) {}
4952
4953 ~CommandObjectProcessGDBRemotePacketHistory() override = default;
4954
4955 bool DoExecute(Args &command, CommandReturnObject &result) override {
4956 ProcessGDBRemote *process =
4957 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4958 if (process) {
4959 process->GetGDBRemote().DumpHistory(result.GetOutputStream());
4960 result.SetStatus(eReturnStatusSuccessFinishResult);
4961 return true;
4962 }
4963 result.SetStatus(eReturnStatusFailed);
4964 return false;
4965 }
4966};
4967
4968class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed {
4969private:
4970public:
4971 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
4972 : CommandObjectParsed(
4973 interpreter, "process plugin packet xfer-size",
4974 "Maximum size that lldb will try to read/write one one chunk.",
4975 nullptr) {
4976 CommandArgumentData max_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
4977 m_arguments.push_back({max_arg});
4978 }
4979
4980 ~CommandObjectProcessGDBRemotePacketXferSize() override = default;
4981
4982 bool DoExecute(Args &command, CommandReturnObject &result) override {
4983 const size_t argc = command.GetArgumentCount();
4984 if (argc == 0) {
4985 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
4986 "amount to be transferred when "
4987 "reading/writing",
4988 m_cmd_name.c_str());
4989 return false;
4990 }
4991
4992 ProcessGDBRemote *process =
4993 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
4994 if (process) {
4995 const char *packet_size = command.GetArgumentAtIndex(0);
4996 errno(*__errno_location ()) = 0;
4997 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
4998 if (errno(*__errno_location ()) == 0 && user_specified_max != 0) {
4999 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5000 result.SetStatus(eReturnStatusSuccessFinishResult);
5001 return true;
5002 }
5003 }
5004 result.SetStatus(eReturnStatusFailed);
5005 return false;
5006 }
5007};
5008
5009class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed {
5010private:
5011public:
5012 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
5013 : CommandObjectParsed(interpreter, "process plugin packet send",
5014 "Send a custom packet through the GDB remote "
5015 "protocol and print the answer. "
5016 "The packet header and footer will automatically "
5017 "be added to the packet prior to sending and "
5018 "stripped from the result.",
5019 nullptr) {
5020 CommandArgumentData packet_arg{eArgTypeNone, eArgRepeatStar};
5021 m_arguments.push_back({packet_arg});
5022 }
5023
5024 ~CommandObjectProcessGDBRemotePacketSend() override = default;
5025
5026 bool DoExecute(Args &command, CommandReturnObject &result) override {
5027 const size_t argc = command.GetArgumentCount();
5028 if (argc == 0) {
5029 result.AppendErrorWithFormat(
5030 "'%s' takes a one or more packet content arguments",
5031 m_cmd_name.c_str());
5032 return false;
5033 }
5034
5035 ProcessGDBRemote *process =
5036 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5037 if (process) {
5038 for (size_t i = 0; i < argc; ++i) {
5039 const char *packet_cstr = command.GetArgumentAtIndex(0);
5040 StringExtractorGDBRemote response;
5041 process->GetGDBRemote().SendPacketAndWaitForResponse(
5042 packet_cstr, response, process->GetInterruptTimeout());
5043 result.SetStatus(eReturnStatusSuccessFinishResult);
5044 Stream &output_strm = result.GetOutputStream();
5045 output_strm.Printf(" packet: %s\n", packet_cstr);
5046 std::string response_str = std::string(response.GetStringRef());
5047
5048 if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5049 response_str = process->HarmonizeThreadIdsForProfileData(response);
5050 }
5051
5052 if (response_str.empty())
5053 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5054 else
5055 output_strm.Printf("response: %s\n", response.GetStringRef().data());
5056 }
5057 }
5058 return true;
5059 }
5060};
5061
5062class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw {
5063private:
5064public:
5065 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
5066 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5067 "Send a qRcmd packet through the GDB remote protocol "
5068 "and print the response."
5069 "The argument passed to this command will be hex "
5070 "encoded into a valid 'qRcmd' packet, sent and the "
5071 "response will be printed.") {}
5072
5073 ~CommandObjectProcessGDBRemotePacketMonitor() override = default;
5074
5075 bool DoExecute(llvm::StringRef command,
5076 CommandReturnObject &result) override {
5077 if (command.empty()) {
5078 result.AppendErrorWithFormat("'%s' takes a command string argument",
5079 m_cmd_name.c_str());
5080 return false;
5081 }
5082
5083 ProcessGDBRemote *process =
5084 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5085 if (process) {
5086 StreamString packet;
5087 packet.PutCString("qRcmd,");
5088 packet.PutBytesAsRawHex8(command.data(), command.size());
5089
5090 StringExtractorGDBRemote response;
5091 Stream &output_strm = result.GetOutputStream();
5092 process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5093 packet.GetString(), response, process->GetInterruptTimeout(),
5094 [&output_strm](llvm::StringRef output) { output_strm << output; });
5095 result.SetStatus(eReturnStatusSuccessFinishResult);
5096 output_strm.Printf(" packet: %s\n", packet.GetData());
5097 const std::string &response_str = std::string(response.GetStringRef());
5098
5099 if (response_str.empty())
5100 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5101 else
5102 output_strm.Printf("response: %s\n", response.GetStringRef().data());
5103 }
5104 return true;
5105 }
5106};
5107
5108class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword {
5109private:
5110public:
5111 CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
5112 : CommandObjectMultiword(interpreter, "process plugin packet",
5113 "Commands that deal with GDB remote packets.",
5114 nullptr) {
5115 LoadSubCommand(
5116 "history",
5117 CommandObjectSP(
5118 new CommandObjectProcessGDBRemotePacketHistory(interpreter)));
5119 LoadSubCommand(
5120 "send", CommandObjectSP(
5121 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
5122 LoadSubCommand(
5123 "monitor",
5124 CommandObjectSP(
5125 new CommandObjectProcessGDBRemotePacketMonitor(interpreter)));
5126 LoadSubCommand(
5127 "xfer-size",
5128 CommandObjectSP(
5129 new CommandObjectProcessGDBRemotePacketXferSize(interpreter)));
5130 LoadSubCommand("speed-test",
5131 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5132 interpreter)));
5133 }
5134
5135 ~CommandObjectProcessGDBRemotePacket() override = default;
5136};
5137
5138class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword {
5139public:
5140 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
5141 : CommandObjectMultiword(
5142 interpreter, "process plugin",
5143 "Commands for operating on a ProcessGDBRemote process.",
5144 "process plugin <subcommand> [<subcommand-options>]") {
5145 LoadSubCommand(
5146 "packet",
5147 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter)));
5148 }
5149
5150 ~CommandObjectMultiwordProcessGDBRemote() override = default;
5151};
5152
5153CommandObject *ProcessGDBRemote::GetPluginCommandObject() {
5154 if (!m_command_sp)
5155 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
5156 GetTarget().GetDebugger().GetCommandInterpreter());
5157 return m_command_sp.get();
5158}
5159
5160void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable) {
5161 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5162 if (bp_site->IsEnabled() &&
5163 (bp_site->GetType() == BreakpointSite::eSoftware ||
5164 bp_site->GetType() == BreakpointSite::eExternal)) {
5165 m_gdb_comm.SendGDBStoppointTypePacket(
5166 eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
5167 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5168 }
5169 });
5170}
5171
5172void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable) {
5173 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
5174 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
5175 if (bp_site->IsEnabled() &&
5176 bp_site->GetType() == BreakpointSite::eHardware) {
5177 m_gdb_comm.SendGDBStoppointTypePacket(
5178 eBreakpointHardware, enable, bp_site->GetLoadAddress(),
5179 GetSoftwareBreakpointTrapOpcode(bp_site), GetInterruptTimeout());
5180 }
5181 });
5182 }
5183
5184 WatchpointList &wps = GetTarget().GetWatchpointList();
5185 size_t wp_count = wps.GetSize();
5186 for (size_t i = 0; i < wp_count; ++i) {
5187 WatchpointSP wp = wps.GetByIndex(i);
5188 if (wp->IsEnabled()) {
5189 GDBStoppointType type = GetGDBStoppointType(wp.get());
5190 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, wp->GetLoadAddress(),
5191 wp->GetByteSize(),
5192 GetInterruptTimeout());
5193 }
5194 }
5195}
5196
5197void ProcessGDBRemote::DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5198 Log *log = GetLog(GDBRLog::Process);
5199
5200 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
5201 // Any valid TID will suffice, thread-relevant actions will set a proper TID
5202 // anyway.
5203 lldb::tid_t parent_tid = m_thread_ids.front();
5204
5205 lldb::pid_t follow_pid, detach_pid;
5206 lldb::tid_t follow_tid, detach_tid;
5207
5208 switch (GetFollowForkMode()) {
5209 case eFollowParent:
5210 follow_pid = parent_pid;
5211 follow_tid = parent_tid;
5212 detach_pid = child_pid;
5213 detach_tid = child_tid;
5214 break;
5215 case eFollowChild:
5216 follow_pid = child_pid;
5217 follow_tid = child_tid;
5218 detach_pid = parent_pid;
5219 detach_tid = parent_tid;
5220 break;
5221 }
5222
5223 // Switch to the process that is going to be detached.
5224 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5225 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() unable to set pid/tid"
); } while (0)
;
5226 return;
5227 }
5228
5229 // Disable all software breakpoints in the forked process.
5230 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5231 DidForkSwitchSoftwareBreakpoints(false);
5232
5233 // Remove hardware breakpoints / watchpoints from parent process if we're
5234 // following child.
5235 if (GetFollowForkMode() == eFollowChild)
5236 DidForkSwitchHardwareTraps(false);
5237
5238 // Switch to the process that is going to be followed
5239 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
5240 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
5241 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() unable to reset pid/tid"
); } while (0)
;
5242 return;
5243 }
5244
5245 LLDB_LOG(log, "Detaching process {0}", detach_pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Detaching process {0}", detach_pid); } while (0)
;
5246 Status error = m_gdb_comm.Detach(false, detach_pid);
5247 if (error.Fail()) {
5248 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() detach packet send failed: {0}"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
5249 error.AsCString() ? error.AsCString() : "<unknown error>")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() detach packet send failed: {0}"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
;
5250 return;
5251 }
5252
5253 // Hardware breakpoints/watchpoints are not inherited implicitly,
5254 // so we need to readd them if we're following child.
5255 if (GetFollowForkMode() == eFollowChild) {
5256 DidForkSwitchHardwareTraps(true);
5257 // Update our PID
5258 SetID(child_pid);
5259 }
5260}
5261
5262void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) {
5263 Log *log = GetLog(GDBRLog::Process);
5264
5265 assert(!m_vfork_in_progress)(static_cast <bool> (!m_vfork_in_progress) ? void (0) :
__assert_fail ("!m_vfork_in_progress", "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 5265, __extension__ __PRETTY_FUNCTION__))
;
5266 m_vfork_in_progress = true;
5267
5268 // Disable all software breakpoints for the duration of vfork.
5269 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5270 DidForkSwitchSoftwareBreakpoints(false);
5271
5272 lldb::pid_t detach_pid;
5273 lldb::tid_t detach_tid;
5274
5275 switch (GetFollowForkMode()) {
5276 case eFollowParent:
5277 detach_pid = child_pid;
5278 detach_tid = child_tid;
5279 break;
5280 case eFollowChild:
5281 detach_pid = m_gdb_comm.GetCurrentProcessID();
5282 // Any valid TID will suffice, thread-relevant actions will set a proper TID
5283 // anyway.
5284 detach_tid = m_thread_ids.front();
5285
5286 // Switch to the parent process before detaching it.
5287 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
5288 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() unable to set pid/tid"
); } while (0)
;
5289 return;
5290 }
5291
5292 // Remove hardware breakpoints / watchpoints from the parent process.
5293 DidForkSwitchHardwareTraps(false);
5294
5295 // Switch to the child process.
5296 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
5297 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
5298 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() unable to reset pid/tid"
); } while (0)
;
5299 return;
5300 }
5301 break;
5302 }
5303
5304 LLDB_LOG(log, "Detaching process {0}", detach_pid)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "Detaching process {0}", detach_pid); } while (0)
;
5305 Status error = m_gdb_comm.Detach(false, detach_pid);
5306 if (error.Fail()) {
5307 LLDB_LOG(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() detach packet send failed: {0}"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
5308 "ProcessGDBRemote::DidFork() detach packet send failed: {0}",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() detach packet send failed: {0}"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
5309 error.AsCString() ? error.AsCString() : "<unknown error>")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Format("lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, __func__, "ProcessGDBRemote::DidFork() detach packet send failed: {0}"
, error.AsCString() ? error.AsCString() : "<unknown error>"
); } while (0)
;
5310 return;
5311 }
5312
5313 if (GetFollowForkMode() == eFollowChild) {
5314 // Update our PID
5315 SetID(child_pid);
5316 }
5317}
5318
5319void ProcessGDBRemote::DidVForkDone() {
5320 assert(m_vfork_in_progress)(static_cast <bool> (m_vfork_in_progress) ? void (0) : __assert_fail
("m_vfork_in_progress", "lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp"
, 5320, __extension__ __PRETTY_FUNCTION__))
;
5321 m_vfork_in_progress = false;
5322
5323 // Reenable all software breakpoints that were enabled before vfork.
5324 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
5325 DidForkSwitchSoftwareBreakpoints(true);
5326}
5327
5328void ProcessGDBRemote::DidExec() {
5329 // If we are following children, vfork is finished by exec (rather than
5330 // vforkdone that is submitted for parent).
5331 if (GetFollowForkMode() == eFollowChild)
5332 m_vfork_in_progress = false;
5333 Process::DidExec();
5334}