Bug Summary

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