Bug Summary

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