1 //===-- ProcessGDBRemote.cpp ----------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Host/Config.h"
14 #include <netinet/in.h>
16 #include <sys/socket.h>
20 #if defined(__APPLE__)
21 #include <sys/sysctl.h>
24 #include <sys/types.h>
26 #include "lldb/Breakpoint/Watchpoint.h"
27 #include "lldb/Breakpoint/WatchpointAlgorithms.h"
28 #include "lldb/Breakpoint/WatchpointResource.h"
29 #include "lldb/Core/Debugger.h"
30 #include "lldb/Core/Module.h"
31 #include "lldb/Core/ModuleSpec.h"
32 #include "lldb/Core/PluginManager.h"
33 #include "lldb/Core/Value.h"
34 #include "lldb/DataFormatters/FormatManager.h"
35 #include "lldb/Host/ConnectionFileDescriptor.h"
36 #include "lldb/Host/FileSystem.h"
37 #include "lldb/Host/HostThread.h"
38 #include "lldb/Host/PosixApi.h"
39 #include "lldb/Host/PseudoTerminal.h"
40 #include "lldb/Host/StreamFile.h"
41 #include "lldb/Host/ThreadLauncher.h"
42 #include "lldb/Host/XML.h"
43 #include "lldb/Interpreter/CommandInterpreter.h"
44 #include "lldb/Interpreter/CommandObject.h"
45 #include "lldb/Interpreter/CommandObjectMultiword.h"
46 #include "lldb/Interpreter/CommandReturnObject.h"
47 #include "lldb/Interpreter/OptionArgParser.h"
48 #include "lldb/Interpreter/OptionGroupBoolean.h"
49 #include "lldb/Interpreter/OptionGroupUInt64.h"
50 #include "lldb/Interpreter/OptionValueProperties.h"
51 #include "lldb/Interpreter/Options.h"
52 #include "lldb/Interpreter/Property.h"
53 #include "lldb/Symbol/ObjectFile.h"
54 #include "lldb/Target/ABI.h"
55 #include "lldb/Target/DynamicLoader.h"
56 #include "lldb/Target/MemoryRegionInfo.h"
57 #include "lldb/Target/RegisterFlags.h"
58 #include "lldb/Target/SystemRuntime.h"
59 #include "lldb/Target/Target.h"
60 #include "lldb/Target/TargetList.h"
61 #include "lldb/Target/ThreadPlanCallFunction.h"
62 #include "lldb/Utility/Args.h"
63 #include "lldb/Utility/FileSpec.h"
64 #include "lldb/Utility/LLDBLog.h"
65 #include "lldb/Utility/State.h"
66 #include "lldb/Utility/StreamString.h"
67 #include "lldb/Utility/Timer.h"
77 #include "GDBRemoteRegisterContext.h"
78 #include "GDBRemoteRegisterFallback.h"
79 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
80 #include "Plugins/Process/Utility/InferiorCallPOSIX.h"
81 #include "Plugins/Process/Utility/StopInfoMachException.h"
82 #include "ProcessGDBRemote.h"
83 #include "ProcessGDBRemoteLog.h"
84 #include "ThreadGDBRemote.h"
85 #include "lldb/Host/Host.h"
86 #include "lldb/Utility/StringExtractorGDBRemote.h"
88 #include "llvm/ADT/ScopeExit.h"
89 #include "llvm/ADT/StringMap.h"
90 #include "llvm/ADT/StringSwitch.h"
91 #include "llvm/Support/FormatAdapters.h"
92 #include "llvm/Support/Threading.h"
93 #include "llvm/Support/raw_ostream.h"
95 #define DEBUGSERVER_BASENAME "debugserver"
97 using namespace lldb_private
;
98 using namespace lldb_private::process_gdb_remote
;
100 LLDB_PLUGIN_DEFINE(ProcessGDBRemote
)
103 // Provide a function that can easily dump the packet history if we know a
104 // ProcessGDBRemote * value (which we can get from logs or from debugging). We
105 // need the function in the lldb namespace so it makes it into the final
106 // executable since the LLDB shared library only exports stuff in the lldb
107 // namespace. This allows you to attach with a debugger and call this function
108 // and get the packet history dumped to a file.
109 void DumpProcessGDBRemotePacketHistory(void *p
, const char *path
) {
110 auto file
= FileSystem::Instance().Open(
111 FileSpec(path
), File::eOpenOptionWriteOnly
| File::eOpenOptionCanCreate
);
113 llvm::consumeError(file
.takeError());
116 StreamFile
stream(std::move(file
.get()));
117 ((Process
*)p
)->DumpPluginHistory(stream
);
123 #define LLDB_PROPERTIES_processgdbremote
124 #include "ProcessGDBRemoteProperties.inc"
127 #define LLDB_PROPERTIES_processgdbremote
128 #include "ProcessGDBRemotePropertiesEnum.inc"
131 class PluginProperties
: public Properties
{
133 static llvm::StringRef
GetSettingName() {
134 return ProcessGDBRemote::GetPluginNameStatic();
137 PluginProperties() : Properties() {
138 m_collection_sp
= std::make_shared
<OptionValueProperties
>(GetSettingName());
139 m_collection_sp
->Initialize(g_processgdbremote_properties
);
142 ~PluginProperties() override
= default;
144 uint64_t GetPacketTimeout() {
145 const uint32_t idx
= ePropertyPacketTimeout
;
146 return GetPropertyAtIndexAs
<uint64_t>(
147 idx
, g_processgdbremote_properties
[idx
].default_uint_value
);
150 bool SetPacketTimeout(uint64_t timeout
) {
151 const uint32_t idx
= ePropertyPacketTimeout
;
152 return SetPropertyAtIndex(idx
, timeout
);
155 FileSpec
GetTargetDefinitionFile() const {
156 const uint32_t idx
= ePropertyTargetDefinitionFile
;
157 return GetPropertyAtIndexAs
<FileSpec
>(idx
, {});
160 bool GetUseSVR4() const {
161 const uint32_t idx
= ePropertyUseSVR4
;
162 return GetPropertyAtIndexAs
<bool>(
163 idx
, g_processgdbremote_properties
[idx
].default_uint_value
!= 0);
166 bool GetUseGPacketForReading() const {
167 const uint32_t idx
= ePropertyUseGPacketForReading
;
168 return GetPropertyAtIndexAs
<bool>(idx
, true);
174 static PluginProperties
&GetGlobalPluginProperties() {
175 static PluginProperties g_settings
;
179 // TODO Randomly assigning a port is unsafe. We should get an unused
180 // ephemeral port from the kernel and make sure we reserve it before passing it
183 #if defined(__APPLE__)
184 #define LOW_PORT (IPPORT_RESERVED)
185 #define HIGH_PORT (IPPORT_HIFIRSTAUTO)
187 #define LOW_PORT (1024u)
188 #define HIGH_PORT (49151u)
191 llvm::StringRef
ProcessGDBRemote::GetPluginDescriptionStatic() {
192 return "GDB Remote protocol based debugging plug-in.";
195 void ProcessGDBRemote::Terminate() {
196 PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance
);
199 lldb::ProcessSP
ProcessGDBRemote::CreateInstance(
200 lldb::TargetSP target_sp
, ListenerSP listener_sp
,
201 const FileSpec
*crash_file_path
, bool can_connect
) {
202 lldb::ProcessSP process_sp
;
203 if (crash_file_path
== nullptr)
204 process_sp
= std::shared_ptr
<ProcessGDBRemote
>(
205 new ProcessGDBRemote(target_sp
, listener_sp
));
209 void ProcessGDBRemote::DumpPluginHistory(Stream
&s
) {
210 GDBRemoteCommunicationClient
&gdb_comm(GetGDBRemote());
211 gdb_comm
.DumpHistory(s
);
214 std::chrono::seconds
ProcessGDBRemote::GetPacketTimeout() {
215 return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
218 ArchSpec
ProcessGDBRemote::GetSystemArchitecture() {
219 return m_gdb_comm
.GetHostArchitecture();
222 bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp
,
223 bool plugin_specified_by_name
) {
224 if (plugin_specified_by_name
)
227 // For now we are just making sure the file exists for a given module
228 Module
*exe_module
= target_sp
->GetExecutableModulePointer();
230 ObjectFile
*exe_objfile
= exe_module
->GetObjectFile();
231 // We can't debug core files...
232 switch (exe_objfile
->GetType()) {
233 case ObjectFile::eTypeInvalid
:
234 case ObjectFile::eTypeCoreFile
:
235 case ObjectFile::eTypeDebugInfo
:
236 case ObjectFile::eTypeObjectFile
:
237 case ObjectFile::eTypeSharedLibrary
:
238 case ObjectFile::eTypeStubLibrary
:
239 case ObjectFile::eTypeJIT
:
241 case ObjectFile::eTypeExecutable
:
242 case ObjectFile::eTypeDynamicLinker
:
243 case ObjectFile::eTypeUnknown
:
246 return FileSystem::Instance().Exists(exe_module
->GetFileSpec());
248 // However, if there is no executable module, we return true since we might
249 // be preparing to attach.
253 // ProcessGDBRemote constructor
254 ProcessGDBRemote::ProcessGDBRemote(lldb::TargetSP target_sp
,
255 ListenerSP listener_sp
)
256 : Process(target_sp
, listener_sp
),
257 m_debugserver_pid(LLDB_INVALID_PROCESS_ID
), m_register_info_sp(nullptr),
258 m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
260 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
261 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
262 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
263 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
264 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
265 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
266 m_waiting_for_attach(false), m_command_sp(), m_breakpoint_pc_offset(0),
267 m_initial_tid(LLDB_INVALID_THREAD_ID
), m_allow_flash_writes(false),
268 m_erased_flash_ranges(), m_vfork_in_progress_count(0) {
269 m_async_broadcaster
.SetEventName(eBroadcastBitAsyncThreadShouldExit
,
270 "async thread should exit");
271 m_async_broadcaster
.SetEventName(eBroadcastBitAsyncContinue
,
272 "async thread continue");
273 m_async_broadcaster
.SetEventName(eBroadcastBitAsyncThreadDidExit
,
274 "async thread did exit");
276 Log
*log
= GetLog(GDBRLog::Async
);
278 const uint32_t async_event_mask
=
279 eBroadcastBitAsyncContinue
| eBroadcastBitAsyncThreadShouldExit
;
281 if (m_async_listener_sp
->StartListeningForEvents(
282 &m_async_broadcaster
, async_event_mask
) != async_event_mask
) {
284 "ProcessGDBRemote::%s failed to listen for "
285 "m_async_broadcaster events",
289 const uint64_t timeout_seconds
=
290 GetGlobalPluginProperties().GetPacketTimeout();
291 if (timeout_seconds
> 0)
292 m_gdb_comm
.SetPacketTimeout(std::chrono::seconds(timeout_seconds
));
294 m_use_g_packet_for_reading
=
295 GetGlobalPluginProperties().GetUseGPacketForReading();
299 ProcessGDBRemote::~ProcessGDBRemote() {
300 // m_mach_process.UnregisterNotificationCallbacks (this);
302 // We need to call finalize on the process before destroying ourselves to
303 // make sure all of the broadcaster cleanup goes as planned. If we destruct
304 // this class, then Process::~Process() might have problems trying to fully
305 // destroy the broadcaster.
306 Finalize(true /* destructing */);
308 // The general Finalize is going to try to destroy the process and that
309 // SHOULD shut down the async thread. However, if we don't kill it it will
310 // get stranded and its connection will go away so when it wakes up it will
311 // crash. So kill it for sure here.
313 KillDebugserverProcess();
316 bool ProcessGDBRemote::ParsePythonTargetDefinition(
317 const FileSpec
&target_definition_fspec
) {
318 ScriptInterpreter
*interpreter
=
319 GetTarget().GetDebugger().GetScriptInterpreter();
321 StructuredData::ObjectSP
module_object_sp(
322 interpreter
->LoadPluginModule(target_definition_fspec
, error
));
323 if (module_object_sp
) {
324 StructuredData::DictionarySP
target_definition_sp(
325 interpreter
->GetDynamicSettings(module_object_sp
, &GetTarget(),
326 "gdb-server-target-definition", error
));
328 if (target_definition_sp
) {
329 StructuredData::ObjectSP
target_object(
330 target_definition_sp
->GetValueForKey("host-info"));
332 if (auto host_info_dict
= target_object
->GetAsDictionary()) {
333 StructuredData::ObjectSP triple_value
=
334 host_info_dict
->GetValueForKey("triple");
335 if (auto triple_string_value
= triple_value
->GetAsString()) {
336 std::string triple_string
=
337 std::string(triple_string_value
->GetValue());
338 ArchSpec
host_arch(triple_string
.c_str());
339 if (!host_arch
.IsCompatibleMatch(GetTarget().GetArchitecture())) {
340 GetTarget().SetArchitecture(host_arch
);
345 m_breakpoint_pc_offset
= 0;
346 StructuredData::ObjectSP breakpoint_pc_offset_value
=
347 target_definition_sp
->GetValueForKey("breakpoint-pc-offset");
348 if (breakpoint_pc_offset_value
) {
349 if (auto breakpoint_pc_int_value
=
350 breakpoint_pc_offset_value
->GetAsSignedInteger())
351 m_breakpoint_pc_offset
= breakpoint_pc_int_value
->GetValue();
354 if (m_register_info_sp
->SetRegisterInfo(
355 *target_definition_sp
, GetTarget().GetArchitecture()) > 0) {
363 static size_t SplitCommaSeparatedRegisterNumberString(
364 const llvm::StringRef
&comma_separated_register_numbers
,
365 std::vector
<uint32_t> ®nums
, int base
) {
367 for (llvm::StringRef x
: llvm::split(comma_separated_register_numbers
, ',')) {
369 if (llvm::to_integer(x
, reg
, base
))
370 regnums
.push_back(reg
);
372 return regnums
.size();
375 void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force
) {
376 if (!force
&& m_register_info_sp
)
379 m_register_info_sp
= std::make_shared
<GDBRemoteDynamicRegisterInfo
>();
381 // Check if qHostInfo specified a specific packet timeout for this
382 // connection. If so then lets update our setting so the user knows what the
383 // timeout is and can see it.
384 const auto host_packet_timeout
= m_gdb_comm
.GetHostDefaultPacketTimeout();
385 if (host_packet_timeout
> std::chrono::seconds(0)) {
386 GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout
.count());
389 // Register info search order:
390 // 1 - Use the target definition python file if one is specified.
391 // 2 - If the target definition doesn't have any of the info from the
392 // target.xml (registers) then proceed to read the target.xml.
393 // 3 - Fall back on the qRegisterInfo packets.
394 // 4 - Use hardcoded defaults if available.
396 FileSpec target_definition_fspec
=
397 GetGlobalPluginProperties().GetTargetDefinitionFile();
398 if (!FileSystem::Instance().Exists(target_definition_fspec
)) {
399 // If the filename doesn't exist, it may be a ~ not having been expanded -
400 // try to resolve it.
401 FileSystem::Instance().Resolve(target_definition_fspec
);
403 if (target_definition_fspec
) {
404 // See if we can get register definitions from a python file
405 if (ParsePythonTargetDefinition(target_definition_fspec
))
408 Debugger::ReportError("target description file " +
409 target_definition_fspec
.GetPath() +
411 GetTarget().GetDebugger().GetID());
414 const ArchSpec
&target_arch
= GetTarget().GetArchitecture();
415 const ArchSpec
&remote_host_arch
= m_gdb_comm
.GetHostArchitecture();
416 const ArchSpec
&remote_process_arch
= m_gdb_comm
.GetProcessArchitecture();
418 // Use the process' architecture instead of the host arch, if available
419 ArchSpec arch_to_use
;
420 if (remote_process_arch
.IsValid())
421 arch_to_use
= remote_process_arch
;
423 arch_to_use
= remote_host_arch
;
425 if (!arch_to_use
.IsValid())
426 arch_to_use
= target_arch
;
428 if (GetGDBServerRegisterInfo(arch_to_use
))
432 std::vector
<DynamicRegisterInfo::Register
> registers
;
433 uint32_t reg_num
= 0;
434 for (StringExtractorGDBRemote::ResponseType response_type
=
435 StringExtractorGDBRemote::eResponse
;
436 response_type
== StringExtractorGDBRemote::eResponse
; ++reg_num
) {
437 const int packet_len
=
438 ::snprintf(packet
, sizeof(packet
), "qRegisterInfo%x", reg_num
);
439 assert(packet_len
< (int)sizeof(packet
));
440 UNUSED_IF_ASSERT_DISABLED(packet_len
);
441 StringExtractorGDBRemote response
;
442 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
, response
) ==
443 GDBRemoteCommunication::PacketResult::Success
) {
444 response_type
= response
.GetResponseType();
445 if (response_type
== StringExtractorGDBRemote::eResponse
) {
446 llvm::StringRef name
;
447 llvm::StringRef value
;
448 DynamicRegisterInfo::Register reg_info
;
450 while (response
.GetNameColonValue(name
, value
)) {
451 if (name
== "name") {
452 reg_info
.name
.SetString(value
);
453 } else if (name
== "alt-name") {
454 reg_info
.alt_name
.SetString(value
);
455 } else if (name
== "bitsize") {
456 if (!value
.getAsInteger(0, reg_info
.byte_size
))
457 reg_info
.byte_size
/= CHAR_BIT
;
458 } else if (name
== "offset") {
459 value
.getAsInteger(0, reg_info
.byte_offset
);
460 } else if (name
== "encoding") {
461 const Encoding encoding
= Args::StringToEncoding(value
);
462 if (encoding
!= eEncodingInvalid
)
463 reg_info
.encoding
= encoding
;
464 } else if (name
== "format") {
465 if (!OptionArgParser::ToFormat(value
.str().c_str(), reg_info
.format
, nullptr)
468 llvm::StringSwitch
<Format
>(value
)
469 .Case("binary", eFormatBinary
)
470 .Case("decimal", eFormatDecimal
)
471 .Case("hex", eFormatHex
)
472 .Case("float", eFormatFloat
)
473 .Case("vector-sint8", eFormatVectorOfSInt8
)
474 .Case("vector-uint8", eFormatVectorOfUInt8
)
475 .Case("vector-sint16", eFormatVectorOfSInt16
)
476 .Case("vector-uint16", eFormatVectorOfUInt16
)
477 .Case("vector-sint32", eFormatVectorOfSInt32
)
478 .Case("vector-uint32", eFormatVectorOfUInt32
)
479 .Case("vector-float32", eFormatVectorOfFloat32
)
480 .Case("vector-uint64", eFormatVectorOfUInt64
)
481 .Case("vector-uint128", eFormatVectorOfUInt128
)
482 .Default(eFormatInvalid
);
483 } else if (name
== "set") {
484 reg_info
.set_name
.SetString(value
);
485 } else if (name
== "gcc" || name
== "ehframe") {
486 value
.getAsInteger(0, reg_info
.regnum_ehframe
);
487 } else if (name
== "dwarf") {
488 value
.getAsInteger(0, reg_info
.regnum_dwarf
);
489 } else if (name
== "generic") {
490 reg_info
.regnum_generic
= Args::StringToGenericRegister(value
);
491 } else if (name
== "container-regs") {
492 SplitCommaSeparatedRegisterNumberString(value
, reg_info
.value_regs
, 16);
493 } else if (name
== "invalidate-regs") {
494 SplitCommaSeparatedRegisterNumberString(value
, reg_info
.invalidate_regs
, 16);
498 assert(reg_info
.byte_size
!= 0);
499 registers
.push_back(reg_info
);
501 break; // ensure exit before reg_num is incremented
508 if (registers
.empty())
509 registers
= GetFallbackRegisters(arch_to_use
);
511 AddRemoteRegisters(registers
, arch_to_use
);
514 Status
ProcessGDBRemote::DoWillLaunch(lldb_private::Module
*module
) {
515 return WillLaunchOrAttach();
518 Status
ProcessGDBRemote::DoWillAttachToProcessWithID(lldb::pid_t pid
) {
519 return WillLaunchOrAttach();
522 Status
ProcessGDBRemote::DoWillAttachToProcessWithName(const char *process_name
,
523 bool wait_for_launch
) {
524 return WillLaunchOrAttach();
527 Status
ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url
) {
528 Log
*log
= GetLog(GDBRLog::Process
);
530 Status
error(WillLaunchOrAttach());
534 error
= ConnectToDebugserver(remote_url
);
540 lldb::pid_t pid
= m_gdb_comm
.GetCurrentProcessID();
541 if (pid
== LLDB_INVALID_PROCESS_ID
) {
542 // We don't have a valid process ID, so note that we are connected and
543 // could now request to launch or attach, or get remote process listings...
544 SetPrivateState(eStateConnected
);
546 // We have a valid process
549 StringExtractorGDBRemote response
;
550 if (m_gdb_comm
.GetStopReply(response
)) {
551 SetLastStopPacket(response
);
553 Target
&target
= GetTarget();
554 if (!target
.GetArchitecture().IsValid()) {
555 if (m_gdb_comm
.GetProcessArchitecture().IsValid()) {
556 target
.SetArchitecture(m_gdb_comm
.GetProcessArchitecture());
558 if (m_gdb_comm
.GetHostArchitecture().IsValid()) {
559 target
.SetArchitecture(m_gdb_comm
.GetHostArchitecture());
564 const StateType state
= SetThreadStopInfo(response
);
565 if (state
!= eStateInvalid
) {
566 SetPrivateState(state
);
568 error
= Status::FromErrorStringWithFormat(
569 "Process %" PRIu64
" was reported after connecting to "
570 "'%s', but state was not stopped: %s",
571 pid
, remote_url
.str().c_str(), StateAsCString(state
));
573 error
= Status::FromErrorStringWithFormat(
574 "Process %" PRIu64
" was reported after connecting to '%s', "
575 "but no stop reply packet was received",
576 pid
, remote_url
.str().c_str());
580 "ProcessGDBRemote::%s pid %" PRIu64
581 ": normalizing target architecture initial triple: %s "
582 "(GetTarget().GetArchitecture().IsValid() %s, "
583 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
584 __FUNCTION__
, GetID(),
585 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
586 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
587 m_gdb_comm
.GetHostArchitecture().IsValid() ? "true" : "false");
589 if (error
.Success() && !GetTarget().GetArchitecture().IsValid() &&
590 m_gdb_comm
.GetHostArchitecture().IsValid()) {
591 // Prefer the *process'* architecture over that of the *host*, if
593 if (m_gdb_comm
.GetProcessArchitecture().IsValid())
594 GetTarget().SetArchitecture(m_gdb_comm
.GetProcessArchitecture());
596 GetTarget().SetArchitecture(m_gdb_comm
.GetHostArchitecture());
600 "ProcessGDBRemote::%s pid %" PRIu64
601 ": normalized target architecture triple: %s",
602 __FUNCTION__
, GetID(),
603 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
608 Status
ProcessGDBRemote::WillLaunchOrAttach() {
610 m_stdio_communication
.Clear();
615 Status
ProcessGDBRemote::DoLaunch(lldb_private::Module
*exe_module
,
616 ProcessLaunchInfo
&launch_info
) {
617 Log
*log
= GetLog(GDBRLog::Process
);
620 LLDB_LOGF(log
, "ProcessGDBRemote::%s() entered", __FUNCTION__
);
622 uint32_t launch_flags
= launch_info
.GetFlags().Get();
623 FileSpec stdin_file_spec
{};
624 FileSpec stdout_file_spec
{};
625 FileSpec stderr_file_spec
{};
626 FileSpec working_dir
= launch_info
.GetWorkingDirectory();
628 const FileAction
*file_action
;
629 file_action
= launch_info
.GetFileActionForFD(STDIN_FILENO
);
631 if (file_action
->GetAction() == FileAction::eFileActionOpen
)
632 stdin_file_spec
= file_action
->GetFileSpec();
634 file_action
= launch_info
.GetFileActionForFD(STDOUT_FILENO
);
636 if (file_action
->GetAction() == FileAction::eFileActionOpen
)
637 stdout_file_spec
= file_action
->GetFileSpec();
639 file_action
= launch_info
.GetFileActionForFD(STDERR_FILENO
);
641 if (file_action
->GetAction() == FileAction::eFileActionOpen
)
642 stderr_file_spec
= file_action
->GetFileSpec();
646 if (stdin_file_spec
|| stdout_file_spec
|| stderr_file_spec
)
648 "ProcessGDBRemote::%s provided with STDIO paths via "
649 "launch_info: stdin=%s, stdout=%s, stderr=%s",
651 stdin_file_spec
? stdin_file_spec
.GetPath().c_str() : "<null>",
652 stdout_file_spec
? stdout_file_spec
.GetPath().c_str() : "<null>",
653 stderr_file_spec
? stderr_file_spec
.GetPath().c_str() : "<null>");
656 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
660 const bool disable_stdio
= (launch_flags
& eLaunchFlagDisableSTDIO
) != 0;
661 if (stdin_file_spec
|| disable_stdio
) {
662 // the inferior will be reading stdin from the specified file or stdio is
663 // completely disabled
664 m_stdin_forward
= false;
666 m_stdin_forward
= true;
669 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
670 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
671 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
672 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
673 // ::LogSetLogFile ("/dev/stdout");
675 error
= EstablishConnectionIfNeeded(launch_info
);
676 if (error
.Success()) {
678 const bool disable_stdio
= (launch_flags
& eLaunchFlagDisableSTDIO
) != 0;
680 PlatformSP
platform_sp(GetTarget().GetPlatform());
682 // set to /dev/null unless redirected to a file above
683 if (!stdin_file_spec
)
684 stdin_file_spec
.SetFile(FileSystem::DEV_NULL
,
685 FileSpec::Style::native
);
686 if (!stdout_file_spec
)
687 stdout_file_spec
.SetFile(FileSystem::DEV_NULL
,
688 FileSpec::Style::native
);
689 if (!stderr_file_spec
)
690 stderr_file_spec
.SetFile(FileSystem::DEV_NULL
,
691 FileSpec::Style::native
);
692 } else if (platform_sp
&& platform_sp
->IsHost()) {
693 // If the debugserver is local and we aren't disabling STDIO, lets use
694 // a pseudo terminal to instead of relying on the 'O' packets for stdio
695 // since 'O' packets can really slow down debugging if the inferior
696 // does a lot of output.
697 if ((!stdin_file_spec
|| !stdout_file_spec
|| !stderr_file_spec
) &&
698 !errorToBool(pty
.OpenFirstAvailablePrimary(O_RDWR
| O_NOCTTY
))) {
699 FileSpec
secondary_name(pty
.GetSecondaryName());
701 if (!stdin_file_spec
)
702 stdin_file_spec
= secondary_name
;
704 if (!stdout_file_spec
)
705 stdout_file_spec
= secondary_name
;
707 if (!stderr_file_spec
)
708 stderr_file_spec
= secondary_name
;
712 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
713 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
716 stdin_file_spec
? stdin_file_spec
.GetPath().c_str() : "<null>",
717 stdout_file_spec
? stdout_file_spec
.GetPath().c_str() : "<null>",
718 stderr_file_spec
? stderr_file_spec
.GetPath().c_str() : "<null>");
722 "ProcessGDBRemote::%s final STDIO paths after all "
723 "adjustments: stdin=%s, stdout=%s, stderr=%s",
725 stdin_file_spec
? stdin_file_spec
.GetPath().c_str() : "<null>",
726 stdout_file_spec
? stdout_file_spec
.GetPath().c_str() : "<null>",
727 stderr_file_spec
? stderr_file_spec
.GetPath().c_str() : "<null>");
730 m_gdb_comm
.SetSTDIN(stdin_file_spec
);
731 if (stdout_file_spec
)
732 m_gdb_comm
.SetSTDOUT(stdout_file_spec
);
733 if (stderr_file_spec
)
734 m_gdb_comm
.SetSTDERR(stderr_file_spec
);
736 m_gdb_comm
.SetDisableASLR(launch_flags
& eLaunchFlagDisableASLR
);
737 m_gdb_comm
.SetDetachOnError(launch_flags
& eLaunchFlagDetachOnError
);
739 m_gdb_comm
.SendLaunchArchPacket(
740 GetTarget().GetArchitecture().GetArchitectureName());
742 const char *launch_event_data
= launch_info
.GetLaunchEventData();
743 if (launch_event_data
!= nullptr && *launch_event_data
!= '\0')
744 m_gdb_comm
.SendLaunchEventDataPacket(launch_event_data
);
747 m_gdb_comm
.SetWorkingDir(working_dir
);
750 // Send the environment and the program + arguments after we connect
751 m_gdb_comm
.SendEnvironment(launch_info
.GetEnvironment());
754 // Scope for the scoped timeout object
755 GDBRemoteCommunication::ScopedTimeout
timeout(m_gdb_comm
,
756 std::chrono::seconds(10));
758 // Since we can't send argv0 separate from the executable path, we need to
759 // make sure to use the actual executable path found in the launch_info...
760 Args args
= launch_info
.GetArguments();
761 if (FileSpec exe_file
= launch_info
.GetExecutableFile())
762 args
.ReplaceArgumentAtIndex(0, exe_file
.GetPath(false));
763 if (llvm::Error err
= m_gdb_comm
.LaunchProcess(args
)) {
764 error
= Status::FromErrorStringWithFormatv(
765 "Cannot launch '{0}': {1}", args
.GetArgumentAtIndex(0),
766 llvm::fmt_consume(std::move(err
)));
768 SetID(m_gdb_comm
.GetCurrentProcessID());
772 if (GetID() == LLDB_INVALID_PROCESS_ID
) {
773 LLDB_LOGF(log
, "failed to connect to debugserver: %s",
775 KillDebugserverProcess();
779 StringExtractorGDBRemote response
;
780 if (m_gdb_comm
.GetStopReply(response
)) {
781 SetLastStopPacket(response
);
783 const ArchSpec
&process_arch
= m_gdb_comm
.GetProcessArchitecture();
785 if (process_arch
.IsValid()) {
786 GetTarget().MergeArchitecture(process_arch
);
788 const ArchSpec
&host_arch
= m_gdb_comm
.GetHostArchitecture();
789 if (host_arch
.IsValid())
790 GetTarget().MergeArchitecture(host_arch
);
793 SetPrivateState(SetThreadStopInfo(response
));
795 if (!disable_stdio
) {
796 if (pty
.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd
)
797 SetSTDIOFileDescriptor(pty
.ReleasePrimaryFileDescriptor());
801 LLDB_LOGF(log
, "failed to connect to debugserver: %s", error
.AsCString());
806 Status
ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url
) {
808 // Only connect if we have a valid connect URL
809 Log
*log
= GetLog(GDBRLog::Process
);
811 if (!connect_url
.empty()) {
812 LLDB_LOGF(log
, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__
,
813 connect_url
.str().c_str());
814 std::unique_ptr
<ConnectionFileDescriptor
> conn_up(
815 new ConnectionFileDescriptor());
817 const uint32_t max_retry_count
= 50;
818 uint32_t retry_count
= 0;
819 while (!m_gdb_comm
.IsConnected()) {
820 if (conn_up
->Connect(connect_url
, &error
) == eConnectionStatusSuccess
) {
821 m_gdb_comm
.SetConnection(std::move(conn_up
));
827 if (retry_count
>= max_retry_count
)
830 std::this_thread::sleep_for(std::chrono::milliseconds(100));
835 if (!m_gdb_comm
.IsConnected()) {
837 error
= Status::FromErrorString("not connected to remote gdb server");
841 // We always seem to be able to open a connection to a local port so we need
842 // to make sure we can then send data to it. If we can't then we aren't
843 // actually connected to anything, so try and do the handshake with the
844 // remote GDB server and make sure that goes alright.
845 if (!m_gdb_comm
.HandshakeWithServer(&error
)) {
846 m_gdb_comm
.Disconnect();
848 error
= Status::FromErrorString("not connected to remote gdb server");
852 m_gdb_comm
.GetEchoSupported();
853 m_gdb_comm
.GetThreadSuffixSupported();
854 m_gdb_comm
.GetListThreadsInStopReplySupported();
855 m_gdb_comm
.GetHostInfo();
856 m_gdb_comm
.GetVContSupported('c');
857 m_gdb_comm
.GetVAttachOrWaitSupported();
858 m_gdb_comm
.EnableErrorStringInPacket();
860 // First dispatch any commands from the platform:
861 auto handle_cmds
= [&] (const Args
&args
) -> void {
862 for (const Args::ArgEntry
&entry
: args
) {
863 StringExtractorGDBRemote response
;
864 m_gdb_comm
.SendPacketAndWaitForResponse(
865 entry
.c_str(), response
);
869 PlatformSP platform_sp
= GetTarget().GetPlatform();
871 handle_cmds(platform_sp
->GetExtraStartupCommands());
874 // Then dispatch any process commands:
875 handle_cmds(GetExtraStartupCommands());
880 void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec
&process_arch
) {
881 Log
*log
= GetLog(GDBRLog::Process
);
882 BuildDynamicRegisterInfo(false);
884 // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
885 // qProcessInfo as it will be more specific to our process.
887 const ArchSpec
&remote_process_arch
= m_gdb_comm
.GetProcessArchitecture();
888 if (remote_process_arch
.IsValid()) {
889 process_arch
= remote_process_arch
;
890 LLDB_LOG(log
, "gdb-remote had process architecture, using {0} {1}",
891 process_arch
.GetArchitectureName(),
892 process_arch
.GetTriple().getTriple());
894 process_arch
= m_gdb_comm
.GetHostArchitecture();
896 "gdb-remote did not have process architecture, using gdb-remote "
897 "host architecture {0} {1}",
898 process_arch
.GetArchitectureName(),
899 process_arch
.GetTriple().getTriple());
902 AddressableBits addressable_bits
= m_gdb_comm
.GetAddressableBits();
903 SetAddressableBitMasks(addressable_bits
);
905 if (process_arch
.IsValid()) {
906 const ArchSpec
&target_arch
= GetTarget().GetArchitecture();
907 if (target_arch
.IsValid()) {
908 LLDB_LOG(log
, "analyzing target arch, currently {0} {1}",
909 target_arch
.GetArchitectureName(),
910 target_arch
.GetTriple().getTriple());
912 // If the remote host is ARM and we have apple as the vendor, then
913 // ARM executables and shared libraries can have mixed ARM
915 // You can have an armv6 executable, and if the host is armv7, then the
916 // system will load the best possible architecture for all shared
917 // libraries it has, so we really need to take the remote host
918 // architecture as our defacto architecture in this case.
920 if ((process_arch
.GetMachine() == llvm::Triple::arm
||
921 process_arch
.GetMachine() == llvm::Triple::thumb
) &&
922 process_arch
.GetTriple().getVendor() == llvm::Triple::Apple
) {
923 GetTarget().SetArchitecture(process_arch
);
925 "remote process is ARM/Apple, "
926 "setting target arch to {0} {1}",
927 process_arch
.GetArchitectureName(),
928 process_arch
.GetTriple().getTriple());
930 // Fill in what is missing in the triple
931 const llvm::Triple
&remote_triple
= process_arch
.GetTriple();
932 llvm::Triple new_target_triple
= target_arch
.GetTriple();
933 if (new_target_triple
.getVendorName().size() == 0) {
934 new_target_triple
.setVendor(remote_triple
.getVendor());
936 if (new_target_triple
.getOSName().size() == 0) {
937 new_target_triple
.setOS(remote_triple
.getOS());
939 if (new_target_triple
.getEnvironmentName().size() == 0)
940 new_target_triple
.setEnvironment(remote_triple
.getEnvironment());
943 ArchSpec new_target_arch
= target_arch
;
944 new_target_arch
.SetTriple(new_target_triple
);
945 GetTarget().SetArchitecture(new_target_arch
);
950 "final target arch after adjustments for remote architecture: "
952 target_arch
.GetArchitectureName(),
953 target_arch
.GetTriple().getTriple());
955 // The target doesn't have a valid architecture yet, set it from the
956 // architecture we got from the remote GDB server
957 GetTarget().SetArchitecture(process_arch
);
961 // Target and Process are reasonably initailized;
962 // load any binaries we have metadata for / set load address.
964 MaybeLoadExecutableModule();
966 // Find out which StructuredDataPlugins are supported by the debug monitor.
967 // These plugins transmit data over async $J packets.
968 if (StructuredData::Array
*supported_packets
=
969 m_gdb_comm
.GetSupportedStructuredDataPlugins())
970 MapSupportedStructuredDataPlugins(*supported_packets
);
972 // If connected to LLDB ("native-signals+"), use signal defs for
973 // the remote platform. If connected to GDB, just use the standard set.
974 if (!m_gdb_comm
.UsesNativeSignals()) {
975 SetUnixSignals(std::make_shared
<GDBRemoteSignals
>());
977 PlatformSP platform_sp
= GetTarget().GetPlatform();
978 if (platform_sp
&& platform_sp
->IsConnected())
979 SetUnixSignals(platform_sp
->GetUnixSignals());
981 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
985 void ProcessGDBRemote::LoadStubBinaries() {
986 // The remote stub may know about the "main binary" in
987 // the context of a firmware debug session, and can
988 // give us a UUID and an address/slide of where the
989 // binary is loaded in memory.
990 UUID standalone_uuid
;
991 addr_t standalone_value
;
992 bool standalone_value_is_offset
;
993 if (m_gdb_comm
.GetProcessStandaloneBinary(standalone_uuid
, standalone_value
,
994 standalone_value_is_offset
)) {
997 if (standalone_uuid
.IsValid()) {
998 const bool force_symbol_search
= true;
999 const bool notify
= true;
1000 const bool set_address_in_target
= true;
1001 const bool allow_memory_image_last_resort
= false;
1002 DynamicLoader::LoadBinaryWithUUIDAndAddress(
1003 this, "", standalone_uuid
, standalone_value
,
1004 standalone_value_is_offset
, force_symbol_search
, notify
,
1005 set_address_in_target
, allow_memory_image_last_resort
);
1009 // The remote stub may know about a list of binaries to
1010 // force load into the process -- a firmware type situation
1011 // where multiple binaries are present in virtual memory,
1012 // and we are only given the addresses of the binaries.
1013 // Not intended for use with userland debugging, when we use
1014 // a DynamicLoader plugin that knows how to find the loaded
1015 // binaries, and will track updates as binaries are added.
1017 std::vector
<addr_t
> bin_addrs
= m_gdb_comm
.GetProcessStandaloneBinaries();
1018 if (bin_addrs
.size()) {
1020 const bool value_is_slide
= false;
1021 for (addr_t addr
: bin_addrs
) {
1022 const bool notify
= true;
1023 // First see if this is a special platform
1024 // binary that may determine the DynamicLoader and
1025 // Platform to be used in this Process and Target.
1029 .LoadPlatformBinaryAndSetup(this, addr
, notify
))
1032 const bool force_symbol_search
= true;
1033 const bool set_address_in_target
= true;
1034 const bool allow_memory_image_last_resort
= false;
1035 // Second manually load this binary into the Target.
1036 DynamicLoader::LoadBinaryWithUUIDAndAddress(
1037 this, llvm::StringRef(), uuid
, addr
, value_is_slide
,
1038 force_symbol_search
, notify
, set_address_in_target
,
1039 allow_memory_image_last_resort
);
1044 void ProcessGDBRemote::MaybeLoadExecutableModule() {
1045 ModuleSP module_sp
= GetTarget().GetExecutableModule();
1049 std::optional
<QOffsets
> offsets
= m_gdb_comm
.GetQOffsets();
1054 size_t(llvm::count(offsets
->offsets
, offsets
->offsets
[0])) ==
1055 offsets
->offsets
.size();
1057 return; // TODO: Handle non-uniform responses.
1059 bool changed
= false;
1060 module_sp
->SetLoadAddress(GetTarget(), offsets
->offsets
[0],
1061 /*value_is_offset=*/true, changed
);
1064 list
.Append(module_sp
);
1065 m_process
->GetTarget().ModulesDidLoad(list
);
1069 void ProcessGDBRemote::DidLaunch() {
1070 ArchSpec process_arch
;
1071 DidLaunchOrAttach(process_arch
);
1074 Status
ProcessGDBRemote::DoAttachToProcessWithID(
1075 lldb::pid_t attach_pid
, const ProcessAttachInfo
&attach_info
) {
1076 Log
*log
= GetLog(GDBRLog::Process
);
1079 LLDB_LOGF(log
, "ProcessGDBRemote::%s()", __FUNCTION__
);
1081 // Clear out and clean up from any current state
1083 if (attach_pid
!= LLDB_INVALID_PROCESS_ID
) {
1084 error
= EstablishConnectionIfNeeded(attach_info
);
1085 if (error
.Success()) {
1086 m_gdb_comm
.SetDetachOnError(attach_info
.GetDetachOnError());
1089 const int packet_len
=
1090 ::snprintf(packet
, sizeof(packet
), "vAttach;%" PRIx64
, attach_pid
);
1093 std::make_shared
<EventDataBytes
>(llvm::StringRef(packet
, packet_len
));
1094 m_async_broadcaster
.BroadcastEvent(eBroadcastBitAsyncContinue
, data_sp
);
1096 SetExitStatus(-1, error
.AsCString());
1102 Status
ProcessGDBRemote::DoAttachToProcessWithName(
1103 const char *process_name
, const ProcessAttachInfo
&attach_info
) {
1105 // Clear out and clean up from any current state
1108 if (process_name
&& process_name
[0]) {
1109 error
= EstablishConnectionIfNeeded(attach_info
);
1110 if (error
.Success()) {
1111 StreamString packet
;
1113 m_gdb_comm
.SetDetachOnError(attach_info
.GetDetachOnError());
1115 if (attach_info
.GetWaitForLaunch()) {
1116 if (!m_gdb_comm
.GetVAttachOrWaitSupported()) {
1117 packet
.PutCString("vAttachWait");
1119 if (attach_info
.GetIgnoreExisting())
1120 packet
.PutCString("vAttachWait");
1122 packet
.PutCString("vAttachOrWait");
1125 packet
.PutCString("vAttachName");
1126 packet
.PutChar(';');
1127 packet
.PutBytesAsRawHex8(process_name
, strlen(process_name
),
1128 endian::InlHostByteOrder(),
1129 endian::InlHostByteOrder());
1131 auto data_sp
= std::make_shared
<EventDataBytes
>(packet
.GetString());
1132 m_async_broadcaster
.BroadcastEvent(eBroadcastBitAsyncContinue
, data_sp
);
1135 SetExitStatus(-1, error
.AsCString());
1140 llvm::Expected
<TraceSupportedResponse
> ProcessGDBRemote::TraceSupported() {
1141 return m_gdb_comm
.SendTraceSupported(GetInterruptTimeout());
1144 llvm::Error
ProcessGDBRemote::TraceStop(const TraceStopRequest
&request
) {
1145 return m_gdb_comm
.SendTraceStop(request
, GetInterruptTimeout());
1148 llvm::Error
ProcessGDBRemote::TraceStart(const llvm::json::Value
&request
) {
1149 return m_gdb_comm
.SendTraceStart(request
, GetInterruptTimeout());
1152 llvm::Expected
<std::string
>
1153 ProcessGDBRemote::TraceGetState(llvm::StringRef type
) {
1154 return m_gdb_comm
.SendTraceGetState(type
, GetInterruptTimeout());
1157 llvm::Expected
<std::vector
<uint8_t>>
1158 ProcessGDBRemote::TraceGetBinaryData(const TraceGetBinaryDataRequest
&request
) {
1159 return m_gdb_comm
.SendTraceGetBinaryData(request
, GetInterruptTimeout());
1162 void ProcessGDBRemote::DidExit() {
1163 // When we exit, disconnect from the GDB server communications
1164 m_gdb_comm
.Disconnect();
1167 void ProcessGDBRemote::DidAttach(ArchSpec
&process_arch
) {
1168 // If you can figure out what the architecture is, fill it in here.
1169 process_arch
.Clear();
1170 DidLaunchOrAttach(process_arch
);
1173 Status
ProcessGDBRemote::WillResume() {
1174 m_continue_c_tids
.clear();
1175 m_continue_C_tids
.clear();
1176 m_continue_s_tids
.clear();
1177 m_continue_S_tids
.clear();
1178 m_jstopinfo_sp
.reset();
1179 m_jthreadsinfo_sp
.reset();
1183 Status
ProcessGDBRemote::DoResume() {
1185 Log
*log
= GetLog(GDBRLog::Process
);
1186 LLDB_LOGF(log
, "ProcessGDBRemote::Resume()");
1188 ListenerSP
listener_sp(
1189 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1190 if (listener_sp
->StartListeningForEvents(
1191 &m_gdb_comm
, GDBRemoteClientBase::eBroadcastBitRunPacketSent
)) {
1192 listener_sp
->StartListeningForEvents(
1193 &m_async_broadcaster
,
1194 ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit
);
1196 const size_t num_threads
= GetThreadList().GetSize();
1198 StreamString continue_packet
;
1199 bool continue_packet_error
= false;
1200 if (m_gdb_comm
.HasAnyVContSupport()) {
1201 std::string pid_prefix
;
1202 if (m_gdb_comm
.GetMultiprocessSupported())
1203 pid_prefix
= llvm::formatv("p{0:x-}.", GetID());
1205 if (m_continue_c_tids
.size() == num_threads
||
1206 (m_continue_c_tids
.empty() && m_continue_C_tids
.empty() &&
1207 m_continue_s_tids
.empty() && m_continue_S_tids
.empty())) {
1208 // All threads are continuing
1209 if (m_gdb_comm
.GetMultiprocessSupported())
1210 continue_packet
.Format("vCont;c:{0}-1", pid_prefix
);
1212 continue_packet
.PutCString("c");
1214 continue_packet
.PutCString("vCont");
1216 if (!m_continue_c_tids
.empty()) {
1217 if (m_gdb_comm
.GetVContSupported('c')) {
1218 for (tid_collection::const_iterator
1219 t_pos
= m_continue_c_tids
.begin(),
1220 t_end
= m_continue_c_tids
.end();
1221 t_pos
!= t_end
; ++t_pos
)
1222 continue_packet
.Format(";c:{0}{1:x-}", pid_prefix
, *t_pos
);
1224 continue_packet_error
= true;
1227 if (!continue_packet_error
&& !m_continue_C_tids
.empty()) {
1228 if (m_gdb_comm
.GetVContSupported('C')) {
1229 for (tid_sig_collection::const_iterator
1230 s_pos
= m_continue_C_tids
.begin(),
1231 s_end
= m_continue_C_tids
.end();
1232 s_pos
!= s_end
; ++s_pos
)
1233 continue_packet
.Format(";C{0:x-2}:{1}{2:x-}", s_pos
->second
,
1234 pid_prefix
, s_pos
->first
);
1236 continue_packet_error
= true;
1239 if (!continue_packet_error
&& !m_continue_s_tids
.empty()) {
1240 if (m_gdb_comm
.GetVContSupported('s')) {
1241 for (tid_collection::const_iterator
1242 t_pos
= m_continue_s_tids
.begin(),
1243 t_end
= m_continue_s_tids
.end();
1244 t_pos
!= t_end
; ++t_pos
)
1245 continue_packet
.Format(";s:{0}{1:x-}", pid_prefix
, *t_pos
);
1247 continue_packet_error
= true;
1250 if (!continue_packet_error
&& !m_continue_S_tids
.empty()) {
1251 if (m_gdb_comm
.GetVContSupported('S')) {
1252 for (tid_sig_collection::const_iterator
1253 s_pos
= m_continue_S_tids
.begin(),
1254 s_end
= m_continue_S_tids
.end();
1255 s_pos
!= s_end
; ++s_pos
)
1256 continue_packet
.Format(";S{0:x-2}:{1}{2:x-}", s_pos
->second
,
1257 pid_prefix
, s_pos
->first
);
1259 continue_packet_error
= true;
1262 if (continue_packet_error
)
1263 continue_packet
.Clear();
1266 continue_packet_error
= true;
1268 if (continue_packet_error
) {
1269 // Either no vCont support, or we tried to use part of the vCont packet
1270 // that wasn't supported by the remote GDB server. We need to try and
1271 // make a simple packet that can do our continue
1272 const size_t num_continue_c_tids
= m_continue_c_tids
.size();
1273 const size_t num_continue_C_tids
= m_continue_C_tids
.size();
1274 const size_t num_continue_s_tids
= m_continue_s_tids
.size();
1275 const size_t num_continue_S_tids
= m_continue_S_tids
.size();
1276 if (num_continue_c_tids
> 0) {
1277 if (num_continue_c_tids
== num_threads
) {
1278 // All threads are resuming...
1279 m_gdb_comm
.SetCurrentThreadForRun(-1);
1280 continue_packet
.PutChar('c');
1281 continue_packet_error
= false;
1282 } else if (num_continue_c_tids
== 1 && num_continue_C_tids
== 0 &&
1283 num_continue_s_tids
== 0 && num_continue_S_tids
== 0) {
1284 // Only one thread is continuing
1285 m_gdb_comm
.SetCurrentThreadForRun(m_continue_c_tids
.front());
1286 continue_packet
.PutChar('c');
1287 continue_packet_error
= false;
1291 if (continue_packet_error
&& num_continue_C_tids
> 0) {
1292 if ((num_continue_C_tids
+ num_continue_c_tids
) == num_threads
&&
1293 num_continue_C_tids
> 0 && num_continue_s_tids
== 0 &&
1294 num_continue_S_tids
== 0) {
1295 const int continue_signo
= m_continue_C_tids
.front().second
;
1296 // Only one thread is continuing
1297 if (num_continue_C_tids
> 1) {
1298 // More that one thread with a signal, yet we don't have vCont
1299 // support and we are being asked to resume each thread with a
1300 // signal, we need to make sure they are all the same signal, or we
1301 // can't issue the continue accurately with the current support...
1302 if (num_continue_C_tids
> 1) {
1303 continue_packet_error
= false;
1304 for (size_t i
= 1; i
< m_continue_C_tids
.size(); ++i
) {
1305 if (m_continue_C_tids
[i
].second
!= continue_signo
)
1306 continue_packet_error
= true;
1309 if (!continue_packet_error
)
1310 m_gdb_comm
.SetCurrentThreadForRun(-1);
1312 // Set the continue thread ID
1313 continue_packet_error
= false;
1314 m_gdb_comm
.SetCurrentThreadForRun(m_continue_C_tids
.front().first
);
1316 if (!continue_packet_error
) {
1317 // Add threads continuing with the same signo...
1318 continue_packet
.Printf("C%2.2x", continue_signo
);
1323 if (continue_packet_error
&& num_continue_s_tids
> 0) {
1324 if (num_continue_s_tids
== num_threads
) {
1325 // All threads are resuming...
1326 m_gdb_comm
.SetCurrentThreadForRun(-1);
1328 continue_packet
.PutChar('s');
1330 continue_packet_error
= false;
1331 } else if (num_continue_c_tids
== 0 && num_continue_C_tids
== 0 &&
1332 num_continue_s_tids
== 1 && num_continue_S_tids
== 0) {
1333 // Only one thread is stepping
1334 m_gdb_comm
.SetCurrentThreadForRun(m_continue_s_tids
.front());
1335 continue_packet
.PutChar('s');
1336 continue_packet_error
= false;
1340 if (!continue_packet_error
&& num_continue_S_tids
> 0) {
1341 if (num_continue_S_tids
== num_threads
) {
1342 const int step_signo
= m_continue_S_tids
.front().second
;
1343 // Are all threads trying to step with the same signal?
1344 continue_packet_error
= false;
1345 if (num_continue_S_tids
> 1) {
1346 for (size_t i
= 1; i
< num_threads
; ++i
) {
1347 if (m_continue_S_tids
[i
].second
!= step_signo
)
1348 continue_packet_error
= true;
1351 if (!continue_packet_error
) {
1352 // Add threads stepping with the same signo...
1353 m_gdb_comm
.SetCurrentThreadForRun(-1);
1354 continue_packet
.Printf("S%2.2x", step_signo
);
1356 } else if (num_continue_c_tids
== 0 && num_continue_C_tids
== 0 &&
1357 num_continue_s_tids
== 0 && num_continue_S_tids
== 1) {
1358 // Only one thread is stepping with signal
1359 m_gdb_comm
.SetCurrentThreadForRun(m_continue_S_tids
.front().first
);
1360 continue_packet
.Printf("S%2.2x", m_continue_S_tids
.front().second
);
1361 continue_packet_error
= false;
1366 if (continue_packet_error
) {
1368 Status::FromErrorString("can't make continue packet for this resume");
1371 if (!m_async_thread
.IsJoinable()) {
1372 error
= Status::FromErrorString(
1373 "Trying to resume but the async thread is dead.");
1374 LLDB_LOGF(log
, "ProcessGDBRemote::DoResume: Trying to resume but the "
1375 "async thread is dead.");
1380 std::make_shared
<EventDataBytes
>(continue_packet
.GetString());
1381 m_async_broadcaster
.BroadcastEvent(eBroadcastBitAsyncContinue
, data_sp
);
1383 if (!listener_sp
->GetEvent(event_sp
, std::chrono::seconds(5))) {
1384 error
= Status::FromErrorString("Resume timed out.");
1385 LLDB_LOGF(log
, "ProcessGDBRemote::DoResume: Resume timed out.");
1386 } else if (event_sp
->BroadcasterIs(&m_async_broadcaster
)) {
1387 error
= Status::FromErrorString(
1388 "Broadcast continue, but the async thread was "
1389 "killed before we got an ack back.");
1391 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1392 "async thread was killed before we got an ack back.");
1401 void ProcessGDBRemote::ClearThreadIDList() {
1402 std::lock_guard
<std::recursive_mutex
> guard(m_thread_list_real
.GetMutex());
1403 m_thread_ids
.clear();
1404 m_thread_pcs
.clear();
1407 size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(
1408 llvm::StringRef value
) {
1409 m_thread_ids
.clear();
1410 lldb::pid_t pid
= m_gdb_comm
.GetCurrentProcessID();
1411 StringExtractorGDBRemote thread_ids
{value
};
1414 auto pid_tid
= thread_ids
.GetPidTid(pid
);
1415 if (pid_tid
&& pid_tid
->first
== pid
) {
1416 lldb::tid_t tid
= pid_tid
->second
;
1417 if (tid
!= LLDB_INVALID_THREAD_ID
&&
1418 tid
!= StringExtractorGDBRemote::AllProcesses
)
1419 m_thread_ids
.push_back(tid
);
1421 } while (thread_ids
.GetChar() == ',');
1423 return m_thread_ids
.size();
1426 size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(
1427 llvm::StringRef value
) {
1428 m_thread_pcs
.clear();
1429 for (llvm::StringRef x
: llvm::split(value
, ',')) {
1431 if (llvm::to_integer(x
, pc
, 16))
1432 m_thread_pcs
.push_back(pc
);
1434 return m_thread_pcs
.size();
1437 bool ProcessGDBRemote::UpdateThreadIDList() {
1438 std::lock_guard
<std::recursive_mutex
> guard(m_thread_list_real
.GetMutex());
1440 if (m_jthreadsinfo_sp
) {
1441 // If we have the JSON threads info, we can get the thread list from that
1442 StructuredData::Array
*thread_infos
= m_jthreadsinfo_sp
->GetAsArray();
1443 if (thread_infos
&& thread_infos
->GetSize() > 0) {
1444 m_thread_ids
.clear();
1445 m_thread_pcs
.clear();
1446 thread_infos
->ForEach([this](StructuredData::Object
*object
) -> bool {
1447 StructuredData::Dictionary
*thread_dict
= object
->GetAsDictionary();
1449 // Set the thread stop info from the JSON dictionary
1450 SetThreadStopInfo(thread_dict
);
1451 lldb::tid_t tid
= LLDB_INVALID_THREAD_ID
;
1452 if (thread_dict
->GetValueForKeyAsInteger
<lldb::tid_t
>("tid", tid
))
1453 m_thread_ids
.push_back(tid
);
1455 return true; // Keep iterating through all thread_info objects
1458 if (!m_thread_ids
.empty())
1461 // See if we can get the thread IDs from the current stop reply packets
1462 // that might contain a "threads" key/value pair
1464 if (m_last_stop_packet
) {
1465 // Get the thread stop info
1466 StringExtractorGDBRemote
&stop_info
= *m_last_stop_packet
;
1467 const std::string
&stop_info_str
= std::string(stop_info
.GetStringRef());
1469 m_thread_pcs
.clear();
1470 const size_t thread_pcs_pos
= stop_info_str
.find(";thread-pcs:");
1471 if (thread_pcs_pos
!= std::string::npos
) {
1472 const size_t start
= thread_pcs_pos
+ strlen(";thread-pcs:");
1473 const size_t end
= stop_info_str
.find(';', start
);
1474 if (end
!= std::string::npos
) {
1475 std::string value
= stop_info_str
.substr(start
, end
- start
);
1476 UpdateThreadPCsFromStopReplyThreadsValue(value
);
1480 const size_t threads_pos
= stop_info_str
.find(";threads:");
1481 if (threads_pos
!= std::string::npos
) {
1482 const size_t start
= threads_pos
+ strlen(";threads:");
1483 const size_t end
= stop_info_str
.find(';', start
);
1484 if (end
!= std::string::npos
) {
1485 std::string value
= stop_info_str
.substr(start
, end
- start
);
1486 if (UpdateThreadIDsFromStopReplyThreadsValue(value
))
1493 bool sequence_mutex_unavailable
= false;
1494 m_gdb_comm
.GetCurrentThreadIDs(m_thread_ids
, sequence_mutex_unavailable
);
1495 if (sequence_mutex_unavailable
) {
1496 return false; // We just didn't get the list
1501 bool ProcessGDBRemote::DoUpdateThreadList(ThreadList
&old_thread_list
,
1502 ThreadList
&new_thread_list
) {
1503 // locker will keep a mutex locked until it goes out of scope
1504 Log
*log
= GetLog(GDBRLog::Thread
);
1505 LLDB_LOGV(log
, "pid = {0}", GetID());
1507 size_t num_thread_ids
= m_thread_ids
.size();
1508 // The "m_thread_ids" thread ID list should always be updated after each stop
1509 // reply packet, but in case it isn't, update it here.
1510 if (num_thread_ids
== 0) {
1511 if (!UpdateThreadIDList())
1513 num_thread_ids
= m_thread_ids
.size();
1516 ThreadList
old_thread_list_copy(old_thread_list
);
1517 if (num_thread_ids
> 0) {
1518 for (size_t i
= 0; i
< num_thread_ids
; ++i
) {
1519 lldb::tid_t tid
= m_thread_ids
[i
];
1521 old_thread_list_copy
.RemoveThreadByProtocolID(tid
, false));
1523 thread_sp
= std::make_shared
<ThreadGDBRemote
>(*this, tid
);
1524 LLDB_LOGV(log
, "Making new thread: {0} for thread ID: {1:x}.",
1525 thread_sp
.get(), thread_sp
->GetID());
1527 LLDB_LOGV(log
, "Found old thread: {0} for thread ID: {1:x}.",
1528 thread_sp
.get(), thread_sp
->GetID());
1531 SetThreadPc(thread_sp
, i
);
1532 new_thread_list
.AddThreadSortedByIndexID(thread_sp
);
1536 // Whatever that is left in old_thread_list_copy are not present in
1537 // new_thread_list. Remove non-existent threads from internal id table.
1538 size_t old_num_thread_ids
= old_thread_list_copy
.GetSize(false);
1539 for (size_t i
= 0; i
< old_num_thread_ids
; i
++) {
1540 ThreadSP
old_thread_sp(old_thread_list_copy
.GetThreadAtIndex(i
, false));
1541 if (old_thread_sp
) {
1542 lldb::tid_t old_thread_id
= old_thread_sp
->GetProtocolID();
1543 m_thread_id_to_index_id_map
.erase(old_thread_id
);
1550 void ProcessGDBRemote::SetThreadPc(const ThreadSP
&thread_sp
, uint64_t index
) {
1551 if (m_thread_ids
.size() == m_thread_pcs
.size() && thread_sp
.get() &&
1552 GetByteOrder() != eByteOrderInvalid
) {
1553 ThreadGDBRemote
*gdb_thread
=
1554 static_cast<ThreadGDBRemote
*>(thread_sp
.get());
1555 RegisterContextSP
reg_ctx_sp(thread_sp
->GetRegisterContext());
1557 uint32_t pc_regnum
= reg_ctx_sp
->ConvertRegisterKindToRegisterNumber(
1558 eRegisterKindGeneric
, LLDB_REGNUM_GENERIC_PC
);
1559 if (pc_regnum
!= LLDB_INVALID_REGNUM
) {
1560 gdb_thread
->PrivateSetRegisterValue(pc_regnum
, m_thread_pcs
[index
]);
1566 bool ProcessGDBRemote::GetThreadStopInfoFromJSON(
1567 ThreadGDBRemote
*thread
, const StructuredData::ObjectSP
&thread_infos_sp
) {
1568 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1570 if (thread_infos_sp
) {
1571 StructuredData::Array
*thread_infos
= thread_infos_sp
->GetAsArray();
1574 const size_t n
= thread_infos
->GetSize();
1575 for (size_t i
= 0; i
< n
; ++i
) {
1576 StructuredData::Dictionary
*thread_dict
=
1577 thread_infos
->GetItemAtIndex(i
)->GetAsDictionary();
1579 if (thread_dict
->GetValueForKeyAsInteger
<lldb::tid_t
>(
1580 "tid", tid
, LLDB_INVALID_THREAD_ID
)) {
1581 if (tid
== thread
->GetID())
1582 return (bool)SetThreadStopInfo(thread_dict
);
1591 bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote
*thread
) {
1592 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1594 if (GetThreadStopInfoFromJSON(thread
, m_jthreadsinfo_sp
))
1597 // See if we got thread stop info for any threads valid stop info reasons
1598 // threads via the "jstopinfo" packet stop reply packet key/value pair?
1599 if (m_jstopinfo_sp
) {
1600 // If we have "jstopinfo" then we have stop descriptions for all threads
1601 // that have stop reasons, and if there is no entry for a thread, then it
1602 // has no stop reason.
1603 if (!GetThreadStopInfoFromJSON(thread
, m_jstopinfo_sp
)) {
1604 // If a thread is stopped at a breakpoint site, set that as the stop
1605 // reason even if it hasn't executed the breakpoint instruction yet.
1606 // We will silently step over the breakpoint when we resume execution
1607 // and miss the fact that this thread hit the breakpoint.
1608 const size_t num_thread_ids
= m_thread_ids
.size();
1609 for (size_t i
= 0; i
< num_thread_ids
; i
++) {
1610 if (m_thread_ids
[i
] == thread
->GetID() && m_thread_pcs
.size() > i
) {
1611 addr_t pc
= m_thread_pcs
[i
];
1612 lldb::BreakpointSiteSP bp_site_sp
=
1613 thread
->GetProcess()->GetBreakpointSiteList().FindByAddress(pc
);
1615 if (bp_site_sp
->ValidForThisThread(*thread
)) {
1616 thread
->SetStopInfo(
1617 StopInfo::CreateStopReasonWithBreakpointSiteID(
1618 *thread
, bp_site_sp
->GetID()));
1624 thread
->SetStopInfo(StopInfoSP());
1629 // Fall back to using the qThreadStopInfo packet
1630 StringExtractorGDBRemote stop_packet
;
1631 if (GetGDBRemote().GetThreadStopInfo(thread
->GetProtocolID(), stop_packet
))
1632 return SetThreadStopInfo(stop_packet
) == eStateStopped
;
1636 void ProcessGDBRemote::ParseExpeditedRegisters(
1637 ExpeditedRegisterMap
&expedited_register_map
, ThreadSP thread_sp
) {
1638 ThreadGDBRemote
*gdb_thread
= static_cast<ThreadGDBRemote
*>(thread_sp
.get());
1639 RegisterContextSP
gdb_reg_ctx_sp(gdb_thread
->GetRegisterContext());
1641 for (const auto &pair
: expedited_register_map
) {
1642 StringExtractor
reg_value_extractor(pair
.second
);
1643 WritableDataBufferSP
buffer_sp(
1644 new DataBufferHeap(reg_value_extractor
.GetStringRef().size() / 2, 0));
1645 reg_value_extractor
.GetHexBytes(buffer_sp
->GetData(), '\xcc');
1646 uint32_t lldb_regnum
= gdb_reg_ctx_sp
->ConvertRegisterKindToRegisterNumber(
1647 eRegisterKindProcessPlugin
, pair
.first
);
1648 gdb_thread
->PrivateSetRegisterValue(lldb_regnum
, buffer_sp
->GetData());
1652 ThreadSP
ProcessGDBRemote::SetThreadStopInfo(
1653 lldb::tid_t tid
, ExpeditedRegisterMap
&expedited_register_map
,
1654 uint8_t signo
, const std::string
&thread_name
, const std::string
&reason
,
1655 const std::string
&description
, uint32_t exc_type
,
1656 const std::vector
<addr_t
> &exc_data
, addr_t thread_dispatch_qaddr
,
1657 bool queue_vars_valid
, // Set to true if queue_name, queue_kind and
1658 // queue_serial are valid
1659 LazyBool associated_with_dispatch_queue
, addr_t dispatch_queue_t
,
1660 std::string
&queue_name
, QueueKind queue_kind
, uint64_t queue_serial
) {
1662 if (tid
== LLDB_INVALID_THREAD_ID
)
1666 // Scope for "locker" below
1668 // m_thread_list_real does have its own mutex, but we need to hold onto the
1669 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1670 // m_thread_list_real.AddThread(...) so it doesn't change on us
1671 std::lock_guard
<std::recursive_mutex
> guard(m_thread_list_real
.GetMutex());
1672 thread_sp
= m_thread_list_real
.FindThreadByProtocolID(tid
, false);
1675 // Create the thread if we need to
1676 thread_sp
= std::make_shared
<ThreadGDBRemote
>(*this, tid
);
1677 m_thread_list_real
.AddThread(thread_sp
);
1681 ThreadGDBRemote
*gdb_thread
= static_cast<ThreadGDBRemote
*>(thread_sp
.get());
1682 RegisterContextSP
reg_ctx_sp(gdb_thread
->GetRegisterContext());
1684 reg_ctx_sp
->InvalidateIfNeeded(true);
1686 auto iter
= std::find(m_thread_ids
.begin(), m_thread_ids
.end(), tid
);
1687 if (iter
!= m_thread_ids
.end())
1688 SetThreadPc(thread_sp
, iter
- m_thread_ids
.begin());
1690 ParseExpeditedRegisters(expedited_register_map
, thread_sp
);
1692 if (reg_ctx_sp
->ReconfigureRegisterInfo()) {
1693 // Now we have changed the offsets of all the registers, so the values
1694 // will be corrupted.
1695 reg_ctx_sp
->InvalidateAllRegisters();
1696 // Expedited registers values will never contain registers that would be
1697 // resized by a reconfigure. So we are safe to continue using these
1699 ParseExpeditedRegisters(expedited_register_map
, thread_sp
);
1702 thread_sp
->SetName(thread_name
.empty() ? nullptr : thread_name
.c_str());
1704 gdb_thread
->SetThreadDispatchQAddr(thread_dispatch_qaddr
);
1705 // Check if the GDB server was able to provide the queue name, kind and serial
1707 if (queue_vars_valid
)
1708 gdb_thread
->SetQueueInfo(std::move(queue_name
), queue_kind
, queue_serial
,
1709 dispatch_queue_t
, associated_with_dispatch_queue
);
1711 gdb_thread
->ClearQueueInfo();
1713 gdb_thread
->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue
);
1715 if (dispatch_queue_t
!= LLDB_INVALID_ADDRESS
)
1716 gdb_thread
->SetQueueLibdispatchQueueAddress(dispatch_queue_t
);
1718 // Make sure we update our thread stop reason just once, but don't overwrite
1719 // the stop info for threads that haven't moved:
1720 StopInfoSP current_stop_info_sp
= thread_sp
->GetPrivateStopInfo(false);
1721 if (thread_sp
->GetTemporaryResumeState() == eStateSuspended
&&
1722 current_stop_info_sp
) {
1723 thread_sp
->SetStopInfo(current_stop_info_sp
);
1727 if (!thread_sp
->StopInfoIsUpToDate()) {
1728 thread_sp
->SetStopInfo(StopInfoSP());
1729 // If there's a memory thread backed by this thread, we need to use it to
1730 // calculate StopInfo.
1731 if (ThreadSP memory_thread_sp
= m_thread_list
.GetBackingThread(thread_sp
))
1732 thread_sp
= memory_thread_sp
;
1734 if (exc_type
!= 0) {
1735 // For thread plan async interrupt, creating stop info on the
1736 // original async interrupt request thread instead. If interrupt thread
1737 // does not exist anymore we fallback to current signal receiving thread
1739 ThreadSP interrupt_thread
;
1740 if (m_interrupt_tid
!= LLDB_INVALID_THREAD_ID
)
1741 interrupt_thread
= HandleThreadAsyncInterrupt(signo
, description
);
1742 if (interrupt_thread
)
1743 thread_sp
= interrupt_thread
;
1745 const size_t exc_data_size
= exc_data
.size();
1746 thread_sp
->SetStopInfo(
1747 StopInfoMachException::CreateStopReasonWithMachException(
1748 *thread_sp
, exc_type
, exc_data_size
,
1749 exc_data_size
>= 1 ? exc_data
[0] : 0,
1750 exc_data_size
>= 2 ? exc_data
[1] : 0,
1751 exc_data_size
>= 3 ? exc_data
[2] : 0));
1754 bool handled
= false;
1755 bool did_exec
= false;
1756 // debugserver can send reason = "none" which is equivalent
1758 if (!reason
.empty() && reason
!= "none") {
1759 if (reason
== "trace") {
1760 addr_t pc
= thread_sp
->GetRegisterContext()->GetPC();
1761 lldb::BreakpointSiteSP bp_site_sp
=
1762 thread_sp
->GetProcess()->GetBreakpointSiteList().FindByAddress(
1765 // If the current pc is a breakpoint site then the StopInfo should be
1766 // set to Breakpoint Otherwise, it will be set to Trace.
1767 if (bp_site_sp
&& bp_site_sp
->ValidForThisThread(*thread_sp
)) {
1768 thread_sp
->SetStopInfo(
1769 StopInfo::CreateStopReasonWithBreakpointSiteID(
1770 *thread_sp
, bp_site_sp
->GetID()));
1772 thread_sp
->SetStopInfo(
1773 StopInfo::CreateStopReasonToTrace(*thread_sp
));
1775 } else if (reason
== "breakpoint") {
1776 addr_t pc
= thread_sp
->GetRegisterContext()->GetPC();
1777 lldb::BreakpointSiteSP bp_site_sp
=
1778 thread_sp
->GetProcess()->GetBreakpointSiteList().FindByAddress(
1781 // If the breakpoint is for this thread, then we'll report the hit,
1782 // but if it is for another thread, we can just report no reason.
1783 // We don't need to worry about stepping over the breakpoint here,
1784 // that will be taken care of when the thread resumes and notices
1785 // that there's a breakpoint under the pc.
1787 if (bp_site_sp
->ValidForThisThread(*thread_sp
)) {
1788 thread_sp
->SetStopInfo(
1789 StopInfo::CreateStopReasonWithBreakpointSiteID(
1790 *thread_sp
, bp_site_sp
->GetID()));
1792 StopInfoSP invalid_stop_info_sp
;
1793 thread_sp
->SetStopInfo(invalid_stop_info_sp
);
1796 } else if (reason
== "trap") {
1797 // Let the trap just use the standard signal stop reason below...
1798 } else if (reason
== "watchpoint") {
1799 // We will have between 1 and 3 fields in the description.
1801 // \a wp_addr which is the original start address that
1802 // lldb requested be watched, or an address that the
1803 // hardware reported. This address should be within the
1804 // range of a currently active watchpoint region - lldb
1805 // should be able to find a watchpoint with this address.
1807 // \a wp_index is the hardware watchpoint register number.
1809 // \a wp_hit_addr is the actual address reported by the hardware,
1810 // which may be outside the range of a region we are watching.
1812 // On MIPS, we may get a false watchpoint exception where an
1813 // access to the same 8 byte granule as a watchpoint will trigger,
1814 // even if the access was not within the range of the watched
1815 // region. When we get a \a wp_hit_addr outside the range of any
1816 // set watchpoint, continue execution without making it visible to
1819 // On ARM, a related issue where a large access that starts
1820 // before the watched region (and extends into the watched
1821 // region) may report a hit address before the watched region.
1822 // lldb will not find the "nearest" watchpoint to
1823 // disable/step/re-enable it, so one of the valid watchpoint
1824 // addresses should be provided as \a wp_addr.
1825 StringExtractor
desc_extractor(description
.c_str());
1826 // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this
1828 // <address within wp range> <wp hw index> <actual accessed addr>
1829 // but this is not reading the <wp hw index>. Seems like it
1830 // wouldn't work on MIPS, where that third field is important.
1831 addr_t wp_addr
= desc_extractor
.GetU64(LLDB_INVALID_ADDRESS
);
1832 addr_t wp_hit_addr
= desc_extractor
.GetU64(LLDB_INVALID_ADDRESS
);
1833 watch_id_t watch_id
= LLDB_INVALID_WATCH_ID
;
1834 bool silently_continue
= false;
1835 WatchpointResourceSP wp_resource_sp
;
1836 if (wp_hit_addr
!= LLDB_INVALID_ADDRESS
) {
1838 m_watchpoint_resource_list
.FindByAddress(wp_hit_addr
);
1839 // On MIPS, \a wp_hit_addr outside the range of a watched
1840 // region means we should silently continue, it is a false hit.
1841 ArchSpec::Core core
= GetTarget().GetArchitecture().GetCore();
1842 if (!wp_resource_sp
&& core
>= ArchSpec::kCore_mips_first
&&
1843 core
<= ArchSpec::kCore_mips_last
)
1844 silently_continue
= true;
1846 if (!wp_resource_sp
&& wp_addr
!= LLDB_INVALID_ADDRESS
)
1847 wp_resource_sp
= m_watchpoint_resource_list
.FindByAddress(wp_addr
);
1848 if (!wp_resource_sp
) {
1849 Log
*log(GetLog(GDBRLog::Watchpoints
));
1850 LLDB_LOGF(log
, "failed to find watchpoint");
1851 watch_id
= LLDB_INVALID_SITE_ID
;
1853 // LWP_TODO: This is hardcoding a single Watchpoint in a
1854 // Resource, need to add
1855 // StopInfo::CreateStopReasonWithWatchpointResource which
1856 // represents all watchpoints that were tripped at this stop.
1857 watch_id
= wp_resource_sp
->GetConstituentAtIndex(0)->GetID();
1859 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1860 *thread_sp
, watch_id
, silently_continue
));
1862 } else if (reason
== "exception") {
1863 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonWithException(
1864 *thread_sp
, description
.c_str()));
1866 } else if (reason
== "exec") {
1868 thread_sp
->SetStopInfo(
1869 StopInfo::CreateStopReasonWithExec(*thread_sp
));
1871 } else if (reason
== "processor trace") {
1872 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1873 *thread_sp
, description
.c_str()));
1874 } else if (reason
== "fork") {
1875 StringExtractor
desc_extractor(description
.c_str());
1876 lldb::pid_t child_pid
=
1877 desc_extractor
.GetU64(LLDB_INVALID_PROCESS_ID
);
1878 lldb::tid_t child_tid
= desc_extractor
.GetU64(LLDB_INVALID_THREAD_ID
);
1879 thread_sp
->SetStopInfo(
1880 StopInfo::CreateStopReasonFork(*thread_sp
, child_pid
, child_tid
));
1882 } else if (reason
== "vfork") {
1883 StringExtractor
desc_extractor(description
.c_str());
1884 lldb::pid_t child_pid
=
1885 desc_extractor
.GetU64(LLDB_INVALID_PROCESS_ID
);
1886 lldb::tid_t child_tid
= desc_extractor
.GetU64(LLDB_INVALID_THREAD_ID
);
1887 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonVFork(
1888 *thread_sp
, child_pid
, child_tid
));
1890 } else if (reason
== "vforkdone") {
1891 thread_sp
->SetStopInfo(
1892 StopInfo::CreateStopReasonVForkDone(*thread_sp
));
1895 } else if (!signo
) {
1896 addr_t pc
= thread_sp
->GetRegisterContext()->GetPC();
1897 lldb::BreakpointSiteSP bp_site_sp
=
1898 thread_sp
->GetProcess()->GetBreakpointSiteList().FindByAddress(pc
);
1900 // If a thread is stopped at a breakpoint site, set that as the stop
1901 // reason even if it hasn't executed the breakpoint instruction yet.
1902 // We will silently step over the breakpoint when we resume execution
1903 // and miss the fact that this thread hit the breakpoint.
1904 if (bp_site_sp
&& bp_site_sp
->ValidForThisThread(*thread_sp
)) {
1905 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonWithBreakpointSiteID(
1906 *thread_sp
, bp_site_sp
->GetID()));
1911 if (!handled
&& signo
&& !did_exec
) {
1912 if (signo
== SIGTRAP
) {
1913 // Currently we are going to assume SIGTRAP means we are either
1914 // hitting a breakpoint or hardware single stepping.
1917 thread_sp
->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset
;
1918 lldb::BreakpointSiteSP bp_site_sp
=
1919 thread_sp
->GetProcess()->GetBreakpointSiteList().FindByAddress(
1923 // If the breakpoint is for this thread, then we'll report the hit,
1924 // but if it is for another thread, we can just report no reason.
1925 // We don't need to worry about stepping over the breakpoint here,
1926 // that will be taken care of when the thread resumes and notices
1927 // that there's a breakpoint under the pc.
1928 if (bp_site_sp
->ValidForThisThread(*thread_sp
)) {
1929 if (m_breakpoint_pc_offset
!= 0)
1930 thread_sp
->GetRegisterContext()->SetPC(pc
);
1931 thread_sp
->SetStopInfo(
1932 StopInfo::CreateStopReasonWithBreakpointSiteID(
1933 *thread_sp
, bp_site_sp
->GetID()));
1935 StopInfoSP invalid_stop_info_sp
;
1936 thread_sp
->SetStopInfo(invalid_stop_info_sp
);
1939 // If we were stepping then assume the stop was the result of the
1940 // trace. If we were not stepping then report the SIGTRAP.
1941 // FIXME: We are still missing the case where we single step over a
1942 // trap instruction.
1943 if (thread_sp
->GetTemporaryResumeState() == eStateStepping
)
1944 thread_sp
->SetStopInfo(
1945 StopInfo::CreateStopReasonToTrace(*thread_sp
));
1947 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1948 *thread_sp
, signo
, description
.c_str()));
1952 // For thread plan async interrupt, creating stop info on the
1953 // original async interrupt request thread instead. If interrupt
1954 // thread does not exist anymore we fallback to current signal
1955 // receiving thread instead.
1956 ThreadSP interrupt_thread
;
1957 if (m_interrupt_tid
!= LLDB_INVALID_THREAD_ID
)
1958 interrupt_thread
= HandleThreadAsyncInterrupt(signo
, description
);
1959 if (interrupt_thread
)
1960 thread_sp
= interrupt_thread
;
1962 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1963 *thread_sp
, signo
, description
.c_str()));
1967 if (!description
.empty()) {
1968 lldb::StopInfoSP
stop_info_sp(thread_sp
->GetStopInfo());
1970 const char *stop_info_desc
= stop_info_sp
->GetDescription();
1971 if (!stop_info_desc
|| !stop_info_desc
[0])
1972 stop_info_sp
->SetDescription(description
.c_str());
1974 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonWithException(
1975 *thread_sp
, description
.c_str()));
1984 ProcessGDBRemote::HandleThreadAsyncInterrupt(uint8_t signo
,
1985 const std::string
&description
) {
1988 std::lock_guard
<std::recursive_mutex
> guard(m_thread_list_real
.GetMutex());
1989 thread_sp
= m_thread_list_real
.FindThreadByProtocolID(m_interrupt_tid
,
1990 /*can_update=*/false);
1993 thread_sp
->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(
1994 *thread_sp
, signo
, description
.c_str()));
1995 // Clear m_interrupt_tid regardless we can find original interrupt thread or
1997 m_interrupt_tid
= LLDB_INVALID_THREAD_ID
;
2002 ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary
*thread_dict
) {
2003 static constexpr llvm::StringLiteral
g_key_tid("tid");
2004 static constexpr llvm::StringLiteral
g_key_name("name");
2005 static constexpr llvm::StringLiteral
g_key_reason("reason");
2006 static constexpr llvm::StringLiteral
g_key_metype("metype");
2007 static constexpr llvm::StringLiteral
g_key_medata("medata");
2008 static constexpr llvm::StringLiteral
g_key_qaddr("qaddr");
2009 static constexpr llvm::StringLiteral
g_key_dispatch_queue_t(
2010 "dispatch_queue_t");
2011 static constexpr llvm::StringLiteral
g_key_associated_with_dispatch_queue(
2012 "associated_with_dispatch_queue");
2013 static constexpr llvm::StringLiteral
g_key_queue_name("qname");
2014 static constexpr llvm::StringLiteral
g_key_queue_kind("qkind");
2015 static constexpr llvm::StringLiteral
g_key_queue_serial_number("qserialnum");
2016 static constexpr llvm::StringLiteral
g_key_registers("registers");
2017 static constexpr llvm::StringLiteral
g_key_memory("memory");
2018 static constexpr llvm::StringLiteral
g_key_description("description");
2019 static constexpr llvm::StringLiteral
g_key_signal("signal");
2021 // Stop with signal and thread info
2022 lldb::tid_t tid
= LLDB_INVALID_THREAD_ID
;
2025 std::string thread_name
;
2027 std::string description
;
2028 uint32_t exc_type
= 0;
2029 std::vector
<addr_t
> exc_data
;
2030 addr_t thread_dispatch_qaddr
= LLDB_INVALID_ADDRESS
;
2031 ExpeditedRegisterMap expedited_register_map
;
2032 bool queue_vars_valid
= false;
2033 addr_t dispatch_queue_t
= LLDB_INVALID_ADDRESS
;
2034 LazyBool associated_with_dispatch_queue
= eLazyBoolCalculate
;
2035 std::string queue_name
;
2036 QueueKind queue_kind
= eQueueKindUnknown
;
2037 uint64_t queue_serial_number
= 0;
2038 // Iterate through all of the thread dictionary key/value pairs from the
2039 // structured data dictionary
2041 // FIXME: we're silently ignoring invalid data here
2042 thread_dict
->ForEach([this, &tid
, &expedited_register_map
, &thread_name
,
2043 &signo
, &reason
, &description
, &exc_type
, &exc_data
,
2044 &thread_dispatch_qaddr
, &queue_vars_valid
,
2045 &associated_with_dispatch_queue
, &dispatch_queue_t
,
2046 &queue_name
, &queue_kind
, &queue_serial_number
](
2047 llvm::StringRef key
,
2048 StructuredData::Object
*object
) -> bool {
2049 if (key
== g_key_tid
) {
2050 // thread in big endian hex
2051 tid
= object
->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID
);
2052 } else if (key
== g_key_metype
) {
2053 // exception type in big endian hex
2054 exc_type
= object
->GetUnsignedIntegerValue(0);
2055 } else if (key
== g_key_medata
) {
2056 // exception data in big endian hex
2057 StructuredData::Array
*array
= object
->GetAsArray();
2059 array
->ForEach([&exc_data
](StructuredData::Object
*object
) -> bool {
2060 exc_data
.push_back(object
->GetUnsignedIntegerValue());
2061 return true; // Keep iterating through all array items
2064 } else if (key
== g_key_name
) {
2065 thread_name
= std::string(object
->GetStringValue());
2066 } else if (key
== g_key_qaddr
) {
2067 thread_dispatch_qaddr
=
2068 object
->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS
);
2069 } else if (key
== g_key_queue_name
) {
2070 queue_vars_valid
= true;
2071 queue_name
= std::string(object
->GetStringValue());
2072 } else if (key
== g_key_queue_kind
) {
2073 std::string queue_kind_str
= std::string(object
->GetStringValue());
2074 if (queue_kind_str
== "serial") {
2075 queue_vars_valid
= true;
2076 queue_kind
= eQueueKindSerial
;
2077 } else if (queue_kind_str
== "concurrent") {
2078 queue_vars_valid
= true;
2079 queue_kind
= eQueueKindConcurrent
;
2081 } else if (key
== g_key_queue_serial_number
) {
2082 queue_serial_number
= object
->GetUnsignedIntegerValue(0);
2083 if (queue_serial_number
!= 0)
2084 queue_vars_valid
= true;
2085 } else if (key
== g_key_dispatch_queue_t
) {
2086 dispatch_queue_t
= object
->GetUnsignedIntegerValue(0);
2087 if (dispatch_queue_t
!= 0 && dispatch_queue_t
!= LLDB_INVALID_ADDRESS
)
2088 queue_vars_valid
= true;
2089 } else if (key
== g_key_associated_with_dispatch_queue
) {
2090 queue_vars_valid
= true;
2091 bool associated
= object
->GetBooleanValue();
2093 associated_with_dispatch_queue
= eLazyBoolYes
;
2095 associated_with_dispatch_queue
= eLazyBoolNo
;
2096 } else if (key
== g_key_reason
) {
2097 reason
= std::string(object
->GetStringValue());
2098 } else if (key
== g_key_description
) {
2099 description
= std::string(object
->GetStringValue());
2100 } else if (key
== g_key_registers
) {
2101 StructuredData::Dictionary
*registers_dict
= object
->GetAsDictionary();
2103 if (registers_dict
) {
2104 registers_dict
->ForEach(
2105 [&expedited_register_map
](llvm::StringRef key
,
2106 StructuredData::Object
*object
) -> bool {
2108 if (llvm::to_integer(key
, reg
))
2109 expedited_register_map
[reg
] =
2110 std::string(object
->GetStringValue());
2111 return true; // Keep iterating through all array items
2114 } else if (key
== g_key_memory
) {
2115 StructuredData::Array
*array
= object
->GetAsArray();
2117 array
->ForEach([this](StructuredData::Object
*object
) -> bool {
2118 StructuredData::Dictionary
*mem_cache_dict
=
2119 object
->GetAsDictionary();
2120 if (mem_cache_dict
) {
2121 lldb::addr_t mem_cache_addr
= LLDB_INVALID_ADDRESS
;
2122 if (mem_cache_dict
->GetValueForKeyAsInteger
<lldb::addr_t
>(
2123 "address", mem_cache_addr
)) {
2124 if (mem_cache_addr
!= LLDB_INVALID_ADDRESS
) {
2125 llvm::StringRef str
;
2126 if (mem_cache_dict
->GetValueForKeyAsString("bytes", str
)) {
2127 StringExtractor
bytes(str
);
2128 bytes
.SetFilePos(0);
2130 const size_t byte_size
= bytes
.GetStringRef().size() / 2;
2131 WritableDataBufferSP
data_buffer_sp(
2132 new DataBufferHeap(byte_size
, 0));
2133 const size_t bytes_copied
=
2134 bytes
.GetHexBytes(data_buffer_sp
->GetData(), 0);
2135 if (bytes_copied
== byte_size
)
2136 m_memory_cache
.AddL1CacheData(mem_cache_addr
,
2142 return true; // Keep iterating through all array items
2146 } else if (key
== g_key_signal
)
2147 signo
= object
->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER
);
2148 return true; // Keep iterating through all dictionary key/value pairs
2151 return SetThreadStopInfo(tid
, expedited_register_map
, signo
, thread_name
,
2152 reason
, description
, exc_type
, exc_data
,
2153 thread_dispatch_qaddr
, queue_vars_valid
,
2154 associated_with_dispatch_queue
, dispatch_queue_t
,
2155 queue_name
, queue_kind
, queue_serial_number
);
2158 StateType
ProcessGDBRemote::SetThreadStopInfo(StringExtractor
&stop_packet
) {
2159 lldb::pid_t pid
= m_gdb_comm
.GetCurrentProcessID();
2160 stop_packet
.SetFilePos(0);
2161 const char stop_type
= stop_packet
.GetChar();
2162 switch (stop_type
) {
2165 // This is a bit of a hack, but it is required. If we did exec, we need to
2166 // clear our thread lists and also know to rebuild our dynamic register
2167 // info before we lookup and threads and populate the expedited register
2168 // values so we need to know this right away so we can cleanup and update
2170 const uint32_t stop_id
= GetStopID();
2172 // Our first stop, make sure we have a process ID, and also make sure we
2173 // know about our registers
2174 if (GetID() == LLDB_INVALID_PROCESS_ID
&& pid
!= LLDB_INVALID_PROCESS_ID
)
2176 BuildDynamicRegisterInfo(true);
2178 // Stop with signal and thread info
2179 lldb::pid_t stop_pid
= LLDB_INVALID_PROCESS_ID
;
2180 lldb::tid_t tid
= LLDB_INVALID_THREAD_ID
;
2181 const uint8_t signo
= stop_packet
.GetHexU8();
2182 llvm::StringRef key
;
2183 llvm::StringRef value
;
2184 std::string thread_name
;
2186 std::string description
;
2187 uint32_t exc_type
= 0;
2188 std::vector
<addr_t
> exc_data
;
2189 addr_t thread_dispatch_qaddr
= LLDB_INVALID_ADDRESS
;
2190 bool queue_vars_valid
=
2191 false; // says if locals below that start with "queue_" are valid
2192 addr_t dispatch_queue_t
= LLDB_INVALID_ADDRESS
;
2193 LazyBool associated_with_dispatch_queue
= eLazyBoolCalculate
;
2194 std::string queue_name
;
2195 QueueKind queue_kind
= eQueueKindUnknown
;
2196 uint64_t queue_serial_number
= 0;
2197 ExpeditedRegisterMap expedited_register_map
;
2198 AddressableBits addressable_bits
;
2199 while (stop_packet
.GetNameColonValue(key
, value
)) {
2200 if (key
.compare("metype") == 0) {
2201 // exception type in big endian hex
2202 value
.getAsInteger(16, exc_type
);
2203 } else if (key
.compare("medata") == 0) {
2204 // exception data in big endian hex
2206 value
.getAsInteger(16, x
);
2207 exc_data
.push_back(x
);
2208 } else if (key
.compare("thread") == 0) {
2210 StringExtractorGDBRemote thread_id
{value
};
2211 auto pid_tid
= thread_id
.GetPidTid(pid
);
2213 stop_pid
= pid_tid
->first
;
2214 tid
= pid_tid
->second
;
2216 tid
= LLDB_INVALID_THREAD_ID
;
2217 } else if (key
.compare("threads") == 0) {
2218 std::lock_guard
<std::recursive_mutex
> guard(
2219 m_thread_list_real
.GetMutex());
2220 UpdateThreadIDsFromStopReplyThreadsValue(value
);
2221 } else if (key
.compare("thread-pcs") == 0) {
2222 m_thread_pcs
.clear();
2223 // A comma separated list of all threads in the current
2224 // process that includes the thread for this stop reply packet
2226 while (!value
.empty()) {
2227 llvm::StringRef pc_str
;
2228 std::tie(pc_str
, value
) = value
.split(',');
2229 if (pc_str
.getAsInteger(16, pc
))
2230 pc
= LLDB_INVALID_ADDRESS
;
2231 m_thread_pcs
.push_back(pc
);
2233 } else if (key
.compare("jstopinfo") == 0) {
2234 StringExtractor
json_extractor(value
);
2236 // Now convert the HEX bytes into a string value
2237 json_extractor
.GetHexByteString(json
);
2239 // This JSON contains thread IDs and thread stop info for all threads.
2240 // It doesn't contain expedited registers, memory or queue info.
2241 m_jstopinfo_sp
= StructuredData::ParseJSON(json
);
2242 } else if (key
.compare("hexname") == 0) {
2243 StringExtractor
name_extractor(value
);
2245 // Now convert the HEX bytes into a string value
2246 name_extractor
.GetHexByteString(thread_name
);
2247 } else if (key
.compare("name") == 0) {
2248 thread_name
= std::string(value
);
2249 } else if (key
.compare("qaddr") == 0) {
2250 value
.getAsInteger(16, thread_dispatch_qaddr
);
2251 } else if (key
.compare("dispatch_queue_t") == 0) {
2252 queue_vars_valid
= true;
2253 value
.getAsInteger(16, dispatch_queue_t
);
2254 } else if (key
.compare("qname") == 0) {
2255 queue_vars_valid
= true;
2256 StringExtractor
name_extractor(value
);
2257 // Now convert the HEX bytes into a string value
2258 name_extractor
.GetHexByteString(queue_name
);
2259 } else if (key
.compare("qkind") == 0) {
2260 queue_kind
= llvm::StringSwitch
<QueueKind
>(value
)
2261 .Case("serial", eQueueKindSerial
)
2262 .Case("concurrent", eQueueKindConcurrent
)
2263 .Default(eQueueKindUnknown
);
2264 queue_vars_valid
= queue_kind
!= eQueueKindUnknown
;
2265 } else if (key
.compare("qserialnum") == 0) {
2266 if (!value
.getAsInteger(0, queue_serial_number
))
2267 queue_vars_valid
= true;
2268 } else if (key
.compare("reason") == 0) {
2269 reason
= std::string(value
);
2270 } else if (key
.compare("description") == 0) {
2271 StringExtractor
desc_extractor(value
);
2272 // Now convert the HEX bytes into a string value
2273 desc_extractor
.GetHexByteString(description
);
2274 } else if (key
.compare("memory") == 0) {
2275 // Expedited memory. GDB servers can choose to send back expedited
2276 // memory that can populate the L1 memory cache in the process so that
2277 // things like the frame pointer backchain can be expedited. This will
2278 // help stack backtracing be more efficient by not having to send as
2279 // many memory read requests down the remote GDB server.
2281 // Key/value pair format: memory:<addr>=<bytes>;
2282 // <addr> is a number whose base will be interpreted by the prefix:
2283 // "0x[0-9a-fA-F]+" for hex
2284 // "0[0-7]+" for octal
2285 // "[1-9]+" for decimal
2286 // <bytes> is native endian ASCII hex bytes just like the register
2288 llvm::StringRef addr_str
, bytes_str
;
2289 std::tie(addr_str
, bytes_str
) = value
.split('=');
2290 if (!addr_str
.empty() && !bytes_str
.empty()) {
2291 lldb::addr_t mem_cache_addr
= LLDB_INVALID_ADDRESS
;
2292 if (!addr_str
.getAsInteger(0, mem_cache_addr
)) {
2293 StringExtractor
bytes(bytes_str
);
2294 const size_t byte_size
= bytes
.GetBytesLeft() / 2;
2295 WritableDataBufferSP
data_buffer_sp(
2296 new DataBufferHeap(byte_size
, 0));
2297 const size_t bytes_copied
=
2298 bytes
.GetHexBytes(data_buffer_sp
->GetData(), 0);
2299 if (bytes_copied
== byte_size
)
2300 m_memory_cache
.AddL1CacheData(mem_cache_addr
, data_buffer_sp
);
2303 } else if (key
.compare("watch") == 0 || key
.compare("rwatch") == 0 ||
2304 key
.compare("awatch") == 0) {
2305 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2306 lldb::addr_t wp_addr
= LLDB_INVALID_ADDRESS
;
2307 value
.getAsInteger(16, wp_addr
);
2309 WatchpointResourceSP wp_resource_sp
=
2310 m_watchpoint_resource_list
.FindByAddress(wp_addr
);
2312 // Rewrite gdb standard watch/rwatch/awatch to
2313 // "reason:watchpoint" + "description:ADDR",
2314 // which is parsed in SetThreadStopInfo.
2315 reason
= "watchpoint";
2317 ostr
.Printf("%" PRIu64
, wp_addr
);
2318 description
= std::string(ostr
.GetString());
2319 } else if (key
.compare("swbreak") == 0 || key
.compare("hwbreak") == 0) {
2320 reason
= "breakpoint";
2321 } else if (key
.compare("library") == 0) {
2322 auto error
= LoadModules();
2324 Log
*log(GetLog(GDBRLog::Process
));
2325 LLDB_LOG_ERROR(log
, std::move(error
), "Failed to load modules: {0}");
2327 } else if (key
.compare("fork") == 0 || key
.compare("vfork") == 0) {
2328 // fork includes child pid/tid in thread-id format
2329 StringExtractorGDBRemote thread_id
{value
};
2330 auto pid_tid
= thread_id
.GetPidTid(LLDB_INVALID_PROCESS_ID
);
2332 Log
*log(GetLog(GDBRLog::Process
));
2333 LLDB_LOG(log
, "Invalid PID/TID to fork: {0}", value
);
2334 pid_tid
= {{LLDB_INVALID_PROCESS_ID
, LLDB_INVALID_THREAD_ID
}};
2339 ostr
.Printf("%" PRIu64
" %" PRIu64
, pid_tid
->first
, pid_tid
->second
);
2340 description
= std::string(ostr
.GetString());
2341 } else if (key
.compare("addressing_bits") == 0) {
2342 uint64_t addressing_bits
;
2343 if (!value
.getAsInteger(0, addressing_bits
)) {
2344 addressable_bits
.SetAddressableBits(addressing_bits
);
2346 } else if (key
.compare("low_mem_addressing_bits") == 0) {
2347 uint64_t addressing_bits
;
2348 if (!value
.getAsInteger(0, addressing_bits
)) {
2349 addressable_bits
.SetLowmemAddressableBits(addressing_bits
);
2351 } else if (key
.compare("high_mem_addressing_bits") == 0) {
2352 uint64_t addressing_bits
;
2353 if (!value
.getAsInteger(0, addressing_bits
)) {
2354 addressable_bits
.SetHighmemAddressableBits(addressing_bits
);
2356 } else if (key
.size() == 2 && ::isxdigit(key
[0]) && ::isxdigit(key
[1])) {
2357 uint32_t reg
= UINT32_MAX
;
2358 if (!key
.getAsInteger(16, reg
))
2359 expedited_register_map
[reg
] = std::string(std::move(value
));
2361 // swbreak and hwbreak are also expected keys, but we don't need to
2362 // change our behaviour for them because lldb always expects the remote
2363 // to adjust the program counter (if relevant, e.g., for x86 targets)
2366 if (stop_pid
!= LLDB_INVALID_PROCESS_ID
&& stop_pid
!= pid
) {
2367 Log
*log
= GetLog(GDBRLog::Process
);
2369 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2371 return eStateInvalid
;
2374 if (tid
== LLDB_INVALID_THREAD_ID
) {
2375 // A thread id may be invalid if the response is old style 'S' packet
2376 // which does not provide the
2377 // thread information. So update the thread list and choose the first
2379 UpdateThreadIDList();
2381 if (!m_thread_ids
.empty()) {
2382 tid
= m_thread_ids
.front();
2386 SetAddressableBitMasks(addressable_bits
);
2388 ThreadSP thread_sp
= SetThreadStopInfo(
2389 tid
, expedited_register_map
, signo
, thread_name
, reason
, description
,
2390 exc_type
, exc_data
, thread_dispatch_qaddr
, queue_vars_valid
,
2391 associated_with_dispatch_queue
, dispatch_queue_t
, queue_name
,
2392 queue_kind
, queue_serial_number
);
2394 return eStateStopped
;
2400 return eStateExited
;
2405 return eStateInvalid
;
2408 void ProcessGDBRemote::RefreshStateAfterStop() {
2409 std::lock_guard
<std::recursive_mutex
> guard(m_thread_list_real
.GetMutex());
2411 m_thread_ids
.clear();
2412 m_thread_pcs
.clear();
2414 // Set the thread stop info. It might have a "threads" key whose value is a
2415 // list of all thread IDs in the current process, so m_thread_ids might get
2417 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2418 if (m_thread_ids
.empty()) {
2419 // No, we need to fetch the thread list manually
2420 UpdateThreadIDList();
2423 // We might set some stop info's so make sure the thread list is up to
2424 // date before we do that or we might overwrite what was computed here.
2425 UpdateThreadListIfNeeded();
2427 if (m_last_stop_packet
)
2428 SetThreadStopInfo(*m_last_stop_packet
);
2429 m_last_stop_packet
.reset();
2431 // If we have queried for a default thread id
2432 if (m_initial_tid
!= LLDB_INVALID_THREAD_ID
) {
2433 m_thread_list
.SetSelectedThreadByID(m_initial_tid
);
2434 m_initial_tid
= LLDB_INVALID_THREAD_ID
;
2437 // Let all threads recover from stopping and do any clean up based on the
2438 // previous thread state (if any).
2439 m_thread_list_real
.RefreshStateAfterStop();
2442 Status
ProcessGDBRemote::DoHalt(bool &caused_stop
) {
2445 if (m_public_state
.GetValue() == eStateAttaching
) {
2446 // We are being asked to halt during an attach. We used to just close our
2447 // file handle and debugserver will go away, but with remote proxies, it
2448 // is better to send a positive signal, so let's send the interrupt first...
2449 caused_stop
= m_gdb_comm
.Interrupt(GetInterruptTimeout());
2450 m_gdb_comm
.Disconnect();
2452 caused_stop
= m_gdb_comm
.Interrupt(GetInterruptTimeout());
2456 Status
ProcessGDBRemote::DoDetach(bool keep_stopped
) {
2458 Log
*log
= GetLog(GDBRLog::Process
);
2459 LLDB_LOGF(log
, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped
);
2461 error
= m_gdb_comm
.Detach(keep_stopped
);
2463 if (error
.Success())
2465 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2468 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2469 error
.AsCString() ? error
.AsCString() : "<unknown error>");
2472 if (!error
.Success())
2475 // Sleep for one second to let the process get all detached...
2478 SetPrivateState(eStateDetached
);
2479 ResumePrivateStateThread();
2481 // KillDebugserverProcess ();
2485 Status
ProcessGDBRemote::DoDestroy() {
2486 Log
*log
= GetLog(GDBRLog::Process
);
2487 LLDB_LOGF(log
, "ProcessGDBRemote::DoDestroy()");
2489 // Interrupt if our inferior is running...
2490 int exit_status
= SIGABRT
;
2491 std::string exit_string
;
2493 if (m_gdb_comm
.IsConnected()) {
2494 if (m_public_state
.GetValue() != eStateAttaching
) {
2495 llvm::Expected
<int> kill_res
= m_gdb_comm
.KillProcess(GetID());
2498 exit_status
= kill_res
.get();
2499 #if defined(__APPLE__)
2500 // For Native processes on Mac OS X, we launch through the Host
2501 // Platform, then hand the process off to debugserver, which becomes
2502 // the parent process through "PT_ATTACH". Then when we go to kill
2503 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2504 // we call waitpid which returns with no error and the correct
2505 // status. But amusingly enough that doesn't seem to actually reap
2506 // the process, but instead it is left around as a Zombie. Probably
2507 // the kernel is in the process of switching ownership back to lldb
2508 // which was the original parent, and gets confused in the handoff.
2509 // Anyway, so call waitpid here to finally reap it.
2510 PlatformSP
platform_sp(GetTarget().GetPlatform());
2511 if (platform_sp
&& platform_sp
->IsHost()) {
2514 reap_pid
= waitpid(GetID(), &status
, WNOHANG
);
2515 LLDB_LOGF(log
, "Reaped pid: %d, status: %d.\n", reap_pid
, status
);
2518 ClearThreadIDList();
2519 exit_string
.assign("killed");
2521 exit_string
.assign(llvm::toString(kill_res
.takeError()));
2524 exit_string
.assign("killed or interrupted while attaching.");
2527 // If we missed setting the exit status on the way out, do it here.
2528 // NB set exit status can be called multiple times, the first one sets the
2530 exit_string
.assign("destroying when not connected to debugserver");
2533 SetExitStatus(exit_status
, exit_string
.c_str());
2536 KillDebugserverProcess();
2540 void ProcessGDBRemote::SetLastStopPacket(
2541 const StringExtractorGDBRemote
&response
) {
2542 const bool did_exec
=
2543 response
.GetStringRef().find(";reason:exec;") != std::string::npos
;
2545 Log
*log
= GetLog(GDBRLog::Process
);
2546 LLDB_LOGF(log
, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2548 m_thread_list_real
.Clear();
2549 m_thread_list
.Clear();
2550 BuildDynamicRegisterInfo(true);
2551 m_gdb_comm
.ResetDiscoverableSettings(did_exec
);
2554 m_last_stop_packet
= response
;
2557 void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP
&signals_sp
) {
2558 Process::SetUnixSignals(std::make_shared
<GDBRemoteSignals
>(signals_sp
));
2563 bool ProcessGDBRemote::IsAlive() {
2564 return m_gdb_comm
.IsConnected() && Process::IsAlive();
2567 addr_t
ProcessGDBRemote::GetImageInfoAddress() {
2568 // request the link map address via the $qShlibInfoAddr packet
2569 lldb::addr_t addr
= m_gdb_comm
.GetShlibInfoAddr();
2571 // the loaded module list can also provides a link map address
2572 if (addr
== LLDB_INVALID_ADDRESS
) {
2573 llvm::Expected
<LoadedModuleInfoList
> list
= GetLoadedModuleList();
2575 Log
*log
= GetLog(GDBRLog::Process
);
2576 LLDB_LOG_ERROR(log
, list
.takeError(), "Failed to read module list: {0}.");
2578 addr
= list
->m_link_map
;
2585 void ProcessGDBRemote::WillPublicStop() {
2586 // See if the GDB remote client supports the JSON threads info. If so, we
2587 // gather stop info for all threads, expedited registers, expedited memory,
2588 // runtime queue information (iOS and MacOSX only), and more. Expediting
2589 // memory will help stack backtracing be much faster. Expediting registers
2590 // will make sure we don't have to read the thread registers for GPRs.
2591 m_jthreadsinfo_sp
= m_gdb_comm
.GetThreadsInfo();
2593 if (m_jthreadsinfo_sp
) {
2594 // Now set the stop info for each thread and also expedite any registers
2595 // and memory that was in the jThreadsInfo response.
2596 StructuredData::Array
*thread_infos
= m_jthreadsinfo_sp
->GetAsArray();
2598 const size_t n
= thread_infos
->GetSize();
2599 for (size_t i
= 0; i
< n
; ++i
) {
2600 StructuredData::Dictionary
*thread_dict
=
2601 thread_infos
->GetItemAtIndex(i
)->GetAsDictionary();
2603 SetThreadStopInfo(thread_dict
);
2610 size_t ProcessGDBRemote::DoReadMemory(addr_t addr
, void *buf
, size_t size
,
2613 bool binary_memory_read
= m_gdb_comm
.GetxPacketSupported();
2614 // M and m packets take 2 bytes for 1 byte of memory
2615 size_t max_memory_size
=
2616 binary_memory_read
? m_max_memory_size
: m_max_memory_size
/ 2;
2617 if (size
> max_memory_size
) {
2618 // Keep memory read sizes down to a sane limit. This function will be
2619 // called multiple times in order to complete the task by
2620 // lldb_private::Process so it is ok to do this.
2621 size
= max_memory_size
;
2626 packet_len
= ::snprintf(packet
, sizeof(packet
), "%c%" PRIx64
",%" PRIx64
,
2627 binary_memory_read
? 'x' : 'm', (uint64_t)addr
,
2629 assert(packet_len
+ 1 < (int)sizeof(packet
));
2630 UNUSED_IF_ASSERT_DISABLED(packet_len
);
2631 StringExtractorGDBRemote response
;
2632 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
, response
,
2633 GetInterruptTimeout()) ==
2634 GDBRemoteCommunication::PacketResult::Success
) {
2635 if (response
.IsNormalResponse()) {
2637 if (binary_memory_read
) {
2638 // The lower level GDBRemoteCommunication packet receive layer has
2639 // already de-quoted any 0x7d character escaping that was present in
2642 size_t data_received_size
= response
.GetBytesLeft();
2643 if (data_received_size
> size
) {
2644 // Don't write past the end of BUF if the remote debug server gave us
2645 // too much data for some reason.
2646 data_received_size
= size
;
2648 memcpy(buf
, response
.GetStringRef().data(), data_received_size
);
2649 return data_received_size
;
2651 return response
.GetHexBytes(
2652 llvm::MutableArrayRef
<uint8_t>((uint8_t *)buf
, size
), '\xdd');
2654 } else if (response
.IsErrorResponse())
2655 error
= Status::FromErrorStringWithFormat(
2656 "memory read failed for 0x%" PRIx64
, addr
);
2657 else if (response
.IsUnsupportedResponse())
2658 error
= Status::FromErrorStringWithFormat(
2659 "GDB server does not support reading memory");
2661 error
= Status::FromErrorStringWithFormat(
2662 "unexpected response to GDB server memory read packet '%s': '%s'",
2663 packet
, response
.GetStringRef().data());
2665 error
= Status::FromErrorStringWithFormat("failed to send packet: '%s'",
2671 bool ProcessGDBRemote::SupportsMemoryTagging() {
2672 return m_gdb_comm
.GetMemoryTaggingSupported();
2675 llvm::Expected
<std::vector
<uint8_t>>
2676 ProcessGDBRemote::DoReadMemoryTags(lldb::addr_t addr
, size_t len
,
2678 // By this point ReadMemoryTags has validated that tagging is enabled
2679 // for this target/process/address.
2680 DataBufferSP buffer_sp
= m_gdb_comm
.ReadMemoryTags(addr
, len
, type
);
2682 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2683 "Error reading memory tags from remote");
2686 // Return the raw tag data
2687 llvm::ArrayRef
<uint8_t> tag_data
= buffer_sp
->GetData();
2688 std::vector
<uint8_t> got
;
2689 got
.reserve(tag_data
.size());
2690 std::copy(tag_data
.begin(), tag_data
.end(), std::back_inserter(got
));
2694 Status
ProcessGDBRemote::DoWriteMemoryTags(lldb::addr_t addr
, size_t len
,
2696 const std::vector
<uint8_t> &tags
) {
2697 // By now WriteMemoryTags should have validated that tagging is enabled
2698 // for this target/process.
2699 return m_gdb_comm
.WriteMemoryTags(addr
, len
, type
, tags
);
2702 Status
ProcessGDBRemote::WriteObjectFile(
2703 std::vector
<ObjectFile::LoadableData
> entries
) {
2705 // Sort the entries by address because some writes, like those to flash
2706 // memory, must happen in order of increasing address.
2708 std::begin(entries
), std::end(entries
),
2709 [](const ObjectFile::LoadableData a
, const ObjectFile::LoadableData b
) {
2710 return a
.Dest
< b
.Dest
;
2712 m_allow_flash_writes
= true;
2713 error
= Process::WriteObjectFile(entries
);
2714 if (error
.Success())
2715 error
= FlashDone();
2717 // Even though some of the writing failed, try to send a flash done if some
2718 // of the writing succeeded so the flash state is reset to normal, but
2719 // don't stomp on the error status that was set in the write failure since
2720 // that's the one we want to report back.
2722 m_allow_flash_writes
= false;
2726 bool ProcessGDBRemote::HasErased(FlashRange range
) {
2727 auto size
= m_erased_flash_ranges
.GetSize();
2728 for (size_t i
= 0; i
< size
; ++i
)
2729 if (m_erased_flash_ranges
.GetEntryAtIndex(i
)->Contains(range
))
2734 Status
ProcessGDBRemote::FlashErase(lldb::addr_t addr
, size_t size
) {
2737 MemoryRegionInfo region
;
2738 status
= GetMemoryRegionInfo(addr
, region
);
2739 if (!status
.Success())
2742 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2743 // but we'll disallow it to be safe and to keep the logic simple by worring
2744 // about only one region's block size. DoMemoryWrite is this function's
2745 // primary user, and it can easily keep writes within a single memory region
2746 if (addr
+ size
> region
.GetRange().GetRangeEnd()) {
2748 Status::FromErrorString("Unable to erase flash in multiple regions");
2752 uint64_t blocksize
= region
.GetBlocksize();
2753 if (blocksize
== 0) {
2755 Status::FromErrorString("Unable to erase flash because blocksize is 0");
2759 // Erasures can only be done on block boundary adresses, so round down addr
2760 // and round up size
2761 lldb::addr_t block_start_addr
= addr
- (addr
% blocksize
);
2762 size
+= (addr
- block_start_addr
);
2763 if ((size
% blocksize
) != 0)
2764 size
+= (blocksize
- size
% blocksize
);
2766 FlashRange
range(block_start_addr
, size
);
2768 if (HasErased(range
))
2771 // We haven't erased the entire range, but we may have erased part of it.
2772 // (e.g., block A is already erased and range starts in A and ends in B). So,
2773 // adjust range if necessary to exclude already erased blocks.
2774 if (!m_erased_flash_ranges
.IsEmpty()) {
2775 // Assuming that writes and erasures are done in increasing addr order,
2776 // because that is a requirement of the vFlashWrite command. Therefore, we
2777 // only need to look at the last range in the list for overlap.
2778 const auto &last_range
= *m_erased_flash_ranges
.Back();
2779 if (range
.GetRangeBase() < last_range
.GetRangeEnd()) {
2780 auto overlap
= last_range
.GetRangeEnd() - range
.GetRangeBase();
2781 // overlap will be less than range.GetByteSize() or else HasErased()
2782 // would have been true
2783 range
.SetByteSize(range
.GetByteSize() - overlap
);
2784 range
.SetRangeBase(range
.GetRangeBase() + overlap
);
2788 StreamString packet
;
2789 packet
.Printf("vFlashErase:%" PRIx64
",%" PRIx64
, range
.GetRangeBase(),
2790 (uint64_t)range
.GetByteSize());
2792 StringExtractorGDBRemote response
;
2793 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
.GetString(), response
,
2794 GetInterruptTimeout()) ==
2795 GDBRemoteCommunication::PacketResult::Success
) {
2796 if (response
.IsOKResponse()) {
2797 m_erased_flash_ranges
.Insert(range
, true);
2799 if (response
.IsErrorResponse())
2800 status
= Status::FromErrorStringWithFormat(
2801 "flash erase failed for 0x%" PRIx64
, addr
);
2802 else if (response
.IsUnsupportedResponse())
2803 status
= Status::FromErrorStringWithFormat(
2804 "GDB server does not support flashing");
2806 status
= Status::FromErrorStringWithFormat(
2807 "unexpected response to GDB server flash erase packet '%s': '%s'",
2808 packet
.GetData(), response
.GetStringRef().data());
2811 status
= Status::FromErrorStringWithFormat("failed to send packet: '%s'",
2817 Status
ProcessGDBRemote::FlashDone() {
2819 // If we haven't erased any blocks, then we must not have written anything
2820 // either, so there is no need to actually send a vFlashDone command
2821 if (m_erased_flash_ranges
.IsEmpty())
2823 StringExtractorGDBRemote response
;
2824 if (m_gdb_comm
.SendPacketAndWaitForResponse("vFlashDone", response
,
2825 GetInterruptTimeout()) ==
2826 GDBRemoteCommunication::PacketResult::Success
) {
2827 if (response
.IsOKResponse()) {
2828 m_erased_flash_ranges
.Clear();
2830 if (response
.IsErrorResponse())
2831 status
= Status::FromErrorStringWithFormat("flash done failed");
2832 else if (response
.IsUnsupportedResponse())
2833 status
= Status::FromErrorStringWithFormat(
2834 "GDB server does not support flashing");
2836 status
= Status::FromErrorStringWithFormat(
2837 "unexpected response to GDB server flash done packet: '%s'",
2838 response
.GetStringRef().data());
2842 Status::FromErrorStringWithFormat("failed to send flash done packet");
2847 size_t ProcessGDBRemote::DoWriteMemory(addr_t addr
, const void *buf
,
2848 size_t size
, Status
&error
) {
2850 // M and m packets take 2 bytes for 1 byte of memory
2851 size_t max_memory_size
= m_max_memory_size
/ 2;
2852 if (size
> max_memory_size
) {
2853 // Keep memory read sizes down to a sane limit. This function will be
2854 // called multiple times in order to complete the task by
2855 // lldb_private::Process so it is ok to do this.
2856 size
= max_memory_size
;
2859 StreamGDBRemote packet
;
2861 MemoryRegionInfo region
;
2862 Status region_status
= GetMemoryRegionInfo(addr
, region
);
2865 region_status
.Success() && region
.GetFlash() == MemoryRegionInfo::eYes
;
2868 if (!m_allow_flash_writes
) {
2869 error
= Status::FromErrorString("Writing to flash memory is not allowed");
2872 // Keep the write within a flash memory region
2873 if (addr
+ size
> region
.GetRange().GetRangeEnd())
2874 size
= region
.GetRange().GetRangeEnd() - addr
;
2875 // Flash memory must be erased before it can be written
2876 error
= FlashErase(addr
, size
);
2877 if (!error
.Success())
2879 packet
.Printf("vFlashWrite:%" PRIx64
":", addr
);
2880 packet
.PutEscapedBytes(buf
, size
);
2882 packet
.Printf("M%" PRIx64
",%" PRIx64
":", addr
, (uint64_t)size
);
2883 packet
.PutBytesAsRawHex8(buf
, size
, endian::InlHostByteOrder(),
2884 endian::InlHostByteOrder());
2886 StringExtractorGDBRemote response
;
2887 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
.GetString(), response
,
2888 GetInterruptTimeout()) ==
2889 GDBRemoteCommunication::PacketResult::Success
) {
2890 if (response
.IsOKResponse()) {
2893 } else if (response
.IsErrorResponse())
2894 error
= Status::FromErrorStringWithFormat(
2895 "memory write failed for 0x%" PRIx64
, addr
);
2896 else if (response
.IsUnsupportedResponse())
2897 error
= Status::FromErrorStringWithFormat(
2898 "GDB server does not support writing memory");
2900 error
= Status::FromErrorStringWithFormat(
2901 "unexpected response to GDB server memory write packet '%s': '%s'",
2902 packet
.GetData(), response
.GetStringRef().data());
2904 error
= Status::FromErrorStringWithFormat("failed to send packet: '%s'",
2910 lldb::addr_t
ProcessGDBRemote::DoAllocateMemory(size_t size
,
2911 uint32_t permissions
,
2913 Log
*log
= GetLog(LLDBLog::Process
| LLDBLog::Expressions
);
2914 addr_t allocated_addr
= LLDB_INVALID_ADDRESS
;
2916 if (m_gdb_comm
.SupportsAllocDeallocMemory() != eLazyBoolNo
) {
2917 allocated_addr
= m_gdb_comm
.AllocateMemory(size
, permissions
);
2918 if (allocated_addr
!= LLDB_INVALID_ADDRESS
||
2919 m_gdb_comm
.SupportsAllocDeallocMemory() == eLazyBoolYes
)
2920 return allocated_addr
;
2923 if (m_gdb_comm
.SupportsAllocDeallocMemory() == eLazyBoolNo
) {
2924 // Call mmap() to create memory in the inferior..
2926 if (permissions
& lldb::ePermissionsReadable
)
2927 prot
|= eMmapProtRead
;
2928 if (permissions
& lldb::ePermissionsWritable
)
2929 prot
|= eMmapProtWrite
;
2930 if (permissions
& lldb::ePermissionsExecutable
)
2931 prot
|= eMmapProtExec
;
2933 if (InferiorCallMmap(this, allocated_addr
, 0, size
, prot
,
2934 eMmapFlagsAnon
| eMmapFlagsPrivate
, -1, 0))
2935 m_addr_to_mmap_size
[allocated_addr
] = size
;
2937 allocated_addr
= LLDB_INVALID_ADDRESS
;
2939 "ProcessGDBRemote::%s no direct stub support for memory "
2940 "allocation, and InferiorCallMmap also failed - is stub "
2941 "missing register context save/restore capability?",
2946 if (allocated_addr
== LLDB_INVALID_ADDRESS
)
2947 error
= Status::FromErrorStringWithFormat(
2948 "unable to allocate %" PRIu64
" bytes of memory with permissions %s",
2949 (uint64_t)size
, GetPermissionsAsCString(permissions
));
2952 return allocated_addr
;
2955 Status
ProcessGDBRemote::DoGetMemoryRegionInfo(addr_t load_addr
,
2956 MemoryRegionInfo
®ion_info
) {
2958 Status
error(m_gdb_comm
.GetMemoryRegionInfo(load_addr
, region_info
));
2962 std::optional
<uint32_t> ProcessGDBRemote::GetWatchpointSlotCount() {
2963 return m_gdb_comm
.GetWatchpointSlotCount();
2966 std::optional
<bool> ProcessGDBRemote::DoGetWatchpointReportedAfter() {
2967 return m_gdb_comm
.GetWatchpointReportedAfter();
2970 Status
ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr
) {
2972 LazyBool supported
= m_gdb_comm
.SupportsAllocDeallocMemory();
2974 switch (supported
) {
2975 case eLazyBoolCalculate
:
2976 // We should never be deallocating memory without allocating memory first
2977 // so we should never get eLazyBoolCalculate
2978 error
= Status::FromErrorString(
2979 "tried to deallocate memory without ever allocating memory");
2983 if (!m_gdb_comm
.DeallocateMemory(addr
))
2984 error
= Status::FromErrorStringWithFormat(
2985 "unable to deallocate memory at 0x%" PRIx64
, addr
);
2989 // Call munmap() to deallocate memory in the inferior..
2991 MMapMap::iterator pos
= m_addr_to_mmap_size
.find(addr
);
2992 if (pos
!= m_addr_to_mmap_size
.end() &&
2993 InferiorCallMunmap(this, addr
, pos
->second
))
2994 m_addr_to_mmap_size
.erase(pos
);
2996 error
= Status::FromErrorStringWithFormat(
2997 "unable to deallocate memory at 0x%" PRIx64
, addr
);
3006 size_t ProcessGDBRemote::PutSTDIN(const char *src
, size_t src_len
,
3008 if (m_stdio_communication
.IsConnected()) {
3009 ConnectionStatus status
;
3010 m_stdio_communication
.WriteAll(src
, src_len
, status
, nullptr);
3011 } else if (m_stdin_forward
) {
3012 m_gdb_comm
.SendStdinNotification(src
, src_len
);
3017 Status
ProcessGDBRemote::EnableBreakpointSite(BreakpointSite
*bp_site
) {
3019 assert(bp_site
!= nullptr);
3022 Log
*log
= GetLog(GDBRLog::Breakpoints
);
3023 user_id_t site_id
= bp_site
->GetID();
3025 // Get the breakpoint address
3026 const addr_t addr
= bp_site
->GetLoadAddress();
3028 // Log that a breakpoint was requested
3030 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3031 ") address = 0x%" PRIx64
,
3032 site_id
, (uint64_t)addr
);
3034 // Breakpoint already exists and is enabled
3035 if (bp_site
->IsEnabled()) {
3037 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3038 ") address = 0x%" PRIx64
" -- SUCCESS (already enabled)",
3039 site_id
, (uint64_t)addr
);
3043 // Get the software breakpoint trap opcode size
3044 const size_t bp_op_size
= GetSoftwareBreakpointTrapOpcode(bp_site
);
3046 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3047 // breakpoint type is supported by the remote stub. These are set to true by
3048 // default, and later set to false only after we receive an unimplemented
3049 // response when sending a breakpoint packet. This means initially that
3050 // unless we were specifically instructed to use a hardware breakpoint, LLDB
3051 // will attempt to set a software breakpoint. HardwareRequired() also queries
3052 // a boolean variable which indicates if the user specifically asked for
3053 // hardware breakpoints. If true then we will skip over software
3055 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointSoftware
) &&
3056 (!bp_site
->HardwareRequired())) {
3057 // Try to send off a software breakpoint packet ($Z0)
3058 uint8_t error_no
= m_gdb_comm
.SendGDBStoppointTypePacket(
3059 eBreakpointSoftware
, true, addr
, bp_op_size
, GetInterruptTimeout());
3060 if (error_no
== 0) {
3061 // The breakpoint was placed successfully
3062 bp_site
->SetEnabled(true);
3063 bp_site
->SetType(BreakpointSite::eExternal
);
3067 // SendGDBStoppointTypePacket() will return an error if it was unable to
3068 // set this breakpoint. We need to differentiate between a error specific
3069 // to placing this breakpoint or if we have learned that this breakpoint
3070 // type is unsupported. To do this, we must test the support boolean for
3071 // this breakpoint type to see if it now indicates that this breakpoint
3072 // type is unsupported. If they are still supported then we should return
3073 // with the error code. If they are now unsupported, then we would like to
3074 // fall through and try another form of breakpoint.
3075 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointSoftware
)) {
3076 if (error_no
!= UINT8_MAX
)
3077 error
= Status::FromErrorStringWithFormat(
3078 "error: %d sending the breakpoint request", error_no
);
3080 error
= Status::FromErrorString("error sending the breakpoint request");
3084 // We reach here when software breakpoints have been found to be
3085 // unsupported. For future calls to set a breakpoint, we will not attempt
3086 // to set a breakpoint with a type that is known not to be supported.
3087 LLDB_LOGF(log
, "Software breakpoints are unsupported");
3089 // So we will fall through and try a hardware breakpoint
3092 // The process of setting a hardware breakpoint is much the same as above.
3093 // We check the supported boolean for this breakpoint type, and if it is
3094 // thought to be supported then we will try to set this breakpoint with a
3095 // hardware breakpoint.
3096 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointHardware
)) {
3097 // Try to send off a hardware breakpoint packet ($Z1)
3098 uint8_t error_no
= m_gdb_comm
.SendGDBStoppointTypePacket(
3099 eBreakpointHardware
, true, addr
, bp_op_size
, GetInterruptTimeout());
3100 if (error_no
== 0) {
3101 // The breakpoint was placed successfully
3102 bp_site
->SetEnabled(true);
3103 bp_site
->SetType(BreakpointSite::eHardware
);
3107 // Check if the error was something other then an unsupported breakpoint
3109 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointHardware
)) {
3110 // Unable to set this hardware breakpoint
3111 if (error_no
!= UINT8_MAX
)
3112 error
= Status::FromErrorStringWithFormat(
3113 "error: %d sending the hardware breakpoint request "
3114 "(hardware breakpoint resources might be exhausted or unavailable)",
3117 error
= Status::FromErrorString(
3118 "error sending the hardware breakpoint request "
3119 "(hardware breakpoint resources "
3120 "might be exhausted or unavailable)");
3124 // We will reach here when the stub gives an unsupported response to a
3125 // hardware breakpoint
3126 LLDB_LOGF(log
, "Hardware breakpoints are unsupported");
3128 // Finally we will falling through to a #trap style breakpoint
3131 // Don't fall through when hardware breakpoints were specifically requested
3132 if (bp_site
->HardwareRequired()) {
3133 error
= Status::FromErrorString("hardware breakpoints are not supported");
3137 // As a last resort we want to place a manual breakpoint. An instruction is
3138 // placed into the process memory using memory write packets.
3139 return EnableSoftwareBreakpoint(bp_site
);
3142 Status
ProcessGDBRemote::DisableBreakpointSite(BreakpointSite
*bp_site
) {
3144 assert(bp_site
!= nullptr);
3145 addr_t addr
= bp_site
->GetLoadAddress();
3146 user_id_t site_id
= bp_site
->GetID();
3147 Log
*log
= GetLog(GDBRLog::Breakpoints
);
3149 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3150 ") addr = 0x%8.8" PRIx64
,
3151 site_id
, (uint64_t)addr
);
3153 if (bp_site
->IsEnabled()) {
3154 const size_t bp_op_size
= GetSoftwareBreakpointTrapOpcode(bp_site
);
3156 BreakpointSite::Type bp_type
= bp_site
->GetType();
3158 case BreakpointSite::eSoftware
:
3159 error
= DisableSoftwareBreakpoint(bp_site
);
3162 case BreakpointSite::eHardware
:
3163 if (m_gdb_comm
.SendGDBStoppointTypePacket(eBreakpointHardware
, false,
3165 GetInterruptTimeout()))
3166 error
= Status::FromErrorString("unknown error");
3169 case BreakpointSite::eExternal
: {
3170 if (m_gdb_comm
.SendGDBStoppointTypePacket(eBreakpointSoftware
, false,
3172 GetInterruptTimeout()))
3173 error
= Status::FromErrorString("unknown error");
3176 if (error
.Success())
3177 bp_site
->SetEnabled(false);
3180 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3181 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3182 site_id
, (uint64_t)addr
);
3186 if (error
.Success())
3187 error
= Status::FromErrorString("unknown error");
3191 // Pre-requisite: wp != NULL.
3192 static GDBStoppointType
3193 GetGDBStoppointType(const WatchpointResourceSP
&wp_res_sp
) {
3195 bool read
= wp_res_sp
->WatchpointResourceRead();
3196 bool write
= wp_res_sp
->WatchpointResourceWrite();
3198 assert((read
|| write
) &&
3199 "WatchpointResource type is neither read nor write");
3201 return eWatchpointReadWrite
;
3203 return eWatchpointRead
;
3205 return eWatchpointWrite
;
3208 Status
ProcessGDBRemote::EnableWatchpoint(WatchpointSP wp_sp
, bool notify
) {
3211 error
= Status::FromErrorString("No watchpoint specified");
3214 user_id_t watchID
= wp_sp
->GetID();
3215 addr_t addr
= wp_sp
->GetLoadAddress();
3216 Log
*log(GetLog(GDBRLog::Watchpoints
));
3217 LLDB_LOGF(log
, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
")",
3219 if (wp_sp
->IsEnabled()) {
3221 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3222 ") addr = 0x%8.8" PRIx64
": watchpoint already enabled.",
3223 watchID
, (uint64_t)addr
);
3227 bool read
= wp_sp
->WatchpointRead();
3228 bool write
= wp_sp
->WatchpointWrite() || wp_sp
->WatchpointModify();
3229 size_t size
= wp_sp
->GetByteSize();
3231 ArchSpec target_arch
= GetTarget().GetArchitecture();
3232 WatchpointHardwareFeature supported_features
=
3233 m_gdb_comm
.GetSupportedWatchpointTypes();
3235 std::vector
<WatchpointResourceSP
> resources
=
3236 WatchpointAlgorithms::AtomizeWatchpointRequest(
3237 addr
, size
, read
, write
, supported_features
, target_arch
);
3239 // LWP_TODO: Now that we know the WP Resources needed to implement this
3240 // Watchpoint, we need to look at currently allocated Resources in the
3241 // Process and if they match, or are within the same memory granule, or
3242 // overlapping memory ranges, then we need to combine them. e.g. one
3243 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1
3244 // byte at 0x1003, they must use the same hardware watchpoint register
3245 // (Resource) to watch them.
3247 // This may mean that an existing resource changes its type (read to
3248 // read+write) or address range it is watching, in which case the old
3249 // watchpoint needs to be disabled and the new Resource addr/size/type
3250 // watchpoint enabled.
3252 // If we modify a shared Resource to accomodate this newly added Watchpoint,
3253 // and we are unable to set all of the Resources for it in the inferior, we
3254 // will return an error for this Watchpoint and the shared Resource should
3255 // be restored. e.g. this Watchpoint requires three Resources, one which
3256 // is shared with another Watchpoint. We extend the shared Resouce to
3257 // handle both Watchpoints and we try to set two new ones. But if we don't
3258 // have sufficient watchpoint register for all 3, we need to show an error
3259 // for creating this Watchpoint and we should reset the shared Resource to
3260 // its original configuration because it is no longer shared.
3262 bool set_all_resources
= true;
3263 std::vector
<WatchpointResourceSP
> succesfully_set_resources
;
3264 for (const auto &wp_res_sp
: resources
) {
3265 addr_t addr
= wp_res_sp
->GetLoadAddress();
3266 size_t size
= wp_res_sp
->GetByteSize();
3267 GDBStoppointType type
= GetGDBStoppointType(wp_res_sp
);
3268 if (!m_gdb_comm
.SupportsGDBStoppointPacket(type
) ||
3269 m_gdb_comm
.SendGDBStoppointTypePacket(type
, true, addr
, size
,
3270 GetInterruptTimeout())) {
3271 set_all_resources
= false;
3274 succesfully_set_resources
.push_back(wp_res_sp
);
3277 if (set_all_resources
) {
3278 wp_sp
->SetEnabled(true, notify
);
3279 for (const auto &wp_res_sp
: resources
) {
3280 // LWP_TODO: If we expanded/reused an existing Resource,
3281 // it's already in the WatchpointResourceList.
3282 wp_res_sp
->AddConstituent(wp_sp
);
3283 m_watchpoint_resource_list
.Add(wp_res_sp
);
3287 // We failed to allocate one of the resources. Unset all
3288 // of the new resources we did successfully set in the
3290 for (const auto &wp_res_sp
: succesfully_set_resources
) {
3291 addr_t addr
= wp_res_sp
->GetLoadAddress();
3292 size_t size
= wp_res_sp
->GetByteSize();
3293 GDBStoppointType type
= GetGDBStoppointType(wp_res_sp
);
3294 m_gdb_comm
.SendGDBStoppointTypePacket(type
, false, addr
, size
,
3295 GetInterruptTimeout());
3297 error
= Status::FromErrorString(
3298 "Setting one of the watchpoint resources failed");
3303 Status
ProcessGDBRemote::DisableWatchpoint(WatchpointSP wp_sp
, bool notify
) {
3306 error
= Status::FromErrorString("Watchpoint argument was NULL.");
3310 user_id_t watchID
= wp_sp
->GetID();
3312 Log
*log(GetLog(GDBRLog::Watchpoints
));
3314 addr_t addr
= wp_sp
->GetLoadAddress();
3317 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3318 ") addr = 0x%8.8" PRIx64
,
3319 watchID
, (uint64_t)addr
);
3321 if (!wp_sp
->IsEnabled()) {
3323 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3324 ") addr = 0x%8.8" PRIx64
" -- SUCCESS (already disabled)",
3325 watchID
, (uint64_t)addr
);
3326 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3327 // attempt might come from the user-supplied actions, we'll route it in
3328 // order for the watchpoint object to intelligently process this action.
3329 wp_sp
->SetEnabled(false, notify
);
3333 if (wp_sp
->IsHardware()) {
3334 bool disabled_all
= true;
3336 std::vector
<WatchpointResourceSP
> unused_resources
;
3337 for (const auto &wp_res_sp
: m_watchpoint_resource_list
.Sites()) {
3338 if (wp_res_sp
->ConstituentsContains(wp_sp
)) {
3339 GDBStoppointType type
= GetGDBStoppointType(wp_res_sp
);
3340 addr_t addr
= wp_res_sp
->GetLoadAddress();
3341 size_t size
= wp_res_sp
->GetByteSize();
3342 if (m_gdb_comm
.SendGDBStoppointTypePacket(type
, false, addr
, size
,
3343 GetInterruptTimeout())) {
3344 disabled_all
= false;
3346 wp_res_sp
->RemoveConstituent(wp_sp
);
3347 if (wp_res_sp
->GetNumberOfConstituents() == 0)
3348 unused_resources
.push_back(wp_res_sp
);
3352 for (auto &wp_res_sp
: unused_resources
)
3353 m_watchpoint_resource_list
.Remove(wp_res_sp
->GetID());
3355 wp_sp
->SetEnabled(false, notify
);
3357 error
= Status::FromErrorString(
3358 "Failure disabling one of the watchpoint locations");
3363 void ProcessGDBRemote::Clear() {
3364 m_thread_list_real
.Clear();
3365 m_thread_list
.Clear();
3368 Status
ProcessGDBRemote::DoSignal(int signo
) {
3370 Log
*log
= GetLog(GDBRLog::Process
);
3371 LLDB_LOGF(log
, "ProcessGDBRemote::DoSignal (signal = %d)", signo
);
3373 if (!m_gdb_comm
.SendAsyncSignal(signo
, GetInterruptTimeout()))
3375 Status::FromErrorStringWithFormat("failed to send signal %i", signo
);
3380 ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo
&process_info
) {
3381 // Make sure we aren't already connected?
3382 if (m_gdb_comm
.IsConnected())
3385 PlatformSP
platform_sp(GetTarget().GetPlatform());
3386 if (platform_sp
&& !platform_sp
->IsHost())
3387 return Status::FromErrorString("Lost debug server connection");
3389 auto error
= LaunchAndConnectToDebugserver(process_info
);
3391 const char *error_string
= error
.AsCString();
3392 if (error_string
== nullptr)
3393 error_string
= "unable to launch " DEBUGSERVER_BASENAME
;
3397 #if !defined(_WIN32)
3398 #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3401 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3402 static bool SetCloexecFlag(int fd
) {
3403 #if defined(FD_CLOEXEC)
3404 int flags
= ::fcntl(fd
, F_GETFD
);
3407 return (::fcntl(fd
, F_SETFD
, flags
| FD_CLOEXEC
) == 0);
3414 Status
ProcessGDBRemote::LaunchAndConnectToDebugserver(
3415 const ProcessInfo
&process_info
) {
3416 using namespace std::placeholders
; // For _1, _2, etc.
3419 if (m_debugserver_pid
== LLDB_INVALID_PROCESS_ID
) {
3420 // If we locate debugserver, keep that located version around
3421 static FileSpec g_debugserver_file_spec
;
3423 ProcessLaunchInfo debugserver_launch_info
;
3424 // Make debugserver run in its own session so signals generated by special
3425 // terminal key sequences (^C) don't affect debugserver.
3426 debugserver_launch_info
.SetLaunchInSeparateProcessGroup(true);
3428 const std::weak_ptr
<ProcessGDBRemote
> this_wp
=
3429 std::static_pointer_cast
<ProcessGDBRemote
>(shared_from_this());
3430 debugserver_launch_info
.SetMonitorProcessCallback(
3431 std::bind(MonitorDebugserverProcess
, this_wp
, _1
, _2
, _3
));
3432 debugserver_launch_info
.SetUserID(process_info
.GetUserID());
3434 #if defined(__APPLE__)
3435 // On macOS 11, we need to support x86_64 applications translated to
3436 // arm64. We check whether a binary is translated and spawn the correct
3437 // debugserver accordingly.
3438 int mib
[] = { CTL_KERN
, KERN_PROC
, KERN_PROC_PID
,
3439 static_cast<int>(process_info
.GetProcessID()) };
3440 struct kinfo_proc processInfo
;
3441 size_t bufsize
= sizeof(processInfo
);
3442 if (sysctl(mib
, (unsigned)(sizeof(mib
)/sizeof(int)), &processInfo
,
3443 &bufsize
, NULL
, 0) == 0 && bufsize
> 0) {
3444 if (processInfo
.kp_proc
.p_flag
& P_TRANSLATED
) {
3445 FileSpec
rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3446 debugserver_launch_info
.SetExecutableFile(rosetta_debugserver
, false);
3451 shared_fd_t communication_fd
= SharedSocket::kInvalidFD
;
3452 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3453 // Use a socketpair on non-Windows systems for security and performance
3455 int sockets
[2]; /* the pair of socket descriptors */
3456 if (socketpair(AF_UNIX
, SOCK_STREAM
, 0, sockets
) == -1) {
3457 error
= Status::FromErrno();
3461 int our_socket
= sockets
[0];
3462 int gdb_socket
= sockets
[1];
3463 auto cleanup_our
= llvm::make_scope_exit([&]() { close(our_socket
); });
3464 auto cleanup_gdb
= llvm::make_scope_exit([&]() { close(gdb_socket
); });
3466 // Don't let any child processes inherit our communication socket
3467 SetCloexecFlag(our_socket
);
3468 communication_fd
= gdb_socket
;
3471 error
= m_gdb_comm
.StartDebugserverProcess(
3472 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info
,
3473 nullptr, nullptr, communication_fd
);
3475 if (error
.Success())
3476 m_debugserver_pid
= debugserver_launch_info
.GetProcessID();
3478 m_debugserver_pid
= LLDB_INVALID_PROCESS_ID
;
3480 if (m_debugserver_pid
!= LLDB_INVALID_PROCESS_ID
) {
3481 #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3482 // Our process spawned correctly, we can now set our connection to use
3483 // our end of the socket pair
3484 cleanup_our
.release();
3485 m_gdb_comm
.SetConnection(
3486 std::make_unique
<ConnectionFileDescriptor
>(our_socket
, true));
3492 Log
*log
= GetLog(GDBRLog::Process
);
3494 LLDB_LOGF(log
, "failed to start debugserver process: %s",
3499 if (m_gdb_comm
.IsConnected()) {
3500 // Finish the connection process by doing the handshake without
3501 // connecting (send NULL URL)
3502 error
= ConnectToDebugserver("");
3504 error
= Status::FromErrorString("connection failed");
3510 void ProcessGDBRemote::MonitorDebugserverProcess(
3511 std::weak_ptr
<ProcessGDBRemote
> process_wp
, lldb::pid_t debugserver_pid
,
3512 int signo
, // Zero for no signal
3513 int exit_status
// Exit value of process if signal is zero
3515 // "debugserver_pid" argument passed in is the process ID for debugserver
3516 // that we are tracking...
3517 Log
*log
= GetLog(GDBRLog::Process
);
3520 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3521 ", signo=%i (0x%x), exit_status=%i)",
3522 __FUNCTION__
, debugserver_pid
, signo
, signo
, exit_status
);
3524 std::shared_ptr
<ProcessGDBRemote
> process_sp
= process_wp
.lock();
3525 LLDB_LOGF(log
, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__
,
3526 static_cast<void *>(process_sp
.get()));
3527 if (!process_sp
|| process_sp
->m_debugserver_pid
!= debugserver_pid
)
3530 // Sleep for a half a second to make sure our inferior process has time to
3531 // set its exit status before we set it incorrectly when both the debugserver
3532 // and the inferior process shut down.
3533 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3535 // If our process hasn't yet exited, debugserver might have died. If the
3536 // process did exit, then we are reaping it.
3537 const StateType state
= process_sp
->GetState();
3539 if (state
!= eStateInvalid
&& state
!= eStateUnloaded
&&
3540 state
!= eStateExited
&& state
!= eStateDetached
) {
3541 StreamString stream
;
3543 stream
.Format(DEBUGSERVER_BASENAME
" died with an exit status of {0:x8}",
3546 llvm::StringRef signal_name
=
3547 process_sp
->GetUnixSignals()->GetSignalAsStringRef(signo
);
3548 const char *format_str
= DEBUGSERVER_BASENAME
" died with signal {0}";
3549 if (!signal_name
.empty())
3550 stream
.Format(format_str
, signal_name
);
3552 stream
.Format(format_str
, signo
);
3554 process_sp
->SetExitStatus(-1, stream
.GetString());
3556 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3557 // longer has a debugserver instance
3558 process_sp
->m_debugserver_pid
= LLDB_INVALID_PROCESS_ID
;
3561 void ProcessGDBRemote::KillDebugserverProcess() {
3562 m_gdb_comm
.Disconnect();
3563 if (m_debugserver_pid
!= LLDB_INVALID_PROCESS_ID
) {
3564 Host::Kill(m_debugserver_pid
, SIGINT
);
3565 m_debugserver_pid
= LLDB_INVALID_PROCESS_ID
;
3569 void ProcessGDBRemote::Initialize() {
3570 static llvm::once_flag g_once_flag
;
3572 llvm::call_once(g_once_flag
, []() {
3573 PluginManager::RegisterPlugin(GetPluginNameStatic(),
3574 GetPluginDescriptionStatic(), CreateInstance
,
3575 DebuggerInitialize
);
3579 void ProcessGDBRemote::DebuggerInitialize(Debugger
&debugger
) {
3580 if (!PluginManager::GetSettingForProcessPlugin(
3581 debugger
, PluginProperties::GetSettingName())) {
3582 const bool is_global_setting
= true;
3583 PluginManager::CreateSettingForProcessPlugin(
3584 debugger
, GetGlobalPluginProperties().GetValueProperties(),
3585 "Properties for the gdb-remote process plug-in.", is_global_setting
);
3589 bool ProcessGDBRemote::StartAsyncThread() {
3590 Log
*log
= GetLog(GDBRLog::Process
);
3592 LLDB_LOGF(log
, "ProcessGDBRemote::%s ()", __FUNCTION__
);
3594 std::lock_guard
<std::recursive_mutex
> guard(m_async_thread_state_mutex
);
3595 if (!m_async_thread
.IsJoinable()) {
3596 // Create a thread that watches our internal state and controls which
3597 // events make it to clients (into the DCProcess event queue).
3599 llvm::Expected
<HostThread
> async_thread
=
3600 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3601 return ProcessGDBRemote::AsyncThread();
3603 if (!async_thread
) {
3604 LLDB_LOG_ERROR(GetLog(LLDBLog::Host
), async_thread
.takeError(),
3605 "failed to launch host thread: {0}");
3608 m_async_thread
= *async_thread
;
3611 "ProcessGDBRemote::%s () - Called when Async thread was "
3615 return m_async_thread
.IsJoinable();
3618 void ProcessGDBRemote::StopAsyncThread() {
3619 Log
*log
= GetLog(GDBRLog::Process
);
3621 LLDB_LOGF(log
, "ProcessGDBRemote::%s ()", __FUNCTION__
);
3623 std::lock_guard
<std::recursive_mutex
> guard(m_async_thread_state_mutex
);
3624 if (m_async_thread
.IsJoinable()) {
3625 m_async_broadcaster
.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit
);
3627 // This will shut down the async thread.
3628 m_gdb_comm
.Disconnect(); // Disconnect from the debug server.
3630 // Stop the stdio thread
3631 m_async_thread
.Join(nullptr);
3632 m_async_thread
.Reset();
3636 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3640 thread_result_t
ProcessGDBRemote::AsyncThread() {
3641 Log
*log
= GetLog(GDBRLog::Process
);
3642 LLDB_LOGF(log
, "ProcessGDBRemote::%s(pid = %" PRIu64
") thread starting...",
3643 __FUNCTION__
, GetID());
3647 // We need to ignore any packets that come in after we have
3648 // have decided the process has exited. There are some
3649 // situations, for instance when we try to interrupt a running
3650 // process and the interrupt fails, where another packet might
3651 // get delivered after we've decided to give up on the process.
3652 // But once we've decided we are done with the process we will
3653 // not be in a state to do anything useful with new packets.
3654 // So it is safer to simply ignore any remaining packets by
3655 // explicitly checking for eStateExited before reentering the
3659 while (!done
&& GetPrivateState() != eStateExited
) {
3661 "ProcessGDBRemote::%s(pid = %" PRIu64
3662 ") listener.WaitForEvent (NULL, event_sp)...",
3663 __FUNCTION__
, GetID());
3665 if (m_async_listener_sp
->GetEvent(event_sp
, std::nullopt
)) {
3666 const uint32_t event_type
= event_sp
->GetType();
3667 if (event_sp
->BroadcasterIs(&m_async_broadcaster
)) {
3669 "ProcessGDBRemote::%s(pid = %" PRIu64
3670 ") Got an event of type: %d...",
3671 __FUNCTION__
, GetID(), event_type
);
3673 switch (event_type
) {
3674 case eBroadcastBitAsyncContinue
: {
3675 const EventDataBytes
*continue_packet
=
3676 EventDataBytes::GetEventDataFromEvent(event_sp
.get());
3678 if (continue_packet
) {
3679 const char *continue_cstr
=
3680 (const char *)continue_packet
->GetBytes();
3681 const size_t continue_cstr_len
= continue_packet
->GetByteSize();
3683 "ProcessGDBRemote::%s(pid = %" PRIu64
3684 ") got eBroadcastBitAsyncContinue: %s",
3685 __FUNCTION__
, GetID(), continue_cstr
);
3687 if (::strstr(continue_cstr
, "vAttach") == nullptr)
3688 SetPrivateState(eStateRunning
);
3689 StringExtractorGDBRemote response
;
3691 StateType stop_state
=
3692 GetGDBRemote().SendContinuePacketAndWaitForResponse(
3693 *this, *GetUnixSignals(),
3694 llvm::StringRef(continue_cstr
, continue_cstr_len
),
3695 GetInterruptTimeout(), response
);
3697 // We need to immediately clear the thread ID list so we are sure
3698 // to get a valid list of threads. The thread ID list might be
3699 // contained within the "response", or the stop reply packet that
3700 // caused the stop. So clear it now before we give the stop reply
3701 // packet to the process using the
3702 // SetLastStopPacket()...
3703 ClearThreadIDList();
3705 switch (stop_state
) {
3708 case eStateSuspended
:
3709 SetLastStopPacket(response
);
3710 SetPrivateState(stop_state
);
3713 case eStateExited
: {
3714 SetLastStopPacket(response
);
3715 ClearThreadIDList();
3716 response
.SetFilePos(1);
3718 int exit_status
= response
.GetHexU8();
3719 std::string desc_string
;
3720 if (response
.GetBytesLeft() > 0 && response
.GetChar('-') == ';') {
3721 llvm::StringRef desc_str
;
3722 llvm::StringRef desc_token
;
3723 while (response
.GetNameColonValue(desc_token
, desc_str
)) {
3724 if (desc_token
!= "description")
3726 StringExtractor
extractor(desc_str
);
3727 extractor
.GetHexByteString(desc_string
);
3730 SetExitStatus(exit_status
, desc_string
.c_str());
3734 case eStateInvalid
: {
3735 // Check to see if we were trying to attach and if we got back
3736 // the "E87" error code from debugserver -- this indicates that
3737 // the process is not debuggable. Return a slightly more
3738 // helpful error message about why the attach failed.
3739 if (::strstr(continue_cstr
, "vAttach") != nullptr &&
3740 response
.GetError() == 0x87) {
3741 SetExitStatus(-1, "cannot attach to process due to "
3742 "System Integrity Protection");
3743 } else if (::strstr(continue_cstr
, "vAttach") != nullptr &&
3744 response
.GetStatus().Fail()) {
3745 SetExitStatus(-1, response
.GetStatus().AsCString());
3747 SetExitStatus(-1, "lost connection");
3754 SetPrivateState(stop_state
);
3756 } // switch(stop_state)
3757 } // if (continue_packet)
3758 } // case eBroadcastBitAsyncContinue
3761 case eBroadcastBitAsyncThreadShouldExit
:
3763 "ProcessGDBRemote::%s(pid = %" PRIu64
3764 ") got eBroadcastBitAsyncThreadShouldExit...",
3765 __FUNCTION__
, GetID());
3771 "ProcessGDBRemote::%s(pid = %" PRIu64
3772 ") got unknown event 0x%8.8x",
3773 __FUNCTION__
, GetID(), event_type
);
3780 "ProcessGDBRemote::%s(pid = %" PRIu64
3781 ") listener.WaitForEvent (NULL, event_sp) => false",
3782 __FUNCTION__
, GetID());
3787 LLDB_LOGF(log
, "ProcessGDBRemote::%s(pid = %" PRIu64
") thread exiting...",
3788 __FUNCTION__
, GetID());
3794 // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3795 // &matches, std::vector<lldb::pid_t> &pids)
3797 // // If we are planning to launch the debugserver remotely, then we need to
3798 // fire up a debugserver
3799 // // process and ask it for the list of processes. But if we are local, we
3800 // can let the Host do it.
3801 // if (m_local_debugserver)
3803 // return Host::ListProcessesMatchingName (name, matches, pids);
3807 // // FIXME: Implement talking to the remote debugserver.
3813 bool ProcessGDBRemote::NewThreadNotifyBreakpointHit(
3814 void *baton
, StoppointCallbackContext
*context
, lldb::user_id_t break_id
,
3815 lldb::user_id_t break_loc_id
) {
3816 // I don't think I have to do anything here, just make sure I notice the new
3817 // thread when it starts to
3818 // run so I can stop it if that's what I want to do.
3819 Log
*log
= GetLog(LLDBLog::Step
);
3820 LLDB_LOGF(log
, "Hit New Thread Notification breakpoint.");
3824 Status
ProcessGDBRemote::UpdateAutomaticSignalFiltering() {
3825 Log
*log
= GetLog(GDBRLog::Process
);
3826 LLDB_LOG(log
, "Check if need to update ignored signals");
3828 // QPassSignals package is not supported by the server, there is no way we
3829 // can ignore any signals on server side.
3830 if (!m_gdb_comm
.GetQPassSignalsSupported())
3833 // No signals, nothing to send.
3834 if (m_unix_signals_sp
== nullptr)
3837 // Signals' version hasn't changed, no need to send anything.
3838 uint64_t new_signals_version
= m_unix_signals_sp
->GetVersion();
3839 if (new_signals_version
== m_last_signals_version
) {
3840 LLDB_LOG(log
, "Signals' version hasn't changed. version={0}",
3841 m_last_signals_version
);
3845 auto signals_to_ignore
=
3846 m_unix_signals_sp
->GetFilteredSignals(false, false, false);
3847 Status error
= m_gdb_comm
.SendSignalsToIgnore(signals_to_ignore
);
3850 "Signals' version changed. old version={0}, new version={1}, "
3851 "signals ignored={2}, update result={3}",
3852 m_last_signals_version
, new_signals_version
,
3853 signals_to_ignore
.size(), error
);
3855 if (error
.Success())
3856 m_last_signals_version
= new_signals_version
;
3861 bool ProcessGDBRemote::StartNoticingNewThreads() {
3862 Log
*log
= GetLog(LLDBLog::Step
);
3863 if (m_thread_create_bp_sp
) {
3864 if (log
&& log
->GetVerbose())
3865 LLDB_LOGF(log
, "Enabled noticing new thread breakpoint.");
3866 m_thread_create_bp_sp
->SetEnabled(true);
3868 PlatformSP
platform_sp(GetTarget().GetPlatform());
3870 m_thread_create_bp_sp
=
3871 platform_sp
->SetThreadCreationBreakpoint(GetTarget());
3872 if (m_thread_create_bp_sp
) {
3873 if (log
&& log
->GetVerbose())
3875 log
, "Successfully created new thread notification breakpoint %i",
3876 m_thread_create_bp_sp
->GetID());
3877 m_thread_create_bp_sp
->SetCallback(
3878 ProcessGDBRemote::NewThreadNotifyBreakpointHit
, this, true);
3880 LLDB_LOGF(log
, "Failed to create new thread notification breakpoint.");
3884 return m_thread_create_bp_sp
.get() != nullptr;
3887 bool ProcessGDBRemote::StopNoticingNewThreads() {
3888 Log
*log
= GetLog(LLDBLog::Step
);
3889 if (log
&& log
->GetVerbose())
3890 LLDB_LOGF(log
, "Disabling new thread notification breakpoint.");
3892 if (m_thread_create_bp_sp
)
3893 m_thread_create_bp_sp
->SetEnabled(false);
3898 DynamicLoader
*ProcessGDBRemote::GetDynamicLoader() {
3899 if (m_dyld_up
.get() == nullptr)
3900 m_dyld_up
.reset(DynamicLoader::FindPlugin(this, ""));
3901 return m_dyld_up
.get();
3904 Status
ProcessGDBRemote::SendEventData(const char *data
) {
3910 return_value
= m_gdb_comm
.SendLaunchEventDataPacket(data
, &was_supported
);
3911 if (return_value
!= 0) {
3913 error
= Status::FromErrorString(
3914 "Sending events is not supported for this process.");
3916 error
= Status::FromErrorStringWithFormat("Error sending event data: %d.",
3922 DataExtractor
ProcessGDBRemote::GetAuxvData() {
3924 if (m_gdb_comm
.GetQXferAuxvReadSupported()) {
3925 llvm::Expected
<std::string
> response
= m_gdb_comm
.ReadExtFeature("auxv", "");
3927 buf
= std::make_shared
<DataBufferHeap
>(response
->c_str(),
3928 response
->length());
3930 LLDB_LOG_ERROR(GetLog(GDBRLog::Process
), response
.takeError(), "{0}");
3932 return DataExtractor(buf
, GetByteOrder(), GetAddressByteSize());
3935 StructuredData::ObjectSP
3936 ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid
) {
3937 StructuredData::ObjectSP object_sp
;
3939 if (m_gdb_comm
.GetThreadExtendedInfoSupported()) {
3940 StructuredData::ObjectSP
args_dict(new StructuredData::Dictionary());
3941 SystemRuntime
*runtime
= GetSystemRuntime();
3943 runtime
->AddThreadExtendedInfoPacketHints(args_dict
);
3945 args_dict
->GetAsDictionary()->AddIntegerItem("thread", tid
);
3947 StreamString packet
;
3948 packet
<< "jThreadExtendedInfo:";
3949 args_dict
->Dump(packet
, false);
3951 // FIXME the final character of a JSON dictionary, '}', is the escape
3952 // character in gdb-remote binary mode. lldb currently doesn't escape
3953 // these characters in its packet output -- so we add the quoted version of
3954 // the } character here manually in case we talk to a debugserver which un-
3955 // escapes the characters at packet read time.
3956 packet
<< (char)(0x7d ^ 0x20);
3958 StringExtractorGDBRemote response
;
3959 response
.SetResponseValidatorToJSON();
3960 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
.GetString(), response
) ==
3961 GDBRemoteCommunication::PacketResult::Success
) {
3962 StringExtractorGDBRemote::ResponseType response_type
=
3963 response
.GetResponseType();
3964 if (response_type
== StringExtractorGDBRemote::eResponse
) {
3965 if (!response
.Empty()) {
3966 object_sp
= StructuredData::ParseJSON(response
.GetStringRef());
3974 StructuredData::ObjectSP
ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3975 lldb::addr_t image_list_address
, lldb::addr_t image_count
) {
3977 StructuredData::ObjectSP
args_dict(new StructuredData::Dictionary());
3978 args_dict
->GetAsDictionary()->AddIntegerItem("image_list_address",
3979 image_list_address
);
3980 args_dict
->GetAsDictionary()->AddIntegerItem("image_count", image_count
);
3982 return GetLoadedDynamicLibrariesInfos_sender(args_dict
);
3985 StructuredData::ObjectSP
ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() {
3986 StructuredData::ObjectSP
args_dict(new StructuredData::Dictionary());
3988 args_dict
->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3990 return GetLoadedDynamicLibrariesInfos_sender(args_dict
);
3993 StructuredData::ObjectSP
ProcessGDBRemote::GetLoadedDynamicLibrariesInfos(
3994 const std::vector
<lldb::addr_t
> &load_addresses
) {
3995 StructuredData::ObjectSP
args_dict(new StructuredData::Dictionary());
3996 StructuredData::ArraySP
addresses(new StructuredData::Array
);
3998 for (auto addr
: load_addresses
)
3999 addresses
->AddIntegerItem(addr
);
4001 args_dict
->GetAsDictionary()->AddItem("solib_addresses", addresses
);
4003 return GetLoadedDynamicLibrariesInfos_sender(args_dict
);
4006 StructuredData::ObjectSP
4007 ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender(
4008 StructuredData::ObjectSP args_dict
) {
4009 StructuredData::ObjectSP object_sp
;
4011 if (m_gdb_comm
.GetLoadedDynamicLibrariesInfosSupported()) {
4012 // Scope for the scoped timeout object
4013 GDBRemoteCommunication::ScopedTimeout
timeout(m_gdb_comm
,
4014 std::chrono::seconds(10));
4016 StreamString packet
;
4017 packet
<< "jGetLoadedDynamicLibrariesInfos:";
4018 args_dict
->Dump(packet
, false);
4020 // FIXME the final character of a JSON dictionary, '}', is the escape
4021 // character in gdb-remote binary mode. lldb currently doesn't escape
4022 // these characters in its packet output -- so we add the quoted version of
4023 // the } character here manually in case we talk to a debugserver which un-
4024 // escapes the characters at packet read time.
4025 packet
<< (char)(0x7d ^ 0x20);
4027 StringExtractorGDBRemote response
;
4028 response
.SetResponseValidatorToJSON();
4029 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
.GetString(), response
) ==
4030 GDBRemoteCommunication::PacketResult::Success
) {
4031 StringExtractorGDBRemote::ResponseType response_type
=
4032 response
.GetResponseType();
4033 if (response_type
== StringExtractorGDBRemote::eResponse
) {
4034 if (!response
.Empty()) {
4035 object_sp
= StructuredData::ParseJSON(response
.GetStringRef());
4043 StructuredData::ObjectSP
ProcessGDBRemote::GetDynamicLoaderProcessState() {
4044 StructuredData::ObjectSP object_sp
;
4045 StructuredData::ObjectSP
args_dict(new StructuredData::Dictionary());
4047 if (m_gdb_comm
.GetDynamicLoaderProcessStateSupported()) {
4048 StringExtractorGDBRemote response
;
4049 response
.SetResponseValidatorToJSON();
4050 if (m_gdb_comm
.SendPacketAndWaitForResponse("jGetDyldProcessState",
4052 GDBRemoteCommunication::PacketResult::Success
) {
4053 StringExtractorGDBRemote::ResponseType response_type
=
4054 response
.GetResponseType();
4055 if (response_type
== StringExtractorGDBRemote::eResponse
) {
4056 if (!response
.Empty()) {
4057 object_sp
= StructuredData::ParseJSON(response
.GetStringRef());
4065 StructuredData::ObjectSP
ProcessGDBRemote::GetSharedCacheInfo() {
4066 StructuredData::ObjectSP object_sp
;
4067 StructuredData::ObjectSP
args_dict(new StructuredData::Dictionary());
4069 if (m_gdb_comm
.GetSharedCacheInfoSupported()) {
4070 StreamString packet
;
4071 packet
<< "jGetSharedCacheInfo:";
4072 args_dict
->Dump(packet
, false);
4074 // FIXME the final character of a JSON dictionary, '}', is the escape
4075 // character in gdb-remote binary mode. lldb currently doesn't escape
4076 // these characters in its packet output -- so we add the quoted version of
4077 // the } character here manually in case we talk to a debugserver which un-
4078 // escapes the characters at packet read time.
4079 packet
<< (char)(0x7d ^ 0x20);
4081 StringExtractorGDBRemote response
;
4082 response
.SetResponseValidatorToJSON();
4083 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
.GetString(), response
) ==
4084 GDBRemoteCommunication::PacketResult::Success
) {
4085 StringExtractorGDBRemote::ResponseType response_type
=
4086 response
.GetResponseType();
4087 if (response_type
== StringExtractorGDBRemote::eResponse
) {
4088 if (!response
.Empty()) {
4089 object_sp
= StructuredData::ParseJSON(response
.GetStringRef());
4097 Status
ProcessGDBRemote::ConfigureStructuredData(
4098 llvm::StringRef type_name
, const StructuredData::ObjectSP
&config_sp
) {
4099 return m_gdb_comm
.ConfigureRemoteStructuredData(type_name
, config_sp
);
4102 // Establish the largest memory read/write payloads we should use. If the
4103 // remote stub has a max packet size, stay under that size.
4105 // If the remote stub's max packet size is crazy large, use a reasonable
4106 // largeish default.
4108 // If the remote stub doesn't advertise a max packet size, use a conservative
4111 void ProcessGDBRemote::GetMaxMemorySize() {
4112 const uint64_t reasonable_largeish_default
= 128 * 1024;
4113 const uint64_t conservative_default
= 512;
4115 if (m_max_memory_size
== 0) {
4116 uint64_t stub_max_size
= m_gdb_comm
.GetRemoteMaxPacketSize();
4117 if (stub_max_size
!= UINT64_MAX
&& stub_max_size
!= 0) {
4118 // Save the stub's claimed maximum packet size
4119 m_remote_stub_max_memory_size
= stub_max_size
;
4121 // Even if the stub says it can support ginormous packets, don't exceed
4122 // our reasonable largeish default packet size.
4123 if (stub_max_size
> reasonable_largeish_default
) {
4124 stub_max_size
= reasonable_largeish_default
;
4127 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4128 // calculating the bytes taken by size and addr every time, we take a
4129 // maximum guess here.
4130 if (stub_max_size
> 70)
4131 stub_max_size
-= 32 + 32 + 6;
4133 // In unlikely scenario that max packet size is less then 70, we will
4134 // hope that data being written is small enough to fit.
4135 Log
*log(GetLog(GDBRLog::Comm
| GDBRLog::Memory
));
4137 log
->Warning("Packet size is too small. "
4138 "LLDB may face problems while writing memory");
4141 m_max_memory_size
= stub_max_size
;
4143 m_max_memory_size
= conservative_default
;
4148 void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize(
4149 uint64_t user_specified_max
) {
4150 if (user_specified_max
!= 0) {
4153 if (m_remote_stub_max_memory_size
!= 0) {
4154 if (m_remote_stub_max_memory_size
< user_specified_max
) {
4155 m_max_memory_size
= m_remote_stub_max_memory_size
; // user specified a
4158 // as the remote stub says we can go.
4160 m_max_memory_size
= user_specified_max
; // user's packet size is good
4164 user_specified_max
; // user's packet size is probably fine
4169 bool ProcessGDBRemote::GetModuleSpec(const FileSpec
&module_file_spec
,
4170 const ArchSpec
&arch
,
4171 ModuleSpec
&module_spec
) {
4172 Log
*log
= GetLog(LLDBLog::Platform
);
4174 const ModuleCacheKey
key(module_file_spec
.GetPath(),
4175 arch
.GetTriple().getTriple());
4176 auto cached
= m_cached_module_specs
.find(key
);
4177 if (cached
!= m_cached_module_specs
.end()) {
4178 module_spec
= cached
->second
;
4179 return bool(module_spec
);
4182 if (!m_gdb_comm
.GetModuleInfo(module_file_spec
, arch
, module_spec
)) {
4183 LLDB_LOGF(log
, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4184 __FUNCTION__
, module_file_spec
.GetPath().c_str(),
4185 arch
.GetTriple().getTriple().c_str());
4190 StreamString stream
;
4191 module_spec
.Dump(stream
);
4192 LLDB_LOGF(log
, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4193 __FUNCTION__
, module_file_spec
.GetPath().c_str(),
4194 arch
.GetTriple().getTriple().c_str(), stream
.GetData());
4197 m_cached_module_specs
[key
] = module_spec
;
4201 void ProcessGDBRemote::PrefetchModuleSpecs(
4202 llvm::ArrayRef
<FileSpec
> module_file_specs
, const llvm::Triple
&triple
) {
4203 auto module_specs
= m_gdb_comm
.GetModulesInfo(module_file_specs
, triple
);
4205 for (const FileSpec
&spec
: module_file_specs
)
4206 m_cached_module_specs
[ModuleCacheKey(spec
.GetPath(),
4207 triple
.getTriple())] = ModuleSpec();
4208 for (const ModuleSpec
&spec
: *module_specs
)
4209 m_cached_module_specs
[ModuleCacheKey(spec
.GetFileSpec().GetPath(),
4210 triple
.getTriple())] = spec
;
4214 llvm::VersionTuple
ProcessGDBRemote::GetHostOSVersion() {
4215 return m_gdb_comm
.GetOSVersion();
4218 llvm::VersionTuple
ProcessGDBRemote::GetHostMacCatalystVersion() {
4219 return m_gdb_comm
.GetMacCatalystVersion();
4224 typedef std::vector
<std::string
> stringVec
;
4226 typedef std::vector
<struct GdbServerRegisterInfo
> GDBServerRegisterVec
;
4227 struct RegisterSetInfo
{
4231 typedef std::map
<uint32_t, RegisterSetInfo
> RegisterSetMap
;
4233 struct GdbServerTargetInfo
{
4237 RegisterSetMap reg_set_map
;
4240 static FieldEnum::Enumerators
ParseEnumEvalues(const XMLNode
&enum_node
) {
4241 Log
*log(GetLog(GDBRLog::Process
));
4242 // We will use the last instance of each value. Also we preserve the order
4243 // of declaration in the XML, as it may not be numerical.
4244 // For example, hardware may intially release with two states that softwware
4245 // can read from a register field:
4246 // 0 = startup, 1 = running
4247 // If in a future hardware release, the designers added a pre-startup state:
4248 // 0 = startup, 1 = running, 2 = pre-startup
4249 // Now it makes more sense to list them in this logical order as opposed to
4251 // 2 = pre-startup, 1 = startup, 0 = startup
4252 // This only matters for "register info" but let's trust what the server
4253 // chose regardless.
4254 std::map
<uint64_t, FieldEnum::Enumerator
> enumerators
;
4256 enum_node
.ForEachChildElementWithName(
4257 "evalue", [&enumerators
, &log
](const XMLNode
&enumerator_node
) {
4258 std::optional
<llvm::StringRef
> name
;
4259 std::optional
<uint64_t> value
;
4261 enumerator_node
.ForEachAttribute(
4262 [&name
, &value
, &log
](const llvm::StringRef
&attr_name
,
4263 const llvm::StringRef
&attr_value
) {
4264 if (attr_name
== "name") {
4265 if (attr_value
.size())
4268 LLDB_LOG(log
, "ProcessGDBRemote::ParseEnumEvalues "
4269 "Ignoring empty name in evalue");
4270 } else if (attr_name
== "value") {
4271 uint64_t parsed_value
= 0;
4272 if (llvm::to_integer(attr_value
, parsed_value
))
4273 value
= parsed_value
;
4276 "ProcessGDBRemote::ParseEnumEvalues "
4277 "Invalid value \"{0}\" in "
4282 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
4283 "unknown attribute "
4284 "\"{0}\" in evalue",
4287 // Keep walking attributes.
4292 enumerators
.insert_or_assign(
4293 *value
, FieldEnum::Enumerator(*value
, name
->str()));
4295 // Find all evalue elements.
4299 FieldEnum::Enumerators final_enumerators
;
4300 for (auto [_
, enumerator
] : enumerators
)
4301 final_enumerators
.push_back(enumerator
);
4303 return final_enumerators
;
4307 ParseEnums(XMLNode feature_node
,
4308 llvm::StringMap
<std::unique_ptr
<FieldEnum
>> ®isters_enum_types
) {
4309 Log
*log(GetLog(GDBRLog::Process
));
4311 // The top level element is "<enum...".
4312 feature_node
.ForEachChildElementWithName(
4313 "enum", [log
, ®isters_enum_types
](const XMLNode
&enum_node
) {
4316 enum_node
.ForEachAttribute([&id
](const llvm::StringRef
&attr_name
,
4317 const llvm::StringRef
&attr_value
) {
4318 if (attr_name
== "id")
4321 // There is also a "size" attribute that is supposed to be the size in
4322 // bytes of the register this applies to. However:
4323 // * LLDB doesn't need this information.
4324 // * It is difficult to verify because you have to wait until the
4325 // enum is applied to a field.
4327 // So we will emit this attribute in XML for GDB's sake, but will not
4328 // bother ingesting it.
4330 // Walk all attributes.
4335 FieldEnum::Enumerators enumerators
= ParseEnumEvalues(enum_node
);
4336 if (!enumerators
.empty()) {
4338 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
4340 registers_enum_types
.insert_or_assign(
4341 id
, std::make_unique
<FieldEnum
>(id
, enumerators
));
4345 // Find all <enum> elements.
4350 static std::vector
<RegisterFlags::Field
> ParseFlagsFields(
4351 XMLNode flags_node
, unsigned size
,
4352 const llvm::StringMap
<std::unique_ptr
<FieldEnum
>> ®isters_enum_types
) {
4353 Log
*log(GetLog(GDBRLog::Process
));
4354 const unsigned max_start_bit
= size
* 8 - 1;
4356 // Process the fields of this set of flags.
4357 std::vector
<RegisterFlags::Field
> fields
;
4358 flags_node
.ForEachChildElementWithName("field", [&fields
, max_start_bit
, &log
,
4359 ®isters_enum_types
](
4362 std::optional
<llvm::StringRef
> name
;
4363 std::optional
<unsigned> start
;
4364 std::optional
<unsigned> end
;
4365 std::optional
<llvm::StringRef
> type
;
4367 field_node
.ForEachAttribute([&name
, &start
, &end
, &type
, max_start_bit
,
4368 &log
](const llvm::StringRef
&attr_name
,
4369 const llvm::StringRef
&attr_value
) {
4370 // Note that XML in general requires that each of these attributes only
4371 // appears once, so we don't have to handle that here.
4372 if (attr_name
== "name") {
4375 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
4378 } else if (attr_name
== "start") {
4379 unsigned parsed_start
= 0;
4380 if (llvm::to_integer(attr_value
, parsed_start
)) {
4381 if (parsed_start
> max_start_bit
) {
4383 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
4386 parsed_start
, max_start_bit
);
4388 start
= parsed_start
;
4392 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
4396 } else if (attr_name
== "end") {
4397 unsigned parsed_end
= 0;
4398 if (llvm::to_integer(attr_value
, parsed_end
))
4399 if (parsed_end
> max_start_bit
) {
4401 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
4404 parsed_end
, max_start_bit
);
4409 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
4413 } else if (attr_name
== "type") {
4418 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
4419 "\"{0}\" in field node",
4423 return true; // Walk all attributes of the field.
4426 if (name
&& start
&& end
) {
4430 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
4431 "\"{2}\", ignoring",
4432 *start
, *end
, name
->data());
4434 if (RegisterFlags::Field::GetSizeInBits(*start
, *end
) > 64)
4436 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" "
4438 "size > 64 bits, this is not supported",
4441 // A field's type may be set to the name of an enum type.
4442 const FieldEnum
*enum_type
= nullptr;
4443 if (type
&& !type
->empty()) {
4444 auto found
= registers_enum_types
.find(*type
);
4445 if (found
!= registers_enum_types
.end()) {
4446 enum_type
= found
->second
.get();
4448 // No enumerator can exceed the range of the field itself.
4449 uint64_t max_value
=
4450 RegisterFlags::Field::GetMaxValue(*start
, *end
);
4451 for (const auto &enumerator
: enum_type
->GetEnumerators()) {
4452 if (enumerator
.m_value
> max_value
) {
4453 enum_type
= nullptr;
4456 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
4457 "evalue \"{1}\" with value {2} exceeds the maximum value "
4458 "of field \"{3}\" ({4}), ignoring enum",
4459 type
->data(), enumerator
.m_name
, enumerator
.m_value
,
4460 name
->data(), max_value
);
4466 "ProcessGDBRemote::ParseFlagsFields Could not find type "
4468 "for field \"{1}\", ignoring",
4469 type
->data(), name
->data());
4474 RegisterFlags::Field(name
->str(), *start
, *end
, enum_type
));
4479 return true; // Iterate all "field" nodes.
4485 XMLNode feature_node
,
4486 llvm::StringMap
<std::unique_ptr
<RegisterFlags
>> ®isters_flags_types
,
4487 const llvm::StringMap
<std::unique_ptr
<FieldEnum
>> ®isters_enum_types
) {
4488 Log
*log(GetLog(GDBRLog::Process
));
4490 feature_node
.ForEachChildElementWithName(
4492 [&log
, ®isters_flags_types
,
4493 ®isters_enum_types
](const XMLNode
&flags_node
) -> bool {
4494 LLDB_LOG(log
, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4495 flags_node
.GetAttributeValue("id").c_str());
4497 std::optional
<llvm::StringRef
> id
;
4498 std::optional
<unsigned> size
;
4499 flags_node
.ForEachAttribute(
4500 [&id
, &size
, &log
](const llvm::StringRef
&name
,
4501 const llvm::StringRef
&value
) {
4504 } else if (name
== "size") {
4505 unsigned parsed_size
= 0;
4506 if (llvm::to_integer(value
, parsed_size
))
4510 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4516 "ProcessGDBRemote::ParseFlags Ignoring unknown "
4517 "attribute \"{0}\" in flags node",
4520 return true; // Walk all attributes.
4524 // Process the fields of this set of flags.
4525 std::vector
<RegisterFlags::Field
> fields
=
4526 ParseFlagsFields(flags_node
, *size
, registers_enum_types
);
4527 if (fields
.size()) {
4528 // Sort so that the fields with the MSBs are first.
4529 std::sort(fields
.rbegin(), fields
.rend());
4530 std::vector
<RegisterFlags::Field
>::const_iterator overlap
=
4531 std::adjacent_find(fields
.begin(), fields
.end(),
4532 [](const RegisterFlags::Field
&lhs
,
4533 const RegisterFlags::Field
&rhs
) {
4534 return lhs
.Overlaps(rhs
);
4537 // If no fields overlap, use them.
4538 if (overlap
== fields
.end()) {
4539 if (registers_flags_types
.contains(*id
)) {
4540 // In theory you could define some flag set, use it with a
4541 // register then redefine it. We do not know if anyone does
4542 // that, or what they would expect to happen in that case.
4544 // LLDB chooses to take the first definition and ignore the rest
4545 // as waiting until everything has been processed is more
4546 // expensive and difficult. This means that pointers to flag
4547 // sets in the register info remain valid if later the flag set
4548 // is redefined. If we allowed redefinitions, LLDB would crash
4549 // when you tried to print a register that used the original
4553 "ProcessGDBRemote::ParseFlags Definition of flags "
4555 "previous definition, using original definition instead.",
4558 registers_flags_types
.insert_or_assign(
4559 *id
, std::make_unique
<RegisterFlags
>(id
->str(), *size
,
4560 std::move(fields
)));
4563 // If any fields overlap, ignore the whole set of flags.
4564 std::vector
<RegisterFlags::Field
>::const_iterator next
=
4568 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4569 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4571 overlap
->GetName().c_str(), overlap
->GetStart(),
4572 overlap
->GetEnd(), next
->GetName().c_str(), next
->GetStart(),
4578 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4579 "\"{0}\" because it contains no fields.",
4584 return true; // Keep iterating through all "flags" elements.
4588 bool ParseRegisters(
4589 XMLNode feature_node
, GdbServerTargetInfo
&target_info
,
4590 std::vector
<DynamicRegisterInfo::Register
> ®isters
,
4591 llvm::StringMap
<std::unique_ptr
<RegisterFlags
>> ®isters_flags_types
,
4592 llvm::StringMap
<std::unique_ptr
<FieldEnum
>> ®isters_enum_types
) {
4596 Log
*log(GetLog(GDBRLog::Process
));
4598 // Enums first because they are referenced by fields in the flags.
4599 ParseEnums(feature_node
, registers_enum_types
);
4600 for (const auto &enum_type
: registers_enum_types
)
4601 enum_type
.second
->DumpToLog(log
);
4603 ParseFlags(feature_node
, registers_flags_types
, registers_enum_types
);
4604 for (const auto &flags
: registers_flags_types
)
4605 flags
.second
->DumpToLog(log
);
4607 feature_node
.ForEachChildElementWithName(
4609 [&target_info
, ®isters
, ®isters_flags_types
,
4610 log
](const XMLNode
®_node
) -> bool {
4611 std::string gdb_group
;
4612 std::string gdb_type
;
4613 DynamicRegisterInfo::Register reg_info
;
4614 bool encoding_set
= false;
4615 bool format_set
= false;
4617 // FIXME: we're silently ignoring invalid data here
4618 reg_node
.ForEachAttribute([&target_info
, &gdb_group
, &gdb_type
,
4619 &encoding_set
, &format_set
, ®_info
,
4620 log
](const llvm::StringRef
&name
,
4621 const llvm::StringRef
&value
) -> bool {
4622 if (name
== "name") {
4623 reg_info
.name
.SetString(value
);
4624 } else if (name
== "bitsize") {
4625 if (llvm::to_integer(value
, reg_info
.byte_size
))
4626 reg_info
.byte_size
=
4627 llvm::divideCeil(reg_info
.byte_size
, CHAR_BIT
);
4628 } else if (name
== "type") {
4629 gdb_type
= value
.str();
4630 } else if (name
== "group") {
4631 gdb_group
= value
.str();
4632 } else if (name
== "regnum") {
4633 llvm::to_integer(value
, reg_info
.regnum_remote
);
4634 } else if (name
== "offset") {
4635 llvm::to_integer(value
, reg_info
.byte_offset
);
4636 } else if (name
== "altname") {
4637 reg_info
.alt_name
.SetString(value
);
4638 } else if (name
== "encoding") {
4639 encoding_set
= true;
4640 reg_info
.encoding
= Args::StringToEncoding(value
, eEncodingUint
);
4641 } else if (name
== "format") {
4643 if (!OptionArgParser::ToFormat(value
.data(), reg_info
.format
,
4647 llvm::StringSwitch
<lldb::Format
>(value
)
4648 .Case("vector-sint8", eFormatVectorOfSInt8
)
4649 .Case("vector-uint8", eFormatVectorOfUInt8
)
4650 .Case("vector-sint16", eFormatVectorOfSInt16
)
4651 .Case("vector-uint16", eFormatVectorOfUInt16
)
4652 .Case("vector-sint32", eFormatVectorOfSInt32
)
4653 .Case("vector-uint32", eFormatVectorOfUInt32
)
4654 .Case("vector-float32", eFormatVectorOfFloat32
)
4655 .Case("vector-uint64", eFormatVectorOfUInt64
)
4656 .Case("vector-uint128", eFormatVectorOfUInt128
)
4657 .Default(eFormatInvalid
);
4658 } else if (name
== "group_id") {
4659 uint32_t set_id
= UINT32_MAX
;
4660 llvm::to_integer(value
, set_id
);
4661 RegisterSetMap::const_iterator pos
=
4662 target_info
.reg_set_map
.find(set_id
);
4663 if (pos
!= target_info
.reg_set_map
.end())
4664 reg_info
.set_name
= pos
->second
.name
;
4665 } else if (name
== "gcc_regnum" || name
== "ehframe_regnum") {
4666 llvm::to_integer(value
, reg_info
.regnum_ehframe
);
4667 } else if (name
== "dwarf_regnum") {
4668 llvm::to_integer(value
, reg_info
.regnum_dwarf
);
4669 } else if (name
== "generic") {
4670 reg_info
.regnum_generic
= Args::StringToGenericRegister(value
);
4671 } else if (name
== "value_regnums") {
4672 SplitCommaSeparatedRegisterNumberString(value
, reg_info
.value_regs
,
4674 } else if (name
== "invalidate_regnums") {
4675 SplitCommaSeparatedRegisterNumberString(
4676 value
, reg_info
.invalidate_regs
, 0);
4679 "ProcessGDBRemote::ParseRegisters unhandled reg "
4680 "attribute %s = %s",
4681 name
.data(), value
.data());
4683 return true; // Keep iterating through all attributes
4686 if (!gdb_type
.empty()) {
4687 // gdb_type could reference some flags type defined in XML.
4688 llvm::StringMap
<std::unique_ptr
<RegisterFlags
>>::iterator it
=
4689 registers_flags_types
.find(gdb_type
);
4690 if (it
!= registers_flags_types
.end()) {
4691 auto flags_type
= it
->second
.get();
4692 if (reg_info
.byte_size
== flags_type
->GetSize())
4693 reg_info
.flags_type
= flags_type
;
4696 "ProcessGDBRemote::ParseRegisters Size of register "
4697 "flags %s (%d bytes) for "
4698 "register %s does not match the register size (%d "
4699 "bytes). Ignoring this set of flags.",
4700 flags_type
->GetID().c_str(), flags_type
->GetSize(),
4701 reg_info
.name
.AsCString(), reg_info
.byte_size
);
4704 // There's a slim chance that the gdb_type name is both a flags type
4705 // and a simple type. Just in case, look for that too (setting both
4707 if (!gdb_type
.empty() && !(encoding_set
|| format_set
)) {
4708 if (llvm::StringRef(gdb_type
).starts_with("int")) {
4709 reg_info
.format
= eFormatHex
;
4710 reg_info
.encoding
= eEncodingUint
;
4711 } else if (gdb_type
== "data_ptr" || gdb_type
== "code_ptr") {
4712 reg_info
.format
= eFormatAddressInfo
;
4713 reg_info
.encoding
= eEncodingUint
;
4714 } else if (gdb_type
== "float") {
4715 reg_info
.format
= eFormatFloat
;
4716 reg_info
.encoding
= eEncodingIEEE754
;
4717 } else if (gdb_type
== "aarch64v" ||
4718 llvm::StringRef(gdb_type
).starts_with("vec") ||
4719 gdb_type
== "i387_ext" || gdb_type
== "uint128" ||
4720 reg_info
.byte_size
> 16) {
4721 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
4722 // treat them as vector (similarly to xmm/ymm).
4723 // We can fall back to handling anything else <= 128 bit as an
4724 // unsigned integer, more than that, call it a vector of bytes.
4725 // This can happen if we don't recognise the type for AArc64 SVE
4727 reg_info
.format
= eFormatVectorOfUInt8
;
4728 reg_info
.encoding
= eEncodingVector
;
4732 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4733 "format and encoding for gdb type %s",
4739 // Only update the register set name if we didn't get a "reg_set"
4740 // attribute. "set_name" will be empty if we didn't have a "reg_set"
4742 if (!reg_info
.set_name
) {
4743 if (!gdb_group
.empty()) {
4744 reg_info
.set_name
.SetCString(gdb_group
.c_str());
4746 // If no register group name provided anywhere,
4747 // we'll create a 'general' register set
4748 reg_info
.set_name
.SetCString("general");
4752 if (reg_info
.byte_size
== 0) {
4754 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4755 __FUNCTION__
, reg_info
.name
.AsCString());
4757 registers
.push_back(reg_info
);
4759 return true; // Keep iterating through all "reg" elements
4766 // This method fetches a register description feature xml file from
4767 // the remote stub and adds registers/register groupsets/architecture
4768 // information to the current process. It will call itself recursively
4769 // for nested register definition files. It returns true if it was able
4770 // to fetch and parse an xml file.
4771 bool ProcessGDBRemote::GetGDBServerRegisterInfoXMLAndProcess(
4772 ArchSpec
&arch_to_use
, std::string xml_filename
,
4773 std::vector
<DynamicRegisterInfo::Register
> ®isters
) {
4774 // request the target xml file
4775 llvm::Expected
<std::string
> raw
= m_gdb_comm
.ReadExtFeature("features", xml_filename
);
4776 if (errorToBool(raw
.takeError()))
4779 XMLDocument xml_document
;
4781 if (xml_document
.ParseMemory(raw
->c_str(), raw
->size(),
4782 xml_filename
.c_str())) {
4783 GdbServerTargetInfo target_info
;
4784 std::vector
<XMLNode
> feature_nodes
;
4786 // The top level feature XML file will start with a <target> tag.
4787 XMLNode target_node
= xml_document
.GetRootElement("target");
4789 target_node
.ForEachChildElement([&target_info
, &feature_nodes
](
4790 const XMLNode
&node
) -> bool {
4791 llvm::StringRef name
= node
.GetName();
4792 if (name
== "architecture") {
4793 node
.GetElementText(target_info
.arch
);
4794 } else if (name
== "osabi") {
4795 node
.GetElementText(target_info
.osabi
);
4796 } else if (name
== "xi:include" || name
== "include") {
4797 std::string href
= node
.GetAttributeValue("href");
4799 target_info
.includes
.push_back(href
);
4800 } else if (name
== "feature") {
4801 feature_nodes
.push_back(node
);
4802 } else if (name
== "groups") {
4803 node
.ForEachChildElementWithName(
4804 "group", [&target_info
](const XMLNode
&node
) -> bool {
4805 uint32_t set_id
= UINT32_MAX
;
4806 RegisterSetInfo set_info
;
4808 node
.ForEachAttribute(
4809 [&set_id
, &set_info
](const llvm::StringRef
&name
,
4810 const llvm::StringRef
&value
) -> bool {
4811 // FIXME: we're silently ignoring invalid data here
4813 llvm::to_integer(value
, set_id
);
4815 set_info
.name
= ConstString(value
);
4816 return true; // Keep iterating through all attributes
4819 if (set_id
!= UINT32_MAX
)
4820 target_info
.reg_set_map
[set_id
] = set_info
;
4821 return true; // Keep iterating through all "group" elements
4824 return true; // Keep iterating through all children of the target_node
4827 // In an included XML feature file, we're already "inside" the <target>
4828 // tag of the initial XML file; this included file will likely only have
4829 // a <feature> tag. Need to check for any more included files in this
4830 // <feature> element.
4831 XMLNode feature_node
= xml_document
.GetRootElement("feature");
4833 feature_nodes
.push_back(feature_node
);
4834 feature_node
.ForEachChildElement([&target_info
](
4835 const XMLNode
&node
) -> bool {
4836 llvm::StringRef name
= node
.GetName();
4837 if (name
== "xi:include" || name
== "include") {
4838 std::string href
= node
.GetAttributeValue("href");
4840 target_info
.includes
.push_back(href
);
4847 // gdbserver does not implement the LLDB packets used to determine host
4848 // or process architecture. If that is the case, attempt to use
4849 // the <architecture/> field from target.xml, e.g.:
4851 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4852 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
4854 if (!arch_to_use
.IsValid() && !target_info
.arch
.empty()) {
4855 // We don't have any information about vendor or OS.
4856 arch_to_use
.SetTriple(llvm::StringSwitch
<std::string
>(target_info
.arch
)
4857 .Case("i386:x86-64", "x86_64")
4858 .Case("riscv:rv64", "riscv64")
4859 .Case("riscv:rv32", "riscv32")
4860 .Default(target_info
.arch
) +
4863 if (arch_to_use
.IsValid())
4864 GetTarget().MergeArchitecture(arch_to_use
);
4867 if (arch_to_use
.IsValid()) {
4868 for (auto &feature_node
: feature_nodes
) {
4869 ParseRegisters(feature_node
, target_info
, registers
,
4870 m_registers_flags_types
, m_registers_enum_types
);
4873 for (const auto &include
: target_info
.includes
) {
4874 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use
, include
,
4884 void ProcessGDBRemote::AddRemoteRegisters(
4885 std::vector
<DynamicRegisterInfo::Register
> ®isters
,
4886 const ArchSpec
&arch_to_use
) {
4887 std::map
<uint32_t, uint32_t> remote_to_local_map
;
4888 uint32_t remote_regnum
= 0;
4889 for (auto it
: llvm::enumerate(registers
)) {
4890 DynamicRegisterInfo::Register
&remote_reg_info
= it
.value();
4892 // Assign successive remote regnums if missing.
4893 if (remote_reg_info
.regnum_remote
== LLDB_INVALID_REGNUM
)
4894 remote_reg_info
.regnum_remote
= remote_regnum
;
4896 // Create a mapping from remote to local regnos.
4897 remote_to_local_map
[remote_reg_info
.regnum_remote
] = it
.index();
4899 remote_regnum
= remote_reg_info
.regnum_remote
+ 1;
4902 for (DynamicRegisterInfo::Register
&remote_reg_info
: registers
) {
4903 auto proc_to_lldb
= [&remote_to_local_map
](uint32_t process_regnum
) {
4904 auto lldb_regit
= remote_to_local_map
.find(process_regnum
);
4905 return lldb_regit
!= remote_to_local_map
.end() ? lldb_regit
->second
4906 : LLDB_INVALID_REGNUM
;
4909 llvm::transform(remote_reg_info
.value_regs
,
4910 remote_reg_info
.value_regs
.begin(), proc_to_lldb
);
4911 llvm::transform(remote_reg_info
.invalidate_regs
,
4912 remote_reg_info
.invalidate_regs
.begin(), proc_to_lldb
);
4915 // Don't use Process::GetABI, this code gets called from DidAttach, and
4916 // in that context we haven't set the Target's architecture yet, so the
4917 // ABI is also potentially incorrect.
4918 if (ABISP abi_sp
= ABI::FindPlugin(shared_from_this(), arch_to_use
))
4919 abi_sp
->AugmentRegisterInfo(registers
);
4921 m_register_info_sp
->SetRegisterInfo(std::move(registers
), arch_to_use
);
4924 // query the target of gdb-remote for extended target information returns
4925 // true on success (got register definitions), false on failure (did not).
4926 bool ProcessGDBRemote::GetGDBServerRegisterInfo(ArchSpec
&arch_to_use
) {
4927 // Make sure LLDB has an XML parser it can use first
4928 if (!XMLDocument::XMLEnabled())
4931 // check that we have extended feature read support
4932 if (!m_gdb_comm
.GetQXferFeaturesReadSupported())
4935 // These hold register type information for the whole of target.xml.
4936 // target.xml may include further documents that
4937 // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.
4938 // That's why we clear the cache here, and not in
4939 // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every
4941 m_registers_flags_types
.clear();
4942 m_registers_enum_types
.clear();
4943 std::vector
<DynamicRegisterInfo::Register
> registers
;
4944 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use
, "target.xml",
4946 // Target XML is not required to include register information.
4948 AddRemoteRegisters(registers
, arch_to_use
);
4950 return m_register_info_sp
->GetNumRegisters() > 0;
4953 llvm::Expected
<LoadedModuleInfoList
> ProcessGDBRemote::GetLoadedModuleList() {
4954 // Make sure LLDB has an XML parser it can use first
4955 if (!XMLDocument::XMLEnabled())
4956 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4957 "XML parsing not available");
4959 Log
*log
= GetLog(LLDBLog::Process
);
4960 LLDB_LOGF(log
, "ProcessGDBRemote::%s", __FUNCTION__
);
4962 LoadedModuleInfoList list
;
4963 GDBRemoteCommunicationClient
&comm
= m_gdb_comm
;
4964 bool can_use_svr4
= GetGlobalPluginProperties().GetUseSVR4();
4966 // check that we have extended feature read support
4967 if (can_use_svr4
&& comm
.GetQXferLibrariesSVR4ReadSupported()) {
4968 // request the loaded library list
4969 llvm::Expected
<std::string
> raw
= comm
.ReadExtFeature("libraries-svr4", "");
4971 return raw
.takeError();
4973 // parse the xml file in memory
4974 LLDB_LOGF(log
, "parsing: %s", raw
->c_str());
4977 if (!doc
.ParseMemory(raw
->c_str(), raw
->size(), "noname.xml"))
4978 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4979 "Error reading noname.xml");
4981 XMLNode root_element
= doc
.GetRootElement("library-list-svr4");
4983 return llvm::createStringError(
4984 llvm::inconvertibleErrorCode(),
4985 "Error finding library-list-svr4 xml element");
4987 // main link map structure
4988 std::string main_lm
= root_element
.GetAttributeValue("main-lm");
4989 // FIXME: we're silently ignoring invalid data here
4990 if (!main_lm
.empty())
4991 llvm::to_integer(main_lm
, list
.m_link_map
);
4993 root_element
.ForEachChildElementWithName(
4994 "library", [log
, &list
](const XMLNode
&library
) -> bool {
4995 LoadedModuleInfoList::LoadedModuleInfo module
;
4997 // FIXME: we're silently ignoring invalid data here
4998 library
.ForEachAttribute(
4999 [&module
](const llvm::StringRef
&name
,
5000 const llvm::StringRef
&value
) -> bool {
5001 uint64_t uint_value
= LLDB_INVALID_ADDRESS
;
5003 module
.set_name(value
.str());
5004 else if (name
== "lm") {
5005 // the address of the link_map struct.
5006 llvm::to_integer(value
, uint_value
);
5007 module
.set_link_map(uint_value
);
5008 } else if (name
== "l_addr") {
5009 // the displacement as read from the field 'l_addr' of the
5011 llvm::to_integer(value
, uint_value
);
5012 module
.set_base(uint_value
);
5013 // base address is always a displacement, not an absolute
5015 module
.set_base_is_offset(true);
5016 } else if (name
== "l_ld") {
5017 // the memory address of the libraries PT_DYNAMIC section.
5018 llvm::to_integer(value
, uint_value
);
5019 module
.set_dynamic(uint_value
);
5022 return true; // Keep iterating over all properties of "library"
5027 lldb::addr_t lm
= 0, base
= 0, ld
= 0;
5028 bool base_is_offset
;
5030 module
.get_name(name
);
5031 module
.get_link_map(lm
);
5032 module
.get_base(base
);
5033 module
.get_base_is_offset(base_is_offset
);
5034 module
.get_dynamic(ld
);
5037 "found (link_map:0x%08" PRIx64
", base:0x%08" PRIx64
5038 "[%s], ld:0x%08" PRIx64
", name:'%s')",
5039 lm
, base
, (base_is_offset
? "offset" : "absolute"), ld
,
5044 return true; // Keep iterating over all "library" elements in the root
5049 LLDB_LOGF(log
, "found %" PRId32
" modules in total",
5050 (int)list
.m_list
.size());
5052 } else if (comm
.GetQXferLibrariesReadSupported()) {
5053 // request the loaded library list
5054 llvm::Expected
<std::string
> raw
= comm
.ReadExtFeature("libraries", "");
5057 return raw
.takeError();
5059 LLDB_LOGF(log
, "parsing: %s", raw
->c_str());
5062 if (!doc
.ParseMemory(raw
->c_str(), raw
->size(), "noname.xml"))
5063 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5064 "Error reading noname.xml");
5066 XMLNode root_element
= doc
.GetRootElement("library-list");
5068 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5069 "Error finding library-list xml element");
5071 // FIXME: we're silently ignoring invalid data here
5072 root_element
.ForEachChildElementWithName(
5073 "library", [log
, &list
](const XMLNode
&library
) -> bool {
5074 LoadedModuleInfoList::LoadedModuleInfo module
;
5076 std::string name
= library
.GetAttributeValue("name");
5077 module
.set_name(name
);
5079 // The base address of a given library will be the address of its
5080 // first section. Most remotes send only one section for Windows
5081 // targets for example.
5082 const XMLNode
§ion
=
5083 library
.FindFirstChildElementWithName("section");
5084 std::string address
= section
.GetAttributeValue("address");
5085 uint64_t address_value
= LLDB_INVALID_ADDRESS
;
5086 llvm::to_integer(address
, address_value
);
5087 module
.set_base(address_value
);
5088 // These addresses are absolute values.
5089 module
.set_base_is_offset(false);
5093 lldb::addr_t base
= 0;
5094 bool base_is_offset
;
5095 module
.get_name(name
);
5096 module
.get_base(base
);
5097 module
.get_base_is_offset(base_is_offset
);
5099 LLDB_LOGF(log
, "found (base:0x%08" PRIx64
"[%s], name:'%s')", base
,
5100 (base_is_offset
? "offset" : "absolute"), name
.c_str());
5104 return true; // Keep iterating over all "library" elements in the root
5109 LLDB_LOGF(log
, "found %" PRId32
" modules in total",
5110 (int)list
.m_list
.size());
5113 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5114 "Remote libraries not supported");
5118 lldb::ModuleSP
ProcessGDBRemote::LoadModuleAtAddress(const FileSpec
&file
,
5119 lldb::addr_t link_map
,
5120 lldb::addr_t base_addr
,
5121 bool value_is_offset
) {
5122 DynamicLoader
*loader
= GetDynamicLoader();
5126 return loader
->LoadModuleAtAddress(file
, link_map
, base_addr
,
5130 llvm::Error
ProcessGDBRemote::LoadModules() {
5131 using lldb_private::process_gdb_remote::ProcessGDBRemote
;
5133 // request a list of loaded libraries from GDBServer
5134 llvm::Expected
<LoadedModuleInfoList
> module_list
= GetLoadedModuleList();
5136 return module_list
.takeError();
5138 // get a list of all the modules
5139 ModuleList new_modules
;
5141 for (LoadedModuleInfoList::LoadedModuleInfo
&modInfo
: module_list
->m_list
) {
5142 std::string mod_name
;
5143 lldb::addr_t mod_base
;
5144 lldb::addr_t link_map
;
5145 bool mod_base_is_offset
;
5148 valid
&= modInfo
.get_name(mod_name
);
5149 valid
&= modInfo
.get_base(mod_base
);
5150 valid
&= modInfo
.get_base_is_offset(mod_base_is_offset
);
5154 if (!modInfo
.get_link_map(link_map
))
5155 link_map
= LLDB_INVALID_ADDRESS
;
5157 FileSpec
file(mod_name
);
5158 FileSystem::Instance().Resolve(file
);
5159 lldb::ModuleSP module_sp
=
5160 LoadModuleAtAddress(file
, link_map
, mod_base
, mod_base_is_offset
);
5162 if (module_sp
.get())
5163 new_modules
.Append(module_sp
);
5166 if (new_modules
.GetSize() > 0) {
5167 ModuleList removed_modules
;
5168 Target
&target
= GetTarget();
5169 ModuleList
&loaded_modules
= m_process
->GetTarget().GetImages();
5171 for (size_t i
= 0; i
< loaded_modules
.GetSize(); ++i
) {
5172 const lldb::ModuleSP loaded_module
= loaded_modules
.GetModuleAtIndex(i
);
5175 for (size_t j
= 0; j
< new_modules
.GetSize(); ++j
) {
5176 if (new_modules
.GetModuleAtIndex(j
).get() == loaded_module
.get())
5180 // The main executable will never be included in libraries-svr4, don't
5183 loaded_module
.get() != target
.GetExecutableModulePointer()) {
5184 removed_modules
.Append(loaded_module
);
5188 loaded_modules
.Remove(removed_modules
);
5189 m_process
->GetTarget().ModulesDidUnload(removed_modules
, false);
5191 new_modules
.ForEach([&target
](const lldb::ModuleSP module_sp
) -> bool {
5192 lldb_private::ObjectFile
*obj
= module_sp
->GetObjectFile();
5196 if (obj
->GetType() != ObjectFile::Type::eTypeExecutable
)
5199 lldb::ModuleSP module_copy_sp
= module_sp
;
5200 target
.SetExecutableModule(module_copy_sp
, eLoadDependentsNo
);
5204 loaded_modules
.AppendIfNeeded(new_modules
);
5205 m_process
->GetTarget().ModulesDidLoad(new_modules
);
5208 return llvm::ErrorSuccess();
5211 Status
ProcessGDBRemote::GetFileLoadAddress(const FileSpec
&file
,
5213 lldb::addr_t
&load_addr
) {
5215 load_addr
= LLDB_INVALID_ADDRESS
;
5217 std::string file_path
= file
.GetPath(false);
5218 if (file_path
.empty())
5219 return Status::FromErrorString("Empty file name specified");
5221 StreamString packet
;
5222 packet
.PutCString("qFileLoadAddress:");
5223 packet
.PutStringAsRawHex8(file_path
);
5225 StringExtractorGDBRemote response
;
5226 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
.GetString(), response
) !=
5227 GDBRemoteCommunication::PacketResult::Success
)
5228 return Status::FromErrorString("Sending qFileLoadAddress packet failed");
5230 if (response
.IsErrorResponse()) {
5231 if (response
.GetError() == 1) {
5232 // The file is not loaded into the inferior
5234 load_addr
= LLDB_INVALID_ADDRESS
;
5238 return Status::FromErrorString(
5239 "Fetching file load address from remote server returned an error");
5242 if (response
.IsNormalResponse()) {
5244 load_addr
= response
.GetHexMaxU64(false, LLDB_INVALID_ADDRESS
);
5248 return Status::FromErrorString(
5249 "Unknown error happened during sending the load address packet");
5252 void ProcessGDBRemote::ModulesDidLoad(ModuleList
&module_list
) {
5253 // We must call the lldb_private::Process::ModulesDidLoad () first before we
5255 Process::ModulesDidLoad(module_list
);
5257 // After loading shared libraries, we can ask our remote GDB server if it
5258 // needs any symbols.
5259 m_gdb_comm
.ServeSymbolLookups(this);
5262 void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out
) {
5263 AppendSTDOUT(out
.data(), out
.size());
5266 static const char *end_delimiter
= "--end--;";
5267 static const int end_delimiter_len
= 8;
5269 void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data
) {
5270 std::string input
= data
.str(); // '1' to move beyond 'A'
5271 if (m_partial_profile_data
.length() > 0) {
5272 m_partial_profile_data
.append(input
);
5273 input
= m_partial_profile_data
;
5274 m_partial_profile_data
.clear();
5277 size_t found
, pos
= 0, len
= input
.length();
5278 while ((found
= input
.find(end_delimiter
, pos
)) != std::string::npos
) {
5279 StringExtractorGDBRemote
profileDataExtractor(
5280 input
.substr(pos
, found
).c_str());
5281 std::string profile_data
=
5282 HarmonizeThreadIdsForProfileData(profileDataExtractor
);
5283 BroadcastAsyncProfileData(profile_data
);
5285 pos
= found
+ end_delimiter_len
;
5289 // Last incomplete chunk.
5290 m_partial_profile_data
= input
.substr(pos
);
5294 std::string
ProcessGDBRemote::HarmonizeThreadIdsForProfileData(
5295 StringExtractorGDBRemote
&profileDataExtractor
) {
5296 std::map
<uint64_t, uint32_t> new_thread_id_to_used_usec_map
;
5298 llvm::raw_string_ostream
output_stream(output
);
5299 llvm::StringRef name
, value
;
5301 // Going to assuming thread_used_usec comes first, else bail out.
5302 while (profileDataExtractor
.GetNameColonValue(name
, value
)) {
5303 if (name
.compare("thread_used_id") == 0) {
5304 StringExtractor
threadIDHexExtractor(value
);
5305 uint64_t thread_id
= threadIDHexExtractor
.GetHexMaxU64(false, 0);
5307 bool has_used_usec
= false;
5308 uint32_t curr_used_usec
= 0;
5309 llvm::StringRef usec_name
, usec_value
;
5310 uint32_t input_file_pos
= profileDataExtractor
.GetFilePos();
5311 if (profileDataExtractor
.GetNameColonValue(usec_name
, usec_value
)) {
5312 if (usec_name
== "thread_used_usec") {
5313 has_used_usec
= true;
5314 usec_value
.getAsInteger(0, curr_used_usec
);
5316 // We didn't find what we want, it is probably an older version. Bail
5318 profileDataExtractor
.SetFilePos(input_file_pos
);
5322 if (has_used_usec
) {
5323 uint32_t prev_used_usec
= 0;
5324 std::map
<uint64_t, uint32_t>::iterator iterator
=
5325 m_thread_id_to_used_usec_map
.find(thread_id
);
5326 if (iterator
!= m_thread_id_to_used_usec_map
.end())
5327 prev_used_usec
= iterator
->second
;
5329 uint32_t real_used_usec
= curr_used_usec
- prev_used_usec
;
5330 // A good first time record is one that runs for at least 0.25 sec
5331 bool good_first_time
=
5332 (prev_used_usec
== 0) && (real_used_usec
> 250000);
5333 bool good_subsequent_time
=
5334 (prev_used_usec
> 0) &&
5335 ((real_used_usec
> 0) || (HasAssignedIndexIDToThread(thread_id
)));
5337 if (good_first_time
|| good_subsequent_time
) {
5338 // We try to avoid doing too many index id reservation, resulting in
5339 // fast increase of index ids.
5341 output_stream
<< name
<< ":";
5342 int32_t index_id
= AssignIndexIDToThread(thread_id
);
5343 output_stream
<< index_id
<< ";";
5345 output_stream
<< usec_name
<< ":" << usec_value
<< ";";
5347 // Skip past 'thread_used_name'.
5348 llvm::StringRef local_name
, local_value
;
5349 profileDataExtractor
.GetNameColonValue(local_name
, local_value
);
5352 // Store current time as previous time so that they can be compared
5354 new_thread_id_to_used_usec_map
[thread_id
] = curr_used_usec
;
5356 // Bail out and use old string.
5357 output_stream
<< name
<< ":" << value
<< ";";
5360 output_stream
<< name
<< ":" << value
<< ";";
5363 output_stream
<< end_delimiter
;
5364 m_thread_id_to_used_usec_map
= new_thread_id_to_used_usec_map
;
5369 void ProcessGDBRemote::HandleStopReply() {
5370 if (GetStopID() != 0)
5373 if (GetID() == LLDB_INVALID_PROCESS_ID
) {
5374 lldb::pid_t pid
= m_gdb_comm
.GetCurrentProcessID();
5375 if (pid
!= LLDB_INVALID_PROCESS_ID
)
5378 BuildDynamicRegisterInfo(true);
5381 llvm::Expected
<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile
) {
5382 if (!m_gdb_comm
.GetSaveCoreSupported())
5385 StreamString packet
;
5386 packet
.PutCString("qSaveCore;path-hint:");
5387 packet
.PutStringAsRawHex8(outfile
);
5389 StringExtractorGDBRemote response
;
5390 if (m_gdb_comm
.SendPacketAndWaitForResponse(packet
.GetString(), response
) ==
5391 GDBRemoteCommunication::PacketResult::Success
) {
5392 // TODO: grab error message from the packet? StringExtractor seems to
5393 // be missing a method for that
5394 if (response
.IsErrorResponse())
5395 return llvm::createStringError(
5396 llvm::inconvertibleErrorCode(),
5397 llvm::formatv("qSaveCore returned an error"));
5401 // process the response
5402 for (auto x
: llvm::split(response
.GetStringRef(), ';')) {
5403 if (x
.consume_front("core-path:"))
5404 StringExtractor(x
).GetHexByteString(path
);
5407 // verify that we've gotten what we need
5409 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5410 "qSaveCore returned no core path");
5412 // now transfer the core file
5413 FileSpec remote_core
{llvm::StringRef(path
)};
5414 Platform
&platform
= *GetTarget().GetPlatform();
5415 Status error
= platform
.GetFile(remote_core
, FileSpec(outfile
));
5417 if (platform
.IsRemote()) {
5418 // NB: we unlink the file on error too
5419 platform
.Unlink(remote_core
);
5421 return error
.ToError();
5427 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5428 "Unable to send qSaveCore");
5431 static const char *const s_async_json_packet_prefix
= "JSON-async:";
5433 static StructuredData::ObjectSP
5434 ParseStructuredDataPacket(llvm::StringRef packet
) {
5435 Log
*log
= GetLog(GDBRLog::Process
);
5437 if (!packet
.consume_front(s_async_json_packet_prefix
)) {
5441 "GDBRemoteCommunicationClientBase::%s() received $J packet "
5442 "but was not a StructuredData packet: packet starts with "
5445 packet
.slice(0, strlen(s_async_json_packet_prefix
)).str().c_str());
5447 return StructuredData::ObjectSP();
5450 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5451 StructuredData::ObjectSP json_sp
= StructuredData::ParseJSON(packet
);
5454 StreamString json_str
;
5455 json_sp
->Dump(json_str
, true);
5458 "ProcessGDBRemote::%s() "
5459 "received Async StructuredData packet: %s",
5460 __FUNCTION__
, json_str
.GetData());
5463 "ProcessGDBRemote::%s"
5464 "() received StructuredData packet:"
5472 void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data
) {
5473 auto structured_data_sp
= ParseStructuredDataPacket(data
);
5474 if (structured_data_sp
)
5475 RouteAsyncStructuredData(structured_data_sp
);
5478 class CommandObjectProcessGDBRemoteSpeedTest
: public CommandObjectParsed
{
5480 CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter
&interpreter
)
5481 : CommandObjectParsed(interpreter
, "process plugin packet speed-test",
5482 "Tests packet speeds of various sizes to determine "
5483 "the performance characteristics of the GDB remote "
5487 m_num_packets(LLDB_OPT_SET_1
, false, "count", 'c', 0, eArgTypeCount
,
5488 "The number of packets to send of each varying size "
5489 "(default is 1000).",
5491 m_max_send(LLDB_OPT_SET_1
, false, "max-send", 's', 0, eArgTypeCount
,
5492 "The maximum number of bytes to send in a packet. Sizes "
5493 "increase in powers of 2 while the size is less than or "
5494 "equal to this option value. (default 1024).",
5496 m_max_recv(LLDB_OPT_SET_1
, false, "max-receive", 'r', 0, eArgTypeCount
,
5497 "The maximum number of bytes to receive in a packet. Sizes "
5498 "increase in powers of 2 while the size is less than or "
5499 "equal to this option value. (default 1024).",
5501 m_json(LLDB_OPT_SET_1
, false, "json", 'j',
5502 "Print the output as JSON data for easy parsing.", false, true) {
5503 m_option_group
.Append(&m_num_packets
, LLDB_OPT_SET_ALL
, LLDB_OPT_SET_1
);
5504 m_option_group
.Append(&m_max_send
, LLDB_OPT_SET_ALL
, LLDB_OPT_SET_1
);
5505 m_option_group
.Append(&m_max_recv
, LLDB_OPT_SET_ALL
, LLDB_OPT_SET_1
);
5506 m_option_group
.Append(&m_json
, LLDB_OPT_SET_ALL
, LLDB_OPT_SET_1
);
5507 m_option_group
.Finalize();
5510 ~CommandObjectProcessGDBRemoteSpeedTest() override
= default;
5512 Options
*GetOptions() override
{ return &m_option_group
; }
5514 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
5515 const size_t argc
= command
.GetArgumentCount();
5517 ProcessGDBRemote
*process
=
5518 (ProcessGDBRemote
*)m_interpreter
.GetExecutionContext()
5521 StreamSP output_stream_sp
= result
.GetImmediateOutputStream();
5522 if (!output_stream_sp
)
5524 StreamSP(m_interpreter
.GetDebugger().GetAsyncOutputStream());
5525 result
.SetImmediateOutputStream(output_stream_sp
);
5527 const uint32_t num_packets
=
5528 (uint32_t)m_num_packets
.GetOptionValue().GetCurrentValue();
5529 const uint64_t max_send
= m_max_send
.GetOptionValue().GetCurrentValue();
5530 const uint64_t max_recv
= m_max_recv
.GetOptionValue().GetCurrentValue();
5531 const bool json
= m_json
.GetOptionValue().GetCurrentValue();
5532 const uint64_t k_recv_amount
=
5533 4 * 1024 * 1024; // Receive amount in bytes
5534 process
->GetGDBRemote().TestPacketSpeed(
5535 num_packets
, max_send
, max_recv
, k_recv_amount
, json
,
5536 output_stream_sp
? *output_stream_sp
: result
.GetOutputStream());
5537 result
.SetStatus(eReturnStatusSuccessFinishResult
);
5541 result
.AppendErrorWithFormat("'%s' takes no arguments",
5542 m_cmd_name
.c_str());
5544 result
.SetStatus(eReturnStatusFailed
);
5548 OptionGroupOptions m_option_group
;
5549 OptionGroupUInt64 m_num_packets
;
5550 OptionGroupUInt64 m_max_send
;
5551 OptionGroupUInt64 m_max_recv
;
5552 OptionGroupBoolean m_json
;
5555 class CommandObjectProcessGDBRemotePacketHistory
: public CommandObjectParsed
{
5558 CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter
&interpreter
)
5559 : CommandObjectParsed(interpreter
, "process plugin packet history",
5560 "Dumps the packet history buffer. ", nullptr) {}
5562 ~CommandObjectProcessGDBRemotePacketHistory() override
= default;
5564 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
5565 ProcessGDBRemote
*process
=
5566 (ProcessGDBRemote
*)m_interpreter
.GetExecutionContext().GetProcessPtr();
5568 process
->DumpPluginHistory(result
.GetOutputStream());
5569 result
.SetStatus(eReturnStatusSuccessFinishResult
);
5572 result
.SetStatus(eReturnStatusFailed
);
5576 class CommandObjectProcessGDBRemotePacketXferSize
: public CommandObjectParsed
{
5579 CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter
&interpreter
)
5580 : CommandObjectParsed(
5581 interpreter
, "process plugin packet xfer-size",
5582 "Maximum size that lldb will try to read/write one one chunk.",
5584 AddSimpleArgumentList(eArgTypeUnsignedInteger
);
5587 ~CommandObjectProcessGDBRemotePacketXferSize() override
= default;
5589 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
5590 const size_t argc
= command
.GetArgumentCount();
5592 result
.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5593 "amount to be transferred when "
5595 m_cmd_name
.c_str());
5599 ProcessGDBRemote
*process
=
5600 (ProcessGDBRemote
*)m_interpreter
.GetExecutionContext().GetProcessPtr();
5602 const char *packet_size
= command
.GetArgumentAtIndex(0);
5604 uint64_t user_specified_max
= strtoul(packet_size
, nullptr, 10);
5605 if (errno
== 0 && user_specified_max
!= 0) {
5606 process
->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max
);
5607 result
.SetStatus(eReturnStatusSuccessFinishResult
);
5611 result
.SetStatus(eReturnStatusFailed
);
5615 class CommandObjectProcessGDBRemotePacketSend
: public CommandObjectParsed
{
5618 CommandObjectProcessGDBRemotePacketSend(CommandInterpreter
&interpreter
)
5619 : CommandObjectParsed(interpreter
, "process plugin packet send",
5620 "Send a custom packet through the GDB remote "
5621 "protocol and print the answer. "
5622 "The packet header and footer will automatically "
5623 "be added to the packet prior to sending and "
5624 "stripped from the result.",
5626 AddSimpleArgumentList(eArgTypeNone
, eArgRepeatStar
);
5629 ~CommandObjectProcessGDBRemotePacketSend() override
= default;
5631 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
5632 const size_t argc
= command
.GetArgumentCount();
5634 result
.AppendErrorWithFormat(
5635 "'%s' takes a one or more packet content arguments",
5636 m_cmd_name
.c_str());
5640 ProcessGDBRemote
*process
=
5641 (ProcessGDBRemote
*)m_interpreter
.GetExecutionContext().GetProcessPtr();
5643 for (size_t i
= 0; i
< argc
; ++i
) {
5644 const char *packet_cstr
= command
.GetArgumentAtIndex(0);
5645 StringExtractorGDBRemote response
;
5646 process
->GetGDBRemote().SendPacketAndWaitForResponse(
5647 packet_cstr
, response
, process
->GetInterruptTimeout());
5648 result
.SetStatus(eReturnStatusSuccessFinishResult
);
5649 Stream
&output_strm
= result
.GetOutputStream();
5650 output_strm
.Printf(" packet: %s\n", packet_cstr
);
5651 std::string response_str
= std::string(response
.GetStringRef());
5653 if (strstr(packet_cstr
, "qGetProfileData") != nullptr) {
5654 response_str
= process
->HarmonizeThreadIdsForProfileData(response
);
5657 if (response_str
.empty())
5658 output_strm
.PutCString("response: \nerror: UNIMPLEMENTED\n");
5660 output_strm
.Printf("response: %s\n", response
.GetStringRef().data());
5666 class CommandObjectProcessGDBRemotePacketMonitor
: public CommandObjectRaw
{
5669 CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter
&interpreter
)
5670 : CommandObjectRaw(interpreter
, "process plugin packet monitor",
5671 "Send a qRcmd packet through the GDB remote protocol "
5672 "and print the response."
5673 "The argument passed to this command will be hex "
5674 "encoded into a valid 'qRcmd' packet, sent and the "
5675 "response will be printed.") {}
5677 ~CommandObjectProcessGDBRemotePacketMonitor() override
= default;
5679 void DoExecute(llvm::StringRef command
,
5680 CommandReturnObject
&result
) override
{
5681 if (command
.empty()) {
5682 result
.AppendErrorWithFormat("'%s' takes a command string argument",
5683 m_cmd_name
.c_str());
5687 ProcessGDBRemote
*process
=
5688 (ProcessGDBRemote
*)m_interpreter
.GetExecutionContext().GetProcessPtr();
5690 StreamString packet
;
5691 packet
.PutCString("qRcmd,");
5692 packet
.PutBytesAsRawHex8(command
.data(), command
.size());
5694 StringExtractorGDBRemote response
;
5695 Stream
&output_strm
= result
.GetOutputStream();
5696 process
->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport(
5697 packet
.GetString(), response
, process
->GetInterruptTimeout(),
5698 [&output_strm
](llvm::StringRef output
) { output_strm
<< output
; });
5699 result
.SetStatus(eReturnStatusSuccessFinishResult
);
5700 output_strm
.Printf(" packet: %s\n", packet
.GetData());
5701 const std::string
&response_str
= std::string(response
.GetStringRef());
5703 if (response_str
.empty())
5704 output_strm
.PutCString("response: \nerror: UNIMPLEMENTED\n");
5706 output_strm
.Printf("response: %s\n", response
.GetStringRef().data());
5711 class CommandObjectProcessGDBRemotePacket
: public CommandObjectMultiword
{
5714 CommandObjectProcessGDBRemotePacket(CommandInterpreter
&interpreter
)
5715 : CommandObjectMultiword(interpreter
, "process plugin packet",
5716 "Commands that deal with GDB remote packets.",
5721 new CommandObjectProcessGDBRemotePacketHistory(interpreter
)));
5723 "send", CommandObjectSP(
5724 new CommandObjectProcessGDBRemotePacketSend(interpreter
)));
5728 new CommandObjectProcessGDBRemotePacketMonitor(interpreter
)));
5732 new CommandObjectProcessGDBRemotePacketXferSize(interpreter
)));
5733 LoadSubCommand("speed-test",
5734 CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest(
5738 ~CommandObjectProcessGDBRemotePacket() override
= default;
5741 class CommandObjectMultiwordProcessGDBRemote
: public CommandObjectMultiword
{
5743 CommandObjectMultiwordProcessGDBRemote(CommandInterpreter
&interpreter
)
5744 : CommandObjectMultiword(
5745 interpreter
, "process plugin",
5746 "Commands for operating on a ProcessGDBRemote process.",
5747 "process plugin <subcommand> [<subcommand-options>]") {
5750 CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter
)));
5753 ~CommandObjectMultiwordProcessGDBRemote() override
= default;
5756 CommandObject
*ProcessGDBRemote::GetPluginCommandObject() {
5758 m_command_sp
= std::make_shared
<CommandObjectMultiwordProcessGDBRemote
>(
5759 GetTarget().GetDebugger().GetCommandInterpreter());
5760 return m_command_sp
.get();
5763 void ProcessGDBRemote::DidForkSwitchSoftwareBreakpoints(bool enable
) {
5764 GetBreakpointSiteList().ForEach([this, enable
](BreakpointSite
*bp_site
) {
5765 if (bp_site
->IsEnabled() &&
5766 (bp_site
->GetType() == BreakpointSite::eSoftware
||
5767 bp_site
->GetType() == BreakpointSite::eExternal
)) {
5768 m_gdb_comm
.SendGDBStoppointTypePacket(
5769 eBreakpointSoftware
, enable
, bp_site
->GetLoadAddress(),
5770 GetSoftwareBreakpointTrapOpcode(bp_site
), GetInterruptTimeout());
5775 void ProcessGDBRemote::DidForkSwitchHardwareTraps(bool enable
) {
5776 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointHardware
)) {
5777 GetBreakpointSiteList().ForEach([this, enable
](BreakpointSite
*bp_site
) {
5778 if (bp_site
->IsEnabled() &&
5779 bp_site
->GetType() == BreakpointSite::eHardware
) {
5780 m_gdb_comm
.SendGDBStoppointTypePacket(
5781 eBreakpointHardware
, enable
, bp_site
->GetLoadAddress(),
5782 GetSoftwareBreakpointTrapOpcode(bp_site
), GetInterruptTimeout());
5787 for (const auto &wp_res_sp
: m_watchpoint_resource_list
.Sites()) {
5788 addr_t addr
= wp_res_sp
->GetLoadAddress();
5789 size_t size
= wp_res_sp
->GetByteSize();
5790 GDBStoppointType type
= GetGDBStoppointType(wp_res_sp
);
5791 m_gdb_comm
.SendGDBStoppointTypePacket(type
, enable
, addr
, size
,
5792 GetInterruptTimeout());
5796 void ProcessGDBRemote::DidFork(lldb::pid_t child_pid
, lldb::tid_t child_tid
) {
5797 Log
*log
= GetLog(GDBRLog::Process
);
5799 lldb::pid_t parent_pid
= m_gdb_comm
.GetCurrentProcessID();
5800 // Any valid TID will suffice, thread-relevant actions will set a proper TID
5802 lldb::tid_t parent_tid
= m_thread_ids
.front();
5804 lldb::pid_t follow_pid
, detach_pid
;
5805 lldb::tid_t follow_tid
, detach_tid
;
5807 switch (GetFollowForkMode()) {
5809 follow_pid
= parent_pid
;
5810 follow_tid
= parent_tid
;
5811 detach_pid
= child_pid
;
5812 detach_tid
= child_tid
;
5815 follow_pid
= child_pid
;
5816 follow_tid
= child_tid
;
5817 detach_pid
= parent_pid
;
5818 detach_tid
= parent_tid
;
5822 // Switch to the process that is going to be detached.
5823 if (!m_gdb_comm
.SetCurrentThread(detach_tid
, detach_pid
)) {
5824 LLDB_LOG(log
, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5828 // Disable all software breakpoints in the forked process.
5829 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointSoftware
))
5830 DidForkSwitchSoftwareBreakpoints(false);
5832 // Remove hardware breakpoints / watchpoints from parent process if we're
5834 if (GetFollowForkMode() == eFollowChild
)
5835 DidForkSwitchHardwareTraps(false);
5837 // Switch to the process that is going to be followed
5838 if (!m_gdb_comm
.SetCurrentThread(follow_tid
, follow_pid
) ||
5839 !m_gdb_comm
.SetCurrentThreadForRun(follow_tid
, follow_pid
)) {
5840 LLDB_LOG(log
, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5844 LLDB_LOG(log
, "Detaching process {0}", detach_pid
);
5845 Status error
= m_gdb_comm
.Detach(false, detach_pid
);
5847 LLDB_LOG(log
, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5848 error
.AsCString() ? error
.AsCString() : "<unknown error>");
5852 // Hardware breakpoints/watchpoints are not inherited implicitly,
5853 // so we need to readd them if we're following child.
5854 if (GetFollowForkMode() == eFollowChild
) {
5855 DidForkSwitchHardwareTraps(true);
5861 void ProcessGDBRemote::DidVFork(lldb::pid_t child_pid
, lldb::tid_t child_tid
) {
5862 Log
*log
= GetLog(GDBRLog::Process
);
5866 "ProcessGDBRemote::DidFork() called for child_pid: {0}, child_tid {1}",
5867 child_pid
, child_tid
);
5868 ++m_vfork_in_progress_count
;
5870 // Disable all software breakpoints for the duration of vfork.
5871 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointSoftware
))
5872 DidForkSwitchSoftwareBreakpoints(false);
5874 lldb::pid_t detach_pid
;
5875 lldb::tid_t detach_tid
;
5877 switch (GetFollowForkMode()) {
5879 detach_pid
= child_pid
;
5880 detach_tid
= child_tid
;
5883 detach_pid
= m_gdb_comm
.GetCurrentProcessID();
5884 // Any valid TID will suffice, thread-relevant actions will set a proper TID
5886 detach_tid
= m_thread_ids
.front();
5888 // Switch to the parent process before detaching it.
5889 if (!m_gdb_comm
.SetCurrentThread(detach_tid
, detach_pid
)) {
5890 LLDB_LOG(log
, "ProcessGDBRemote::DidFork() unable to set pid/tid");
5894 // Remove hardware breakpoints / watchpoints from the parent process.
5895 DidForkSwitchHardwareTraps(false);
5897 // Switch to the child process.
5898 if (!m_gdb_comm
.SetCurrentThread(child_tid
, child_pid
) ||
5899 !m_gdb_comm
.SetCurrentThreadForRun(child_tid
, child_pid
)) {
5900 LLDB_LOG(log
, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
5906 LLDB_LOG(log
, "Detaching process {0}", detach_pid
);
5907 Status error
= m_gdb_comm
.Detach(false, detach_pid
);
5910 "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
5911 error
.AsCString() ? error
.AsCString() : "<unknown error>");
5915 if (GetFollowForkMode() == eFollowChild
) {
5921 void ProcessGDBRemote::DidVForkDone() {
5922 assert(m_vfork_in_progress_count
> 0);
5923 --m_vfork_in_progress_count
;
5925 // Reenable all software breakpoints that were enabled before vfork.
5926 if (m_gdb_comm
.SupportsGDBStoppointPacket(eBreakpointSoftware
))
5927 DidForkSwitchSoftwareBreakpoints(true);
5930 void ProcessGDBRemote::DidExec() {
5931 // If we are following children, vfork is finished by exec (rather than
5932 // vforkdone that is submitted for parent).
5933 if (GetFollowForkMode() == eFollowChild
) {
5934 if (m_vfork_in_progress_count
> 0)
5935 --m_vfork_in_progress_count
;