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

source code of lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp