Bug Summary

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