LLDB mainline
ProcessGDBRemote.cpp
Go to the documentation of this file.
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/ioctl.h>
16#include <sys/mman.h>
17#include <sys/socket.h>
18#include <unistd.h>
19#endif
20#include <sys/stat.h>
21#if defined(__APPLE__)
22#include <sys/sysctl.h>
23#endif
24#ifdef _WIN32
26#endif
27#include <ctime>
28#include <sys/types.h>
29
35#include "lldb/Core/Debugger.h"
37#include "lldb/Core/Module.h"
40#include "lldb/Core/Value.h"
44#include "lldb/Host/HostInfo.h"
46#include "lldb/Host/PosixApi.h"
50#include "lldb/Host/XML.h"
63#include "lldb/Symbol/Symbol.h"
65#include "lldb/Target/ABI.h"
70#include "lldb/Target/Target.h"
75#include "lldb/Utility/Args.h"
76#include "lldb/Utility/Baton.h"
83#include "lldb/Utility/State.h"
85#include "lldb/Utility/Timer.h"
86#include <algorithm>
87#include <csignal>
88#include <map>
89#include <memory>
90#include <mutex>
91#include <optional>
92#include <sstream>
93#include <thread>
94
100#include "ProcessGDBRemote.h"
101#include "ProcessGDBRemoteLog.h"
102#include "ThreadGDBRemote.h"
103#include "lldb/Host/Host.h"
105
106#include "llvm/ADT/STLExtras.h"
107#include "llvm/ADT/ScopeExit.h"
108#include "llvm/ADT/StringMap.h"
109#include "llvm/ADT/StringSwitch.h"
110#include "llvm/Support/Casting.h"
111#include "llvm/Support/Chrono.h"
112#include "llvm/Support/ErrorExtras.h"
113#include "llvm/Support/FormatAdapters.h"
114#include "llvm/Support/Threading.h"
115#include "llvm/Support/raw_ostream.h"
116
117#if defined(__APPLE__)
118#define DEBUGSERVER_BASENAME "debugserver"
119#elif defined(_WIN32)
120#define DEBUGSERVER_BASENAME "lldb-server.exe"
121#else
122#define DEBUGSERVER_BASENAME "lldb-server"
123#endif
124
125using namespace lldb;
126using namespace lldb_private;
128
130
131namespace lldb {
132// Provide a function that can easily dump the packet history if we know a
133// ProcessGDBRemote * value (which we can get from logs or from debugging). We
134// need the function in the lldb namespace so it makes it into the final
135// executable since the LLDB shared library only exports stuff in the lldb
136// namespace. This allows you to attach with a debugger and call this function
137// and get the packet history dumped to a file.
138void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
139 auto file = FileSystem::Instance().Open(
141 if (!file) {
142 llvm::consumeError(file.takeError());
143 return;
144 }
145 StreamFile stream(std::move(file.get()));
146 ((Process *)p)->DumpPluginHistory(stream);
147}
148} // namespace lldb
149
150namespace {
151
152#define LLDB_PROPERTIES_processgdbremote
153#include "ProcessGDBRemoteProperties.inc"
154
155enum {
156#define LLDB_PROPERTIES_processgdbremote
157#include "ProcessGDBRemotePropertiesEnum.inc"
158};
159
160class PluginProperties : public Properties {
161public:
162 static llvm::StringRef GetSettingName() {
164 }
165
166 PluginProperties() : Properties() {
167 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
168 m_collection_sp->Initialize(g_processgdbremote_properties_def);
169 }
170
171 ~PluginProperties() override = default;
172
173 uint64_t GetPacketTimeout() {
174 const uint32_t idx = ePropertyPacketTimeout;
175 return GetPropertyAtIndexAs<uint64_t>(
176 idx, g_processgdbremote_properties[idx].default_uint_value);
177 }
178
179 bool SetPacketTimeout(uint64_t timeout) {
180 const uint32_t idx = ePropertyPacketTimeout;
181 return SetPropertyAtIndex(idx, timeout);
182 }
183
184 FileSpec GetTargetDefinitionFile() const {
185 const uint32_t idx = ePropertyTargetDefinitionFile;
186 return GetPropertyAtIndexAs<FileSpec>(idx, {});
187 }
188
189 bool GetUseSVR4() const {
190 const uint32_t idx = ePropertyUseSVR4;
191 return GetPropertyAtIndexAs<bool>(
192 idx, g_processgdbremote_properties[idx].default_uint_value != 0);
193 }
194
195 bool GetUseGPacketForReading() const {
196 const uint32_t idx = ePropertyUseGPacketForReading;
197 return GetPropertyAtIndexAs<bool>(idx, true);
198 }
199
200 uint64_t GetPacketTestDelay() const {
201 const uint32_t idx = ePropertyPacketTestDelay;
202 return GetPropertyAtIndexAs<uint64_t>(
203 idx, g_processgdbremote_properties[idx].default_uint_value);
204 }
205};
206
207std::chrono::seconds ResumeTimeout() { return std::chrono::seconds(5); }
208
209static std::pair<uint16_t, uint16_t> GetClientTerminalSize() {
210#ifdef _WIN32
211 CONSOLE_SCREEN_BUFFER_INFO csbi{};
212 HANDLE h = ::GetStdHandle(STD_OUTPUT_HANDLE);
213 if (h != INVALID_HANDLE_VALUE && ::GetConsoleScreenBufferInfo(h, &csbi)) {
214 int cols = csbi.srWindow.Right - csbi.srWindow.Left + 1;
215 int rows = csbi.srWindow.Bottom - csbi.srWindow.Top + 1;
216 if (cols > 0 && rows > 0)
217 return {static_cast<uint16_t>(cols), static_cast<uint16_t>(rows)};
218 }
219#elif LLDB_ENABLE_POSIX
220 struct winsize ws{};
221 if (::ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0 &&
222 ws.ws_row > 0)
223 return {ws.ws_col, ws.ws_row};
224#endif
225 return {0, 0};
226}
227
228} // namespace
229
230static PluginProperties &GetGlobalPluginProperties() {
231 static PluginProperties g_settings;
232 return g_settings;
233}
234
235// TODO Randomly assigning a port is unsafe. We should get an unused
236// ephemeral port from the kernel and make sure we reserve it before passing it
237// to debugserver.
238
239#if defined(__APPLE__)
240#define LOW_PORT (IPPORT_RESERVED)
241#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
242#else
243#define LOW_PORT (1024u)
244#define HIGH_PORT (49151u)
245#endif
246
248 return "GDB Remote protocol based debugging plug-in.";
249}
250
254
256 lldb::TargetSP target_sp, ListenerSP listener_sp,
257 const FileSpec *crash_file_path, bool can_connect) {
258 if (crash_file_path)
259 return nullptr; // Cannot create a GDBRemote process from a crash_file.
260 return lldb::ProcessSP(new ProcessGDBRemote(target_sp, listener_sp));
261}
262
267
269 return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
270}
271
272std::chrono::milliseconds ProcessGDBRemote::GetPacketTestDelay() {
273 return std::chrono::milliseconds(
275}
276
278 return m_gdb_comm.GetHostArchitecture();
279}
280
282 bool plugin_specified_by_name) {
283 if (plugin_specified_by_name)
284 return true;
285
286 // For now we are just making sure the file exists for a given module
287 Module *exe_module = target_sp->GetExecutableModulePointer();
288 if (exe_module) {
289 ObjectFile *exe_objfile = exe_module->GetObjectFile();
290 // We can't debug core files...
291 switch (exe_objfile->GetType()) {
299 return false;
303 break;
304 }
305 return FileSystem::Instance().Exists(exe_module->GetFileSpec());
306 }
307 // However, if there is no executable module, we return true since we might
308 // be preparing to attach.
309 return true;
310}
311
312// ProcessGDBRemote constructor
314 ListenerSP listener_sp)
315 : Process(target_sp, listener_sp),
317 m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
319 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
329 "async thread should exit");
331 "async thread continue");
333 "async thread did exit");
334
335 Log *log = GetLog(GDBRLog::Async);
336
337 const uint32_t async_event_mask =
339
340 if (m_async_listener_sp->StartListeningForEvents(
341 &m_async_broadcaster, async_event_mask) != async_event_mask) {
342 LLDB_LOGF(log,
343 "ProcessGDBRemote::%s failed to listen for "
344 "m_async_broadcaster events",
345 __FUNCTION__);
346 }
347
348 const uint64_t timeout_seconds =
349 GetGlobalPluginProperties().GetPacketTimeout();
350 if (timeout_seconds > 0)
351 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
352
354 GetGlobalPluginProperties().GetUseGPacketForReading();
355
356 // Contribute the packet history to diagnostics bundles, named with the
357 // creation timestamp so files from different processes stay distinguishable.
358 if (Diagnostics::Enabled()) {
359 llvm::sys::TimePoint<> now = std::chrono::system_clock::now();
360 std::string name = llvm::formatv(
361 "gdb-remote-packet-history-{0:%Y-%m-%dT%H-%M-%S}.txt", now);
363 std::move(name), [this]() -> std::string {
364 StreamString stream;
365 DumpPluginHistory(stream);
366 return stream.GetString().str();
367 });
368 }
369}
370
371// Destructor
373 // Unregister before teardown so a concurrent collection can't run the
374 // provider on a half-destroyed process.
377
378 // m_mach_process.UnregisterNotificationCallbacks (this);
379 Clear();
380 // We need to call finalize on the process before destroying ourselves to
381 // make sure all of the broadcaster cleanup goes as planned. If we destruct
382 // this class, then Process::~Process() might have problems trying to fully
383 // destroy the broadcaster.
384 Finalize(true /* destructing */);
385
386 // The general Finalize is going to try to destroy the process and that
387 // SHOULD shut down the async thread. However, if we don't kill it it will
388 // get stranded and its connection will go away so when it wakes up it will
389 // crash. So kill it for sure here.
392}
393
394std::shared_ptr<ThreadGDBRemote>
396 return std::make_shared<ThreadGDBRemote>(*this, tid);
397}
398
400 const FileSpec &target_definition_fspec) {
401 ScriptInterpreter *interpreter =
404 StructuredData::ObjectSP module_object_sp(
405 interpreter->LoadPluginModule(target_definition_fspec, error));
406 if (module_object_sp) {
407 StructuredData::DictionarySP target_definition_sp(
408 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
409 "gdb-server-target-definition", error));
410
411 if (target_definition_sp) {
412 StructuredData::ObjectSP target_object(
413 target_definition_sp->GetValueForKey("host-info"));
414 if (target_object) {
415 if (auto host_info_dict = target_object->GetAsDictionary()) {
416 StructuredData::ObjectSP triple_value =
417 host_info_dict->GetValueForKey("triple");
418 if (auto triple_string_value = triple_value->GetAsString()) {
419 std::string triple_string =
420 std::string(triple_string_value->GetValue());
421 ArchSpec host_arch(triple_string.c_str());
422 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
423 GetTarget().SetArchitecture(host_arch);
424 }
425 }
426 }
427 }
429 StructuredData::ObjectSP breakpoint_pc_offset_value =
430 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
431 if (breakpoint_pc_offset_value) {
432 if (auto breakpoint_pc_int_value =
433 breakpoint_pc_offset_value->GetAsSignedInteger())
434 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
435 }
436
437 if (m_register_info_sp->SetRegisterInfo(
438 *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
439 return true;
440 }
441 }
442 }
443 return false;
444}
445
447 const llvm::StringRef &comma_separated_register_numbers,
448 std::vector<uint32_t> &regnums, int base) {
449 regnums.clear();
450 for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
451 uint32_t reg;
452 if (llvm::to_integer(x, reg, base))
453 regnums.push_back(reg);
454 }
455 return regnums.size();
456}
457
459 if (!force && m_register_info_sp)
460 return;
461
462 m_register_info_sp = std::make_shared<DynamicRegisterInfo>();
463
464 // Check if qHostInfo specified a specific packet timeout for this
465 // connection. If so then lets update our setting so the user knows what the
466 // timeout is and can see it.
467 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
468 if (host_packet_timeout > std::chrono::seconds(0)) {
469 GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
470 }
471
472 // Register info search order:
473 // 1 - Use the target definition python file if one is specified.
474 // 2 - If the target definition doesn't have any of the info from the
475 // target.xml (registers) then proceed to read the target.xml.
476 // 3 - Fall back on the qRegisterInfo packets.
477 // 4 - Use hardcoded defaults if available.
478
479 FileSpec target_definition_fspec =
480 GetGlobalPluginProperties().GetTargetDefinitionFile();
481 if (!FileSystem::Instance().Exists(target_definition_fspec)) {
482 // If the filename doesn't exist, it may be a ~ not having been expanded -
483 // try to resolve it.
484 FileSystem::Instance().Resolve(target_definition_fspec);
485 }
486 if (target_definition_fspec) {
487 // See if we can get register definitions from a python file
488 if (ParsePythonTargetDefinition(target_definition_fspec))
489 return;
490
491 Debugger::ReportError("target description file " +
492 target_definition_fspec.GetPath() +
493 " failed to parse",
494 GetTarget().GetDebugger().GetID());
495 }
496
497 const ArchSpec &target_arch = GetTarget().GetArchitecture();
498 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
499 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
500
501 // Use the process' architecture instead of the host arch, if available
502 ArchSpec arch_to_use;
503 if (remote_process_arch.IsValid())
504 arch_to_use = remote_process_arch;
505 else
506 arch_to_use = remote_host_arch;
507
508 if (!arch_to_use.IsValid())
509 arch_to_use = target_arch;
510
511 llvm::Error register_info_err = GetGDBServerRegisterInfo(arch_to_use);
512 if (!register_info_err) {
513 // We got the registers from target XML.
514 return;
515 }
516
518 LLDB_LOG_ERROR(log, std::move(register_info_err),
519 "Failed to read register information from target XML: {0}");
520 LLDB_LOG(log, "Now trying to use qRegisterInfo instead.");
521
522 char packet[128];
523 std::vector<DynamicRegisterInfo::Register> registers;
524 uint32_t reg_num = 0;
525 for (StringExtractorGDBRemote::ResponseType response_type =
527 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
528 const int packet_len =
529 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
530 assert(packet_len < (int)sizeof(packet));
531 UNUSED_IF_ASSERT_DISABLED(packet_len);
533 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
535 response_type = response.GetResponseType();
536 if (response_type == StringExtractorGDBRemote::eResponse) {
537 llvm::StringRef name;
538 llvm::StringRef value;
540
541 while (response.GetNameColonValue(name, value)) {
542 if (name == "name") {
543 reg_info.name = value.str();
544 } else if (name == "alt-name") {
545 reg_info.alt_name = value.str();
546 } else if (name == "bitsize") {
547 if (!value.getAsInteger(BASE_10, reg_info.byte_size))
548 reg_info.byte_size /= CHAR_BIT;
549 } else if (name == "offset") {
550 value.getAsInteger(BASE_10, reg_info.byte_offset);
551 } else if (name == "encoding") {
552 const Encoding encoding = Args::StringToEncoding(value);
553 if (encoding != eEncodingInvalid)
554 reg_info.encoding = encoding;
555 } else if (name == "format") {
556 if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
557 .Success())
558 reg_info.format =
559 llvm::StringSwitch<Format>(value)
560 .Case("boolean", eFormatBoolean)
561 .Case("binary", eFormatBinary)
562 .Case("bytes", eFormatBytes)
563 .Case("bytes-with-ascii", eFormatBytesWithASCII)
564 .Case("char", eFormatChar)
565 .Case("char-printable", eFormatCharPrintable)
566 .Case("complex", eFormatComplex)
567 .Case("cstring", eFormatCString)
568 .Case("decimal", eFormatDecimal)
569 .Case("enum", eFormatEnum)
570 .Case("hex", eFormatHex)
571 .Case("hex-uppercase", eFormatHexUppercase)
572 .Case("float", eFormatFloat)
573 .Case("octal", eFormatOctal)
574 .Case("ostype", eFormatOSType)
575 .Case("unicode16", eFormatUnicode16)
576 .Case("unicode32", eFormatUnicode32)
577 .Case("unsigned", eFormatUnsigned)
578 .Case("pointer", eFormatPointer)
579 .Case("vector-char", eFormatVectorOfChar)
580 .Case("vector-sint64", eFormatVectorOfSInt64)
581 .Case("vector-float16", eFormatVectorOfFloat16)
582 .Case("vector-float64", eFormatVectorOfFloat64)
583 .Case("vector-sint8", eFormatVectorOfSInt8)
584 .Case("vector-uint8", eFormatVectorOfUInt8)
585 .Case("vector-sint16", eFormatVectorOfSInt16)
586 .Case("vector-uint16", eFormatVectorOfUInt16)
587 .Case("vector-sint32", eFormatVectorOfSInt32)
588 .Case("vector-uint32", eFormatVectorOfUInt32)
589 .Case("vector-float32", eFormatVectorOfFloat32)
590 .Case("vector-uint64", eFormatVectorOfUInt64)
591 .Case("vector-uint128", eFormatVectorOfUInt128)
592 .Case("complex-integer", eFormatComplexInteger)
593 .Case("char-array", eFormatCharArray)
594 .Case("address-info", eFormatAddressInfo)
595 .Case("hex-float", eFormatHexFloat)
596 .Case("instruction", eFormatInstruction)
597 .Case("void", eFormatVoid)
598 .Case("unicode8", eFormatUnicode8)
599 .Case("float128", eFormatFloat128)
600 .Default(eFormatInvalid);
601 } else if (name == "set") {
602 reg_info.set_name = value.str();
603 } else if (name == "gcc" || name == "ehframe") {
604 value.getAsInteger(BASE_AUTOSENSE, reg_info.regnum_ehframe);
605 } else if (name == "dwarf") {
606 value.getAsInteger(BASE_AUTOSENSE, reg_info.regnum_dwarf);
607 } else if (name == "generic") {
609 } else if (name == "container-regs") {
611 } else if (name == "invalidate-regs") {
613 }
614 }
615
616 assert(reg_info.byte_size != 0);
617 registers.push_back(reg_info);
618 } else {
619 // Only warn if we were offered Target XML and could not use it, and
620 // the qRegisterInfo fallback failed. This is something a user could
621 // take action on by getting an lldb with libxml2.
622 //
623 // It's possible we weren't offered Target XML and qRegisterInfo failed,
624 // but there's no much a user can do about that. It may be the intended
625 // way the debug stub works, so we do not warn for that case.
626 if (response_type == StringExtractorGDBRemote::eUnsupported &&
627 m_gdb_comm.GetQXferFeaturesReadSupported() &&
630 "the debug server supports Target Description XML but LLDB does "
631 "not have XML parsing enabled. Using \"qRegisterInfo\" was also "
632 "not possible. Register information may be incorrect or missing",
633 GetTarget().GetDebugger().GetID());
634 }
635 break;
636 }
637 } else {
638 break;
639 }
640 }
641
642 if (registers.empty()) {
643 registers = GetFallbackRegisters(arch_to_use);
644 if (!registers.empty())
645 LLDB_LOG(
646 log,
647 "All other methods failed, using fallback register information.");
648 }
649
650 AddRemoteRegisters(registers, arch_to_use);
651}
652
656
660
662 bool wait_for_launch) {
663 return WillLaunchOrAttach();
664}
665
666Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
668
670 if (error.Fail())
671 return error;
672
673 error = ConnectToDebugserver(remote_url);
674 if (error.Fail())
675 return error;
676
678
679 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
680 if (pid == LLDB_INVALID_PROCESS_ID) {
681 // We don't have a valid process ID, so note that we are connected and
682 // could now request to launch or attach, or get remote process listings...
684 } else {
685 // We have a valid process
686 SetID(pid);
689 if (m_gdb_comm.GetStopReply(response)) {
690 SetLastStopPacket(response);
691
692 Target &target = GetTarget();
693 if (!target.GetArchitecture().IsValid()) {
694 if (m_gdb_comm.GetProcessArchitecture().IsValid()) {
695 target.SetArchitecture(m_gdb_comm.GetProcessArchitecture());
696 } else {
697 if (m_gdb_comm.GetHostArchitecture().IsValid()) {
698 target.SetArchitecture(m_gdb_comm.GetHostArchitecture());
699 }
700 }
701 }
702
703 const StateType state = SetThreadStopInfo(response);
704 if (state != eStateInvalid) {
705 SetPrivateState(state);
706 } else
708 "Process %" PRIu64 " was reported after connecting to "
709 "'%s', but state was not stopped: %s",
710 pid, remote_url.str().c_str(), StateAsCString(state));
711 } else
713 "Process %" PRIu64 " was reported after connecting to '%s', "
714 "but no stop reply packet was received",
715 pid, remote_url.str().c_str());
716 }
717
718 LLDB_LOGF(log,
719 "ProcessGDBRemote::%s pid %" PRIu64
720 ": normalizing target architecture initial triple: %s "
721 "(GetTarget().GetArchitecture().IsValid() %s, "
722 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
723 __FUNCTION__, GetID(),
724 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
725 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
726 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
727
728 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
729 m_gdb_comm.GetHostArchitecture().IsValid()) {
730 // Prefer the *process'* architecture over that of the *host*, if
731 // available.
732 if (m_gdb_comm.GetProcessArchitecture().IsValid())
733 GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture());
734 else
735 GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture());
736 }
737
738 LLDB_LOGF(log,
739 "ProcessGDBRemote::%s pid %" PRIu64
740 ": normalized target architecture triple: %s",
741 __FUNCTION__, GetID(),
742 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
743
744 return error;
745}
746
752
753// Process Control
755 ProcessLaunchInfo &launch_info) {
758
759 LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
760
761 uint32_t launch_flags = launch_info.GetFlags().Get();
762 FileSpec stdin_file_spec{};
763 FileSpec stdout_file_spec{};
764 FileSpec stderr_file_spec{};
765 FileSpec working_dir = launch_info.GetWorkingDirectory();
766
767 const FileAction *file_action;
768 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
769 if (file_action) {
770 if (file_action->GetAction() == FileAction::eFileActionOpen)
771 stdin_file_spec = file_action->GetFileSpec();
772 }
773 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
774 if (file_action) {
775 if (file_action->GetAction() == FileAction::eFileActionOpen)
776 stdout_file_spec = file_action->GetFileSpec();
777 }
778 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
779 if (file_action) {
780 if (file_action->GetAction() == FileAction::eFileActionOpen)
781 stderr_file_spec = file_action->GetFileSpec();
782 }
783
784 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
785 LLDB_LOGF(log,
786 "ProcessGDBRemote::%s provided with STDIO paths via "
787 "launch_info: stdin=%s, stdout=%s, stderr=%s",
788 __FUNCTION__,
789 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
790 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
791 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
792 else
793 LLDB_LOGF(log, "ProcessGDBRemote::%s no STDIO paths given via launch_info",
794 __FUNCTION__);
795
796 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
797 if (stdin_file_spec || disable_stdio) {
798 // the inferior will be reading stdin from the specified file or stdio is
799 // completely disabled
800 m_stdin_forward = false;
801 } else {
802 m_stdin_forward = true;
803 }
804
805 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
806 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
807 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
808 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
809 // ::LogSetLogFile ("/dev/stdout");
810
811 error = EstablishConnectionIfNeeded(launch_info);
812 if (error.Success()) {
813 PseudoTerminal pty;
814 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
815
816 PlatformSP platform_sp(GetTarget().GetPlatform());
817 if (disable_stdio) {
818 // set to /dev/null unless redirected to a file above
819 if (!stdin_file_spec)
820 stdin_file_spec.SetFile(FileSystem::DEV_NULL,
821 FileSpec::Style::native);
822 if (!stdout_file_spec)
823 stdout_file_spec.SetFile(FileSystem::DEV_NULL,
824 FileSpec::Style::native);
825 if (!stderr_file_spec)
826 stderr_file_spec.SetFile(FileSystem::DEV_NULL,
827 FileSpec::Style::native);
828 } else if (platform_sp && platform_sp->IsHost()) {
829 // If the debugserver is local and we aren't disabling STDIO, lets use
830 // a pseudo terminal to instead of relying on the 'O' packets for stdio
831 // since 'O' packets can really slow down debugging if the inferior
832 // does a lot of output.
833 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
834 !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
835 FileSpec secondary_name(pty.GetSecondaryName());
836
837 if (!stdin_file_spec)
838 stdin_file_spec = secondary_name;
839
840 if (!stdout_file_spec)
841 stdout_file_spec = secondary_name;
842
843 if (!stderr_file_spec)
844 stderr_file_spec = secondary_name;
845 }
846 LLDB_LOGF(
847 log,
848 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
849 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
850 "stderr=%s",
851 __FUNCTION__,
852 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
853 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
854 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
855 }
856
857 LLDB_LOGF(log,
858 "ProcessGDBRemote::%s final STDIO paths after all "
859 "adjustments: stdin=%s, stdout=%s, stderr=%s",
860 __FUNCTION__,
861 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
862 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
863 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
864
865 if (stdin_file_spec)
866 m_gdb_comm.SetSTDIN(stdin_file_spec);
867 if (stdout_file_spec)
868 m_gdb_comm.SetSTDOUT(stdout_file_spec);
869 if (stderr_file_spec)
870 m_gdb_comm.SetSTDERR(stderr_file_spec);
871
872 if (launch_flags & eLaunchFlagUsePipes) {
873 m_gdb_comm.SetSTDIOWindowSize(0, 0);
874 } else {
875 auto [terminal_cols, terminal_rows] = GetClientTerminalSize();
876 m_gdb_comm.SetSTDIOWindowSize(terminal_cols, terminal_rows);
877 }
878
879 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
880 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
881
882 m_gdb_comm.SendLaunchArchPacket(
883 GetTarget().GetArchitecture().GetArchitectureName());
884
885 const char *launch_event_data = launch_info.GetLaunchEventData();
886 if (launch_event_data != nullptr && *launch_event_data != '\0')
887 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
888
889 if (working_dir) {
890 m_gdb_comm.SetWorkingDir(working_dir);
891 }
892
893 // Send the environment and the program + arguments after we connect
894 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
895
897 {
898 // Scope for the scoped timeout object
900 std::chrono::seconds(10));
901
902 // Since we can't send argv0 separate from the executable path, we need to
903 // make sure to use the actual executable path found in the launch_info...
904 Args args = launch_info.GetArguments();
905 if (FileSpec exe_file = launch_info.GetExecutableFile()) {
906 const llvm::Triple &remote_triple =
908 if (remote_triple.getOS() != llvm::Triple::UnknownOS) {
909 FileSpec remote_exe_file(exe_file.GetPath(/*denormalize=*/false),
910 remote_triple);
912 0, remote_exe_file.GetPath(/*denormalize=*/true));
913 } else {
915 exe_file.GetPath(/*denormalize=*/true));
916 }
917 }
918 llvm::Expected<StringExtractorGDBRemote> launch_response =
919 m_gdb_comm.LaunchProcess(args);
920 if (!launch_response) {
922 "Cannot launch '{0}': {1}", args.GetArgumentAtIndex(0),
923 llvm::fmt_consume(launch_response.takeError()));
924 } else {
925 response = std::move(*launch_response);
926 SetID(m_gdb_comm.GetCurrentProcessID());
927 }
928 }
929
931 LLDB_LOGF(log, "failed to connect to debugserver: %s",
932 error.AsCString());
934 return error;
935 }
936
938 m_gdb_comm.GetStopReply(response)) {
939 SetLastStopPacket(response);
940
941 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
942
943 if (process_arch.IsValid()) {
944 GetTarget().MergeArchitecture(process_arch);
945 } else {
946 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
947 if (host_arch.IsValid())
948 GetTarget().MergeArchitecture(host_arch);
949 }
950
951 StateType state = SetThreadStopInfo(response);
952 if (state == eStateExited)
954 else
955 SetPrivateState(state);
956
957 if (!disable_stdio) {
959#ifdef _WIN32
961#else
963#endif
964 }
965#ifdef _WIN32
966 else if (m_stdin_forward) {
967 // No client-side PTY FD on Windows.
968 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
971 std::make_shared<IOHandlerProcessSTDIOWindows>(this);
972 }
973#endif
974 }
975 }
976 } else {
977 LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
978 }
979 return error;
980}
981
982Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
984 // Only connect if we have a valid connect URL
986
987 if (!connect_url.empty()) {
988 LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
989 connect_url.str().c_str());
990 std::unique_ptr<ConnectionFileDescriptor> conn_up(
992 if (conn_up) {
993 const uint32_t max_retry_count = 50;
994 uint32_t retry_count = 0;
995 while (!m_gdb_comm.IsConnected()) {
996 if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
997 m_gdb_comm.SetConnection(std::move(conn_up));
998 break;
999 }
1000
1001 retry_count++;
1002
1003 if (retry_count >= max_retry_count)
1004 break;
1005
1006 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1007 }
1008 }
1009 }
1010
1011 if (!m_gdb_comm.IsConnected()) {
1012 if (error.Success())
1013 error = Status::FromErrorString("not connected to remote gdb server");
1014 return error;
1015 }
1016
1017 // We always seem to be able to open a connection to a local port so we need
1018 // to make sure we can then send data to it. If we can't then we aren't
1019 // actually connected to anything, so try and do the handshake with the
1020 // remote GDB server and make sure that goes alright.
1021 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1022 m_gdb_comm.Disconnect();
1023 if (error.Success())
1024 error = Status::FromErrorString("not connected to remote gdb server");
1025 return error;
1026 }
1027
1028 m_gdb_comm.GetEchoSupported();
1029 m_gdb_comm.GetThreadSuffixSupported();
1030 m_gdb_comm.GetListThreadsInStopReplySupported();
1031 m_gdb_comm.GetHostInfo();
1032 m_gdb_comm.GetVContSupported("c");
1033 m_gdb_comm.GetVAttachOrWaitSupported();
1034 m_gdb_comm.EnableErrorStringInPacket();
1035
1036 // Empty unless the server advertised "address-spaces+" in qSupported.
1037 m_address_spaces = m_gdb_comm.GetAddressSpaces();
1038
1039 // First dispatch any commands from the platform:
1040 auto handle_cmds = [&] (const Args &args) -> void {
1041 for (const Args::ArgEntry &entry : args) {
1042 StringExtractorGDBRemote response;
1043 m_gdb_comm.SendPacketAndWaitForResponse(
1044 entry.c_str(), response);
1045 }
1046 };
1047
1048 PlatformSP platform_sp = GetTarget().GetPlatform();
1049 if (platform_sp) {
1050 handle_cmds(platform_sp->GetExtraStartupCommands());
1051 }
1052
1053 // Then dispatch any process commands:
1054 handle_cmds(GetExtraStartupCommands());
1055
1056 return error;
1057}
1058
1060 Log *log = GetLog(GDBRLog::Process);
1062
1063 // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
1064 // qProcessInfo as it will be more specific to our process.
1065
1066 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1067 if (remote_process_arch.IsValid()) {
1068 process_arch = remote_process_arch;
1069 LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
1070 process_arch.GetArchitectureName(),
1071 process_arch.GetTriple().getTriple());
1072 } else {
1073 process_arch = m_gdb_comm.GetHostArchitecture();
1074 LLDB_LOG(log,
1075 "gdb-remote did not have process architecture, using gdb-remote "
1076 "host architecture {0} {1}",
1077 process_arch.GetArchitectureName(),
1078 process_arch.GetTriple().getTriple());
1079 }
1080
1081 AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits();
1082 SetAddressableBitMasks(addressable_bits);
1083
1084 if (process_arch.IsValid()) {
1085 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1086 if (target_arch.IsValid()) {
1087 LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
1088 target_arch.GetArchitectureName(),
1089 target_arch.GetTriple().getTriple());
1090
1091 // If the remote host is ARM and we have apple as the vendor, then
1092 // ARM executables and shared libraries can have mixed ARM
1093 // architectures.
1094 // You can have an armv6 executable, and if the host is armv7, then the
1095 // system will load the best possible architecture for all shared
1096 // libraries it has, so we really need to take the remote host
1097 // architecture as our defacto architecture in this case.
1098
1099 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1100 process_arch.GetMachine() == llvm::Triple::thumb) &&
1101 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1102 GetTarget().SetArchitecture(process_arch);
1103 LLDB_LOG(log,
1104 "remote process is ARM/Apple, "
1105 "setting target arch to {0} {1}",
1106 process_arch.GetArchitectureName(),
1107 process_arch.GetTriple().getTriple());
1108 } else {
1109 // Fill in what is missing in the triple
1110 const llvm::Triple &remote_triple = process_arch.GetTriple();
1111 llvm::Triple new_target_triple = target_arch.GetTriple();
1112 if (new_target_triple.getVendorName().size() == 0) {
1113 new_target_triple.setVendor(remote_triple.getVendor());
1114
1115 if (new_target_triple.getOSName().size() == 0) {
1116 new_target_triple.setOS(remote_triple.getOS());
1117
1118 if (new_target_triple.getEnvironmentName().size() == 0)
1119 new_target_triple.setEnvironment(remote_triple.getEnvironment());
1120 }
1121
1122 ArchSpec new_target_arch = target_arch;
1123 new_target_arch.SetTriple(new_target_triple);
1124 GetTarget().SetArchitecture(new_target_arch);
1125 }
1126 }
1127
1128 LLDB_LOG(log,
1129 "final target arch after adjustments for remote architecture: "
1130 "{0} {1}",
1131 target_arch.GetArchitectureName(),
1132 target_arch.GetTriple().getTriple());
1133 } else {
1134 // The target doesn't have a valid architecture yet, set it from the
1135 // architecture we got from the remote GDB server
1136 GetTarget().SetArchitecture(process_arch);
1137 }
1138 }
1139
1140 // Target and Process are reasonably initailized;
1141 // load any binaries we have metadata for / set load address.
1144
1145 // Find out which StructuredDataPlugins are supported by the debug monitor.
1146 // These plugins transmit data over async $J packets.
1147 if (StructuredData::Array *supported_packets =
1148 m_gdb_comm.GetSupportedStructuredDataPlugins())
1149 MapSupportedStructuredDataPlugins(*supported_packets);
1150
1151 // If connected to LLDB ("native-signals+"), use signal defs for
1152 // the remote platform. If connected to GDB, just use the standard set.
1153 if (!m_gdb_comm.UsesNativeSignals()) {
1154 SetUnixSignals(std::make_shared<GDBRemoteSignals>());
1155 } else {
1156 PlatformSP platform_sp = GetTarget().GetPlatform();
1157 if (platform_sp && platform_sp->IsConnected())
1158 SetUnixSignals(platform_sp->GetUnixSignals());
1159 else
1160 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
1161 }
1162
1163 // Ask any accelerator plugins installed in lldb-server for their initial
1164 // actions (e.g. breakpoints to set in the native process).
1165 llvm::Expected<std::vector<AcceleratorActions>> init_actions =
1166 m_gdb_comm.GetAcceleratorInitializeActions();
1167 if (!init_actions) {
1168 LLDB_LOG_ERROR(log, init_actions.takeError(),
1169 "failed to get accelerator initialize actions: {0}");
1170 } else {
1171 for (const AcceleratorActions &actions : *init_actions) {
1172 if (llvm::Error error = HandleAcceleratorActions(actions))
1173 LLDB_LOG_ERROR(log, std::move(error),
1174 "failed to handle accelerator actions: {0}");
1175 }
1176 }
1177}
1178
1180 // The remote stub may know about the "main binary" in
1181 // the context of a firmware debug session, and can
1182 // give us a UUID and an address/slide of where the
1183 // binary is loaded in memory.
1184 UUID standalone_uuid;
1185 addr_t standalone_value;
1186 bool standalone_value_is_offset;
1187 if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value,
1188 standalone_value_is_offset)) {
1189 if (standalone_uuid.IsValid()) {
1191 bin_spec.uuid = standalone_uuid;
1192 bin_spec.value = standalone_value;
1193 bin_spec.value_is_offset = standalone_value_is_offset;
1194 bin_spec.force_symbol_search = true;
1195 bin_spec.notify = true;
1196 bin_spec.set_address_in_target = true;
1197 bin_spec.is_main_executable = true;
1198 llvm::Expected<ModuleSP> module =
1199 DynamicLoader::LocateAndLoadBinary(this, bin_spec);
1200 if (!module)
1202 << llvm::toString(module.takeError()) << "\n";
1203 }
1204 }
1205
1206 // The remote stub may know about a list of binaries to
1207 // force load into the process -- a firmware type situation
1208 // where multiple binaries are present in virtual memory,
1209 // and we are only given the addresses of the binaries.
1210 // Not intended for use with userland debugging, when we use
1211 // a DynamicLoader plugin that knows how to find the loaded
1212 // binaries, and will track updates as binaries are added.
1213
1214 std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
1215 if (bin_addrs.size()) {
1216 for (addr_t addr : bin_addrs) {
1217 const bool notify = true;
1218 // First see if this is a special platform
1219 // binary that may determine the DynamicLoader and
1220 // Platform to be used in this Process and Target.
1221 if (GetTarget()
1222 .GetDebugger()
1223 .GetPlatformList()
1224 .LoadPlatformBinaryAndSetup(this, addr, notify))
1225 continue;
1226
1227 // Second manually load this binary into the Target.
1229 bin_spec.value = addr;
1230 bin_spec.force_symbol_search = true;
1231 bin_spec.notify = notify;
1232 bin_spec.set_address_in_target = true;
1233 llvm::Expected<ModuleSP> module =
1234 DynamicLoader::LocateAndLoadBinary(this, bin_spec);
1235 if (!module)
1237 << llvm::toString(module.takeError()) << "\n";
1238 }
1239 }
1240}
1241
1243 ModuleSP module_sp = GetTarget().GetExecutableModule();
1244 if (!module_sp)
1245 return;
1246
1247 std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1248 if (!offsets)
1249 return;
1250
1251 bool is_uniform =
1252 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1253 offsets->offsets.size();
1254 if (!is_uniform)
1255 return; // TODO: Handle non-uniform responses.
1256
1257 bool changed = false;
1258 module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1259 /*value_is_offset=*/true, changed);
1260 if (changed) {
1261 ModuleList list;
1262 list.Append(module_sp);
1263 m_process->GetTarget().ModulesDidLoad(list);
1264 }
1265}
1266
1268 ArchSpec process_arch;
1269 DidLaunchOrAttach(process_arch);
1270}
1271
1273 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1274 Log *log = GetLog(GDBRLog::Process);
1275 Status error;
1276
1277 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1278
1279 // Clear out and clean up from any current state
1280 Clear();
1281 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1282 error = EstablishConnectionIfNeeded(attach_info);
1283 if (error.Success()) {
1284 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1285
1286 char packet[64];
1287 const int packet_len =
1288 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1289 SetID(attach_pid);
1290 auto data_sp =
1291 std::make_shared<EventDataBytes>(llvm::StringRef(packet, packet_len));
1292 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1293 } else
1294 SetExitStatus(-1, error.AsCString());
1295 }
1296
1297 return error;
1298}
1299
1301 const char *process_name, const ProcessAttachInfo &attach_info) {
1302 Status error;
1303 // Clear out and clean up from any current state
1304 Clear();
1305
1306 if (process_name && process_name[0]) {
1307 error = EstablishConnectionIfNeeded(attach_info);
1308 if (error.Success()) {
1309 StreamString packet;
1310
1311 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1312
1313 if (attach_info.GetWaitForLaunch()) {
1314 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1315 packet.PutCString("vAttachWait");
1316 } else {
1317 if (attach_info.GetIgnoreExisting())
1318 packet.PutCString("vAttachWait");
1319 else
1320 packet.PutCString("vAttachOrWait");
1321 }
1322 } else
1323 packet.PutCString("vAttachName");
1324 packet.PutChar(';');
1325 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1328
1329 auto data_sp = std::make_shared<EventDataBytes>(packet.GetString());
1330 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1331
1332 } else
1333 SetExitStatus(-1, error.AsCString());
1334 }
1335 return error;
1336}
1337
1338llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1339 return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
1340}
1341
1343 return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1344}
1345
1346llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1347 return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1348}
1349
1350llvm::Expected<std::string>
1351ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1352 return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
1353}
1354
1355llvm::Expected<std::vector<uint8_t>>
1357 return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1358}
1359
1361 // When we exit, disconnect from the GDB server communications
1362 m_gdb_comm.Disconnect();
1363}
1364
1366 // If you can figure out what the architecture is, fill it in here.
1367 process_arch.Clear();
1368 DidLaunchOrAttach(process_arch);
1369}
1370
1372 m_continue_c_tids.clear();
1373 m_continue_C_tids.clear();
1374 m_continue_s_tids.clear();
1375 m_continue_S_tids.clear();
1376 m_jstopinfo.Lock()->reset();
1377 m_jthreadsinfo.Lock()->reset();
1378 m_shared_cache_info.Lock()->reset();
1379 return Status();
1380}
1381
1383 return m_gdb_comm.GetReverseStepSupported() ||
1384 m_gdb_comm.GetReverseContinueSupported();
1385}
1386
1388 Status error;
1389 Log *log = GetLog(GDBRLog::Process);
1390 LLDB_LOGF(log, "ProcessGDBRemote::Resume(%s)",
1391 direction == RunDirection::eRunForward ? "" : "reverse");
1392
1393 ListenerSP listener_sp(
1394 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1395 if (listener_sp->StartListeningForEvents(
1397 listener_sp->StartListeningForEvents(
1400
1401 const size_t num_threads = GetThreadList().GetSize();
1402
1403 StreamString continue_packet;
1404 bool continue_packet_error = false;
1405 // Number of threads continuing with "c", i.e. continuing without a signal
1406 // to deliver.
1407 const size_t num_continue_c_tids = m_continue_c_tids.size();
1408 // Number of threads continuing with "C", i.e. continuing with a signal to
1409 // deliver.
1410 const size_t num_continue_C_tids = m_continue_C_tids.size();
1411 // Number of threads continuing with "s", i.e. single-stepping.
1412 const size_t num_continue_s_tids = m_continue_s_tids.size();
1413 // Number of threads continuing with "S", i.e. single-stepping with a signal
1414 // to deliver.
1415 const size_t num_continue_S_tids = m_continue_S_tids.size();
1416 if (direction == RunDirection::eRunForward &&
1417 m_gdb_comm.HasAnyVContSupport()) {
1418 std::string pid_prefix;
1419 if (m_gdb_comm.GetMultiprocessSupported())
1420 pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1421
1422 if (num_continue_c_tids == num_threads ||
1423 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1424 m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1425 // All threads are continuing
1426 if (m_gdb_comm.GetMultiprocessSupported())
1427 continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1428 else
1429 continue_packet.PutCString("c");
1430 } else {
1431 continue_packet.PutCString("vCont");
1432
1433 if (!m_continue_c_tids.empty()) {
1434 if (m_gdb_comm.GetVContSupported("c")) {
1435 for (tid_collection::const_iterator
1436 t_pos = m_continue_c_tids.begin(),
1437 t_end = m_continue_c_tids.end();
1438 t_pos != t_end; ++t_pos)
1439 continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1440 } else
1441 continue_packet_error = true;
1442 }
1443
1444 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1445 if (m_gdb_comm.GetVContSupported("C")) {
1446 for (tid_sig_collection::const_iterator
1447 s_pos = m_continue_C_tids.begin(),
1448 s_end = m_continue_C_tids.end();
1449 s_pos != s_end; ++s_pos)
1450 continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1451 pid_prefix, s_pos->first);
1452 } else
1453 continue_packet_error = true;
1454 }
1455
1456 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1457 if (m_gdb_comm.GetVContSupported("s")) {
1458 for (tid_collection::const_iterator
1459 t_pos = m_continue_s_tids.begin(),
1460 t_end = m_continue_s_tids.end();
1461 t_pos != t_end; ++t_pos)
1462 continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1463 } else
1464 continue_packet_error = true;
1465 }
1466
1467 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1468 if (m_gdb_comm.GetVContSupported("S")) {
1469 for (tid_sig_collection::const_iterator
1470 s_pos = m_continue_S_tids.begin(),
1471 s_end = m_continue_S_tids.end();
1472 s_pos != s_end; ++s_pos)
1473 continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1474 pid_prefix, s_pos->first);
1475 } else
1476 continue_packet_error = true;
1477 }
1478
1479 if (continue_packet_error)
1480 continue_packet.Clear();
1481 }
1482 } else
1483 continue_packet_error = true;
1484
1485 if (direction == RunDirection::eRunForward && continue_packet_error) {
1486 // Either no vCont support, or we tried to use part of the vCont packet
1487 // that wasn't supported by the remote GDB server. We need to try and
1488 // make a simple packet that can do our continue.
1489 if (num_continue_c_tids > 0) {
1490 if (num_continue_c_tids == num_threads) {
1491 // All threads are resuming...
1492 m_gdb_comm.SetCurrentThreadForRun(-1);
1493 continue_packet.PutChar('c');
1494 continue_packet_error = false;
1495 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1496 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1497 // Only one thread is continuing
1498 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1499 continue_packet.PutChar('c');
1500 continue_packet_error = false;
1501 }
1502 }
1503
1504 if (continue_packet_error && num_continue_C_tids > 0) {
1505 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1506 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1507 num_continue_S_tids == 0) {
1508 const int continue_signo = m_continue_C_tids.front().second;
1509 // Only one thread is continuing
1510 if (num_continue_C_tids > 1) {
1511 // More that one thread with a signal, yet we don't have vCont
1512 // support and we are being asked to resume each thread with a
1513 // signal, we need to make sure they are all the same signal, or we
1514 // can't issue the continue accurately with the current support...
1515 if (num_continue_C_tids > 1) {
1516 continue_packet_error = false;
1517 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1518 if (m_continue_C_tids[i].second != continue_signo)
1519 continue_packet_error = true;
1520 }
1521 }
1522 if (!continue_packet_error)
1523 m_gdb_comm.SetCurrentThreadForRun(-1);
1524 } else {
1525 // Set the continue thread ID
1526 continue_packet_error = false;
1527 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1528 }
1529 if (!continue_packet_error) {
1530 // Add threads continuing with the same signo...
1531 continue_packet.Printf("C%2.2x", continue_signo);
1532 }
1533 }
1534 }
1535
1536 if (continue_packet_error && num_continue_s_tids > 0) {
1537 if (num_continue_s_tids == num_threads) {
1538 // All threads are resuming...
1539 m_gdb_comm.SetCurrentThreadForRun(-1);
1540
1541 continue_packet.PutChar('s');
1542
1543 continue_packet_error = false;
1544 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1545 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1546 // Only one thread is stepping
1547 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1548 continue_packet.PutChar('s');
1549 continue_packet_error = false;
1550 }
1551 }
1552
1553 if (!continue_packet_error && num_continue_S_tids > 0) {
1554 if (num_continue_S_tids == num_threads) {
1555 const int step_signo = m_continue_S_tids.front().second;
1556 // Are all threads trying to step with the same signal?
1557 continue_packet_error = false;
1558 if (num_continue_S_tids > 1) {
1559 for (size_t i = 1; i < num_threads; ++i) {
1560 if (m_continue_S_tids[i].second != step_signo)
1561 continue_packet_error = true;
1562 }
1563 }
1564 if (!continue_packet_error) {
1565 // Add threads stepping with the same signo...
1566 m_gdb_comm.SetCurrentThreadForRun(-1);
1567 continue_packet.Printf("S%2.2x", step_signo);
1568 }
1569 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1570 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1571 // Only one thread is stepping with signal
1572 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1573 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1574 continue_packet_error = false;
1575 }
1576 }
1577 }
1578
1579 if (direction == RunDirection::eRunReverse) {
1580 if (num_continue_s_tids > 0 || num_continue_S_tids > 0) {
1581 if (!m_gdb_comm.GetReverseStepSupported()) {
1582 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1583 "support reverse-stepping");
1585 "target does not support reverse-stepping");
1586 }
1587
1588 if (num_continue_S_tids > 0) {
1589 LLDB_LOGF(
1590 log,
1591 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1593 "can't deliver signals while running in reverse");
1594 }
1595
1596 if (num_continue_s_tids > 1) {
1597 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: can't step multiple "
1598 "threads in reverse");
1600 "can't step multiple threads while reverse-stepping");
1601 }
1602
1603 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1604 continue_packet.PutCString("bs");
1605 } else {
1606 if (!m_gdb_comm.GetReverseContinueSupported()) {
1607 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1608 "support reverse-continue");
1610 "target does not support reverse execution of processes");
1611 }
1612
1613 if (num_continue_C_tids > 0) {
1614 LLDB_LOGF(
1615 log,
1616 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1618 "can't deliver signals while running in reverse");
1619 }
1620
1621 // All threads continue whether requested or not ---
1622 // we can't change how threads ran in the past.
1623 continue_packet.PutCString("bc");
1624 }
1625
1626 continue_packet_error = false;
1627 }
1628
1629 if (continue_packet_error) {
1631 "can't make continue packet for this resume");
1632 } else {
1633 EventSP event_sp;
1634 if (!m_async_thread.IsJoinable()) {
1636 "Trying to resume but the async thread is dead.");
1637 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1638 "async thread is dead.");
1639 return error;
1640 }
1641
1642 auto data_sp =
1643 std::make_shared<EventDataBytes>(continue_packet.GetString());
1644 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1645
1646 if (!listener_sp->GetEvent(event_sp, ResumeTimeout())) {
1647 error = Status::FromErrorString("Resume timed out.");
1648 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1649 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1651 "Broadcast continue, but the async thread was "
1652 "killed before we got an ack back.");
1653 LLDB_LOGF(log,
1654 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1655 "async thread was killed before we got an ack back.");
1656 return error;
1657 }
1658 }
1659 }
1660
1661 return error;
1662}
1663
1665 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1666 m_thread_ids.clear();
1667 m_thread_pcs.clear();
1668}
1669
1671 llvm::StringRef value) {
1672 m_thread_ids.clear();
1673 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1674 StringExtractorGDBRemote thread_ids{value};
1675
1676 do {
1677 auto pid_tid = thread_ids.GetPidTid(pid);
1678 if (pid_tid && pid_tid->first == pid) {
1679 lldb::tid_t tid = pid_tid->second;
1680 if (tid != LLDB_INVALID_THREAD_ID &&
1682 m_thread_ids.push_back(tid);
1683 }
1684 } while (thread_ids.GetChar() == ',');
1685
1686 return m_thread_ids.size();
1687}
1688
1690 llvm::StringRef value) {
1691 m_thread_pcs.clear();
1692 for (llvm::StringRef x : llvm::split(value, ',')) {
1694 if (llvm::to_integer(x, pc, 16))
1695 m_thread_pcs.push_back(pc);
1696 }
1697 return m_thread_pcs.size();
1698}
1699
1701 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1702
1703 ThreadInfosSP threads_info_sp = *m_jthreadsinfo.Lock();
1704 if (threads_info_sp) {
1705 // If we have the JSON threads info, we can get the thread list from that
1706 StructuredData::Array *thread_infos = threads_info_sp->GetArray();
1707 if (thread_infos && thread_infos->GetSize() > 0) {
1708 m_thread_ids.clear();
1709 m_thread_pcs.clear();
1710 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1711 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1712 if (thread_dict) {
1713 // Set the thread stop info from the JSON dictionary
1714 SetThreadStopInfo(thread_dict);
1716 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1717 m_thread_ids.push_back(tid);
1718 }
1719 return true; // Keep iterating through all thread_info objects
1720 });
1721 }
1722 if (!m_thread_ids.empty())
1723 return true;
1724 } else {
1725 // See if we can get the thread IDs from the current stop reply packets
1726 // that might contain a "threads" key/value pair
1727
1728 if (m_last_stop_packet) {
1729 // Get the thread stop info
1731 const llvm::StringRef stop_info_str = stop_info.GetStringRef();
1732
1733 m_thread_pcs.clear();
1734 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1735 if (thread_pcs_pos != llvm::StringRef::npos) {
1736 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1737 const size_t end = stop_info_str.find(';', start);
1738 if (end != llvm::StringRef::npos) {
1739 llvm::StringRef value = stop_info_str.substr(start, end - start);
1741 }
1742 }
1743
1744 const size_t threads_pos = stop_info_str.find(";threads:");
1745 if (threads_pos != llvm::StringRef::npos) {
1746 const size_t start = threads_pos + strlen(";threads:");
1747 const size_t end = stop_info_str.find(';', start);
1748 if (end != llvm::StringRef::npos) {
1749 llvm::StringRef value = stop_info_str.substr(start, end - start);
1751 return true;
1752 }
1753 }
1754 }
1755 }
1756
1757 bool sequence_mutex_unavailable = false;
1758 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1759 if (sequence_mutex_unavailable) {
1760 return false; // We just didn't get the list
1761 }
1762 return true;
1763}
1764
1766 ThreadList &new_thread_list) {
1767 // locker will keep a mutex locked until it goes out of scope
1768 Log *log = GetLog(GDBRLog::Thread);
1769 LLDB_LOG_VERBOSE(log, "pid = {0}", GetID());
1770
1771 size_t num_thread_ids = m_thread_ids.size();
1772 // The "m_thread_ids" thread ID list should always be updated after each stop
1773 // reply packet, but in case it isn't, update it here.
1774 if (num_thread_ids == 0) {
1775 if (!UpdateThreadIDList())
1776 return false;
1777 num_thread_ids = m_thread_ids.size();
1778 }
1779
1780 ThreadList old_thread_list_copy(old_thread_list);
1781 if (num_thread_ids > 0) {
1782 for (size_t i = 0; i < num_thread_ids; ++i) {
1783 lldb::tid_t tid = m_thread_ids[i];
1784 ThreadSP thread_sp(
1785 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1786 if (!thread_sp) {
1787 thread_sp = CreateThread(tid);
1788 LLDB_LOG_VERBOSE(log, "Making new thread: {0} for thread ID: {1:x}.",
1789 thread_sp.get(), thread_sp->GetID());
1790 } else {
1791 LLDB_LOG_VERBOSE(log, "Found old thread: {0} for thread ID: {1:x}.",
1792 thread_sp.get(), thread_sp->GetID());
1793 }
1794
1795 SetThreadPc(thread_sp, i);
1796 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1797 }
1798 }
1799
1800 // Whatever that is left in old_thread_list_copy are not present in
1801 // new_thread_list. Remove non-existent threads from internal id table.
1802 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1803 for (size_t i = 0; i < old_num_thread_ids; i++) {
1804 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1805 if (old_thread_sp) {
1806 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1807 m_thread_id_to_index_id_map.erase(old_thread_id);
1808 }
1809 }
1810
1811 return true;
1812}
1813
1814void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1815 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1817 ThreadGDBRemote *gdb_thread =
1818 static_cast<ThreadGDBRemote *>(thread_sp.get());
1819 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1820 if (reg_ctx_sp) {
1821 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1823 if (pc_regnum != LLDB_INVALID_REGNUM) {
1824 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1825 }
1826 }
1827 }
1828}
1829
1831 // This runs for every thread at a stop, so searching m_thread_ids would make
1832 // the stop quadratic in the number of threads. m_thread_ids is rewritten in
1833 // several places that leave m_thread_id_positions alone, so trust a cached
1834 // position only if m_thread_ids still has tid there, and rebuild otherwise.
1835 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1836 auto it = m_thread_id_positions.find(tid);
1837 if (it != m_thread_id_positions.end() && it->second < m_thread_ids.size() &&
1838 m_thread_ids[it->second] == tid)
1839 return it->second;
1840
1841 m_thread_id_positions.clear();
1842 for (auto [i, id] : llvm::enumerate(m_thread_ids))
1843 m_thread_id_positions.try_emplace(id, i);
1844 it = m_thread_id_positions.find(tid);
1845 if (it == m_thread_id_positions.end())
1846 return std::nullopt;
1847 return it->second;
1848}
1849
1851 : m_json_sp(std::move(json_sp)) {
1852 StructuredData::Array *array = m_json_sp->GetAsArray();
1853 if (!array)
1854 return;
1855 const size_t n = array->GetSize();
1856 m_thread_dicts.reserve(n);
1857 for (size_t i = 0; i < n; ++i) {
1858 StructuredData::Dictionary *thread_dict =
1859 array->GetItemAtIndex(i)->GetAsDictionary();
1861 // If a reply lists a thread more than once, use its first entry.
1862 if (thread_dict && thread_dict->GetValueForKeyAsInteger("tid", tid))
1863 m_thread_dicts.try_emplace(tid, thread_dict);
1864 }
1865}
1866
1869 auto it = m_thread_dicts.find(tid);
1870 return it == m_thread_dicts.end() ? nullptr : it->second;
1871}
1872
1875 if (!json_sp)
1876 return nullptr;
1877 return std::make_shared<const ThreadInfos>(std::move(json_sp));
1878}
1879
1881 ThreadGDBRemote *thread, const ThreadInfosSP &thread_infos_sp) {
1882 if (!thread_infos_sp)
1883 return false;
1884 StructuredData::Dictionary *thread_dict =
1885 thread_infos_sp->FindThread(thread->GetID());
1886 if (!thread_dict)
1887 return false;
1888 return SetThreadStopInfo(thread_dict, thread->shared_from_this()) != nullptr;
1889}
1890
1892 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1893 // packet (we're at a public stop).
1894 ThreadInfosSP threads_info_sp = *m_jthreadsinfo.Lock();
1895 if (GetThreadStopInfoFromJSON(thread, threads_info_sp))
1896 return true;
1897
1898 // See if the stop-reply packet (T05 etc) included a `jstopinfo` key
1899 // with a mach exception description for any thread that has a stop reason.
1900 ThreadInfosSP stop_info_sp = *m_jstopinfo.Lock();
1901 if (stop_info_sp) {
1902 // Any thread not described in `jstopinfo` has no stop reason.
1903 // If a no-stop-reason thread is stopped at a breakpoint site (but
1904 // hasn't yet hit the breakpoint instruction), note that in the
1905 // Thread state so we will hit the breakpoint when we resume execution.
1906 if (!GetThreadStopInfoFromJSON(thread, stop_info_sp)) {
1907 addr_t pc = thread->GetRegisterContext()->GetPC();
1908 BreakpointSiteSP bp_site_sp =
1909 thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1910 if (bp_site_sp && IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
1911 thread->SetThreadStoppedAtUnexecutedBP(pc);
1912 thread->SetStopInfo(StopInfoSP());
1913 }
1914 return true;
1915 }
1916
1917 // Fall back to using the qThreadStopInfo packet
1918 StringExtractorGDBRemote stop_packet;
1919 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1920 return SetThreadStopInfo(stop_packet) == eStateStopped;
1921 return false;
1922}
1923
1925 ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) {
1926 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1927 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1928
1929 for (const auto &pair : expedited_register_map) {
1930 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1931 eRegisterKindProcessPlugin, pair.first);
1932 if (lldb_regnum != LLDB_INVALID_REGNUM) {
1933 StringExtractor reg_value_extractor(pair.second);
1934 if (reg_value_extractor.GetStringRef().empty()) {
1935 gdb_thread->PrivateSetRegisterUnavailable(lldb_regnum);
1936 continue;
1937 }
1938 WritableDataBufferSP buffer_sp(
1939 new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1940 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1941 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1942 }
1943 }
1944}
1945
1947 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1948 uint8_t signo, const std::string &thread_name, const std::string &reason,
1949 const std::string &description, uint32_t exc_type,
1950 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1951 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1952 // queue_serial are valid
1953 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1954 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial,
1955 std::vector<lldb::addr_t> &added_binaries,
1956 StructuredData::ObjectSP &detailed_binaries_info, ThreadSP thread_sp) {
1957
1958 if (tid == LLDB_INVALID_THREAD_ID)
1959 return nullptr;
1960
1961 // Stop info is set for every thread at a stop, so a search of the thread
1962 // list for each would take time quadratic in the number of threads.
1963 if (!thread_sp || thread_sp->GetProtocolID() != tid) {
1964 // m_thread_list_real does have its own mutex, but we need to hold onto the
1965 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1966 // m_thread_list_real.AddThread(...) so it doesn't change on us
1967 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1968 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1969
1970 if (!thread_sp) {
1971 // Create the thread if we need to
1972 thread_sp = CreateThread(tid);
1973 m_thread_list_real.AddThread(thread_sp);
1974 }
1975 }
1976
1977 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1978 RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext());
1979
1980 reg_ctx_sp->InvalidateIfNeeded(true);
1981
1982 if (std::optional<size_t> index = FindThreadIDIndex(tid))
1983 SetThreadPc(thread_sp, *index);
1984
1985 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1986
1987 if (reg_ctx_sp->ReconfigureRegisterInfo()) {
1988 // Now we have changed the offsets of all the registers, so the values
1989 // will be corrupted.
1990 reg_ctx_sp->InvalidateAllRegisters();
1991 // Expedited registers values will never contain registers that would be
1992 // resized by a reconfigure. So we are safe to continue using these
1993 // values.
1994 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1995 }
1996
1997 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1998
1999 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
2000 // Check if the GDB server was able to provide the queue name, kind and serial
2001 // number
2002 if (queue_vars_valid)
2003 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
2004 dispatch_queue_t, associated_with_dispatch_queue);
2005 else
2006 gdb_thread->ClearQueueInfo();
2007
2008 gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);
2009
2010 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
2011 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
2012
2013 gdb_thread->SetNewlyAddedBinaries(added_binaries);
2014 gdb_thread->SetDetailedBinariesInfo(detailed_binaries_info);
2015
2016 // Make sure we update our thread stop reason just once, but don't overwrite
2017 // the stop info for threads that haven't moved:
2018 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
2019 if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
2020 current_stop_info_sp) {
2021 thread_sp->SetStopInfo(current_stop_info_sp);
2022 return thread_sp;
2023 }
2024
2025 if (!thread_sp->StopInfoIsUpToDate()) {
2026 thread_sp->SetStopInfo(StopInfoSP());
2027
2028 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2029 BreakpointSiteSP bp_site_sp =
2030 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2031 if (bp_site_sp && IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
2032 thread_sp->SetThreadStoppedAtUnexecutedBP(pc);
2033
2034 if (exc_type != 0) {
2035 // For thread plan async interrupt, creating stop info on the
2036 // original async interrupt request thread instead. If interrupt thread
2037 // does not exist anymore we fallback to current signal receiving thread
2038 // instead.
2039 ThreadSP interrupt_thread;
2041 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
2042 if (interrupt_thread)
2043 thread_sp = interrupt_thread;
2044 else {
2045 const size_t exc_data_size = exc_data.size();
2046 thread_sp->SetStopInfo(
2048 *thread_sp, exc_type, exc_data_size,
2049 exc_data_size >= 1 ? exc_data[0] : 0,
2050 exc_data_size >= 2 ? exc_data[1] : 0,
2051 exc_data_size >= 3 ? exc_data[2] : 0));
2052 }
2053 } else {
2054 bool handled = false;
2055 bool did_exec = false;
2056 // debugserver can send reason = "none" which is equivalent
2057 // to no reason.
2058 if (!reason.empty() && reason != "none") {
2059 if (reason == "trace") {
2060 thread_sp->SetStopInfo(StopInfo::CreateStopReasonToTrace(*thread_sp));
2061 handled = true;
2062 } else if (reason == "breakpoint") {
2063 thread_sp->SetThreadHitBreakpointSite();
2064 if (bp_site_sp) {
2065 // If the breakpoint is for this thread, then we'll report the hit,
2066 // but if it is for another thread, we can just report no reason.
2067 // We don't need to worry about stepping over the breakpoint here,
2068 // that will be taken care of when the thread resumes and notices
2069 // that there's a breakpoint under the pc.
2070 handled = true;
2071 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2072 thread_sp->SetStopInfo(
2074 *thread_sp, bp_site_sp->GetID()));
2075 } else {
2076 StopInfoSP invalid_stop_info_sp;
2077 thread_sp->SetStopInfo(invalid_stop_info_sp);
2078 }
2079 }
2080 } else if (reason == "trap") {
2081 // Let the trap just use the standard signal stop reason below...
2082 } else if (reason == "watchpoint") {
2083 // We will have between 1 and 3 fields in the description.
2084 //
2085 // \a wp_addr which is the original start address that
2086 // lldb requested be watched, or an address that the
2087 // hardware reported. This address should be within the
2088 // range of a currently active watchpoint region - lldb
2089 // should be able to find a watchpoint with this address.
2090 //
2091 // \a wp_index is the hardware watchpoint register number.
2092 //
2093 // \a wp_hit_addr is the actual address reported by the hardware,
2094 // which may be outside the range of a region we are watching.
2095 //
2096 // On MIPS, we may get a false watchpoint exception where an
2097 // access to the same 8 byte granule as a watchpoint will trigger,
2098 // even if the access was not within the range of the watched
2099 // region. When we get a \a wp_hit_addr outside the range of any
2100 // set watchpoint, continue execution without making it visible to
2101 // the user.
2102 //
2103 // On ARM, a related issue where a large access that starts
2104 // before the watched region (and extends into the watched
2105 // region) may report a hit address before the watched region.
2106 // lldb will not find the "nearest" watchpoint to
2107 // disable/step/re-enable it, so one of the valid watchpoint
2108 // addresses should be provided as \a wp_addr.
2109 StringExtractor desc_extractor(description.c_str());
2110 // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this
2111 // up as
2112 // <address within wp range> <wp hw index> <actual accessed addr>
2113 // but this is not reading the <wp hw index>. Seems like it
2114 // wouldn't work on MIPS, where that third field is important.
2115 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2116 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2118 bool silently_continue = false;
2119 WatchpointResourceSP wp_resource_sp;
2120 if (wp_hit_addr != LLDB_INVALID_ADDRESS) {
2121 wp_resource_sp =
2122 m_watchpoint_resource_list.FindByAddress(wp_hit_addr);
2123 // On MIPS, \a wp_hit_addr outside the range of a watched
2124 // region means we should silently continue, it is a false hit.
2126 if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first &&
2128 silently_continue = true;
2129 }
2130 if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS)
2131 wp_resource_sp = m_watchpoint_resource_list.FindByAddress(wp_addr);
2132 if (!wp_resource_sp) {
2134 LLDB_LOGF(log, "failed to find watchpoint");
2135 watch_id = LLDB_INVALID_SITE_ID;
2136 } else {
2137 // LWP_TODO: This is hardcoding a single Watchpoint in a
2138 // Resource, need to add
2139 // StopInfo::CreateStopReasonWithWatchpointResource which
2140 // represents all watchpoints that were tripped at this stop.
2141 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();
2142 }
2143 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
2144 *thread_sp, watch_id, silently_continue));
2145 handled = true;
2146 } else if (reason == "exception") {
2147 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2148 *thread_sp, description.c_str()));
2149 handled = true;
2150 } else if (reason == "history boundary") {
2151 thread_sp->SetStopInfo(StopInfo::CreateStopReasonHistoryBoundary(
2152 *thread_sp, description.c_str()));
2153 handled = true;
2154 } else if (reason == "exec") {
2155 did_exec = true;
2156 thread_sp->SetStopInfo(
2158 handled = true;
2159 } else if (reason == "processor trace") {
2160 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
2161 *thread_sp, description.c_str()));
2162 } else if (reason == "fork") {
2163 StringExtractor desc_extractor(description.c_str());
2164 lldb::pid_t child_pid =
2165 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
2166 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
2167 thread_sp->SetStopInfo(
2168 StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));
2169 handled = true;
2170 } else if (reason == "vfork") {
2171 StringExtractor desc_extractor(description.c_str());
2172 lldb::pid_t child_pid =
2173 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
2174 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
2175 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
2176 *thread_sp, child_pid, child_tid));
2177 handled = true;
2178 } else if (reason == "vforkdone") {
2179 thread_sp->SetStopInfo(
2181 handled = true;
2182 } else if (reason == "dyld") {
2183 if (llvm::Error error = LoadModules()) {
2184 Log *log = GetLog(GDBRLog::Process);
2185 LLDB_LOG_ERROR(log, std::move(error),
2186 "failed to load modules: {0}");
2187 }
2188 thread_sp->SetStopInfo(
2189 StopInfo::CreateStopReasonDyld(*thread_sp, description.c_str()));
2190 handled = true;
2191 }
2192 }
2193
2194 if (!handled && signo && !did_exec) {
2195 if (signo == SIGTRAP) {
2196 // Currently we are going to assume SIGTRAP means we are either
2197 // hitting a breakpoint or hardware single stepping.
2198
2199 // We can't disambiguate between stepping-to-a-breakpointsite and
2200 // hitting-a-breakpointsite.
2201 //
2202 // A user can instruction-step, and be stopped at a BreakpointSite.
2203 // Or a user can be sitting at a BreakpointSite,
2204 // instruction-step which hits the breakpoint and the pc does not
2205 // advance.
2206 //
2207 // In both cases, we're at a BreakpointSite when stopped, and
2208 // the resume state was eStateStepping.
2209
2210 // Assume if we're at a BreakpointSite, we hit it.
2211 handled = true;
2212 addr_t pc =
2213 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2214 BreakpointSiteSP bp_site_sp =
2215 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
2216 pc);
2217
2218 // We can't know if we hit it or not. So if we are stopped at
2219 // a BreakpointSite, assume we hit it, and should step past the
2220 // breakpoint when we resume. This is contrary to how we handle
2221 // BreakpointSites in any other location, but we can't know for
2222 // sure what happened so it's a reasonable default.
2223 if (bp_site_sp) {
2224 if (IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
2225 thread_sp->SetThreadHitBreakpointSite();
2226
2227 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2228 if (m_breakpoint_pc_offset != 0)
2229 thread_sp->GetRegisterContext()->SetPC(pc);
2230 thread_sp->SetStopInfo(
2232 *thread_sp, bp_site_sp->GetID()));
2233 } else {
2234 StopInfoSP invalid_stop_info_sp;
2235 thread_sp->SetStopInfo(invalid_stop_info_sp);
2236 }
2237 } else {
2238 // If we were stepping then assume the stop was the result of the
2239 // trace. If we were not stepping then report the SIGTRAP.
2240 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2241 thread_sp->SetStopInfo(
2243 else
2244 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2245 *thread_sp, signo, description.c_str()));
2246 }
2247 }
2248 if (!handled) {
2249 // For thread plan async interrupt, creating stop info on the
2250 // original async interrupt request thread instead. If interrupt
2251 // thread does not exist anymore we fallback to current signal
2252 // receiving thread instead.
2253 ThreadSP interrupt_thread;
2255 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
2256 if (interrupt_thread)
2257 thread_sp = interrupt_thread;
2258 else
2259 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2260 *thread_sp, signo, description.c_str()));
2261 }
2262 }
2263
2264 if (!description.empty()) {
2265 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2266 if (stop_info_sp) {
2267 const char *stop_info_desc = stop_info_sp->GetDescription();
2268 if (!stop_info_desc || !stop_info_desc[0])
2269 stop_info_sp->SetDescription(description.c_str());
2270 } else {
2271 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2272 *thread_sp, description.c_str()));
2273 }
2274 }
2275 }
2276 }
2277 return thread_sp;
2278}
2279
2282 const std::string &description) {
2283 ThreadSP thread_sp;
2284 {
2285 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2286 thread_sp = m_thread_list_real.FindThreadByProtocolID(m_interrupt_tid,
2287 /*can_update=*/false);
2288 }
2289 if (thread_sp)
2290 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(
2291 *thread_sp, signo, description.c_str()));
2292 // Clear m_interrupt_tid regardless we can find original interrupt thread or
2293 // not.
2295 return thread_sp;
2296}
2297
2300 lldb::ThreadSP thread_sp) {
2301 static constexpr llvm::StringLiteral g_key_tid("tid");
2302 static constexpr llvm::StringLiteral g_key_name("name");
2303 static constexpr llvm::StringLiteral g_key_reason("reason");
2304 static constexpr llvm::StringLiteral g_key_metype("metype");
2305 static constexpr llvm::StringLiteral g_key_medata("medata");
2306 static constexpr llvm::StringLiteral g_key_qaddr("qaddr");
2307 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2308 "dispatch_queue_t");
2309 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2310 "associated_with_dispatch_queue");
2311 static constexpr llvm::StringLiteral g_key_queue_name("qname");
2312 static constexpr llvm::StringLiteral g_key_queue_kind("qkind");
2313 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");
2314 static constexpr llvm::StringLiteral g_key_registers("registers");
2315 static constexpr llvm::StringLiteral g_key_memory("memory");
2316 static constexpr llvm::StringLiteral g_key_description("description");
2317 static constexpr llvm::StringLiteral g_key_signal("signal");
2318 static constexpr llvm::StringLiteral g_key_added_binaries("added-binaries");
2319 static constexpr llvm::StringLiteral g_key_detailed_binaries_info(
2320 "detailed-binaries-info");
2321
2322 // Stop with signal and thread info
2324 uint8_t signo = 0;
2325 std::string thread_name;
2326 std::string reason;
2327 std::string description;
2328 uint32_t exc_type = 0;
2329 std::vector<addr_t> exc_data;
2330 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2331 ExpeditedRegisterMap expedited_register_map;
2332 bool queue_vars_valid = false;
2333 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2334 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2335 std::string queue_name;
2336 QueueKind queue_kind = eQueueKindUnknown;
2337 uint64_t queue_serial_number = 0;
2338 std::vector<addr_t> added_binaries;
2339 StructuredData::ObjectSP detailed_binaries_info;
2340 // Iterate through all of the thread dictionary key/value pairs from the
2341 // structured data dictionary
2342
2343 // FIXME: we're silently ignoring invalid data here
2344 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2345 &signo, &reason, &description, &exc_type, &exc_data,
2346 &thread_dispatch_qaddr, &queue_vars_valid,
2347 &associated_with_dispatch_queue, &dispatch_queue_t,
2348 &queue_name, &queue_kind, &queue_serial_number,
2349 &added_binaries, &detailed_binaries_info](
2350 llvm::StringRef key,
2351 StructuredData::Object *object) -> bool {
2352 if (key == g_key_tid) {
2353 // thread in big endian hex
2354 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
2355 } else if (key == g_key_metype) {
2356 // exception type in big endian hex
2357 exc_type = object->GetUnsignedIntegerValue(0);
2358 } else if (key == g_key_medata) {
2359 // exception data in big endian hex
2360 StructuredData::Array *array = object->GetAsArray();
2361 if (array) {
2362 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2363 exc_data.push_back(object->GetUnsignedIntegerValue());
2364 return true; // Keep iterating through all array items
2365 });
2366 }
2367 } else if (key == g_key_name) {
2368 thread_name = std::string(object->GetStringValue());
2369 } else if (key == g_key_qaddr) {
2370 thread_dispatch_qaddr =
2371 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
2372 } else if (key == g_key_queue_name) {
2373 queue_vars_valid = true;
2374 queue_name = std::string(object->GetStringValue());
2375 } else if (key == g_key_queue_kind) {
2376 std::string queue_kind_str = std::string(object->GetStringValue());
2377 if (queue_kind_str == "serial") {
2378 queue_vars_valid = true;
2379 queue_kind = eQueueKindSerial;
2380 } else if (queue_kind_str == "concurrent") {
2381 queue_vars_valid = true;
2382 queue_kind = eQueueKindConcurrent;
2383 }
2384 } else if (key == g_key_queue_serial_number) {
2385 queue_serial_number = object->GetUnsignedIntegerValue(0);
2386 if (queue_serial_number != 0)
2387 queue_vars_valid = true;
2388 } else if (key == g_key_dispatch_queue_t) {
2389 dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2390 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2391 queue_vars_valid = true;
2392 } else if (key == g_key_associated_with_dispatch_queue) {
2393 queue_vars_valid = true;
2394 bool associated = object->GetBooleanValue();
2395 if (associated)
2396 associated_with_dispatch_queue = eLazyBoolYes;
2397 else
2398 associated_with_dispatch_queue = eLazyBoolNo;
2399 } else if (key == g_key_reason) {
2400 reason = std::string(object->GetStringValue());
2401 } else if (key == g_key_description) {
2402 description = std::string(object->GetStringValue());
2403 } else if (key == g_key_registers) {
2404 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2405
2406 if (registers_dict) {
2407 registers_dict->ForEach(
2408 [&expedited_register_map](llvm::StringRef key,
2409 StructuredData::Object *object) -> bool {
2410 uint32_t reg;
2411 if (llvm::to_integer(key, reg))
2412 expedited_register_map[reg] =
2413 std::string(object->GetStringValue());
2414 return true; // Keep iterating through all array items
2415 });
2416 }
2417 } else if (key == g_key_memory) {
2418 StructuredData::Array *array = object->GetAsArray();
2419 if (array) {
2420 array->ForEach([this](StructuredData::Object *object) -> bool {
2421 StructuredData::Dictionary *mem_cache_dict =
2422 object->GetAsDictionary();
2423 if (mem_cache_dict) {
2424 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2425 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2426 "address", mem_cache_addr)) {
2427 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2428 llvm::StringRef str;
2429 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2430 StringExtractor bytes(str);
2431 bytes.SetFilePos(0);
2432
2433 const size_t byte_size = bytes.GetStringRef().size() / 2;
2434 WritableDataBufferSP data_buffer_sp(
2435 new DataBufferHeap(byte_size, 0));
2436 const size_t bytes_copied =
2437 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2438 if (bytes_copied == byte_size)
2439 AddCacheData(mem_cache_addr, data_buffer_sp);
2440 }
2441 }
2442 }
2443 }
2444 return true; // Keep iterating through all array items
2445 });
2446 }
2447 } else if (key == g_key_signal)
2448 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2449 else if (key == g_key_added_binaries) {
2450 StructuredData::Array *array = object->GetAsArray();
2451 if (array) {
2452 array->ForEach([&added_binaries](
2453 StructuredData::Object *object) -> bool {
2455 object->GetAsUnsignedInteger();
2456 if (addr) {
2458 if (value != LLDB_INVALID_ADDRESS)
2459 added_binaries.push_back(value);
2460 }
2461 return true; // Keep iterating through all array items
2462 });
2463 }
2464 } else if (key == g_key_detailed_binaries_info) {
2465 // Get a string representation and then parse it into
2466 // StructuredData to get a separate copy of this part of
2467 // the response. We only have an Object* here, not the
2468 // original shared pointer, to increase the ref count.
2469 if (object->GetAsDictionary()) {
2470 StreamString json_str;
2471 object->Dump(json_str);
2472 detailed_binaries_info =
2474 }
2475 }
2476 return true; // Keep iterating through all dictionary key/value pairs
2477 });
2478
2479 return SetThreadStopInfo(
2480 tid, expedited_register_map, signo, thread_name, reason, description,
2481 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2482 associated_with_dispatch_queue, dispatch_queue_t, queue_name, queue_kind,
2483 queue_serial_number, added_binaries, detailed_binaries_info,
2484 std::move(thread_sp));
2485}
2486
2488 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2489 stop_packet.SetFilePos(0);
2490 const char stop_type = stop_packet.GetChar();
2491 switch (stop_type) {
2492 case 'T':
2493 case 'S': {
2494 // This is a bit of a hack, but it is required. If we did exec, we need to
2495 // clear our thread lists and also know to rebuild our dynamic register
2496 // info before we lookup and threads and populate the expedited register
2497 // values so we need to know this right away so we can cleanup and update
2498 // our registers.
2499 const uint32_t stop_id = GetStopID();
2500 if (stop_id == 0) {
2501 // Our first stop, make sure we have a process ID, and also make sure we
2502 // know about our registers
2504 SetID(pid);
2506 }
2507 // Stop with signal and thread info
2510 const uint8_t signo = stop_packet.GetHexU8();
2511 llvm::StringRef key;
2512 llvm::StringRef value;
2513 std::string thread_name;
2514 std::string reason;
2515 std::string description;
2516 std::vector<addr_t> added_binaries;
2517 StructuredData::ObjectSP detailed_binaries_info;
2518 uint32_t exc_type = 0;
2519 std::vector<addr_t> exc_data;
2520 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2521 bool queue_vars_valid =
2522 false; // says if locals below that start with "queue_" are valid
2523 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2524 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2525 std::string queue_name;
2526 QueueKind queue_kind = eQueueKindUnknown;
2527 uint64_t queue_serial_number = 0;
2528 ExpeditedRegisterMap expedited_register_map;
2529 AddressableBits addressable_bits;
2530 while (stop_packet.GetNameColonValue(key, value)) {
2531 if (key.compare("metype") == 0) {
2532 // exception type in big endian hex
2533 value.getAsInteger(BASE_16, exc_type);
2534 } else if (key.compare("medata") == 0) {
2535 // exception data in big endian hex
2536 uint64_t x;
2537 value.getAsInteger(BASE_16, x);
2538 exc_data.push_back(x);
2539 } else if (key.compare("thread") == 0) {
2540 // thread-id
2541 StringExtractorGDBRemote thread_id{value};
2542 auto pid_tid = thread_id.GetPidTid(pid);
2543 if (pid_tid) {
2544 stop_pid = pid_tid->first;
2545 tid = pid_tid->second;
2546 } else
2548 } else if (key.compare("threads") == 0) {
2549 std::lock_guard<std::recursive_mutex> guard(
2550 m_thread_list_real.GetMutex());
2552 } else if (key.compare("thread-pcs") == 0) {
2553 m_thread_pcs.clear();
2554 // A comma separated list of all threads in the current
2555 // process that includes the thread for this stop reply packet
2557 while (!value.empty()) {
2558 llvm::StringRef pc_str;
2559 std::tie(pc_str, value) = value.split(',');
2560 if (pc_str.getAsInteger(BASE_16, pc))
2562 m_thread_pcs.push_back(pc);
2563 }
2564 } else if (key.compare("jstopinfo") == 0) {
2565 StringExtractor json_extractor(value);
2566 std::string json;
2567 // Now convert the HEX bytes into a string value
2568 json_extractor.GetHexByteString(json);
2569
2570 // This JSON contains thread IDs and thread stop info for all threads.
2571 // It doesn't contain expedited registers, memory or queue info.
2573 } else if (key.compare("hexname") == 0) {
2574 StringExtractor name_extractor(value);
2575 // Now convert the HEX bytes into a string value
2576 name_extractor.GetHexByteString(thread_name);
2577 } else if (key.compare("name") == 0) {
2578 thread_name = std::string(value);
2579 } else if (key.compare("qaddr") == 0) {
2580 value.getAsInteger(BASE_16, thread_dispatch_qaddr);
2581 } else if (key.compare("dispatch_queue_t") == 0) {
2582 queue_vars_valid = true;
2583 value.getAsInteger(BASE_16, dispatch_queue_t);
2584 } else if (key.compare("qname") == 0) {
2585 queue_vars_valid = true;
2586 StringExtractor name_extractor(value);
2587 // Now convert the HEX bytes into a string value
2588 name_extractor.GetHexByteString(queue_name);
2589 } else if (key.compare("qkind") == 0) {
2590 queue_kind = llvm::StringSwitch<QueueKind>(value)
2591 .Case("serial", eQueueKindSerial)
2592 .Case("concurrent", eQueueKindConcurrent)
2593 .Default(eQueueKindUnknown);
2594 queue_vars_valid = queue_kind != eQueueKindUnknown;
2595 } else if (key.compare("qserialnum") == 0) {
2596 if (!value.getAsInteger(BASE_10, queue_serial_number))
2597 queue_vars_valid = true;
2598 } else if (key.compare("reason") == 0) {
2599 reason = std::string(value);
2600 } else if (key.compare("description") == 0) {
2601 StringExtractor desc_extractor(value);
2602 // Now convert the HEX bytes into a string value
2603 desc_extractor.GetHexByteString(description);
2604 } else if (key.compare("memory") == 0) {
2605 // Expedited memory. GDB servers can choose to send back expedited
2606 // memory that can populate the L1 memory cache in the process so that
2607 // things like the frame pointer backchain can be expedited. This will
2608 // help stack backtracing be more efficient by not having to send as
2609 // many memory read requests down the remote GDB server.
2610
2611 // Key/value pair format: memory:<addr>=<bytes>;
2612 // <addr> is a number whose base will be interpreted by the prefix:
2613 // "0x[0-9a-fA-F]+" for hex
2614 // "0[0-7]+" for octal
2615 // "[1-9]+" for decimal
2616 // <bytes> is native endian ASCII hex bytes just like the register
2617 // values
2618 llvm::StringRef addr_str, bytes_str;
2619 std::tie(addr_str, bytes_str) = value.split('=');
2620 if (!addr_str.empty() && !bytes_str.empty()) {
2621 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2622 if (!addr_str.getAsInteger(BASE_AUTOSENSE, mem_cache_addr)) {
2623 StringExtractor bytes(bytes_str);
2624 const size_t byte_size = bytes.GetBytesLeft() / 2;
2625 WritableDataBufferSP data_buffer_sp(
2626 new DataBufferHeap(byte_size, 0));
2627 const size_t bytes_copied =
2628 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2629 if (bytes_copied == byte_size)
2630 AddCacheData(mem_cache_addr, data_buffer_sp);
2631 }
2632 }
2633 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2634 key.compare("awatch") == 0) {
2635 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2637 value.getAsInteger(BASE_16, wp_addr);
2638
2639 WatchpointResourceSP wp_resource_sp =
2640 m_watchpoint_resource_list.FindByAddress(wp_addr);
2641
2642 // Rewrite gdb standard watch/rwatch/awatch to
2643 // "reason:watchpoint" + "description:ADDR",
2644 // which is parsed in SetThreadStopInfo.
2645 reason = "watchpoint";
2646 StreamString ostr;
2647 ostr.Printf("%" PRIu64, wp_addr);
2648 description = std::string(ostr.GetString());
2649 } else if (key.compare("swbreak") == 0 || key.compare("hwbreak") == 0) {
2650 reason = "breakpoint";
2651 } else if (key.compare("replaylog") == 0) {
2652 reason = "history boundary";
2653 } else if (key.compare("library") == 0) {
2654 auto error = LoadModules();
2655 if (error) {
2657 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2658 }
2659 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2660 // fork includes child pid/tid in thread-id format
2661 StringExtractorGDBRemote thread_id{value};
2662 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2663 if (!pid_tid) {
2665 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2667 }
2668
2669 reason = key.str();
2670 StreamString ostr;
2671 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2672 description = std::string(ostr.GetString());
2673 } else if (key.compare("addressing_bits") == 0) {
2674 uint64_t addressing_bits;
2675 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2676 addressable_bits.SetAddressableBits(addressing_bits);
2677 }
2678 } else if (key.compare("low_mem_addressing_bits") == 0) {
2679 uint64_t addressing_bits;
2680 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2681 addressable_bits.SetLowmemAddressableBits(addressing_bits);
2682 }
2683 } else if (key.compare("high_mem_addressing_bits") == 0) {
2684 uint64_t addressing_bits;
2685 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2686 addressable_bits.SetHighmemAddressableBits(addressing_bits);
2687 }
2688 } else if (key == "added-binaries") {
2689 // A comma separated list of all threads in the current
2690 // process that includes the thread for this stop reply packet
2692 while (!value.empty()) {
2693 llvm::StringRef pc_str;
2694 std::tie(pc_str, value) = value.split(',');
2695 if (pc_str.getAsInteger(BASE_16, pc))
2697 added_binaries.push_back(pc);
2698 }
2699 } else if (key == "detailed-binaries-info") {
2700 StringExtractor json_extractor(value);
2701 std::string json;
2702 // Now convert the HEX bytes into a string value.
2703 json_extractor.GetHexByteString(json);
2704
2705 // This JSON contains detailed information about binares.
2706 detailed_binaries_info = StructuredData::ParseJSON(json);
2707 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2708 uint32_t reg = UINT32_MAX;
2709 if (!key.getAsInteger(BASE_16, reg))
2710 expedited_register_map[reg] = std::string(std::move(value));
2711 }
2712 // swbreak and hwbreak are also expected keys, but we don't need to
2713 // change our behaviour for them because lldb always expects the remote
2714 // to adjust the program counter (if relevant, e.g., for x86 targets)
2715 }
2716
2717 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2718 Log *log = GetLog(GDBRLog::Process);
2719 LLDB_LOG(log,
2720 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2721 stop_pid, pid);
2722 return eStateInvalid;
2723 }
2724
2725 if (tid == LLDB_INVALID_THREAD_ID) {
2726 // A thread id may be invalid if the response is old style 'S' packet
2727 // which does not provide the
2728 // thread information. So update the thread list and choose the first
2729 // one.
2731
2732 if (!m_thread_ids.empty()) {
2733 tid = m_thread_ids.front();
2734 }
2735 }
2736
2737 SetAddressableBitMasks(addressable_bits);
2738
2740
2741 ThreadSP thread_sp = SetThreadStopInfo(
2742 tid, expedited_register_map, signo, thread_name, reason, description,
2743 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2744 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2745 queue_kind, queue_serial_number, added_binaries,
2746 detailed_binaries_info);
2747
2748 return eStateStopped;
2749 } break;
2750
2751 case 'W':
2752 case 'X':
2753 // process exited
2754 return eStateExited;
2755
2756 default:
2757 break;
2758 }
2759 return eStateInvalid;
2760}
2761
2763 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2764
2765 m_thread_ids.clear();
2766 m_thread_pcs.clear();
2767
2768 // Set the thread stop info. It might have a "threads" key whose value is a
2769 // list of all thread IDs in the current process, so m_thread_ids might get
2770 // set.
2771 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2772 if (m_thread_ids.empty()) {
2773 // No, we need to fetch the thread list manually
2775 }
2776
2777 // We might set some stop info's so make sure the thread list is up to
2778 // date before we do that or we might overwrite what was computed here.
2780
2783 m_last_stop_packet.reset();
2784
2785 // If we have queried for a default thread id
2787 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2791 if (ThreadSP primary_thread_sp = m_thread_list.FindThreadByProtocolID(
2792 m_last_stop_primary_tid, /*can_update=*/false)) {
2793 ThreadSP selected_thread_sp = m_thread_list.GetSelectedThread();
2794 if (!selected_thread_sp ||
2795 selected_thread_sp->GetID() != primary_thread_sp->GetID())
2796 m_thread_list.SetSelectedThreadByID(primary_thread_sp->GetID());
2797 }
2798 }
2800
2801 // Let all threads recover from stopping and do any clean up based on the
2802 // previous thread state (if any).
2803 m_thread_list_real.RefreshStateAfterStop();
2804}
2805
2807 Status error;
2808
2810 // We are being asked to halt during an attach. We used to just close our
2811 // file handle and debugserver will go away, but with remote proxies, it
2812 // is better to send a positive signal, so let's send the interrupt first...
2813 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2814 m_gdb_comm.Disconnect();
2815 } else
2816 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2817 return error;
2818}
2819
2821 Status error;
2822 Log *log = GetLog(GDBRLog::Process);
2823 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2824
2825 error = m_gdb_comm.Detach(keep_stopped);
2826 if (log) {
2827 if (error.Success())
2828 log->PutCString(
2829 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2830 else
2831 LLDB_LOGF(log,
2832 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2833 error.AsCString() ? error.AsCString() : "<unknown error>");
2834 }
2835
2836 if (!error.Success())
2837 return error;
2838
2839 // Sleep for one second to let the process get all detached...
2841
2844
2845 // KillDebugserverProcess ();
2846 return error;
2847}
2848
2850 Log *log = GetLog(GDBRLog::Process);
2851 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2852
2853 // Interrupt if our inferior is running...
2854 int exit_status = SIGABRT;
2855 std::string exit_string;
2856
2857 if (m_gdb_comm.IsConnected()) {
2859 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2860
2861 if (kill_res) {
2862 exit_status = kill_res.get();
2863#if defined(__APPLE__)
2864 // For Native processes on Mac OS X, we launch through the Host
2865 // Platform, then hand the process off to debugserver, which becomes
2866 // the parent process through "PT_ATTACH". Then when we go to kill
2867 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2868 // we call waitpid which returns with no error and the correct
2869 // status. But amusingly enough that doesn't seem to actually reap
2870 // the process, but instead it is left around as a Zombie. Probably
2871 // the kernel is in the process of switching ownership back to lldb
2872 // which was the original parent, and gets confused in the handoff.
2873 // Anyway, so call waitpid here to finally reap it.
2874 PlatformSP platform_sp(GetTarget().GetPlatform());
2875 if (platform_sp && platform_sp->IsHost()) {
2876 int status;
2877 ::pid_t reap_pid;
2878 reap_pid = waitpid(GetID(), &status, WNOHANG);
2879 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2880 }
2881#endif
2883 exit_string.assign("killed");
2884 } else {
2885 exit_string.assign(llvm::toString(kill_res.takeError()));
2886 }
2887 } else {
2888 exit_string.assign("killed or interrupted while attaching.");
2889 }
2890 } else {
2891 // If we missed setting the exit status on the way out, do it here.
2892 // NB set exit status can be called multiple times, the first one sets the
2893 // status.
2894 exit_string.assign("destroying when not connected to debugserver");
2895 }
2896
2897 SetExitStatus(exit_status, exit_string.c_str());
2898
2902 return Status();
2903}
2904
2907 if (TargetSP target_sp = m_target_wp.lock())
2908 target_sp->RemoveBreakpointByID(m_thread_create_bp_sp->GetID());
2909 m_thread_create_bp_sp.reset();
2910 }
2911}
2912
2914 const StringExtractorGDBRemote &response) {
2915 const bool did_exec =
2916 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2917 if (did_exec) {
2918 Log *log = GetLog(GDBRLog::Process);
2919 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2920
2921 m_thread_list_real.Clear();
2922 m_thread_list.Clear();
2924 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2925 }
2926
2927 m_last_stop_packet = response;
2928}
2929
2931 StringExtractorGDBRemote &response) {
2932 response.SetFilePos(1);
2933 int exit_status = response.GetHexU8();
2934 std::string desc_string;
2935 if (response.GetBytesLeft() > 0 && response.GetChar() == ';') {
2936 llvm::StringRef desc_str;
2937 llvm::StringRef desc_token;
2938 while (response.GetNameColonValue(desc_token, desc_str)) {
2939 if (desc_token != "description")
2940 continue;
2941 StringExtractor extractor(desc_str);
2942 extractor.GetHexByteString(desc_string);
2943 }
2944 }
2945 SetExitStatus(exit_status, desc_string);
2946}
2947
2949 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2950}
2951
2952// Process Queries
2953
2955 return m_gdb_comm.IsConnected() && Process::IsAlive();
2956}
2957
2959 // request the link map address via the $qShlibInfoAddr packet
2960 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2961
2962 // the loaded module list can also provides a link map address
2963 if (addr == LLDB_INVALID_ADDRESS) {
2964 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2965 if (!list) {
2966 Log *log = GetLog(GDBRLog::Process);
2967 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2968 } else {
2969 addr = list->m_link_map;
2970 }
2971 }
2972
2973 return addr;
2974}
2975
2977 // See if the GDB remote client supports the JSON threads info. If so, we
2978 // gather stop info for all threads, expedited registers, expedited memory,
2979 // runtime queue information (iOS and MacOSX only), and more. Expediting
2980 // memory will help stack backtracing be much faster. Expediting registers
2981 // will make sure we don't have to read the thread registers for GPRs.
2982 StructuredData::ObjectSP threads_info_sp = m_gdb_comm.GetThreadsInfo();
2983 *m_jthreadsinfo.Lock() = IndexThreadInfos(threads_info_sp);
2984
2985 if (threads_info_sp) {
2986 // Now set the stop info for each thread and also expedite any registers
2987 // and memory that was in the jThreadsInfo response.
2988 StructuredData::Array *thread_infos = threads_info_sp->GetAsArray();
2989 if (thread_infos) {
2990 std::unordered_map<lldb::tid_t, ThreadSP> threads;
2991 for (const ThreadSP &thread_sp : m_thread_list_real.Threads())
2992 threads.try_emplace(thread_sp->GetProtocolID(), thread_sp);
2993 const size_t n = thread_infos->GetSize();
2994 for (size_t i = 0; i < n; ++i) {
2995 StructuredData::Dictionary *thread_dict =
2996 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2997 if (!thread_dict)
2998 continue;
3000 thread_dict->GetValueForKeyAsInteger("tid", tid);
3001 auto thread = threads.find(tid);
3002 SetThreadStopInfo(thread_dict,
3003 thread == threads.end() ? nullptr : thread->second);
3004 }
3005 }
3006 }
3007}
3008
3009// Process Memory
3010
3011/// Returns the error for a failed memory access. Includes the error string if
3012/// the stub sent one.
3013static Status MemoryAccessError(llvm::StringRef access, lldb::addr_t addr,
3014 StringExtractorGDBRemote &response) {
3015 // The error string is hex encoded after "Exx;".
3016 std::string error_string;
3017 response.SetFilePos(4);
3018 response.GetHexByteString(error_string);
3019 if (error_string.empty())
3020 return Status::FromErrorStringWithFormatv("memory {0} failed for {1:x}",
3021 access, addr);
3022 return Status::FromErrorStringWithFormatv("memory {0} failed for {1:x}: {2}",
3023 access, addr, error_string);
3024}
3025
3027 void *buf, size_t size, Status &error) {
3028 using xPacketState = GDBRemoteCommunicationClient::xPacketState;
3029
3030 lldb::addr_t addr = process_addr.GetValue();
3031 lldb::addr_space_t addr_space = process_addr.GetAddressSpace();
3032 if (addr_space != LLDB_DEFAULT_ADDRESS_SPACE_ID &&
3033 !m_gdb_comm.GetAddressSpacesSupported()) {
3034 error = Status::FromErrorString("address spaces are not supported");
3035 return 0;
3036 }
3037
3039 xPacketState x_state = m_gdb_comm.GetxPacketState();
3040
3041 // M and m packets take 2 bytes for 1 byte of memory
3042 size_t max_memory_size = x_state != xPacketState::Unimplemented
3044 : m_max_memory_size / 2;
3045 if (size > max_memory_size) {
3046 // Keep memory read sizes down to a sane limit. This function will be
3047 // called multiple times in order to complete the task by
3048 // lldb_private::Process so it is ok to do this.
3049 size = max_memory_size;
3050 }
3051
3052 // A non-default address space rides on an "address_space:<hex-id>;" suffix,
3053 // followed by "thread:<hex-tid>;" when that space is thread specific.
3054 std::string suffix;
3055 if (addr_space != LLDB_DEFAULT_ADDRESS_SPACE_ID) {
3056 llvm::Expected<AddressSpaceInfo> info = GetAddressSpaceInfo(addr_space);
3057 if (!info) {
3058 error = Status::FromError(info.takeError());
3059 return 0;
3060 }
3061 suffix =
3062 llvm::formatv(";address_space:{0};", llvm::utohexstr(addr_space, true));
3063 if (info->is_thread_specific) {
3064 std::optional<lldb::tid_t> tid = process_addr.GetThreadID();
3065 if (!tid) {
3067 "address space \"%s\" is thread specific, but no thread was "
3068 "specified",
3069 info->name.c_str());
3070 return 0;
3071 }
3072 suffix += llvm::formatv("thread:{0};", llvm::utohexstr(*tid, true));
3073 }
3074 }
3075
3076 char packet[128];
3077 int packet_len =
3078 ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64 "%s",
3079 x_state != xPacketState::Unimplemented ? 'x' : 'm',
3080 (uint64_t)addr, (uint64_t)size, suffix.c_str());
3081 assert(packet_len + 1 < (int)sizeof(packet));
3082 UNUSED_IF_ASSERT_DISABLED(packet_len);
3083 StringExtractorGDBRemote response;
3084 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
3087 if (response.IsNormalResponse()) {
3088 error.Clear();
3089 if (x_state != xPacketState::Unimplemented) {
3090 // The lower level GDBRemoteCommunication packet receive layer has
3091 // already de-quoted any 0x7d character escaping that was present in
3092 // the packet
3093
3094 llvm::StringRef data_received = response.GetStringRef();
3095 if (x_state == xPacketState::Prefixed &&
3096 !data_received.consume_front("b")) {
3098 "unexpected response to GDB server memory read packet '{0}': "
3099 "'{1}'",
3100 packet, data_received);
3101 return 0;
3102 }
3103 // Don't write past the end of BUF if the remote debug server gave us
3104 // too much data for some reason.
3105 size_t memcpy_size = std::min(size, data_received.size());
3106 memcpy(buf, data_received.data(), memcpy_size);
3107 return memcpy_size;
3108 } else {
3109 return response.GetHexBytes(
3110 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
3111 }
3112 } else if (response.IsErrorResponse())
3113 error = MemoryAccessError("read", addr, response);
3114 else if (response.IsUnsupportedResponse())
3116 "GDB server does not support reading memory");
3117 else
3119 "unexpected response to GDB server memory read packet '%s': '%s'",
3120 packet, response.GetStringRef().data());
3121 } else {
3122 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3123 packet);
3124 }
3125 return 0;
3126}
3127
3128/// Returns the number of ranges that is safe to request using MultiMemRead
3129/// while respecting max_packet_size.
3131 uint64_t max_packet_size,
3132 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
3133 // Each range is specified by two numbers (up to 16 ASCII characters) and one
3134 // comma.
3135 constexpr uint64_t range_overhead = 33;
3136 uint64_t current_size = 0;
3137 for (auto [idx, range] : llvm::enumerate(ranges)) {
3138 uint64_t potential_size = current_size + range.size + range_overhead;
3139 if (potential_size > max_packet_size) {
3140 if (idx == 0)
3142 "MultiMemRead input has a range (base = {0:x}, size = {1}) "
3143 "bigger than the maximum allowed by remote",
3144 range.base, range.size);
3145 return idx;
3146 }
3147 }
3148 return ranges.size();
3149}
3150
3151llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
3153 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
3154 llvm::MutableArrayRef<uint8_t> buffer) {
3155 if (!m_gdb_comm.GetMultiMemReadSupported())
3156 return Process::DoReadMemoryRanges(ranges, buffer);
3157
3158 const llvm::ArrayRef<Range<lldb::addr_t, size_t>> original_ranges = ranges;
3159 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory_regions;
3160
3161 while (!ranges.empty()) {
3162 uint64_t num_ranges =
3164 if (num_ranges == 0)
3165 return Process::DoReadMemoryRanges(original_ranges, buffer);
3166
3167 auto ranges_for_request = ranges.take_front(num_ranges);
3168 ranges = ranges.drop_front(num_ranges);
3169
3170 llvm::Expected<StringExtractorGDBRemote> response =
3171 SendMultiMemReadPacket(ranges_for_request);
3172 if (!response) {
3173 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(),
3174 "MultiMemRead error response: {0}");
3175 return Process::DoReadMemoryRanges(original_ranges, buffer);
3176 }
3177
3178 llvm::StringRef response_str = response->GetStringRef();
3179 const unsigned expected_num_ranges = ranges_for_request.size();
3180 if (llvm::Error error = ParseMultiMemReadPacket(
3181 response_str, buffer, expected_num_ranges, memory_regions)) {
3183 "MultiMemRead error parsing response: {0}");
3184 return Process::DoReadMemoryRanges(original_ranges, buffer);
3185 }
3186 }
3187 return memory_regions;
3188}
3189
3190llvm::Expected<StringExtractorGDBRemote>
3192 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
3193 std::string packet_str;
3194 llvm::raw_string_ostream stream(packet_str);
3195 stream << "MultiMemRead:ranges:";
3196
3197 auto range_to_stream = [&](auto range) {
3198 // the "-" marker omits the '0x' prefix.
3199 stream << llvm::formatv("{0:x-},{1:x-}", range.base, range.size);
3200 };
3201 llvm::interleave(ranges, stream, range_to_stream, ",");
3202 stream << ";";
3203
3204 StringExtractorGDBRemote response;
3206 m_gdb_comm.SendPacketAndWaitForResponse(packet_str.data(), response,
3209 return llvm::createStringErrorV("MultiMemRead failed to send packet: '{0}'",
3210 packet_str);
3211
3212 if (response.IsErrorResponse())
3213 return llvm::createStringErrorV("MultiMemRead failed: '{0}'",
3214 response.GetStringRef());
3215
3216 if (!response.IsNormalResponse())
3217 return llvm::createStringErrorV("MultiMemRead unexpected response: '{0}'",
3218 response.GetStringRef());
3219
3220 return response;
3221}
3222
3224 llvm::StringRef response_str, llvm::MutableArrayRef<uint8_t> buffer,
3225 unsigned expected_num_ranges,
3226 llvm::SmallVectorImpl<llvm::MutableArrayRef<uint8_t>> &memory_regions) {
3227 // The sizes and the data are separated by a `;`.
3228 auto [sizes_str, memory_data] = response_str.split(';');
3229 if (sizes_str.size() == response_str.size())
3230 return llvm::createStringErrorV(
3231 "MultiMemRead response missing field separator ';' in: '{0}'",
3232 response_str);
3233
3234 // Sizes are separated by a `,`.
3235 unsigned num_sizes = 0;
3236 for (llvm::StringRef size_str : llvm::split(sizes_str, ',')) {
3237 uint64_t read_size;
3238 if (size_str.getAsInteger(BASE_16, read_size))
3239 return llvm::createStringErrorV(
3240 "MultiMemRead response has invalid size string: {0}", size_str);
3241
3242 if (memory_data.size() < read_size)
3243 return llvm::createStringErrorV("MultiMemRead response did not have "
3244 "enough data, requested sizes: {0}",
3245 sizes_str);
3246
3247 if (read_size > buffer.size())
3248 return llvm::createStringErrorV(
3249 "MultiMemRead response size {0} exceeds remaining buffer {1}",
3250 read_size, buffer.size());
3251
3252 llvm::StringRef region_to_read = memory_data.take_front(read_size);
3253 memory_data = memory_data.drop_front(read_size);
3254
3255 llvm::MutableArrayRef<uint8_t> region_to_write =
3256 buffer.take_front(read_size);
3257 buffer = buffer.drop_front(read_size);
3258
3259 memcpy(region_to_write.data(), region_to_read.data(), read_size);
3260 memory_regions.push_back(region_to_write);
3261 ++num_sizes;
3262 }
3263
3264 if (num_sizes != expected_num_ranges)
3265 return llvm::createStringErrorV(
3266 "MultiMemRead response had {0} sizes, expected {1}", num_sizes,
3267 expected_num_ranges);
3268
3269 return llvm::Error::success();
3270}
3271
3273 return m_gdb_comm.GetMemoryTaggingSupported();
3274}
3275
3276llvm::Expected<std::vector<uint8_t>>
3278 int32_t type) {
3279 // By this point ReadMemoryTags has validated that tagging is enabled
3280 // for this target/process/address.
3281 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
3282 if (!buffer_sp) {
3283 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3284 "Error reading memory tags from remote");
3285 }
3286
3287 // Return the raw tag data
3288 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
3289 std::vector<uint8_t> got;
3290 got.reserve(tag_data.size());
3291 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
3292 return got;
3293}
3294
3296 int32_t type,
3297 const std::vector<uint8_t> &tags) {
3298 // By now WriteMemoryTags should have validated that tagging is enabled
3299 // for this target/process.
3300 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
3301}
3302
3304 std::vector<ObjectFile::LoadableData> entries) {
3305 Status error;
3306 // Sort the entries by address because some writes, like those to flash
3307 // memory, must happen in order of increasing address.
3308 llvm::stable_sort(entries, [](const ObjectFile::LoadableData a,
3309 const ObjectFile::LoadableData b) {
3310 return a.Dest < b.Dest;
3311 });
3312 m_allow_flash_writes = true;
3314 if (error.Success())
3315 error = FlashDone();
3316 else
3317 // Even though some of the writing failed, try to send a flash done if some
3318 // of the writing succeeded so the flash state is reset to normal, but
3319 // don't stomp on the error status that was set in the write failure since
3320 // that's the one we want to report back.
3321 FlashDone();
3322 m_allow_flash_writes = false;
3323 return error;
3324}
3325
3327 auto size = m_erased_flash_ranges.GetSize();
3328 for (size_t i = 0; i < size; ++i)
3329 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
3330 return true;
3331 return false;
3332}
3333
3335 Status status;
3336
3337 MemoryRegionInfo region;
3338 status = GetMemoryRegionInfo(addr, region);
3339 if (!status.Success())
3340 return status;
3341
3342 // The gdb spec doesn't say if erasures are allowed across multiple regions,
3343 // but we'll disallow it to be safe and to keep the logic simple by worring
3344 // about only one region's block size. DoMemoryWrite is this function's
3345 // primary user, and it can easily keep writes within a single memory region
3346 if (addr + size > region.GetRange().GetRangeEnd()) {
3347 status =
3348 Status::FromErrorString("Unable to erase flash in multiple regions");
3349 return status;
3350 }
3351
3352 uint64_t blocksize = region.GetBlocksize();
3353 if (blocksize == 0) {
3354 status =
3355 Status::FromErrorString("Unable to erase flash because blocksize is 0");
3356 return status;
3357 }
3358
3359 // Erasures can only be done on block boundary adresses, so round down addr
3360 // and round up size
3361 lldb::addr_t block_start_addr = addr - (addr % blocksize);
3362 size += (addr - block_start_addr);
3363 if ((size % blocksize) != 0)
3364 size += (blocksize - size % blocksize);
3365
3366 FlashRange range(block_start_addr, size);
3367
3368 if (HasErased(range))
3369 return status;
3370
3371 // We haven't erased the entire range, but we may have erased part of it.
3372 // (e.g., block A is already erased and range starts in A and ends in B). So,
3373 // adjust range if necessary to exclude already erased blocks.
3374 if (!m_erased_flash_ranges.IsEmpty()) {
3375 // Assuming that writes and erasures are done in increasing addr order,
3376 // because that is a requirement of the vFlashWrite command. Therefore, we
3377 // only need to look at the last range in the list for overlap.
3378 const auto &last_range = *m_erased_flash_ranges.Back();
3379 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
3380 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
3381 // overlap will be less than range.GetByteSize() or else HasErased()
3382 // would have been true
3383 range.SetByteSize(range.GetByteSize() - overlap);
3384 range.SetRangeBase(range.GetRangeBase() + overlap);
3385 }
3386 }
3387
3388 StreamString packet;
3389 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
3390 (uint64_t)range.GetByteSize());
3391
3392 StringExtractorGDBRemote response;
3393 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3396 if (response.IsOKResponse()) {
3397 m_erased_flash_ranges.Insert(range, true);
3398 } else {
3399 if (response.IsErrorResponse())
3401 "flash erase failed for 0x%" PRIx64, addr);
3402 else if (response.IsUnsupportedResponse())
3404 "GDB server does not support flashing");
3405 else
3407 "unexpected response to GDB server flash erase packet '%s': '%s'",
3408 packet.GetData(), response.GetStringRef().data());
3409 }
3410 } else {
3411 status = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3412 packet.GetData());
3413 }
3414 return status;
3415}
3416
3418 Status status;
3419 // If we haven't erased any blocks, then we must not have written anything
3420 // either, so there is no need to actually send a vFlashDone command
3421 if (m_erased_flash_ranges.IsEmpty())
3422 return status;
3423 StringExtractorGDBRemote response;
3424 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
3427 if (response.IsOKResponse()) {
3428 m_erased_flash_ranges.Clear();
3429 } else {
3430 if (response.IsErrorResponse())
3431 status = Status::FromErrorStringWithFormat("flash done failed");
3432 else if (response.IsUnsupportedResponse())
3434 "GDB server does not support flashing");
3435 else
3437 "unexpected response to GDB server flash done packet: '%s'",
3438 response.GetStringRef().data());
3439 }
3440 } else {
3441 status =
3442 Status::FromErrorStringWithFormat("failed to send flash done packet");
3443 }
3444 return status;
3445}
3446
3447size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
3448 size_t size, Status &error) {
3450 // M and m packets take 2 bytes for 1 byte of memory
3451 size_t max_memory_size = m_max_memory_size / 2;
3452 if (size > max_memory_size) {
3453 // Keep memory read sizes down to a sane limit. This function will be
3454 // called multiple times in order to complete the task by
3455 // lldb_private::Process so it is ok to do this.
3456 size = max_memory_size;
3457 }
3458
3459 StreamGDBRemote packet;
3460
3461 MemoryRegionInfo region;
3462 Status region_status = GetMemoryRegionInfo(addr, region);
3463
3464 bool is_flash = region_status.Success() && region.GetFlash() == eLazyBoolYes;
3465
3466 if (is_flash) {
3467 if (!m_allow_flash_writes) {
3468 error = Status::FromErrorString("Writing to flash memory is not allowed");
3469 return 0;
3470 }
3471 // Keep the write within a flash memory region
3472 if (addr + size > region.GetRange().GetRangeEnd())
3473 size = region.GetRange().GetRangeEnd() - addr;
3474 // Flash memory must be erased before it can be written
3475 error = FlashErase(addr, size);
3476 if (!error.Success())
3477 return 0;
3478 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
3479 packet.PutEscapedBytes(buf, size);
3480 } else {
3481 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
3482 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
3484 }
3485 StringExtractorGDBRemote response;
3486 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3489 if (response.IsOKResponse()) {
3490 error.Clear();
3491 return size;
3492 } else if (response.IsErrorResponse())
3493 error = MemoryAccessError("write", addr, response);
3494 else if (response.IsUnsupportedResponse())
3496 "GDB server does not support writing memory");
3497 else
3499 "unexpected response to GDB server memory write packet '%s': '%s'",
3500 packet.GetData(), response.GetStringRef().data());
3501 } else {
3502 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3503 packet.GetData());
3504 }
3505 return 0;
3506}
3507
3509 // Probe the _M packet. Falling back to mmap() only needs its symbol.
3510 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolCalculate) {
3511 addr_t addr = m_gdb_comm.AllocateMemory(8, ePermissionsReadable |
3512 ePermissionsWritable |
3513 ePermissionsExecutable);
3514 if (addr != LLDB_INVALID_ADDRESS)
3515 m_gdb_comm.DeallocateMemory(addr);
3516 }
3517 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3518 return true;
3519
3521 options.include_symbols = true;
3522 options.include_inlines = false;
3523 SymbolContextList sc_list;
3524 GetTarget().GetImages().FindFunctions("mmap", eFunctionNameTypeFull, options,
3525 sc_list);
3526 return !sc_list.IsEmpty();
3527}
3528
3530 uint32_t permissions,
3531 Status &error) {
3533 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3534
3535 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3536 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3537 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3538 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3539 return allocated_addr;
3540 }
3541
3542 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3543 // Call mmap() to create memory in the inferior..
3544 unsigned prot = 0;
3545 if (permissions & lldb::ePermissionsReadable)
3546 prot |= eMmapProtRead;
3547 if (permissions & lldb::ePermissionsWritable)
3548 prot |= eMmapProtWrite;
3549 if (permissions & lldb::ePermissionsExecutable)
3550 prot |= eMmapProtExec;
3551
3552 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3554 m_addr_to_mmap_size[allocated_addr] = size;
3555 else {
3556 allocated_addr = LLDB_INVALID_ADDRESS;
3557 LLDB_LOGF(log,
3558 "ProcessGDBRemote::%s no direct stub support for memory "
3559 "allocation, and InferiorCallMmap also failed - is stub "
3560 "missing register context save/restore capability?",
3561 __FUNCTION__);
3562 }
3563 }
3564
3565 if (allocated_addr == LLDB_INVALID_ADDRESS)
3567 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3568 (uint64_t)size, GetPermissionsAsCString(permissions));
3569 else
3570 error.Clear();
3571 return allocated_addr;
3572}
3573
3575 MemoryRegionInfo &region_info) {
3576
3577 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
3578 return error;
3579}
3580
3582 return m_gdb_comm.GetWatchpointSlotCount();
3583}
3584
3586 return m_gdb_comm.GetWatchpointReportedAfter();
3587}
3588
3590 Status error;
3591 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3592
3593 switch (supported) {
3594 case eLazyBoolCalculate:
3595 // We should never be deallocating memory without allocating memory first
3596 // so we should never get eLazyBoolCalculate
3598 "tried to deallocate memory without ever allocating memory");
3599 break;
3600
3601 case eLazyBoolYes:
3602 if (!m_gdb_comm.DeallocateMemory(addr))
3604 "unable to deallocate memory at 0x%" PRIx64, addr);
3605 break;
3606
3607 case eLazyBoolNo:
3608 // Call munmap() to deallocate memory in the inferior..
3609 {
3610 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3611 if (pos != m_addr_to_mmap_size.end() &&
3612 InferiorCallMunmap(this, addr, pos->second))
3613 m_addr_to_mmap_size.erase(pos);
3614 else
3616 "unable to deallocate memory at 0x%" PRIx64, addr);
3617 }
3618 break;
3619 }
3620
3621 return error;
3622}
3623
3624// Process STDIO
3625size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3626 Status &error) {
3627 if (m_stdio_communication.IsConnected()) {
3628 ConnectionStatus status;
3629 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
3630 } else if (m_stdin_forward) {
3631 m_gdb_comm.SendStdinNotification(src, src_len, GetInterruptTimeout());
3632 }
3633 return 0;
3634}
3635
3636/// Enable a single breakpoint site by trying Z0 (software), then Z1
3637/// (hardware), then manual memory write as a last resort.
3640 const addr_t addr = bp_site.GetLoadAddress();
3641 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3642 auto &gdb_comm = GetGDBRemote();
3643
3644 // SupportsGDBStoppointPacket always returns true unless a previously sent
3645 // packet failed. As such, query the function before AND after sending the
3646 // packet.
3647 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3648 !bp_site.HardwareRequired()) {
3649 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3650 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
3651 if (error_no == 0) {
3652 SetBreakpointSiteEnabled(bp_site);
3654 return llvm::Error::success();
3655 }
3656 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3657 if (error_no != UINT8_MAX)
3658 return llvm::createStringErrorV(
3659 "error sending the breakpoint request: {0}", error_no);
3660 return llvm::createStringError("error sending the breakpoint request");
3661 }
3662 LLDB_LOG(log, "Software breakpoints are unsupported");
3663 }
3664
3665 // Like above, this is also queried twice.
3666 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3667 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3668 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3669 if (error_no == 0) {
3670 SetBreakpointSiteEnabled(bp_site);
3672 return llvm::Error::success();
3673 }
3674 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3675 if (error_no != UINT8_MAX)
3676 return llvm::createStringErrorV(
3677 "error sending the hardware breakpoint request: {0} "
3678 "(hardware breakpoint resources might be exhausted or unavailable)",
3679 error_no);
3680 return llvm::createStringError(
3681 "error sending the hardware breakpoint request "
3682 "(hardware breakpoint resources might be exhausted or unavailable)");
3683 }
3684 LLDB_LOG(log, "Hardware breakpoints are unsupported");
3685 }
3686
3687 if (bp_site.HardwareRequired())
3688 return llvm::createStringError("hardware breakpoints are not supported");
3689
3690 return EnableSoftwareBreakpoint(&bp_site).takeError();
3691}
3692
3693/// Disable a single breakpoint site directly by sending the appropriate
3694/// z packet or restoring the original instruction.
3696 const addr_t addr = bp_site.GetLoadAddress();
3697 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3698 auto &gdb_comm = GetGDBRemote();
3699
3700 switch (bp_site.GetType()) {
3703 if (error.Fail())
3704 return error.takeError();
3705 break;
3706 }
3708 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr,
3709 bp_op_size, GetInterruptTimeout()))
3710 return llvm::createStringError("unknown error");
3711 break;
3713 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr,
3714 bp_op_size, GetInterruptTimeout()))
3715 return llvm::createStringError("unknown error");
3716 break;
3717 }
3718 SetBreakpointSiteEnabled(bp_site, false);
3719 return llvm::Error::success();
3720}
3721
3724 return {};
3725
3726 struct Guard {
3727 Guard(ProcessGDBRemote &remote)
3728 : process(remote.shared_from_this()),
3729 lock(remote.m_gdb_comm, remote.GetInterruptTimeout()) {}
3730
3731 // The lock references the process's transport. Keep it alive until the
3732 // lock is destroyed.
3733 ProcessSP process;
3735 };
3736
3737 return std::make_shared<Guard>(*this);
3738}
3739
3741 assert(bp_site != nullptr);
3742
3743 // Get logging info
3745 user_id_t site_id = bp_site->GetID();
3746
3747 // Get the breakpoint address
3748 const addr_t addr = bp_site->GetLoadAddress();
3749
3750 // Log that a breakpoint was requested
3751 LLDB_LOGF(log,
3752 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3753 ") address = 0x%" PRIx64,
3754 site_id, (uint64_t)addr);
3755
3756 // Breakpoint already exists and is enabled
3757 if (IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3758 LLDB_LOGF(log,
3759 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3760 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3761 site_id, (uint64_t)addr);
3762 return Status();
3763 }
3764
3765 return Status::FromError(DoEnableBreakpointSite(*bp_site));
3766}
3767
3769 assert(bp_site != nullptr);
3770 addr_t addr = bp_site->GetLoadAddress();
3771 user_id_t site_id = bp_site->GetID();
3773 LLDB_LOGF(log,
3774 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3775 ") addr = 0x%8.8" PRIx64,
3776 site_id, (uint64_t)addr);
3777
3778 if (!IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3779 LLDB_LOGF(log,
3780 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3781 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3782 site_id, (uint64_t)addr);
3783 return Status();
3784 }
3785
3787}
3788
3789// Pre-requisite: wp != NULL.
3790static GDBStoppointType
3792 assert(wp_res_sp);
3793 bool read = wp_res_sp->WatchpointResourceRead();
3794 bool write = wp_res_sp->WatchpointResourceWrite();
3795
3796 assert((read || write) &&
3797 "WatchpointResource type is neither read nor write");
3798 if (read && write)
3799 return eWatchpointReadWrite;
3800 else if (read)
3801 return eWatchpointRead;
3802 else
3803 return eWatchpointWrite;
3804}
3805
3807 Status error;
3808 if (!wp_sp) {
3809 error = Status::FromErrorString("No watchpoint specified");
3810 return error;
3811 }
3812 user_id_t watchID = wp_sp->GetID();
3813 addr_t addr = wp_sp->GetLoadAddress();
3815 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3816 watchID);
3817 if (wp_sp->IsEnabled()) {
3818 LLDB_LOGF(log,
3819 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3820 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3821 watchID, (uint64_t)addr);
3822 return error;
3823 }
3824
3825 bool read = wp_sp->WatchpointRead();
3826 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3827 size_t size = wp_sp->GetByteSize();
3828
3829 ArchSpec target_arch = GetTarget().GetArchitecture();
3830 WatchpointHardwareFeature supported_features =
3831 m_gdb_comm.GetSupportedWatchpointTypes();
3832
3833 std::vector<WatchpointResourceSP> resources =
3835 addr, size, read, write, supported_features, target_arch);
3836
3837 // LWP_TODO: Now that we know the WP Resources needed to implement this
3838 // Watchpoint, we need to look at currently allocated Resources in the
3839 // Process and if they match, or are within the same memory granule, or
3840 // overlapping memory ranges, then we need to combine them. e.g. one
3841 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1
3842 // byte at 0x1003, they must use the same hardware watchpoint register
3843 // (Resource) to watch them.
3844
3845 // This may mean that an existing resource changes its type (read to
3846 // read+write) or address range it is watching, in which case the old
3847 // watchpoint needs to be disabled and the new Resource addr/size/type
3848 // watchpoint enabled.
3849
3850 // If we modify a shared Resource to accomodate this newly added Watchpoint,
3851 // and we are unable to set all of the Resources for it in the inferior, we
3852 // will return an error for this Watchpoint and the shared Resource should
3853 // be restored. e.g. this Watchpoint requires three Resources, one which
3854 // is shared with another Watchpoint. We extend the shared Resouce to
3855 // handle both Watchpoints and we try to set two new ones. But if we don't
3856 // have sufficient watchpoint register for all 3, we need to show an error
3857 // for creating this Watchpoint and we should reset the shared Resource to
3858 // its original configuration because it is no longer shared.
3859
3860 bool set_all_resources = true;
3861 std::vector<WatchpointResourceSP> succesfully_set_resources;
3862 for (const auto &wp_res_sp : resources) {
3863 addr_t addr = wp_res_sp->GetLoadAddress();
3864 size_t size = wp_res_sp->GetByteSize();
3865 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3866 if (!m_gdb_comm.SupportsGDBStoppointPacket(type) ||
3867 m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size,
3869 set_all_resources = false;
3870 break;
3871 } else {
3872 succesfully_set_resources.push_back(wp_res_sp);
3873 }
3874 }
3875 if (set_all_resources) {
3876 wp_sp->SetEnabled(true, notify);
3877 for (const auto &wp_res_sp : resources) {
3878 // LWP_TODO: If we expanded/reused an existing Resource,
3879 // it's already in the WatchpointResourceList.
3880 wp_res_sp->AddConstituent(wp_sp);
3881 m_watchpoint_resource_list.Add(wp_res_sp);
3882 }
3883 return error;
3884 } else {
3885 // We failed to allocate one of the resources. Unset all
3886 // of the new resources we did successfully set in the
3887 // process.
3888 for (const auto &wp_res_sp : succesfully_set_resources) {
3889 addr_t addr = wp_res_sp->GetLoadAddress();
3890 size_t size = wp_res_sp->GetByteSize();
3891 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3892 m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3894 }
3896 "Setting one of the watchpoint resources failed");
3897 }
3898 return error;
3899}
3900
3902 Status error;
3903 if (!wp_sp) {
3904 error = Status::FromErrorString("Watchpoint argument was NULL.");
3905 return error;
3906 }
3907
3908 user_id_t watchID = wp_sp->GetID();
3909
3911
3912 addr_t addr = wp_sp->GetLoadAddress();
3913
3914 LLDB_LOGF(log,
3915 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3916 ") addr = 0x%8.8" PRIx64,
3917 watchID, (uint64_t)addr);
3918
3919 if (!wp_sp->IsEnabled()) {
3920 LLDB_LOGF(log,
3921 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3922 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3923 watchID, (uint64_t)addr);
3924 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3925 // attempt might come from the user-supplied actions, we'll route it in
3926 // order for the watchpoint object to intelligently process this action.
3927 wp_sp->SetEnabled(false, notify);
3928 return error;
3929 }
3930
3931 if (wp_sp->IsHardware()) {
3932 bool disabled_all = true;
3933
3934 std::vector<WatchpointResourceSP> unused_resources;
3935 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
3936 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3937 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3938 addr_t addr = wp_res_sp->GetLoadAddress();
3939 size_t size = wp_res_sp->GetByteSize();
3940 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3942 disabled_all = false;
3943 } else {
3944 wp_res_sp->RemoveConstituent(wp_sp);
3945 if (wp_res_sp->GetNumberOfConstituents() == 0)
3946 unused_resources.push_back(wp_res_sp);
3947 }
3948 }
3949 }
3950 for (auto &wp_res_sp : unused_resources)
3951 m_watchpoint_resource_list.Remove(wp_res_sp->GetID());
3952
3953 wp_sp->SetEnabled(false, notify);
3954 if (!disabled_all)
3956 "Failure disabling one of the watchpoint locations");
3957 }
3958 return error;
3959}
3960
3962 m_thread_list_real.Clear();
3963 m_thread_list.Clear();
3964}
3965
3967 Status error;
3968 Log *log = GetLog(GDBRLog::Process);
3969 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3970
3971 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3972 error =
3973 Status::FromErrorStringWithFormat("failed to send signal %i", signo);
3974 return error;
3975}
3976
3977Status
3979 // Make sure we aren't already connected?
3980 if (m_gdb_comm.IsConnected())
3981 return Status();
3982
3983 PlatformSP platform_sp(GetTarget().GetPlatform());
3984 if (platform_sp && !platform_sp->IsHost())
3985 return Status::FromErrorString("Lost debug server connection");
3986
3987 auto error = LaunchAndConnectToDebugserver(process_info);
3988 if (error.Fail()) {
3989 const char *error_string = error.AsCString();
3990 if (error_string == nullptr)
3991 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3992 }
3993 return error;
3994}
3995
3997 Log *log = GetLog(GDBRLog::Process);
3998 // If we locate debugserver, keep that located version around
3999 static FileSpec g_debugserver_file_spec;
4000 FileSpec debugserver_file_spec;
4001
4002 Environment host_env = Host::GetEnvironment();
4003
4004 // Always check to see if we have an environment override for the path to the
4005 // debugserver to use and use it if we do.
4006 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
4007 if (!env_debugserver_path.empty()) {
4008 debugserver_file_spec.SetFile(env_debugserver_path,
4009 FileSpec::Style::native);
4010 LLDB_LOG(log, "gdb-remote stub exe path set from environment variable: {0}",
4011 env_debugserver_path);
4012 } else
4013 debugserver_file_spec = g_debugserver_file_spec;
4014 if (FileSystem::Instance().Exists(debugserver_file_spec))
4015 return debugserver_file_spec;
4016
4017 // The debugserver binary is in the LLDB.framework/Resources directory.
4018 debugserver_file_spec = HostInfo::GetSupportExeDir();
4019 if (debugserver_file_spec) {
4020 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
4021 if (FileSystem::Instance().Exists(debugserver_file_spec)) {
4022 LLDB_LOG(log, "found gdb-remote stub exe '{0}'", debugserver_file_spec);
4023
4024 g_debugserver_file_spec = debugserver_file_spec;
4025 } else {
4026 debugserver_file_spec = platform.LocateExecutable(DEBUGSERVER_BASENAME);
4027 if (!debugserver_file_spec) {
4028 // Platform::LocateExecutable() wouldn't return a path if it doesn't
4029 // exist
4030 LLDB_LOG(log, "could not find gdb-remote stub exe '{0}'",
4031 debugserver_file_spec);
4032 }
4033 // Don't cache the platform specific GDB server binary as it could
4034 // change from platform to platform
4035 g_debugserver_file_spec.Clear();
4036 }
4037 }
4038 return debugserver_file_spec;
4039}
4040
4042 const ProcessInfo &process_info) {
4043 using namespace std::placeholders; // For _1, _2, etc.
4044
4046 return Status();
4047
4048 ProcessLaunchInfo debugserver_launch_info;
4049 // Make debugserver run in its own session so signals generated by special
4050 // terminal key sequences (^C) don't affect debugserver.
4051 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
4052
4053 const std::weak_ptr<ProcessGDBRemote> this_wp =
4054 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
4055 debugserver_launch_info.SetMonitorProcessCallback(
4056 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
4057 debugserver_launch_info.SetUserID(process_info.GetUserID());
4058
4059 FileSpec debugserver_path = GetDebugserverPath(*GetTarget().GetPlatform());
4060
4061#if defined(__APPLE__)
4062 // On macOS 11, we need to support x86_64 applications translated to
4063 // arm64. We check whether a binary is translated and spawn the correct
4064 // debugserver accordingly.
4065 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID,
4066 static_cast<int>(process_info.GetProcessID())};
4067 struct kinfo_proc processInfo;
4068 size_t bufsize = sizeof(processInfo);
4069 if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize,
4070 NULL, 0) == 0 &&
4071 bufsize > 0) {
4072 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
4073 debugserver_path = FileSpec("/Library/Apple/usr/libexec/oah/debugserver");
4074 }
4075 }
4076#endif
4077
4078 if (!FileSystem::Instance().Exists(debugserver_path))
4079 return Status::FromErrorString("could not find '" DEBUGSERVER_BASENAME
4080 "'. Please ensure it is properly installed "
4081 "and available in your PATH");
4082
4083 debugserver_launch_info.SetExecutableFile(debugserver_path,
4084 /*add_exe_file_as_first_arg=*/true);
4085
4086 llvm::Expected<Socket::Pair> socket_pair = Socket::CreatePair();
4087 if (!socket_pair)
4088 return Status::FromError(socket_pair.takeError());
4089
4090 Status error;
4091 SharedSocket shared_socket(socket_pair->first.get(), error);
4092 if (error.Fail())
4093 return error;
4094
4095 error = m_gdb_comm.StartDebugserverProcess(shared_socket.GetSendableFD(),
4096 debugserver_launch_info, nullptr);
4097
4098 if (error.Fail()) {
4099 Log *log = GetLog(GDBRLog::Process);
4100
4101 LLDB_LOGF(log, "failed to start debugserver process: %s",
4102 error.AsCString());
4103 return error;
4104 }
4105
4106 m_debugserver_pid = debugserver_launch_info.GetProcessID();
4107 shared_socket.CompleteSending(m_debugserver_pid);
4108
4109 // Our process spawned correctly, we can now set our connection to use
4110 // our end of the socket pair
4111 m_gdb_comm.SetConnection(std::make_unique<ConnectionFileDescriptor>(
4112 std::move(socket_pair->second)));
4114
4115 if (m_gdb_comm.IsConnected()) {
4116 // Finish the connection process by doing the handshake without
4117 // connecting (send NULL URL)
4119 } else {
4120 error = Status::FromErrorString("connection failed");
4121 }
4122 return error;
4123}
4124
4126 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
4127 int signo, // Zero for no signal
4128 int exit_status // Exit value of process if signal is zero
4129) {
4130 // "debugserver_pid" argument passed in is the process ID for debugserver
4131 // that we are tracking...
4132 Log *log = GetLog(GDBRLog::Process);
4133
4134 LLDB_LOGF(log,
4135 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
4136 ", signo=%i (0x%x), exit_status=%i)",
4137 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
4138
4139 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
4140 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
4141 static_cast<void *>(process_sp.get()));
4142 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
4143 return;
4144
4145 // Sleep for a half a second to make sure our inferior process has time to
4146 // set its exit status before we set it incorrectly when both the debugserver
4147 // and the inferior process shut down.
4148 std::this_thread::sleep_for(std::chrono::milliseconds(500));
4149
4150 // If our process hasn't yet exited, debugserver might have died. If the
4151 // process did exit, then we are reaping it.
4152 const StateType state = process_sp->GetState();
4153
4154 if (state != eStateInvalid && state != eStateUnloaded &&
4155 state != eStateExited && state != eStateDetached) {
4156 StreamString stream;
4157 if (signo == 0)
4158 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",
4159 exit_status);
4160 else {
4161 llvm::StringRef signal_name =
4162 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
4163 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";
4164 if (!signal_name.empty())
4165 stream.Format(format_str, signal_name);
4166 else
4167 stream.Format(format_str, signo);
4168 }
4169 process_sp->SetExitStatus(-1, stream.GetString());
4170 }
4171 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
4172 // longer has a debugserver instance
4173 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
4174}
4175
4183
4189
4192 debugger, PluginProperties::GetSettingName())) {
4193 const bool is_global_setting = true;
4196 "Properties for the gdb-remote process plug-in.", is_global_setting);
4197 }
4198}
4199
4201 Log *log = GetLog(GDBRLog::Process);
4202
4203 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4204
4205 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4206 if (!m_async_thread.IsJoinable()) {
4207 // Create a thread that watches our internal state and controls which
4208 // events make it to clients (into the DCProcess event queue).
4209
4210 llvm::Expected<HostThread> async_thread =
4211 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
4213 });
4214 if (!async_thread) {
4215 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
4216 "failed to launch host thread: {0}");
4217 return false;
4218 }
4219 m_async_thread = *async_thread;
4220 } else
4221 LLDB_LOGF(log,
4222 "ProcessGDBRemote::%s () - Called when Async thread was "
4223 "already running.",
4224 __FUNCTION__);
4225
4226 return m_async_thread.IsJoinable();
4227}
4228
4230 Log *log = GetLog(GDBRLog::Process);
4231
4232 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4233
4234 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4235 if (m_async_thread.IsJoinable()) {
4237
4238 // This will shut down the async thread.
4239 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
4240
4241 // Stop the stdio thread
4242 m_async_thread.Join(nullptr);
4243 m_async_thread.Reset();
4244 } else
4245 LLDB_LOGF(
4246 log,
4247 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
4248 __FUNCTION__);
4249}
4250
4252 Log *log = GetLog(GDBRLog::Process);
4253 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
4254 __FUNCTION__, GetID());
4255
4256 EventSP event_sp;
4257
4258 // We need to ignore any packets that come in after we have
4259 // have decided the process has exited. There are some
4260 // situations, for instance when we try to interrupt a running
4261 // process and the interrupt fails, where another packet might
4262 // get delivered after we've decided to give up on the process.
4263 // But once we've decided we are done with the process we will
4264 // not be in a state to do anything useful with new packets.
4265 // So it is safer to simply ignore any remaining packets by
4266 // explicitly checking for eStateExited before reentering the
4267 // fetch loop.
4268
4269 bool done = false;
4270 while (!done && GetPrivateState() != eStateExited) {
4271 LLDB_LOGF(log,
4272 "ProcessGDBRemote::%s(pid = %" PRIu64
4273 ") listener.WaitForEvent (NULL, event_sp)...",
4274 __FUNCTION__, GetID());
4275
4276 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
4277 const uint32_t event_type = event_sp->GetType();
4278 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
4279 LLDB_LOGF(log,
4280 "ProcessGDBRemote::%s(pid = %" PRIu64
4281 ") Got an event of type: %d...",
4282 __FUNCTION__, GetID(), event_type);
4283
4284 switch (event_type) {
4286 const EventDataBytes *continue_packet =
4288
4289 if (continue_packet) {
4290 const char *continue_cstr =
4291 (const char *)continue_packet->GetBytes();
4292 const size_t continue_cstr_len = continue_packet->GetByteSize();
4293 LLDB_LOGF(log,
4294 "ProcessGDBRemote::%s(pid = %" PRIu64
4295 ") got eBroadcastBitAsyncContinue: %s",
4296 __FUNCTION__, GetID(), continue_cstr);
4297
4298 if (::strstr(continue_cstr, "vAttach") == nullptr)
4300 StringExtractorGDBRemote response;
4301
4302 StateType stop_state =
4304 *this, *GetUnixSignals(),
4305 llvm::StringRef(continue_cstr, continue_cstr_len),
4306 GetInterruptTimeout(), response);
4307
4308 // We need to immediately clear the thread ID list so we are sure
4309 // to get a valid list of threads. The thread ID list might be
4310 // contained within the "response", or the stop reply packet that
4311 // caused the stop. So clear it now before we give the stop reply
4312 // packet to the process using the
4313 // SetLastStopPacket()...
4315
4316 switch (stop_state) {
4317 case eStateStopped:
4318 case eStateCrashed:
4319 case eStateSuspended:
4320 SetLastStopPacket(response);
4321 SetPrivateState(stop_state);
4322 break;
4323
4324 case eStateExited: {
4325 SetLastStopPacket(response);
4328 done = true;
4329 break;
4330 }
4331 case eStateInvalid: {
4332 // Check to see if we were trying to attach and if we got back
4333 // the "E87" error code from debugserver -- this indicates that
4334 // the process is not debuggable. Return a slightly more
4335 // helpful error message about why the attach failed.
4336 if (::strstr(continue_cstr, "vAttach") != nullptr &&
4337 response.GetError() == 0x87) {
4338 SetExitStatus(-1, "cannot attach to process due to "
4339 "System Integrity Protection");
4340 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
4341 response.GetStatus().Fail()) {
4342 SetExitStatus(-1, response.GetStatus().AsCString());
4343 } else {
4344 SetExitStatus(-1, "lost connection");
4345 }
4346 done = true;
4347 break;
4348 }
4349
4350 default:
4351 SetPrivateState(stop_state);
4352 break;
4353 } // switch(stop_state)
4354 } // if (continue_packet)
4355 } // case eBroadcastBitAsyncContinue
4356 break;
4357
4359 LLDB_LOGF(log,
4360 "ProcessGDBRemote::%s(pid = %" PRIu64
4361 ") got eBroadcastBitAsyncThreadShouldExit...",
4362 __FUNCTION__, GetID());
4363 done = true;
4364 break;
4365
4366 default:
4367 LLDB_LOGF(log,
4368 "ProcessGDBRemote::%s(pid = %" PRIu64
4369 ") got unknown event 0x%8.8x",
4370 __FUNCTION__, GetID(), event_type);
4371 done = true;
4372 break;
4373 }
4374 }
4375 } else {
4376 LLDB_LOGF(log,
4377 "ProcessGDBRemote::%s(pid = %" PRIu64
4378 ") listener.WaitForEvent (NULL, event_sp) => false",
4379 __FUNCTION__, GetID());
4380 done = true;
4381 }
4382 }
4383
4384 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
4385 __FUNCTION__, GetID());
4386
4387 return {};
4388}
4389
4390// uint32_t
4391// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
4392// &matches, std::vector<lldb::pid_t> &pids)
4393//{
4394// // If we are planning to launch the debugserver remotely, then we need to
4395// fire up a debugserver
4396// // process and ask it for the list of processes. But if we are local, we
4397// can let the Host do it.
4398// if (m_local_debugserver)
4399// {
4400// return Host::ListProcessesMatchingName (name, matches, pids);
4401// }
4402// else
4403// {
4404// // FIXME: Implement talking to the remote debugserver.
4405// return 0;
4406// }
4407//
4408//}
4409//
4411 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4412 lldb::user_id_t break_loc_id) {
4413 // I don't think I have to do anything here, just make sure I notice the new
4414 // thread when it starts to
4415 // run so I can stop it if that's what I want to do.
4416 Log *log = GetLog(LLDBLog::Step);
4417 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
4418 return false;
4419}
4420
4421namespace {
4422/// Baton that carries the breakpoint hit arguments to the accelerator plugin
4423/// breakpoint callback.
4424class AcceleratorBreakpointCallbackBaton
4425 : public TypedBaton<AcceleratorBreakpointHitArgs> {
4426public:
4427 explicit AcceleratorBreakpointCallbackBaton(
4428 std::unique_ptr<AcceleratorBreakpointHitArgs> data)
4429 : TypedBaton(std::move(data)) {}
4430};
4431} // namespace
4432
4433llvm::Error
4435 Log *log = GetLog(GDBRLog::Process);
4436
4437 // The same set of actions can be delivered to the client more than once: a
4438 // plugin may keep reporting the same actions (with the same identifier) on
4439 // subsequent native stops until its state advances. The identifier uniquely
4440 // names a set of actions for a plugin, so skip any set we have already
4441 // processed to avoid re-running its side effects (e.g. setting the same
4442 // breakpoints again).
4443 auto it = m_processed_accelerator_actions.find(actions.plugin_name);
4444 if (it != m_processed_accelerator_actions.end() &&
4445 it->second == actions.identifier) {
4446 LLDB_LOG(log,
4447 "ProcessGDBRemote::HandleAcceleratorActions skipping already "
4448 "processed actions for plugin '{0}' with identifier {1}",
4449 actions.plugin_name, actions.identifier);
4450 return llvm::Error::success();
4451 }
4453
4454 // Handle each kind of action. More action kinds will be handled here in the
4455 // future, so only return early on error; otherwise fall through so the next
4456 // kind of action still gets a chance to run.
4457 if (!actions.breakpoints.empty()) {
4458 if (llvm::Error error = HandleAcceleratorBreakpoints(actions))
4459 return error;
4460 }
4461
4462 if (actions.connect_info) {
4463 if (llvm::Error error = HandleAcceleratorConnection(actions))
4464 return error;
4465 }
4466
4467 return llvm::Error::success();
4468}
4469
4471 const AcceleratorActions &actions) {
4472 const AcceleratorConnectionInfo &connect_info = *actions.connect_info;
4473 Debugger &debugger = GetTarget().GetDebugger();
4474
4475 OptionGroupPlatform platform_options(/*include_platform_option=*/false);
4476 platform_options.SetPlatformName(connect_info.platform_name.c_str());
4477 std::string exe_path = connect_info.exe_path.value_or("");
4478 TargetSP accelerator_target_sp;
4480 debugger, exe_path, connect_info.triple, eLoadDependentsNo,
4481 &platform_options, accelerator_target_sp);
4482 if (error.Fail())
4483 return error.takeError();
4484 if (!accelerator_target_sp)
4485 return llvm::createStringError("failed to create accelerator target");
4486
4487 llvm::scope_exit delete_accelerator_target([&] {
4488 debugger.GetTargetList().DeleteTarget(accelerator_target_sp);
4489 accelerator_target_sp->Destroy();
4490 });
4491
4492 PlatformSP platform_sp = accelerator_target_sp->GetPlatform();
4493 if (!platform_sp)
4494 return llvm::createStringErrorV(
4495 "no platform '{0}' compatible with triple '{1}' for the accelerator "
4496 "target",
4497 connect_info.platform_name, connect_info.triple);
4498
4499 TargetSP native_target_sp = GetTarget().shared_from_this();
4500 std::shared_ptr<TargetGroupCPUAndAccelerators> group_sp =
4501 native_target_sp
4502 ->GetFirstTargetGroupOfType<TargetGroupCPUAndAccelerators>();
4503
4504 bool created_group = !group_sp;
4505 if (created_group) {
4506 group_sp = debugger.GetTargetGroupList()
4508 "CPU and accelerator targets");
4509 }
4510
4511 llvm::scope_exit restore_target_group([&] {
4512 group_sp->RemoveTarget(accelerator_target_sp);
4513 if (created_group) {
4514 group_sp->RemoveTarget(native_target_sp);
4515 debugger.GetTargetGroupList().DeleteTargetGroup(group_sp);
4516 }
4517 });
4518
4519 if (llvm::Error membership_error =
4520 group_sp->AddTarget(native_target_sp, TargetGroup::Role::CPU))
4521 return membership_error;
4522 if (llvm::Error membership_error = group_sp->AddTarget(
4523 accelerator_target_sp, TargetGroup::Role::Accelerator))
4524 return membership_error;
4525
4526 ProcessSP process_sp =
4527 connect_info.synchronous
4528 ? platform_sp->ConnectProcessSynchronous(
4529 connect_info.connect_url, GetPluginNameStatic(), debugger,
4530 *debugger.GetAsyncOutputStream(), accelerator_target_sp.get(),
4531 error)
4532 : platform_sp->ConnectProcess(connect_info.connect_url,
4533 GetPluginNameStatic(), debugger,
4534 accelerator_target_sp.get(), error);
4535 if (error.Fail())
4536 return error.takeError();
4537 if (!process_sp)
4538 return llvm::createStringError("failed to connect to the accelerator");
4539
4540 restore_target_group.release();
4541 delete_accelerator_target.release();
4542 accelerator_target_sp->SetTargetSessionName(actions.session_name);
4543
4544 // Broadcast the new-target event so API clients can detect it.
4545 auto event_sp = std::make_shared<Event>(
4547 new Target::TargetEventData(GetTarget().shared_from_this(),
4548 accelerator_target_sp));
4549 GetTarget().BroadcastEvent(event_sp);
4550 return llvm::Error::success();
4551}
4552
4554 const AcceleratorActions &actions) {
4555 Target &target = GetTarget();
4556 llvm::Error error = llvm::Error::success();
4557 for (const AcceleratorBreakpointInfo &bp : actions.breakpoints) {
4558 // Carry data with the breakpoint so the callback can notify the plugin
4559 // when the breakpoint is hit.
4560 auto args_up = std::make_unique<AcceleratorBreakpointHitArgs>();
4561 args_up->plugin_name = actions.plugin_name;
4562 args_up->breakpoint = bp;
4563
4564 // Each breakpoint must specify exactly one of by_name or by_address. Bad
4565 // breakpoints are collected as errors but don't stop the remaining ones
4566 // from being set.
4567 BreakpointSP bp_sp;
4568 if (bp.by_name && bp.by_address) {
4569 error = llvm::joinErrors(
4570 std::move(error),
4571 llvm::createStringErrorV(
4572 "accelerator breakpoint {0} specifies both a by_name and a "
4573 "by_address specification",
4574 bp.identifier));
4575 continue;
4576 } else if (bp.by_name) {
4577 FileSpecList bp_modules;
4578 if (bp.by_name->shlib && !bp.by_name->shlib->empty())
4579 bp_modules.Append(FileSpec(*bp.by_name->shlib));
4580 bp_sp = target.CreateBreakpoint(
4581 bp_modules.GetSize() ? &bp_modules : nullptr, // Containing modules.
4582 nullptr, // Containing source.
4583 bp.by_name->function_name.c_str(), // Function name.
4584 eFunctionNameTypeFull, // Function name type.
4585 eLanguageTypeUnknown, // Language type.
4586 0, // Byte offset.
4587 false, // Offset is insn count.
4588 eLazyBoolNo, // Skip prologue.
4589 true, // Internal breakpoint.
4590 false); // Request hardware.
4591 } else if (bp.by_address) {
4592 bp_sp = target.CreateBreakpoint(bp.by_address->load_address,
4593 /*internal=*/true,
4594 /*request_hardware=*/false);
4595 } else {
4596 error = llvm::joinErrors(
4597 std::move(error),
4598 llvm::createStringErrorV(
4599 "accelerator breakpoint {0} has neither a by_name nor a "
4600 "by_address specification",
4601 bp.identifier));
4602 continue;
4603 }
4604
4605 if (!bp_sp) {
4606 error = llvm::joinErrors(
4607 std::move(error),
4608 llvm::createStringErrorV("failed to set accelerator breakpoint {0}",
4609 bp.identifier));
4610 continue;
4611 }
4612
4613 // Give the internal breakpoint a meaningful description for stop reasons,
4614 // including the plugin that requested it.
4615 std::string kind =
4616 llvm::formatv("accelerator-plugin ({0})", actions.plugin_name);
4617 bp_sp->SetBreakpointKind(kind.c_str());
4618 auto baton_sp = std::make_shared<AcceleratorBreakpointCallbackBaton>(
4619 std::move(args_up));
4620 bp_sp->SetCallback(AcceleratorBreakpointHitCallback, baton_sp,
4621 /*is_synchronous=*/true);
4622 }
4623 return error;
4624}
4625
4627 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4628 lldb::user_id_t break_loc_id) {
4629 ProcessSP process_sp = context->exe_ctx_ref.GetProcessSP();
4630 ProcessGDBRemote *process = static_cast<ProcessGDBRemote *>(process_sp.get());
4631 return process->AcceleratorBreakpointHit(baton, context, break_id,
4632 break_loc_id);
4633}
4634
4636 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4637 lldb::user_id_t break_loc_id) {
4638 AcceleratorBreakpointHitArgs *callback_data =
4639 static_cast<AcceleratorBreakpointHitArgs *>(baton);
4640 // Copy the args so we can fill in requested symbol values before notifying
4641 // lldb-server.
4642 AcceleratorBreakpointHitArgs args = *callback_data;
4643 Target &target = GetTarget();
4644
4645 const std::vector<std::string> &symbol_names = args.breakpoint.symbol_names;
4646 args.symbol_values.resize(symbol_names.size());
4647 for (size_t i = 0; i < symbol_names.size(); ++i) {
4648 args.symbol_values[i].name = symbol_names[i];
4649 SymbolContextList sc_list;
4650 target.GetImages().FindSymbolsWithNameAndType(symbol_names[i],
4651 eSymbolTypeAny, sc_list);
4652 for (const SymbolContext &sc : sc_list) {
4653 if (!sc.symbol)
4654 continue;
4655 addr_t load_addr = sc.symbol->GetAddress().GetLoadAddress(&target);
4656 if (load_addr != LLDB_INVALID_ADDRESS) {
4657 args.symbol_values[i].value = load_addr;
4658 break;
4659 }
4660 }
4661 }
4662
4663 Log *log = GetLog(GDBRLog::Process);
4664 llvm::Expected<AcceleratorBreakpointHitResponse> response =
4665 m_gdb_comm.AcceleratorBreakpointHit(args);
4666 if (!response) {
4667 LLDB_LOG_ERROR(log, response.takeError(),
4668 "accelerator breakpoint hit notification failed: {0}");
4669 // We could not reach the plugin, so auto-resume rather than stopping the
4670 // native process at an internal breakpoint the user can't see.
4671 return false;
4672 }
4673
4674 // Disable the breakpoint if requested, but keep it around so its hit count
4675 // and other stats remain visible.
4676 if (response->disable_bp) {
4677 if (BreakpointSP bp_sp = target.GetBreakpointByID(break_id))
4678 bp_sp->SetEnabled(false);
4679 }
4680
4681 // The plugin may request new actions (e.g. additional breakpoints) in
4682 // response to this breakpoint being hit.
4683 if (response->actions) {
4684 if (llvm::Error error = HandleAcceleratorActions(*response->actions)) {
4685 // Also print the failure to the user; during a stop, logging alone is
4686 // invisible.
4687 std::string message = llvm::toString(std::move(error));
4688 LLDB_LOG(log, "failed to handle accelerator actions: {0}", message);
4689 target.GetDebugger().GetAsyncErrorStream()->Printf(
4690 "error: accelerator plugin '%s': %s\n",
4691 response->actions->plugin_name.c_str(), message.c_str());
4692 }
4693 }
4694
4695 // Returning true stops the native process; false auto-resumes it.
4696 return !response->auto_resume_native;
4697}
4698
4700 Log *log = GetLog(GDBRLog::Process);
4701 LLDB_LOG(log, "Check if need to update ignored signals");
4702
4703 // QPassSignals package is not supported by the server, there is no way we
4704 // can ignore any signals on server side.
4705 if (!m_gdb_comm.GetQPassSignalsSupported())
4706 return Status();
4707
4708 // No signals, nothing to send.
4709 if (m_unix_signals_sp == nullptr)
4710 return Status();
4711
4712 // Signals' version hasn't changed, no need to send anything.
4713 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
4714 if (new_signals_version == m_last_signals_version) {
4715 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
4717 return Status();
4718 }
4719
4720 auto signals_to_ignore =
4721 m_unix_signals_sp->GetFilteredSignals(false, false, false);
4722 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
4723
4724 LLDB_LOG(log,
4725 "Signals' version changed. old version={0}, new version={1}, "
4726 "signals ignored={2}, update result={3}",
4727 m_last_signals_version, new_signals_version,
4728 signals_to_ignore.size(), error);
4729
4730 if (error.Success())
4731 m_last_signals_version = new_signals_version;
4732
4733 return error;
4734}
4735
4737 Log *log = GetLog(LLDBLog::Step);
4739 LLDB_LOGF_VERBOSE(log, "Enabled noticing new thread breakpoint.");
4740 m_thread_create_bp_sp->SetEnabled(true);
4741 } else {
4742 PlatformSP platform_sp(GetTarget().GetPlatform());
4743 if (platform_sp) {
4745 platform_sp->SetThreadCreationBreakpoint(GetTarget());
4748 log, "Successfully created new thread notification breakpoint %i",
4749 m_thread_create_bp_sp->GetID());
4750 m_thread_create_bp_sp->SetCallback(
4752 } else {
4753 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
4754 }
4755 }
4756 }
4757 return m_thread_create_bp_sp.get() != nullptr;
4758}
4759
4761 Log *log = GetLog(LLDBLog::Step);
4762 LLDB_LOGF_VERBOSE(log, "Disabling new thread notification breakpoint.");
4763
4765 m_thread_create_bp_sp->SetEnabled(false);
4766
4767 return true;
4768}
4769
4771 if (m_dyld_up.get() == nullptr) {
4772 std::string plugin_name;
4773 if (std::optional<LLDBSettings> settings = m_gdb_comm.GetLLDBSettings())
4774 plugin_name = settings->dyld_plugin_name;
4775 m_dyld_up.reset(DynamicLoader::FindPlugin(this, plugin_name));
4776 }
4777 return m_dyld_up.get();
4778}
4779
4781 int return_value;
4782 bool was_supported;
4783
4784 Status error;
4785
4786 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4787 if (return_value != 0) {
4788 if (!was_supported)
4790 "Sending events is not supported for this process.");
4791 else
4792 error = Status::FromErrorStringWithFormat("Error sending event data: %d.",
4793 return_value);
4794 }
4795 return error;
4796}
4797
4799 DataBufferSP buf;
4800 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4801 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
4802 if (response)
4803 buf = std::make_shared<DataBufferHeap>(response->c_str(),
4804 response->length());
4805 else
4806 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
4807 }
4809}
4810
4813 StructuredData::ObjectSP object_sp;
4814
4815 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
4817 SystemRuntime *runtime = GetSystemRuntime();
4818 if (runtime) {
4819 runtime->AddThreadExtendedInfoPacketHints(args_dict);
4820 }
4821 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
4822
4823 StreamString packet;
4824 packet << "jThreadExtendedInfo:";
4825 args_dict->Dump(packet, false);
4826
4827 // FIXME the final character of a JSON dictionary, '}', is the escape
4828 // character in gdb-remote binary mode. lldb currently doesn't escape
4829 // these characters in its packet output -- so we add the quoted version of
4830 // the } character here manually in case we talk to a debugserver which un-
4831 // escapes the characters at packet read time.
4832 packet << (char)(0x7d ^ 0x20);
4833
4834 StringExtractorGDBRemote response;
4835 response.SetResponseValidatorToJSON();
4836 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4839 response.GetResponseType();
4840 if (response_type == StringExtractorGDBRemote::eResponse) {
4841 if (!response.Empty()) {
4842 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4843 }
4844 }
4845 }
4846 }
4847 return object_sp;
4848}
4849
4851 lldb::addr_t image_list_address, lldb::addr_t image_count) {
4852
4854 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4855 image_list_address);
4856 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4857
4858 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4859}
4860
4861static std::string
4863 std::string info_level_str;
4864 if (info_level == eBinaryInformationLevelAddrOnly)
4865 info_level_str = "address-only";
4866 else if (info_level == eBinaryInformationLevelAddrName)
4867 info_level_str = "address-name";
4868 else if (info_level == eBinaryInformationLevelAddrNameUUID)
4869 info_level_str = "address-name-uuid";
4870 else if (info_level == eBinaryInformationLevelFull)
4871 info_level_str = "full";
4872
4873 return info_level_str;
4874}
4875
4877 BinaryInformationLevel info_level) {
4879
4880 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4881 if (info_level != eBinaryInformationLevelFull)
4882 args_dict->GetAsDictionary()->AddBooleanItem("report_load_commands", false);
4883 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4884 if (!info_level_str.empty())
4885 args_dict->GetAsDictionary()->AddStringItem("information-level",
4886 info_level_str.c_str());
4887
4888 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4889}
4890
4892 BinaryInformationLevel info_level,
4893 const std::vector<lldb::addr_t> &load_addresses) {
4896
4897 for (auto addr : load_addresses)
4898 addresses->AddIntegerItem(addr);
4899
4900 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4901
4902 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4903 if (!info_level_str.empty())
4904 args_dict->GetAsDictionary()->AddStringItem("information-level",
4905 info_level_str.c_str());
4906
4907 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4908}
4909
4912 StructuredData::ObjectSP args_dict) {
4913 StructuredData::ObjectSP object_sp;
4914
4915 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4916 // Scope for the scoped timeout object
4918 std::chrono::seconds(10));
4919
4920 StreamString packet;
4921 packet << "jGetLoadedDynamicLibrariesInfos:";
4922 args_dict->Dump(packet, false);
4923
4924 // FIXME the final character of a JSON dictionary, '}', is the escape
4925 // character in gdb-remote binary mode. lldb currently doesn't escape
4926 // these characters in its packet output -- so we add the quoted version of
4927 // the } character here manually in case we talk to a debugserver which un-
4928 // escapes the characters at packet read time.
4929 packet << (char)(0x7d ^ 0x20);
4930
4931 StringExtractorGDBRemote response;
4932 response.SetResponseValidatorToJSON();
4933 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4936 response.GetResponseType();
4937 if (response_type == StringExtractorGDBRemote::eResponse) {
4938 if (!response.Empty()) {
4939 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4940 }
4941 }
4942 }
4943 }
4944 return object_sp;
4945}
4946
4948 StructuredData::ObjectSP object_sp;
4950
4951 if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
4952 StringExtractorGDBRemote response;
4953 response.SetResponseValidatorToJSON();
4954 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
4955 response) ==
4958 response.GetResponseType();
4959 if (response_type == StringExtractorGDBRemote::eResponse) {
4960 if (!response.Empty()) {
4961 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4962 }
4963 }
4964 }
4965 }
4966 return object_sp;
4967}
4968
4970 // Held across the query so a second caller waits for the answer instead of
4971 // sending the packet again.
4972 auto shared_cache_info = m_shared_cache_info.Lock();
4974
4975 if (*shared_cache_info || !m_gdb_comm.GetSharedCacheInfoSupported())
4976 return *shared_cache_info;
4977
4978 StreamString packet;
4979 packet << "jGetSharedCacheInfo:";
4980 args_dict->Dump(packet, false);
4981
4982 StringExtractorGDBRemote response;
4983 response.SetResponseValidatorToJSON();
4984 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4987 response.GetResponseType();
4988 if (response_type == StringExtractorGDBRemote::eResponse) {
4989 if (response.Empty())
4990 return {};
4991 StructuredData::ObjectSP response_sp =
4993 if (!response_sp)
4994 return {};
4995 StructuredData::Dictionary *dict = response_sp->GetAsDictionary();
4996 if (!dict)
4997 return {};
4998 if (!dict->HasKey("shared_cache_uuid"))
4999 return {};
5000 llvm::StringRef uuid_str;
5001 if (!dict->GetValueForKeyAsString("shared_cache_uuid", uuid_str, "") ||
5002 uuid_str == "00000000-0000-0000-0000-000000000000")
5003 return {};
5004 if (dict->HasKey("shared_cache_path")) {
5005 UUID uuid;
5006 uuid.SetFromStringRef(uuid_str);
5007 FileSpec sc_path(
5008 dict->GetValueForKey("shared_cache_path")->GetStringValue());
5009
5010 SymbolSharedCacheUse sc_mode =
5013
5016 // Attempt to open the shared cache at sc_path, and
5017 // if the uuid matches, index all the files.
5018 HostInfo::SharedCacheIndexFiles(sc_path, uuid, sc_mode);
5019 }
5020 }
5021 *shared_cache_info = response_sp;
5022 }
5023 }
5024 return *shared_cache_info;
5025}
5026
5028 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
5029 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
5030}
5031
5032// Establish the largest memory read/write payloads we should use. If the
5033// remote stub has a max packet size, stay under that size.
5034//
5035// If the remote stub's max packet size is crazy large, use a reasonable
5036// largeish default.
5037//
5038// If the remote stub doesn't advertise a max packet size, use a conservative
5039// default.
5040
5042 const uint64_t reasonable_largeish_default = 128 * 1024;
5043 const uint64_t conservative_default = 512;
5044
5045 if (m_max_memory_size == 0) {
5046 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
5047 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
5048 // Save the stub's claimed maximum packet size
5049 m_remote_stub_max_memory_size = stub_max_size;
5050
5051 // Even if the stub says it can support ginormous packets, don't exceed
5052 // our reasonable largeish default packet size.
5053 if (stub_max_size > reasonable_largeish_default) {
5054 stub_max_size = reasonable_largeish_default;
5055 }
5056
5057 // Memory packet have other overheads too like Maddr,size:#NN Instead of
5058 // calculating the bytes taken by size and addr every time, we take a
5059 // maximum guess here.
5060 if (stub_max_size > 70)
5061 stub_max_size -= 32 + 32 + 6;
5062 else {
5063 // In unlikely scenario that max packet size is less then 70, we will
5064 // hope that data being written is small enough to fit.
5066 LLDB_LOG(log, "warning: Packet size is too small. "
5067 "LLDB may face problems while writing memory");
5068 }
5069
5070 m_max_memory_size = stub_max_size;
5071 } else {
5072 m_max_memory_size = conservative_default;
5073 }
5074 }
5075}
5076
5078 uint64_t user_specified_max) {
5079 if (user_specified_max != 0) {
5081
5083 if (m_remote_stub_max_memory_size < user_specified_max) {
5085 // packet size too
5086 // big, go as big
5087 // as the remote stub says we can go.
5088 } else {
5089 m_max_memory_size = user_specified_max; // user's packet size is good
5090 }
5091 } else {
5093 user_specified_max; // user's packet size is probably fine
5094 }
5095 }
5096}
5097
5098bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
5099 const ArchSpec &arch,
5100 ModuleSpec &module_spec) {
5102
5103 const ModuleCacheKey key(module_file_spec.GetPath(),
5104 arch.GetTriple().getTriple());
5105 auto cached = m_cached_module_specs.find(key);
5106 if (cached != m_cached_module_specs.end()) {
5107 module_spec = cached->second;
5108 return bool(module_spec);
5109 }
5110
5111 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
5112 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
5113 __FUNCTION__, module_file_spec.GetPath().c_str(),
5114 arch.GetTriple().getTriple().c_str());
5115 return false;
5116 }
5117
5118 if (log) {
5119 StreamString stream;
5120 module_spec.Dump(stream);
5121 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
5122 __FUNCTION__, module_file_spec.GetPath().c_str(),
5123 arch.GetTriple().getTriple().c_str(), stream.GetData());
5124 }
5125
5126 m_cached_module_specs[key] = module_spec;
5127 return true;
5128}
5129
5131 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
5132 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
5133 if (module_specs) {
5134 for (const FileSpec &spec : module_file_specs)
5136 triple.getTriple())] = ModuleSpec();
5137 for (const ModuleSpec &spec : *module_specs)
5138 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
5139 triple.getTriple())] = spec;
5140 }
5141}
5142
5144 return m_gdb_comm.GetOSVersion();
5145}
5146
5148 return m_gdb_comm.GetMacCatalystVersion();
5149}
5150
5151namespace {
5152
5153typedef std::vector<std::string> stringVec;
5154
5155typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
5156struct RegisterSetInfo {
5157 std::string name;
5158};
5159
5160typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
5161
5162struct GdbServerTargetInfo {
5163 std::string arch;
5164 std::string osabi;
5165 stringVec includes;
5166 RegisterSetMap reg_set_map;
5167};
5168
5169using RegisterTypeMap = llvm::StringMap<const RegisterType *>;
5170
5172ParseEnumEvalues(const XMLNode &enum_node) {
5174 // We will use the last instance of each value. Also we preserve the order
5175 // of declaration in the XML, as it may not be numerical.
5176 // For example, hardware may initially release with two states that software
5177 // can read from a register field:
5178 // 0 = startup, 1 = running
5179 // If in a future hardware release, the designers added a pre-startup state:
5180 // 0 = startup, 1 = running, 2 = pre-startup
5181 // Now it makes more sense to list them in this logical order as opposed to
5182 // numerical order:
5183 // 2 = pre-startup, 1 = startup, 0 = startup
5184 // This only matters for "register info" but let's trust what the server
5185 // chose regardless.
5186 std::map<uint64_t, RegisterTypeEnum::Enumerator> enumerators;
5187
5189 "evalue", [&enumerators, &log](const XMLNode &enumerator_node) {
5190 std::optional<llvm::StringRef> name;
5191 std::optional<uint64_t> value;
5192
5193 enumerator_node.ForEachAttribute(
5194 [&name, &value, &log](const llvm::StringRef &attr_name,
5195 const llvm::StringRef &attr_value) {
5196 if (attr_name == "name") {
5197 if (attr_value.size())
5198 name = attr_value;
5199 else
5200 LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues "
5201 "Ignoring empty name in evalue");
5202 } else if (attr_name == "value") {
5203 uint64_t parsed_value = 0;
5204 if (llvm::to_integer(attr_value, parsed_value))
5205 value = parsed_value;
5206 else
5207 LLDB_LOG(log,
5208 "ProcessGDBRemote::ParseEnumEvalues "
5209 "Invalid value \"{0}\" in "
5210 "evalue",
5211 attr_value.data());
5212 } else
5213 LLDB_LOG(log,
5214 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
5215 "unknown attribute "
5216 "\"{0}\" in evalue",
5217 attr_name.data());
5218
5219 // Keep walking attributes.
5220 return true;
5221 });
5222
5223 if (value && name)
5224 enumerators.insert_or_assign(
5225 *value, RegisterTypeEnum::Enumerator(*value, name->str()));
5226
5227 // Find all evalue elements.
5228 return true;
5229 });
5230
5231 RegisterTypeEnum::Enumerators final_enumerators;
5232 for (auto [_, enumerator] : enumerators)
5233 final_enumerators.push_back(enumerator);
5234
5235 return final_enumerators;
5236}
5237
5238static void
5239ParseEnums(XMLNode feature_node, RegisterTypeMap &feature_register_types,
5240 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5241 Log *log(GetLog(GDBRLog::Process));
5242
5243 // The top level element is "<enum...".
5244 feature_node.ForEachChildElementWithName(
5245 "enum", [log, &feature_register_types,
5246 &owned_register_types](const XMLNode &enum_node) {
5247 std::string id;
5248
5249 enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name,
5250 const llvm::StringRef &attr_value) {
5251 if (attr_name == "id")
5252 id = attr_value;
5253
5254 // There is also a "size" attribute that is supposed to be the size in
5255 // bytes of the register this applies to. However:
5256 // * LLDB doesn't need this information.
5257 // * It is difficult to verify because you have to wait until the
5258 // enum is applied to a field.
5259 //
5260 // So we will emit this attribute in XML for GDB's sake, but will not
5261 // bother ingesting it.
5262
5263 // Walk all attributes.
5264 return true;
5265 });
5266
5267 if (!id.empty()) {
5268 RegisterTypeEnum::Enumerators enumerators =
5269 ParseEnumEvalues(enum_node);
5270 if (!enumerators.empty()) {
5271 LLDB_LOG(log,
5272 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
5273 id);
5274 auto enum_type =
5275 std::make_unique<RegisterTypeEnum>(id, enumerators);
5276 const RegisterTypeEnum *enum_type_ptr = enum_type.get();
5277 auto [it, inserted] =
5278 feature_register_types.try_emplace(id, enum_type_ptr);
5279 if (inserted) {
5280 owned_register_types.push_back(std::move(enum_type));
5281 } else if (llvm::isa<RegisterTypeEnum>(it->second)) {
5282 // Preserve the existing behavior where the last valid enum with
5283 // a repeated ID wins. All enums are parsed before flags, so no
5284 // fields can reference the enum being replaced yet. The earlier
5285 // object remains owned; only the feature lookup is updated.
5286 owned_register_types.push_back(std::move(enum_type));
5287 it->second = enum_type_ptr;
5288 } else {
5289 LLDB_LOG(
5290 log,
5291 "ProcessGDBRemote::ParseEnums Ignoring enum type \"{0}\" "
5292 "because another type with that id already exists",
5293 id);
5294 }
5295 }
5296 }
5297
5298 // Find all <enum> elements.
5299 return true;
5300 });
5301}
5302
5303static std::vector<RegisterTypeFlags::Field>
5304ParseFlagsFields(XMLNode flags_node, unsigned size,
5305 const RegisterTypeMap &feature_register_types) {
5306 Log *log(GetLog(GDBRLog::Process));
5307 const unsigned max_start_bit = size * 8 - 1;
5308
5309 // Process the fields of this set of flags.
5310 std::vector<RegisterTypeFlags::Field> fields;
5311 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log,
5312 &feature_register_types](
5313 const XMLNode
5314 &field_node) {
5315 std::optional<llvm::StringRef> name;
5316 std::optional<unsigned> start;
5317 std::optional<unsigned> end;
5318 std::optional<llvm::StringRef> type;
5319
5320 field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit,
5321 &log](const llvm::StringRef &attr_name,
5322 const llvm::StringRef &attr_value) {
5323 // Note that XML in general requires that each of these attributes only
5324 // appears once, so we don't have to handle that here.
5325 if (attr_name == "name") {
5326 LLDB_LOG(
5327 log,
5328 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
5329 attr_value.data());
5330 name = attr_value;
5331 } else if (attr_name == "start") {
5332 unsigned parsed_start = 0;
5333 if (llvm::to_integer(attr_value, parsed_start)) {
5334 if (parsed_start > max_start_bit) {
5335 LLDB_LOG(log,
5336 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
5337 "field node, "
5338 "cannot be > {1}",
5339 parsed_start, max_start_bit);
5340 } else
5341 start = parsed_start;
5342 } else {
5343 LLDB_LOG(
5344 log,
5345 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
5346 "field node",
5347 attr_value.data());
5348 }
5349 } else if (attr_name == "end") {
5350 unsigned parsed_end = 0;
5351 if (llvm::to_integer(attr_value, parsed_end))
5352 if (parsed_end > max_start_bit) {
5353 LLDB_LOG(log,
5354 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
5355 "field node, "
5356 "cannot be > {1}",
5357 parsed_end, max_start_bit);
5358 } else
5359 end = parsed_end;
5360 else {
5361 LLDB_LOG(log,
5362 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
5363 "field node",
5364 attr_value.data());
5365 }
5366 } else if (attr_name == "type") {
5367 type = attr_value;
5368 } else {
5369 LLDB_LOG(
5370 log,
5371 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
5372 "\"{0}\" in field node",
5373 attr_name.data());
5374 }
5375
5376 return true; // Walk all attributes of the field.
5377 });
5378
5379 if (name && start && end) {
5380 if (*start > *end)
5381 LLDB_LOG(
5382 log,
5383 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
5384 "\"{2}\", ignoring",
5385 *start, *end, name->data());
5386 else {
5387 if (RegisterTypeFlags::Field::GetSizeInBits(*start, *end) > 64)
5388 LLDB_LOG(log,
5389 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{}\" "
5390 "that has size > 64 bits, this is not supported",
5391 name->data());
5392 else {
5393 // A field's type may be set to the name of an enum type.
5394 const RegisterTypeEnum *enum_type = nullptr;
5395 if (type && !type->empty()) {
5396 auto found = feature_register_types.find(*type);
5397 if (found != feature_register_types.end()) {
5398 enum_type = llvm::dyn_cast<RegisterTypeEnum>(found->second);
5399
5400 if (!enum_type) {
5401 LLDB_LOG(log,
5402 "ProcessGDBRemote::ParseFlagsFields Type \"{0}\" for "
5403 "field \"{1}\" is not an enum, ignoring",
5404 type->data(), name->data());
5405 }
5406
5407 // No enumerator can exceed the range of the field itself.
5408 if (enum_type) {
5409 uint64_t max_value =
5411 for (const auto &enumerator : enum_type->GetEnumerators()) {
5412 if (enumerator.m_value > max_value) {
5413 enum_type = nullptr;
5414 LLDB_LOG(
5415 log,
5416 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
5417 "evalue \"{1}\" with value {2} exceeds the maximum "
5418 "value of field \"{3}\" ({4}), ignoring enum",
5419 type->data(), enumerator.m_name, enumerator.m_value,
5420 name->data(), max_value);
5421 break;
5422 }
5423 }
5424 }
5425 } else {
5426 LLDB_LOG(log,
5427 "ProcessGDBRemote::ParseFlagsFields Could not find type "
5428 "\"{0}\" "
5429 "for field \"{1}\", ignoring",
5430 type->data(), name->data());
5431 }
5432 }
5433
5434 fields.push_back(
5435 RegisterTypeFlags::Field(name->str(), *start, *end, enum_type));
5436 }
5437 }
5438 }
5439
5440 return true; // Iterate all "field" nodes.
5441 });
5442 return fields;
5443}
5444
5445void ParseFlags(
5446 XMLNode feature_node, RegisterTypeMap &feature_register_types,
5447 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5448 Log *log(GetLog(GDBRLog::Process));
5449
5450 feature_node.ForEachChildElementWithName(
5451 "flags",
5452 [&log, &feature_register_types,
5453 &owned_register_types](const XMLNode &flags_node) -> bool {
5454 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
5455 flags_node.GetAttributeValue("id").c_str());
5456
5457 std::optional<llvm::StringRef> id;
5458 std::optional<unsigned> size;
5459 flags_node.ForEachAttribute(
5460 [&id, &size, &log](const llvm::StringRef &name,
5461 const llvm::StringRef &value) {
5462 if (name == "id") {
5463 id = value;
5464 } else if (name == "size") {
5465 unsigned parsed_size = 0;
5466 if (llvm::to_integer(value, parsed_size))
5467 size = parsed_size;
5468 else {
5469 LLDB_LOG(log,
5470 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
5471 "in flags node",
5472 value.data());
5473 }
5474 } else {
5475 LLDB_LOG(log,
5476 "ProcessGDBRemote::ParseFlags Ignoring unknown "
5477 "attribute \"{0}\" in flags node",
5478 name.data());
5479 }
5480 return true; // Walk all attributes.
5481 });
5482
5483 if (id && size) {
5484 // Process the fields of this set of flags.
5485 std::vector<RegisterTypeFlags::Field> fields =
5486 ParseFlagsFields(flags_node, *size, feature_register_types);
5487 if (fields.size()) {
5488 // Sort so that the fields with the MSBs are first.
5489 std::sort(fields.rbegin(), fields.rend());
5490 std::vector<RegisterTypeFlags::Field>::const_iterator overlap =
5491 std::adjacent_find(fields.begin(), fields.end(),
5492 [](const RegisterTypeFlags::Field &lhs,
5493 const RegisterTypeFlags::Field &rhs) {
5494 return lhs.Overlaps(rhs);
5495 });
5496
5497 // If no fields overlap, use them.
5498 if (overlap == fields.end()) {
5499 if (feature_register_types.contains(*id)) {
5500 // Type IDs must be unique within a feature. Keep the type that
5501 // was already registered by the enum and flags parsing passes.
5502 LLDB_LOG(
5503 log,
5504 "ProcessGDBRemote::ParseFlags Definition of flags \"{0}\" "
5505 "conflicts with an existing type, ignoring this "
5506 "definition.",
5507 id->data());
5508 } else {
5509 auto flags_type = std::make_unique<RegisterTypeFlags>(
5510 id->str(), *size, std::move(fields));
5511 feature_register_types.try_emplace(*id, flags_type.get());
5512 owned_register_types.push_back(std::move(flags_type));
5513 }
5514 } else {
5515 // If any fields overlap, ignore the whole set of flags.
5516 std::vector<RegisterTypeFlags::Field>::const_iterator next =
5517 std::next(overlap);
5518 LLDB_LOG(
5519 log,
5520 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
5521 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
5522 "overlap.",
5523 overlap->GetName().c_str(), overlap->GetStart(),
5524 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
5525 next->GetEnd());
5526 }
5527 } else {
5528 LLDB_LOG(
5529 log,
5530 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
5531 "\"{0}\" because it contains no fields.",
5532 id->data());
5533 }
5534 }
5535
5536 return true; // Keep iterating through all "flags" elements.
5537 });
5538}
5539
5540static const RegisterTypeBuiltin *
5541ResolveGDBBuiltinType(llvm::StringRef type_name) {
5542 // These names and sizes follow GDB's predefined target-description types in
5543 // gdbsupport/tdesc.cc. ARM FPA is intentionally omitted because GCC removed
5544 // support for it in 2012.
5545 static const RegisterTypeBuiltin bool_type("bool", eEncodingUint,
5546 eFormatBoolean, 1);
5547 static const RegisterTypeBuiltin int8_type("int8", eEncodingSint,
5548 eFormatDecimal, 1);
5549 static const RegisterTypeBuiltin int16_type("int16", eEncodingSint,
5550 eFormatDecimal, 2);
5551 static const RegisterTypeBuiltin int32_type("int32", eEncodingSint,
5552 eFormatDecimal, 4);
5553 static const RegisterTypeBuiltin int64_type("int64", eEncodingSint,
5554 eFormatDecimal, 8);
5555 static const RegisterTypeBuiltin int128_type("int128", eEncodingSint,
5556 eFormatDecimal, 16);
5557 static const RegisterTypeBuiltin uint8_type("uint8", eEncodingUint,
5558 eFormatHex, 1);
5559 static const RegisterTypeBuiltin uint16_type("uint16", eEncodingUint,
5560 eFormatHex, 2);
5561 static const RegisterTypeBuiltin uint32_type("uint32", eEncodingUint,
5562 eFormatHex, 4);
5563 static const RegisterTypeBuiltin uint64_type("uint64", eEncodingUint,
5564 eFormatHex, 8);
5565 static const RegisterTypeBuiltin uint128_type("uint128", eEncodingUint,
5566 eFormatHex, 16);
5567 static const RegisterTypeBuiltin code_ptr_type(
5568 "code_ptr", eEncodingUint, eFormatAddressInfo, std::nullopt);
5569 static const RegisterTypeBuiltin data_ptr_type(
5570 "data_ptr", eEncodingUint, eFormatAddressInfo, std::nullopt);
5571 static const RegisterTypeBuiltin ieee_half_type("ieee_half", eEncodingIEEE754,
5572 eFormatFloat, 2);
5573 static const RegisterTypeBuiltin ieee_single_type(
5574 "ieee_single", eEncodingIEEE754, eFormatFloat, 4);
5575 static const RegisterTypeBuiltin ieee_double_type(
5576 "ieee_double", eEncodingIEEE754, eFormatFloat, 8);
5577 static const RegisterTypeBuiltin i387_ext_type("i387_ext", eEncodingIEEE754,
5578 eFormatFloat, 10);
5579 static const RegisterTypeBuiltin bfloat16_type("bfloat16", eEncodingIEEE754,
5580 eFormatFloat, 2);
5581
5582 return llvm::StringSwitch<const RegisterTypeBuiltin *>(type_name)
5583 .Case("bool", &bool_type)
5584 .Case("int8", &int8_type)
5585 .Case("int16", &int16_type)
5586 .Case("int32", &int32_type)
5587 .Case("int64", &int64_type)
5588 .Case("int128", &int128_type)
5589 .Case("uint8", &uint8_type)
5590 .Case("uint16", &uint16_type)
5591 .Case("uint32", &uint32_type)
5592 .Case("uint64", &uint64_type)
5593 .Case("uint128", &uint128_type)
5594 .Case("code_ptr", &code_ptr_type)
5595 .Case("data_ptr", &data_ptr_type)
5596 .Case("ieee_half", &ieee_half_type)
5597 .Case("ieee_single", &ieee_single_type)
5598 .Case("ieee_double", &ieee_double_type)
5599 .Case("i387_ext", &i387_ext_type)
5600 .Case("bfloat16", &bfloat16_type)
5601 .Default(nullptr);
5602}
5603
5604static const RegisterType *
5605ResolveGDBType(llvm::StringRef type_name,
5606 const RegisterTypeMap &feature_register_types) {
5607 auto type_it = feature_register_types.find(type_name);
5608 if (type_it != feature_register_types.end())
5609 return type_it->second;
5610 return ResolveGDBBuiltinType(type_name);
5611}
5612
5613static void
5614ParseVector(const XMLNode &vector_node, RegisterTypeMap &feature_register_types,
5615 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5616 Log *log(GetLog(GDBRLog::Process));
5617 std::optional<llvm::StringRef> id;
5618 std::optional<llvm::StringRef> element_type_name;
5619 std::optional<uint32_t> count;
5620
5621 vector_node.ForEachAttribute(
5622 [&id, &element_type_name, &count, log](llvm::StringRef name,
5623 llvm::StringRef value) {
5624 if (name == "id") {
5625 id = value;
5626 } else if (name == "type") {
5627 element_type_name = value;
5628 } else if (name == "count") {
5629 uint32_t parsed_count = 0;
5630 if (llvm::to_integer(value, parsed_count))
5631 count = parsed_count;
5632 else
5633 LLDB_LOG(log, "ProcessGDBRemote::ParseVector Invalid count \"{0}\"",
5634 value);
5635 } else {
5636 LLDB_LOG(log,
5637 "ProcessGDBRemote::ParseVector Ignoring unknown attribute "
5638 "\"{0}\"",
5639 name);
5640 }
5641 return true;
5642 });
5643
5644 // GDB limits vectors to 65536 elements. This is also LLDB's maximum
5645 // register size in bytes, so use the existing named limit.
5646 constexpr uint32_t max_vector_count = RegisterValue::kMaxRegisterByteSize;
5647 if (!id || id->empty() || !element_type_name || element_type_name->empty() ||
5648 !count || *count == 0 || *count > max_vector_count) {
5649 LLDB_LOG(log, "ProcessGDBRemote::ParseVector Ignoring vector with invalid "
5650 "id, type, or count");
5651 return;
5652 }
5653
5654 if (feature_register_types.contains(*id)) {
5655 LLDB_LOG(log,
5656 "ProcessGDBRemote::ParseVector Ignoring duplicate type \"{0}\"",
5657 *id);
5658 return;
5659 }
5660
5661 const RegisterType *element_type =
5662 ResolveGDBType(*element_type_name, feature_register_types);
5663 if (!element_type) {
5664 LLDB_LOG(log,
5665 "ProcessGDBRemote::ParseVector Could not resolve element type "
5666 "\"{0}\" for vector \"{1}\"",
5667 *element_type_name, *id);
5668 return;
5669 }
5670
5671 if (!llvm::isa<RegisterTypeBuiltin, RegisterTypeVector, RegisterTypeUnion>(
5672 element_type)) {
5673 LLDB_LOG(log,
5674 "ProcessGDBRemote::ParseVector Found element type \"{0}\" for "
5675 "vector \"{1}\", but it is not a builtin, vector, or union "
5676 "type",
5677 *element_type_name, *id);
5678 return;
5679 }
5680
5681 std::optional<uint64_t> element_size = element_type->GetByteSize();
5682 if (element_size &&
5683 *element_size > RegisterValue::kMaxRegisterByteSize / *count) {
5684 LLDB_LOG(log,
5685 "ProcessGDBRemote::ParseVector Size of vector \"{0}\" is too "
5686 "large",
5687 *id);
5688 return;
5689 }
5690
5691 auto vector_type =
5692 std::make_unique<RegisterTypeVector>(id->str(), element_type, *count);
5693 feature_register_types.try_emplace(*id, vector_type.get());
5694 owned_register_types.push_back(std::move(vector_type));
5695}
5696
5697static std::vector<RegisterTypeUnion::Field>
5698ParseUnionFields(const XMLNode &union_node, llvm::StringRef union_id,
5699 const RegisterTypeMap &feature_register_types) {
5700 Log *log(GetLog(GDBRLog::Process));
5701 std::vector<RegisterTypeUnion::Field> fields;
5702 bool invalid_field = false;
5703
5704 union_node.ForEachChildElementWithName(
5705 "field", [&fields, &invalid_field, log, &feature_register_types,
5706 union_id](const XMLNode &field_node) {
5707 std::optional<llvm::StringRef> name;
5708 std::optional<llvm::StringRef> type_name;
5709
5710 field_node.ForEachAttribute(
5711 [&name, &type_name, log, union_id](llvm::StringRef attribute,
5712 llvm::StringRef value) {
5713 if (attribute == "name")
5714 name = value;
5715 else if (attribute == "type")
5716 type_name = value;
5717 else
5718 LLDB_LOG(log,
5719 "ProcessGDBRemote::ParseUnionFields Ignoring unknown "
5720 "attribute \"{0}\" in a field of union \"{1}\"",
5721 attribute, union_id);
5722 return true;
5723 });
5724
5725 if (!name || name->empty() || !type_name || type_name->empty()) {
5726 LLDB_LOG(log,
5727 "ProcessGDBRemote::ParseUnionFields Union \"{0}\" has a "
5728 "field missing a non-empty name or type",
5729 union_id);
5730 invalid_field = true;
5731 return true;
5732 }
5733
5734 const RegisterType *field_type =
5735 ResolveGDBType(*type_name, feature_register_types);
5736 if (!field_type) {
5737 LLDB_LOG(log,
5738 "ProcessGDBRemote::ParseUnionFields Could not resolve type "
5739 "\"{0}\" for field \"{1}\" of union \"{2}\"",
5740 *type_name, *name, union_id);
5741 invalid_field = true;
5742 return true;
5743 }
5744
5745 if (!llvm::isa<RegisterTypeBuiltin, RegisterTypeVector,
5746 RegisterTypeUnion>(field_type)) {
5747 LLDB_LOG(log,
5748 "ProcessGDBRemote::ParseUnionFields Found type \"{0}\" "
5749 "for field \"{1}\", but it is not a builtin, vector, or "
5750 "union type. Union \"{2}\" will be ignored.",
5751 *type_name, *name, union_id);
5752 invalid_field = true;
5753 return true;
5754 }
5755
5756 fields.emplace_back(name->str(), field_type);
5757 return true;
5758 });
5759
5760 // Reject the whole union if any field is invalid. Retaining only valid fields
5761 // would misrepresent the target's type definition.
5762 if (invalid_field) {
5763 LLDB_LOG(log,
5764 "ProcessGDBRemote::ParseUnionFields Ignoring union \"{0}\" "
5765 "because it contains an invalid field",
5766 union_id);
5767 fields.clear();
5768 } else if (fields.empty()) {
5769 LLDB_LOG(log,
5770 "ProcessGDBRemote::ParseUnionFields Ignoring union \"{0}\" "
5771 "because it has no fields",
5772 union_id);
5773 }
5774 return fields;
5775}
5776
5777static void
5778ParseUnion(const XMLNode &union_node, RegisterTypeMap &feature_register_types,
5779 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5780 Log *log(GetLog(GDBRLog::Process));
5781 std::optional<llvm::StringRef> id;
5782
5783 union_node.ForEachAttribute(
5784 [&id, log](llvm::StringRef name, llvm::StringRef value) {
5785 if (name == "id")
5786 id = value;
5787 else
5788 LLDB_LOG(log,
5789 "ProcessGDBRemote::ParseUnion Ignoring unknown attribute "
5790 "\"{0}\"",
5791 name);
5792 return true;
5793 });
5794
5795 if (!id || id->empty()) {
5796 LLDB_LOG(log, "ProcessGDBRemote::ParseUnion Ignoring union without an id");
5797 return;
5798 }
5799
5800 if (feature_register_types.contains(*id)) {
5801 LLDB_LOG(log,
5802 "ProcessGDBRemote::ParseUnion Ignoring duplicate type \"{0}\"",
5803 *id);
5804 return;
5805 }
5806
5807 std::vector<RegisterTypeUnion::Field> fields =
5808 ParseUnionFields(union_node, *id, feature_register_types);
5809 if (fields.empty())
5810 return;
5811
5812 auto union_type =
5813 std::make_unique<RegisterTypeUnion>(id->str(), std::move(fields));
5814 feature_register_types.try_emplace(*id, union_type.get());
5815 owned_register_types.push_back(std::move(union_type));
5816}
5817
5818static void ParseCompositeTypes(
5819 XMLNode feature_node, RegisterTypeMap &feature_register_types,
5820 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5821 feature_node.ForEachChildElement(
5822 [&feature_register_types,
5823 &owned_register_types](const XMLNode &type_node) {
5824 if (type_node.NameIs("vector"))
5825 ParseVector(type_node, feature_register_types, owned_register_types);
5826 else if (type_node.NameIs("union"))
5827 ParseUnion(type_node, feature_register_types, owned_register_types);
5828 return true;
5829 });
5830}
5831
5832bool ParseRegisters(
5833 XMLNode feature_node, GdbServerTargetInfo &target_info,
5834 std::vector<DynamicRegisterInfo::Register> &registers,
5835 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5836 if (!feature_node)
5837 return false;
5838
5839 Log *log(GetLog(GDBRLog::Process));
5840 RegisterTypeMap feature_register_types;
5841
5842 // Enums first because they are referenced by fields in the flags.
5843 ParseEnums(feature_node, feature_register_types, owned_register_types);
5844 for (const auto &register_type : feature_register_types)
5845 if (const auto *enum_type =
5846 llvm::dyn_cast<RegisterTypeEnum>(register_type.second))
5847 enum_type->DumpToLog(log);
5848
5849 ParseFlags(feature_node, feature_register_types, owned_register_types);
5850 for (const auto &register_type : feature_register_types)
5851 if (const auto *flags_type =
5852 llvm::dyn_cast<RegisterTypeFlags>(register_type.second))
5853 flags_type->DumpToLog(log);
5854
5855 // Enums and flags retain their dedicated passes above. Vectors and unions
5856 // can reference one another, so parse them together in document order. A
5857 // referenced composite type must precede its user.
5858 ParseCompositeTypes(feature_node, feature_register_types,
5859 owned_register_types);
5860 for (const auto &register_type : feature_register_types)
5861 if (const auto *vector_type =
5862 llvm::dyn_cast<RegisterTypeVector>(register_type.second))
5863 vector_type->DumpToLog(log);
5864 for (const auto &register_type : feature_register_types)
5865 if (const auto *union_type =
5866 llvm::dyn_cast<RegisterTypeUnion>(register_type.second))
5867 union_type->DumpToLog(log);
5868
5869 feature_node.ForEachChildElementWithName(
5870 "reg",
5871 [&target_info, &registers, &feature_register_types,
5872 log](const XMLNode &reg_node) -> bool {
5873 std::string gdb_group;
5874 std::string gdb_type;
5875 DynamicRegisterInfo::Register reg_info;
5876 bool encoding_set = false;
5877 bool format_set = false;
5878
5879 // FIXME: we're silently ignoring invalid data here
5880 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
5881 &encoding_set, &format_set, &reg_info,
5882 log](const llvm::StringRef &name,
5883 const llvm::StringRef &value) -> bool {
5884 if (name == "name") {
5885 reg_info.name = value.str();
5886 } else if (name == "bitsize") {
5887 if (llvm::to_integer(value, reg_info.byte_size))
5888 reg_info.byte_size =
5889 llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
5890 } else if (name == "type") {
5891 gdb_type = value.str();
5892 } else if (name == "group") {
5893 gdb_group = value.str();
5894 } else if (name == "regnum") {
5895 llvm::to_integer(value, reg_info.regnum_remote);
5896 } else if (name == "offset") {
5897 llvm::to_integer(value, reg_info.byte_offset);
5898 } else if (name == "altname") {
5899 reg_info.alt_name = value.str();
5900 } else if (name == "encoding") {
5901 encoding_set = true;
5903 } else if (name == "format") {
5904 format_set = true;
5905 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
5906 nullptr)
5907 .Success())
5908 reg_info.format =
5909 llvm::StringSwitch<lldb::Format>(value)
5910 .Case("vector-sint8", eFormatVectorOfSInt8)
5911 .Case("vector-uint8", eFormatVectorOfUInt8)
5912 .Case("vector-sint16", eFormatVectorOfSInt16)
5913 .Case("vector-uint16", eFormatVectorOfUInt16)
5914 .Case("vector-sint32", eFormatVectorOfSInt32)
5915 .Case("vector-uint32", eFormatVectorOfUInt32)
5916 .Case("vector-float32", eFormatVectorOfFloat32)
5917 .Case("vector-uint64", eFormatVectorOfUInt64)
5918 .Case("vector-uint128", eFormatVectorOfUInt128)
5919 .Default(eFormatInvalid);
5920 } else if (name == "group_id") {
5921 uint32_t set_id = UINT32_MAX;
5922 llvm::to_integer(value, set_id);
5923 RegisterSetMap::const_iterator pos =
5924 target_info.reg_set_map.find(set_id);
5925 if (pos != target_info.reg_set_map.end())
5926 reg_info.set_name = pos->second.name;
5927 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
5928 llvm::to_integer(value, reg_info.regnum_ehframe);
5929 } else if (name == "dwarf_regnum") {
5930 llvm::to_integer(value, reg_info.regnum_dwarf);
5931 } else if (name == "generic") {
5933 } else if (name == "value_regnums") {
5935 0);
5936 } else if (name == "invalidate_regnums") {
5938 value, reg_info.invalidate_regs, 0);
5939 } else {
5940 LLDB_LOGF(log,
5941 "ProcessGDBRemote::ParseRegisters unhandled reg "
5942 "attribute %s = %s",
5943 name.data(), value.data());
5944 }
5945 return true; // Keep iterating through all attributes
5946 });
5947
5948 if (!gdb_type.empty()) {
5949 // gdb_type could reference a type defined in this feature.
5950 auto it = feature_register_types.find(gdb_type);
5951 if (it != feature_register_types.end()) {
5952 if (const auto *vector_type =
5953 llvm::dyn_cast<RegisterTypeVector>(it->second)) {
5954 std::optional<uint64_t> type_size = vector_type->GetByteSize();
5956 LLDB_LOG(log,
5957 "ProcessGDBRemote::ParseRegisters Register {0} is "
5958 "too large for vector type {1}",
5959 reg_info.name, vector_type->GetID());
5960 } else if (!vector_type->IsByteSizeCompatible(
5961 reg_info.byte_size)) {
5962 if (!type_size) {
5963 LLDB_LOG(log,
5964 "ProcessGDBRemote::ParseRegisters Size of register "
5965 "{0} is incompatible with vector type {1}",
5966 reg_info.name, vector_type->GetID());
5967 } else {
5968 LLDB_LOG(
5969 log,
5970 "ProcessGDBRemote::ParseRegisters Size of register type "
5971 "{0} ({1} bytes) for register {2} does not match the "
5972 "register size ({3} bytes). Ignoring this type.",
5973 vector_type->GetID(), *type_size, reg_info.name,
5974 reg_info.byte_size);
5975 }
5976 } else {
5977 reg_info.register_type = vector_type;
5978 if (!encoding_set) {
5979 reg_info.encoding = eEncodingVector;
5980 encoding_set = true;
5981 }
5982 if (!format_set) {
5983 reg_info.format = eFormatVectorOfUInt8;
5984 format_set = true;
5985 }
5986 }
5987 } else if (const auto *union_type =
5988 llvm::dyn_cast<RegisterTypeUnion>(it->second)) {
5990 LLDB_LOG(log,
5991 "ProcessGDBRemote::ParseRegisters Register {0} is "
5992 "too large for union type {1}",
5993 reg_info.name, union_type->GetID());
5994 } else if (!union_type->IsByteSizeCompatible(
5995 reg_info.byte_size)) {
5996 LLDB_LOG(log,
5997 "ProcessGDBRemote::ParseRegisters Size of register "
5998 "{0} is incompatible with union type {1}",
5999 reg_info.name, union_type->GetID());
6000 } else {
6001 reg_info.register_type = union_type;
6002 if (!encoding_set) {
6003 reg_info.encoding = eEncodingUint;
6004 encoding_set = true;
6005 }
6006 if (!format_set) {
6007 reg_info.format = eFormatHex;
6008 format_set = true;
6009 }
6010 }
6011 } else if (const auto *flags_type =
6012 llvm::dyn_cast<RegisterTypeFlags>(it->second)) {
6013 if (reg_info.byte_size == flags_type->GetSize())
6014 reg_info.register_type = flags_type;
6015 else
6016 LLDB_LOG(
6017 log,
6018 "ProcessGDBRemote::ParseRegisters Size of register flags "
6019 "{0} ({1} bytes) for register {2} does not match the "
6020 "register size ({3} bytes). Ignoring this set of flags.",
6021 flags_type->GetID().c_str(), flags_type->GetSize(),
6022 reg_info.name, reg_info.byte_size);
6023 }
6024 }
6025
6026 // There's a slim chance that the gdb_type name is both a flags type
6027 // and a simple type. Just in case, look for that too (setting both
6028 // does no harm).
6029 if (!gdb_type.empty() && !(encoding_set || format_set)) {
6030 if (llvm::StringRef(gdb_type).starts_with("int")) {
6031 reg_info.format = eFormatHex;
6032 reg_info.encoding = eEncodingUint;
6033 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
6034 reg_info.format = eFormatAddressInfo;
6035 reg_info.encoding = eEncodingUint;
6036 } else if (gdb_type == "float" || gdb_type == "ieee_single" ||
6037 gdb_type == "ieee_double") {
6038 reg_info.format = eFormatFloat;
6039 reg_info.encoding = eEncodingIEEE754;
6040 } else if (gdb_type == "aarch64v" ||
6041 llvm::StringRef(gdb_type).starts_with("vec") ||
6042 gdb_type == "i387_ext" || gdb_type == "uint128" ||
6043 reg_info.byte_size > 16) {
6044 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
6045 // treat them as vector (similarly to xmm/ymm).
6046 // We can fall back to handling anything else <= 128 bit as an
6047 // unsigned integer, more than that, call it a vector of bytes.
6048 // This can happen if we don't recognise the type for AArc64 SVE
6049 // registers.
6050 reg_info.format = eFormatVectorOfUInt8;
6051 reg_info.encoding = eEncodingVector;
6052 } else {
6053 LLDB_LOGF(
6054 log,
6055 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
6056 "format and encoding for gdb type %s",
6057 gdb_type.c_str());
6058 }
6059 }
6060 }
6061
6062 // Only update the register set name if we didn't get a "reg_set"
6063 // attribute. "set_name" will be empty if we didn't have a "reg_set"
6064 // attribute.
6065 if (reg_info.set_name.empty()) {
6066 if (!gdb_group.empty()) {
6067 reg_info.set_name = gdb_group;
6068 } else {
6069 // If no register group name provided anywhere,
6070 // we'll create a 'general' register set
6071 reg_info.set_name = "general";
6072 }
6073 }
6074
6075 if (reg_info.byte_size == 0) {
6076 LLDB_LOG(log,
6077 "ProcessGDBRemote::{0} Skipping zero bitsize register {1}",
6078 __FUNCTION__, reg_info.name);
6079 } else
6080 registers.push_back(reg_info);
6081
6082 return true; // Keep iterating through all "reg" elements
6083 });
6084 return true;
6085}
6086
6087} // namespace
6088
6089// This method fetches a register description feature xml file from
6090// the remote stub and adds registers/register groupsets/architecture
6091// information to the current process. It will call itself recursively
6092// for nested register definition files. It returns true if it was able
6093// to fetch and parse an xml file.
6095 ArchSpec &arch_to_use, std::string xml_filename,
6096 std::vector<DynamicRegisterInfo::Register> &registers) {
6097 // request the target xml file
6098 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
6099 if (errorToBool(raw.takeError()))
6100 return false;
6101
6102 XMLDocument xml_document;
6103
6104 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
6105 xml_filename.c_str())) {
6106 GdbServerTargetInfo target_info;
6107 std::vector<XMLNode> feature_nodes;
6108
6109 // The top level feature XML file will start with a <target> tag.
6110 XMLNode target_node = xml_document.GetRootElement("target");
6111 if (target_node) {
6112 target_node.ForEachChildElement([&target_info, &feature_nodes](
6113 const XMLNode &node) -> bool {
6114 llvm::StringRef name = node.GetName();
6115 if (name == "architecture") {
6116 node.GetElementText(target_info.arch);
6117 } else if (name == "osabi") {
6118 node.GetElementText(target_info.osabi);
6119 } else if (name == "xi:include" || name == "include") {
6120 std::string href = node.GetAttributeValue("href");
6121 if (!href.empty())
6122 target_info.includes.push_back(href);
6123 } else if (name == "feature") {
6124 feature_nodes.push_back(node);
6125 } else if (name == "groups") {
6127 "group", [&target_info](const XMLNode &node) -> bool {
6128 uint32_t set_id = UINT32_MAX;
6129 RegisterSetInfo set_info;
6130
6131 node.ForEachAttribute(
6132 [&set_id, &set_info](const llvm::StringRef &name,
6133 const llvm::StringRef &value) -> bool {
6134 // FIXME: we're silently ignoring invalid data here
6135 if (name == "id")
6136 llvm::to_integer(value, set_id);
6137 if (name == "name")
6138 set_info.name = value.str();
6139 return true; // Keep iterating through all attributes
6140 });
6141
6142 if (set_id != UINT32_MAX)
6143 target_info.reg_set_map[set_id] = set_info;
6144 return true; // Keep iterating through all "group" elements
6145 });
6146 }
6147 return true; // Keep iterating through all children of the target_node
6148 });
6149 } else {
6150 // In an included XML feature file, we're already "inside" the <target>
6151 // tag of the initial XML file; this included file will likely only have
6152 // a <feature> tag. Need to check for any more included files in this
6153 // <feature> element.
6154 XMLNode feature_node = xml_document.GetRootElement("feature");
6155 if (feature_node) {
6156 feature_nodes.push_back(feature_node);
6157 feature_node.ForEachChildElement([&target_info](
6158 const XMLNode &node) -> bool {
6159 llvm::StringRef name = node.GetName();
6160 if (name == "xi:include" || name == "include") {
6161 std::string href = node.GetAttributeValue("href");
6162 if (!href.empty())
6163 target_info.includes.push_back(href);
6164 }
6165 return true;
6166 });
6167 }
6168 }
6169
6170 // gdbserver does not implement the LLDB packets used to determine host
6171 // or process architecture. If that is the case, attempt to use
6172 // the <architecture/> field from target.xml, e.g.:
6173 //
6174 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
6175 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
6176 // arm board)
6177 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
6178 // We don't have any information about vendor or OS.
6179 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
6180 .Case("i386:x86-64", "x86_64")
6181 .Case("riscv:rv64", "riscv64")
6182 .Case("riscv:rv32", "riscv32")
6183 .Default(target_info.arch) +
6184 "--");
6185
6186 if (arch_to_use.IsValid())
6187 GetTarget().MergeArchitecture(arch_to_use);
6188 }
6189
6190 if (arch_to_use.IsValid()) {
6191 for (auto &feature_node : feature_nodes) {
6192 ParseRegisters(feature_node, target_info, registers, m_register_types);
6193 }
6194
6195 for (const auto &include : target_info.includes) {
6196 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
6197 registers);
6198 }
6199 }
6200 } else {
6201 return false;
6202 }
6203 return true;
6204}
6205
6207 std::vector<DynamicRegisterInfo::Register> &registers,
6208 const ArchSpec &arch_to_use) {
6209 std::map<uint32_t, uint32_t> remote_to_local_map;
6210 uint32_t remote_regnum = 0;
6211 for (auto it : llvm::enumerate(registers)) {
6212 DynamicRegisterInfo::Register &remote_reg_info = it.value();
6213
6214 // Assign successive remote regnums if missing.
6215 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
6216 remote_reg_info.regnum_remote = remote_regnum;
6217
6218 // Create a mapping from remote to local regnos.
6219 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
6220
6221 remote_regnum = remote_reg_info.regnum_remote + 1;
6222 }
6223
6224 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
6225 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
6226 auto lldb_regit = remote_to_local_map.find(process_regnum);
6227 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
6229 };
6230
6231 llvm::transform(remote_reg_info.value_regs,
6232 remote_reg_info.value_regs.begin(), proc_to_lldb);
6233 llvm::transform(remote_reg_info.invalidate_regs,
6234 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
6235 }
6236
6237 // Don't use Process::GetABI, this code gets called from DidAttach, and
6238 // in that context we haven't set the Target's architecture yet, so the
6239 // ABI is also potentially incorrect.
6240 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
6241 abi_sp->AugmentRegisterInfo(registers);
6242
6243 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
6244}
6245
6246// query the target of gdb-remote for extended target information returns
6247// true on success (got register definitions), false on failure (did not).
6249 // If the remote does not offer XML, does not matter if we would have been
6250 // able to parse it.
6251 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
6252 return llvm::createStringError(
6253 llvm::inconvertibleErrorCode(),
6254 "the debug server does not support \"qXfer:features:read\"");
6255
6257 return llvm::createStringError(
6258 llvm::inconvertibleErrorCode(),
6259 "the debug server supports \"qXfer:features:read\", but LLDB does not "
6260 "have XML parsing enabled (check LLLDB_ENABLE_LIBXML2)");
6261
6262 std::vector<DynamicRegisterInfo::Register> registers;
6263 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
6264 registers) &&
6265 // Target XML is not required to include register information.
6266 !registers.empty())
6267 AddRemoteRegisters(registers, arch_to_use);
6268
6269 return m_register_info_sp->GetNumRegisters() > 0
6270 ? llvm::ErrorSuccess()
6271 : llvm::createStringError(
6272 llvm::inconvertibleErrorCode(),
6273 "the debug server did not describe any registers");
6274}
6275
6276llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
6277 // Make sure LLDB has an XML parser it can use first
6279 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6280 "XML parsing not available");
6281
6282 Log *log = GetLog(LLDBLog::Process);
6283 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
6284
6287 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
6288
6289 // check that we have extended feature read support
6290 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
6291 // request the loaded library list
6292 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
6293 if (!raw)
6294 return raw.takeError();
6295
6296 // parse the xml file in memory
6297 LLDB_LOGF(log, "parsing: %s", raw->c_str());
6298 XMLDocument doc;
6299
6300 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
6301 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6302 "Error reading noname.xml");
6303
6304 XMLNode root_element = doc.GetRootElement("library-list-svr4");
6305 if (!root_element)
6306 return llvm::createStringError(
6307 llvm::inconvertibleErrorCode(),
6308 "Error finding library-list-svr4 xml element");
6309
6310 // main link map structure
6311 std::string main_lm = root_element.GetAttributeValue("main-lm");
6312 // FIXME: we're silently ignoring invalid data here
6313 if (!main_lm.empty())
6314 llvm::to_integer(main_lm, list.m_link_map);
6315
6316 root_element.ForEachChildElementWithName(
6317 "library", [log, &list](const XMLNode &library) -> bool {
6319
6320 // FIXME: we're silently ignoring invalid data here
6321 library.ForEachAttribute(
6322 [&module](const llvm::StringRef &name,
6323 const llvm::StringRef &value) -> bool {
6324 uint64_t uint_value = LLDB_INVALID_ADDRESS;
6325 if (name == "name")
6326 module.set_name(value.str());
6327 else if (name == "lm") {
6328 // the address of the link_map struct.
6329 llvm::to_integer(value, uint_value);
6330 module.set_link_map(uint_value);
6331 } else if (name == "l_addr") {
6332 // the displacement as read from the field 'l_addr' of the
6333 // link_map struct.
6334 llvm::to_integer(value, uint_value);
6335 module.set_base(uint_value);
6336 // base address is always a displacement, not an absolute
6337 // value.
6338 module.set_base_is_offset(true);
6339 } else if (name == "l_ld") {
6340 // the memory address of the libraries PT_DYNAMIC section.
6341 llvm::to_integer(value, uint_value);
6342 module.set_dynamic(uint_value);
6343 }
6344
6345 return true; // Keep iterating over all properties of "library"
6346 });
6347
6348 if (log) {
6349 std::string name;
6350 lldb::addr_t lm = 0, base = 0, ld = 0;
6351 bool base_is_offset;
6352
6353 module.get_name(name);
6354 module.get_link_map(lm);
6355 module.get_base(base);
6356 module.get_base_is_offset(base_is_offset);
6357 module.get_dynamic(ld);
6358
6359 LLDB_LOGF(log,
6360 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
6361 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
6362 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
6363 name.c_str());
6364 }
6365
6366 list.add(module);
6367 return true; // Keep iterating over all "library" elements in the root
6368 // node
6369 });
6370
6371 LLDB_LOGF(log, "found %" PRId32 " modules in total",
6372 (int)list.m_list.size());
6373 return list;
6374 } else if (comm.GetQXferLibrariesReadSupported()) {
6375 // request the loaded library list
6376 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
6377
6378 if (!raw)
6379 return raw.takeError();
6380
6381 LLDB_LOGF(log, "parsing: %s", raw->c_str());
6382 XMLDocument doc;
6383
6384 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
6385 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6386 "Error reading noname.xml");
6387
6388 XMLNode root_element = doc.GetRootElement("library-list");
6389 if (!root_element)
6390 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6391 "Error finding library-list xml element");
6392
6393 // FIXME: we're silently ignoring invalid data here
6394 root_element.ForEachChildElementWithName(
6395 "library", [log, &list](const XMLNode &library) -> bool {
6397
6398 std::string name = library.GetAttributeValue("name");
6399 module.set_name(name);
6400
6401 // The base address of a given library will be the address of its
6402 // first section. Most remotes send only one section for Windows
6403 // targets for example.
6404 const XMLNode &section =
6405 library.FindFirstChildElementWithName("section");
6406 std::string address = section.GetAttributeValue("address");
6407 uint64_t address_value = LLDB_INVALID_ADDRESS;
6408 llvm::to_integer(address, address_value);
6409 module.set_base(address_value);
6410 // These addresses are absolute values.
6411 module.set_base_is_offset(false);
6412
6413 if (log) {
6414 std::string name;
6415 lldb::addr_t base = 0;
6416 bool base_is_offset;
6417 module.get_name(name);
6418 module.get_base(base);
6419 module.get_base_is_offset(base_is_offset);
6420
6421 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
6422 (base_is_offset ? "offset" : "absolute"), name.c_str());
6423 }
6424
6425 list.add(module);
6426 return true; // Keep iterating over all "library" elements in the root
6427 // node
6428 });
6429
6430 LLDB_LOGF(log, "found %" PRId32 " modules in total",
6431 (int)list.m_list.size());
6432 return list;
6433 } else {
6434 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6435 "Remote libraries not supported");
6436 }
6437}
6438
6440 lldb::addr_t link_map,
6441 lldb::addr_t base_addr,
6442 bool value_is_offset) {
6443 DynamicLoader *loader = GetDynamicLoader();
6444 if (!loader)
6445 return nullptr;
6446
6447 return loader->LoadModuleAtAddress(file, link_map, base_addr,
6448 value_is_offset);
6449}
6450
6453
6454 if (m_dyld_up && m_dyld_up->HandleStopReasonDynamicLoader())
6455 return llvm::ErrorSuccess();
6456
6457 // request a list of loaded libraries from GDBServer
6458 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
6459 if (!module_list)
6460 return module_list.takeError();
6461
6462 // get a list of all the modules
6463 ModuleList new_modules;
6464
6465 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
6466 std::string mod_name;
6467 lldb::addr_t mod_base;
6468 lldb::addr_t link_map;
6469 bool mod_base_is_offset;
6470
6471 bool valid = true;
6472 valid &= modInfo.get_name(mod_name);
6473 valid &= modInfo.get_base(mod_base);
6474 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
6475 if (!valid)
6476 continue;
6477
6478 if (!modInfo.get_link_map(link_map))
6479 link_map = LLDB_INVALID_ADDRESS;
6480
6481 FileSpec file(mod_name);
6483 lldb::ModuleSP module_sp =
6484 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
6485
6486 if (module_sp.get())
6487 new_modules.Append(module_sp);
6488 }
6489
6490 if (new_modules.GetSize() > 0) {
6491 ModuleList removed_modules;
6492 Target &target = GetTarget();
6493 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
6494
6495 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
6496 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
6497
6498 bool found = false;
6499 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
6500 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
6501 found = true;
6502 }
6503
6504 // The main executable will never be included in libraries-svr4, don't
6505 // remove it
6506 if (!found &&
6507 loaded_module.get() != target.GetExecutableModulePointer()) {
6508 removed_modules.Append(loaded_module);
6509 }
6510 }
6511
6512 loaded_modules.Remove(removed_modules);
6513 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
6514
6515 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) {
6516 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
6517 if (!obj)
6519
6522
6523 if (target.GetExecutableModulePointer() == module_sp.get())
6524 return IterationAction::Stop;
6525
6526 lldb::ModuleSP module_copy_sp = module_sp;
6527 target.RebuildModuleListWithExecutable(module_copy_sp, eLoadDependentsNo);
6528 return IterationAction::Stop;
6529 });
6530
6531 loaded_modules.AppendIfNeeded(new_modules);
6532 m_process->GetTarget().ModulesDidLoad(new_modules);
6533 }
6534
6535 return llvm::ErrorSuccess();
6536}
6537
6539 bool &is_loaded,
6540 lldb::addr_t &load_addr) {
6541 is_loaded = false;
6542 load_addr = LLDB_INVALID_ADDRESS;
6543
6544 std::string file_path = file.GetPath(false);
6545 if (file_path.empty())
6546 return Status::FromErrorString("Empty file name specified");
6547
6548 StreamString packet;
6549 packet.PutCString("qFileLoadAddress:");
6550 packet.PutStringAsRawHex8(file_path);
6551
6552 StringExtractorGDBRemote response;
6553 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
6555 return Status::FromErrorString("Sending qFileLoadAddress packet failed");
6556
6557 if (response.IsErrorResponse()) {
6558 if (response.GetError() == 1) {
6559 // The file is not loaded into the inferior
6560 is_loaded = false;
6561 load_addr = LLDB_INVALID_ADDRESS;
6562 return Status();
6563 }
6564
6566 "Fetching file load address from remote server returned an error");
6567 }
6568
6569 if (response.IsNormalResponse()) {
6570 is_loaded = true;
6571 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
6572 return Status();
6573 }
6574
6576 "Unknown error happened during sending the load address packet");
6577}
6578
6580 // We must call the lldb_private::Process::ModulesDidLoad () first before we
6581 // do anything
6582 Process::ModulesDidLoad(module_list);
6583
6584 // After loading shared libraries, we can ask our remote GDB server if it
6585 // needs any symbols.
6586 m_gdb_comm.ServeSymbolLookups(this);
6587}
6588
6589void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
6590 AppendSTDOUT(out.data(), out.size());
6591}
6592
6593static const char *end_delimiter = "--end--;";
6594static const int end_delimiter_len = 8;
6595
6596void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
6597 std::string input = data.str(); // '1' to move beyond 'A'
6598 if (m_partial_profile_data.length() > 0) {
6599 m_partial_profile_data.append(input);
6600 input = m_partial_profile_data;
6601 m_partial_profile_data.clear();
6602 }
6603
6604 size_t found, pos = 0, len = input.length();
6605 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
6606 StringExtractorGDBRemote profileDataExtractor(
6607 input.substr(pos, found).c_str());
6608 std::string profile_data =
6609 HarmonizeThreadIdsForProfileData(profileDataExtractor);
6610 BroadcastAsyncProfileData(profile_data);
6611
6612 pos = found + end_delimiter_len;
6613 }
6614
6615 if (pos < len) {
6616 // Last incomplete chunk.
6617 m_partial_profile_data = input.substr(pos);
6618 }
6619}
6620
6622 StringExtractorGDBRemote &profileDataExtractor) {
6623 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
6624 std::string output;
6625 llvm::raw_string_ostream output_stream(output);
6626 llvm::StringRef name, value;
6627
6628 // Going to assuming thread_used_usec comes first, else bail out.
6629 while (profileDataExtractor.GetNameColonValue(name, value)) {
6630 if (name.compare("thread_used_id") == 0) {
6631 StringExtractor threadIDHexExtractor(value);
6632 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
6633
6634 bool has_used_usec = false;
6635 uint32_t curr_used_usec = 0;
6636 llvm::StringRef usec_name, usec_value;
6637 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
6638 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
6639 if (usec_name == "thread_used_usec") {
6640 has_used_usec = true;
6641 usec_value.getAsInteger(BASE_10, curr_used_usec);
6642 } else {
6643 // We didn't find what we want, it is probably an older version. Bail
6644 // out.
6645 profileDataExtractor.SetFilePos(input_file_pos);
6646 }
6647 }
6648
6649 if (has_used_usec) {
6650 uint32_t prev_used_usec = 0;
6651 std::map<uint64_t, uint32_t>::iterator iterator =
6652 m_thread_id_to_used_usec_map.find(thread_id);
6653 if (iterator != m_thread_id_to_used_usec_map.end())
6654 prev_used_usec = iterator->second;
6655
6656 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
6657 // A good first time record is one that runs for at least 0.25 sec
6658 bool good_first_time =
6659 (prev_used_usec == 0) && (real_used_usec > 250000);
6660 bool good_subsequent_time =
6661 (prev_used_usec > 0) &&
6662 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
6663
6664 if (good_first_time || good_subsequent_time) {
6665 // We try to avoid doing too many index id reservation, resulting in
6666 // fast increase of index ids.
6667
6668 output_stream << name << ":";
6669 int32_t index_id = AssignIndexIDToThread(thread_id);
6670 output_stream << index_id << ";";
6671
6672 output_stream << usec_name << ":" << usec_value << ";";
6673 } else {
6674 // Skip past 'thread_used_name'.
6675 llvm::StringRef local_name, local_value;
6676 profileDataExtractor.GetNameColonValue(local_name, local_value);
6677 }
6678
6679 // Store current time as previous time so that they can be compared
6680 // later.
6681 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
6682 } else {
6683 // Bail out and use old string.
6684 output_stream << name << ":" << value << ";";
6685 }
6686 } else {
6687 output_stream << name << ":" << value << ";";
6688 }
6689 }
6690 output_stream << end_delimiter;
6691 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
6692
6693 return output;
6694}
6695
6697 if (GetStopID() != 0)
6698 return;
6699
6700 if (GetID() == LLDB_INVALID_PROCESS_ID) {
6701 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
6702 if (pid != LLDB_INVALID_PROCESS_ID)
6703 SetID(pid);
6704 }
6706}
6707
6708llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
6709 if (!m_gdb_comm.GetSaveCoreSupported())
6710 return false;
6711
6712 StreamString packet;
6713 packet.PutCString("qSaveCore;path-hint:");
6714 packet.PutStringAsRawHex8(outfile);
6715
6716 StringExtractorGDBRemote response;
6717 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
6719 // TODO: grab error message from the packet? StringExtractor seems to
6720 // be missing a method for that
6721 if (response.IsErrorResponse())
6722 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6723 "qSaveCore returned an error");
6724
6725 std::string path;
6726
6727 // process the response
6728 for (auto x : llvm::split(response.GetStringRef(), ';')) {
6729 if (x.consume_front("core-path:"))
6731 }
6732
6733 // verify that we've gotten what we need
6734 if (path.empty())
6735 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6736 "qSaveCore returned no core path");
6737
6738 FileSpec remote_core{llvm::StringRef(path)};
6739 FileSpec local_core{outfile};
6740 Platform &platform = *GetTarget().GetPlatform();
6741
6742 if (!platform.IsRemote() && remote_core == local_core)
6743 return true;
6744
6745 // now transfer the core file
6746 Status error = platform.GetFile(remote_core, local_core);
6747 // NB: we unlink the file on error too
6748 platform.Unlink(remote_core);
6749 if (error.Fail())
6750 return error.ToError();
6751
6752 return true;
6753 }
6754
6755 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6756 "Unable to send qSaveCore");
6757}
6758
6759static const char *const s_async_json_packet_prefix = "JSON-async:";
6760
6762ParseStructuredDataPacket(llvm::StringRef packet) {
6763 Log *log = GetLog(GDBRLog::Process);
6764
6765 if (!packet.consume_front(s_async_json_packet_prefix)) {
6766 LLDB_LOGF(
6767 log,
6768 "GDBRemoteCommunicationClientBase::%s() received $J packet "
6769 "but was not a StructuredData packet: packet starts with "
6770 "%s",
6771 __FUNCTION__,
6772 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
6773 return StructuredData::ObjectSP();
6774 }
6775
6776 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
6778 if (log) {
6779 if (json_sp) {
6780 StreamString json_str;
6781 json_sp->Dump(json_str, true);
6782 json_str.Flush();
6783 LLDB_LOGF(log,
6784 "ProcessGDBRemote::%s() "
6785 "received Async StructuredData packet: %s",
6786 __FUNCTION__, json_str.GetData());
6787 } else {
6788 LLDB_LOGF(log,
6789 "ProcessGDBRemote::%s"
6790 "() received StructuredData packet:"
6791 " parse failure",
6792 __FUNCTION__);
6793 }
6794 }
6795 return json_sp;
6796}
6797
6799 auto structured_data_sp = ParseStructuredDataPacket(data);
6800 if (structured_data_sp)
6801 RouteAsyncStructuredData(structured_data_sp);
6802}
6803
6805public:
6807 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
6808 "Tests packet speeds of various sizes to determine "
6809 "the performance characteristics of the GDB remote "
6810 "connection. ",
6811 nullptr),
6813 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
6814 "The number of packets to send of each varying size "
6815 "(default is 1000).",
6816 1000),
6817 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
6818 "The maximum number of bytes to send in a packet. Sizes "
6819 "increase in powers of 2 while the size is less than or "
6820 "equal to this option value. (default 1024).",
6821 1024),
6822 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
6823 "The maximum number of bytes to receive in a packet. Sizes "
6824 "increase in powers of 2 while the size is less than or "
6825 "equal to this option value. (default 1024).",
6826 1024),
6827 m_json(LLDB_OPT_SET_1, false, "json", 'j',
6828 "Print the output as JSON data for easy parsing.", false, true) {
6833 m_option_group.Finalize();
6834 }
6835
6837
6838 Options *GetOptions() override { return &m_option_group; }
6839
6840 void DoExecute(Args &command, CommandReturnObject &result) override {
6841 const size_t argc = command.GetArgumentCount();
6842 if (argc == 0) {
6843 ProcessGDBRemote *process =
6844 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
6845 .GetProcessPtr();
6846 if (process) {
6847 StreamSP output_stream_sp = result.GetImmediateOutputStream();
6848 if (!output_stream_sp)
6849 output_stream_sp = m_interpreter.GetDebugger().GetAsyncOutputStream();
6850 result.SetImmediateOutputStream(output_stream_sp);
6851
6852 const uint32_t num_packets =
6853 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
6854 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
6855 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
6856 const bool json = m_json.GetOptionValue().GetCurrentValue();
6857 const uint64_t k_recv_amount =
6858 4 * 1024 * 1024; // Receive amount in bytes
6859 process->GetGDBRemote().TestPacketSpeed(
6860 num_packets, max_send, max_recv, k_recv_amount, json,
6861 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
6863 return;
6864 }
6865 } else {
6866 result.AppendErrorWithFormat("'%s' takes no arguments",
6867 m_cmd_name.c_str());
6868 }
6870 }
6871
6872protected:
6878};
6879
6881private:
6882public:
6884 : CommandObjectParsed(interpreter, "process plugin packet history",
6885 "Dumps the packet history buffer. ", nullptr) {}
6886
6888
6889 void DoExecute(Args &command, CommandReturnObject &result) override {
6890 ProcessGDBRemote *process =
6891 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6892 if (process) {
6893 process->DumpPluginHistory(result.GetOutputStream());
6895 return;
6896 }
6898 }
6899};
6900
6902private:
6903public:
6906 interpreter, "process plugin packet xfer-size",
6907 "Maximum size that lldb will try to read/write one one chunk.",
6908 nullptr) {
6910 }
6911
6913
6914 void DoExecute(Args &command, CommandReturnObject &result) override {
6915 const size_t argc = command.GetArgumentCount();
6916 if (argc == 0) {
6917 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
6918 "amount to be transferred when "
6919 "reading/writing",
6920 m_cmd_name.c_str());
6921 return;
6922 }
6923
6924 ProcessGDBRemote *process =
6925 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6926 if (process) {
6927 const char *packet_size = command.GetArgumentAtIndex(0);
6928 errno = 0;
6929 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
6930 if (errno == 0 && user_specified_max != 0) {
6931 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
6933 return;
6934 }
6935 }
6937 }
6938};
6939
6941private:
6942public:
6944 : CommandObjectParsed(interpreter, "process plugin packet send",
6945 "Send a custom packet through the GDB remote "
6946 "protocol and print the answer. "
6947 "The packet header and footer will automatically "
6948 "be added to the packet prior to sending and "
6949 "stripped from the result.",
6950 nullptr) {
6952 }
6953
6955
6956 void DoExecute(Args &command, CommandReturnObject &result) override {
6957 const size_t argc = command.GetArgumentCount();
6958 if (argc == 0) {
6959 result.AppendErrorWithFormat(
6960 "'%s' takes a one or more packet content arguments",
6961 m_cmd_name.c_str());
6962 return;
6963 }
6964
6965 ProcessGDBRemote *process =
6966 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6967 if (process) {
6968 for (size_t i = 0; i < argc; ++i) {
6969 const char *packet_cstr = command.GetArgumentAtIndex(0);
6970 StringExtractorGDBRemote response;
6972 packet_cstr, response, process->GetInterruptTimeout());
6974 Stream &output_strm = result.GetOutputStream();
6975 output_strm.Printf(" packet: %s\n", packet_cstr);
6976 std::string response_str = std::string(response.GetStringRef());
6977
6978 if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
6979 response_str = process->HarmonizeThreadIdsForProfileData(response);
6980 }
6981
6982 if (response_str.empty())
6983 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6984 else
6985 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6986 }
6987 }
6988 }
6989};
6990
6992private:
6993public:
6995 : CommandObjectRaw(interpreter, "process plugin packet monitor",
6996 "Send a qRcmd packet through the GDB remote protocol "
6997 "and print the response. "
6998 "The argument passed to this command will be hex "
6999 "encoded into a valid 'qRcmd' packet, sent and the "
7000 "response will be printed.") {}
7001
7003
7004 void DoExecute(llvm::StringRef command,
7005 CommandReturnObject &result) override {
7006 if (command.empty()) {
7007 result.AppendErrorWithFormat("'%s' takes a command string argument",
7008 m_cmd_name.c_str());
7009 return;
7010 }
7011
7012 ProcessGDBRemote *process =
7013 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
7014 if (process) {
7015 StreamString packet;
7016 packet.PutCString("qRcmd,");
7017 packet.PutBytesAsRawHex8(command.data(), command.size());
7018
7019 StringExtractorGDBRemote response;
7020 Stream &output_strm = result.GetOutputStream();
7022 packet.GetString(), response, process->GetInterruptTimeout(),
7023 [&output_strm](llvm::StringRef output) { output_strm << output; });
7025 output_strm.Printf(" packet: %s\n", packet.GetData());
7026 const std::string &response_str = std::string(response.GetStringRef());
7027
7028 if (response_str.empty())
7029 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
7030 else
7031 output_strm.Printf("response: %s\n", response.GetStringRef().data());
7032 }
7033 }
7034};
7035
7037private:
7038public:
7040 : CommandObjectMultiword(interpreter, "process plugin packet",
7041 "Commands that deal with GDB remote packets.",
7042 nullptr) {
7044 "history",
7048 "send", CommandObjectSP(
7049 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
7051 "monitor",
7055 "xfer-size",
7058 LoadSubCommand("speed-test",
7060 interpreter)));
7061 }
7062
7064};
7065
7067public:
7070 interpreter, "process plugin",
7071 "Commands for operating on a ProcessGDBRemote process.",
7072 "process plugin <subcommand> [<subcommand-options>]") {
7074 "packet",
7076 }
7077
7079};
7080
7082 if (!m_command_sp)
7083 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
7084 GetTarget().GetDebugger().GetCommandInterpreter());
7085 return m_command_sp.get();
7086}
7087
7089 bool enable, bool is_expression_fork) {
7090 Log *log = GetLog(GDBRLog::Process);
7091
7092 // Resolve the expression-return sentinel address (_start) once. This is
7093 // the same address ThreadPlanCallFunction uses as the return trap.
7095 if (!enable && is_expression_fork) {
7096 if (auto entry = GetTarget().GetEntryPointAddress())
7097 entry_addr = entry->GetOpcodeLoadAddress(&GetTarget());
7098 }
7099
7100 GetBreakpointSiteList().ForEach([this, enable, entry_addr,
7101 log](BreakpointSite *bp_site) {
7102 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
7103 (bp_site->GetType() == BreakpointSite::eSoftware ||
7104 bp_site->GetType() == BreakpointSite::eExternal)) {
7105 // During expression evaluation, retain the expression-return trap
7106 // at _start in the forked child so it dies deterministically on
7107 // SIGTRAP rather than executing _start with a corrupted stack.
7108 if (entry_addr != LLDB_INVALID_ADDRESS &&
7109 bp_site->GetLoadAddress() == entry_addr) {
7110 LLDB_LOG(log,
7111 "DidForkSwitchSoftwareBreakpoints: retaining expression-"
7112 "return trap at {0:x} in forked child",
7113 bp_site->GetLoadAddress());
7114 return;
7115 }
7116 m_gdb_comm.SendGDBStoppointTypePacket(
7117 eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
7119 }
7120 });
7121}
7122
7124 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
7125 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
7126 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
7127 bp_site->GetType() == BreakpointSite::eHardware) {
7128 m_gdb_comm.SendGDBStoppointTypePacket(
7129 eBreakpointHardware, enable, bp_site->GetLoadAddress(),
7131 }
7132 });
7133 }
7134
7135 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
7136 addr_t addr = wp_res_sp->GetLoadAddress();
7137 size_t size = wp_res_sp->GetByteSize();
7138 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
7139 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, addr, size,
7141 }
7142}
7143
7145 bool is_expression_fork) {
7146 Log *log = GetLog(GDBRLog::Process);
7147
7148 // During expression evaluation, force follow-parent regardless of which
7149 // thread forked. The expression is running on the parent and following the
7150 // child would cause the expression thread to vanish (the child has different
7151 // thread IDs). Even if a *different* thread forks, switching to the child
7152 // would destroy the expression thread's process context.
7153 FollowForkMode follow_fork_mode = GetFollowForkMode();
7154 bool overrode_follow_mode = false;
7155 if (follow_fork_mode == eFollowChild &&
7156 GetModIDRef().IsRunningExpression()) {
7157 if (is_expression_fork) {
7158 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
7159 "to parent during expression evaluation");
7160 } else {
7161 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
7162 "to parent during expression evaluation. Child process "
7163 "{0} is available for manual attachment.",
7164 child_pid);
7165 }
7166 follow_fork_mode = eFollowParent;
7167 overrode_follow_mode = true;
7168 }
7169
7170 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
7171 // Any valid TID will suffice, thread-relevant actions will set a proper TID
7172 // anyway.
7173 lldb::tid_t parent_tid = m_thread_ids.front();
7174
7175 lldb::pid_t follow_pid, detach_pid;
7176 lldb::tid_t follow_tid, detach_tid;
7177
7178 switch (follow_fork_mode) {
7179 case eFollowParent:
7180 follow_pid = parent_pid;
7181 follow_tid = parent_tid;
7182 detach_pid = child_pid;
7183 detach_tid = child_tid;
7184 break;
7185 case eFollowChild:
7186 follow_pid = child_pid;
7187 follow_tid = child_tid;
7188 detach_pid = parent_pid;
7189 detach_tid = parent_tid;
7190 break;
7191 }
7192
7193 // Switch to the process that is going to be detached.
7194 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
7195 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
7196 return;
7197 }
7198
7199 // Disable all software breakpoints in the forked process.
7200 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7201 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
7202
7203 // Remove hardware breakpoints / watchpoints from parent process if we're
7204 // following child.
7205 if (follow_fork_mode == eFollowChild)
7207
7208 // Switch to the process that is going to be followed
7209 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
7210 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
7211 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
7212 return;
7213 }
7214
7215 LLDB_LOG(log, "Detaching process {0}", detach_pid);
7216 // When we overrode follow-child because of a concurrent expression, try to
7217 // keep the child stopped so the user can attach to it manually.
7218 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
7219 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
7220 if (error.Fail() && keep_stopped) {
7221 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach-and-stay-stopped not "
7222 "supported, falling back to normal detach");
7223 keep_stopped = false;
7224 error = m_gdb_comm.Detach(false, detach_pid);
7225 }
7226 if (error.Fail()) {
7227 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
7228 error.AsCString() ? error.AsCString() : "<unknown error>");
7229 return;
7230 }
7231
7232 // Notify the user via the async output channel when we overrode
7233 // follow-fork-mode for a non-expression fork during expression evaluation.
7234 if (overrode_follow_mode && !is_expression_fork) {
7235 StreamUP output_up =
7237 if (output_up) {
7238 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
7239 "'parent' because an expression is being evaluated.\n"
7240 "Child process %" PRIu64
7241 " has been detached%s.\n"
7242 "You can attach to it with: process attach -p %" PRIu64
7243 "\n",
7244 child_pid,
7245 keep_stopped ? " and stopped" : " (running)",
7246 child_pid);
7247 output_up->Flush();
7248 }
7249 }
7250
7251 // Hardware breakpoints/watchpoints are not inherited implicitly,
7252 // so we need to readd them if we're following child.
7253 if (follow_fork_mode == eFollowChild) {
7255 // Update our PID
7256 SetID(child_pid);
7257 }
7258}
7259
7261 bool is_expression_fork) {
7262 Log *log = GetLog(GDBRLog::Process);
7263
7264 LLDB_LOG(
7265 log,
7266 "ProcessGDBRemote::DidVFork() called for child_pid: {0}, child_tid {1}",
7267 child_pid, child_tid);
7269
7270 // See comment in DidFork(): force follow-parent during expression evaluation
7271 // regardless of which thread triggered the vfork.
7272 FollowForkMode follow_fork_mode = GetFollowForkMode();
7273 bool overrode_follow_mode = false;
7274 if (follow_fork_mode == eFollowChild &&
7275 GetModIDRef().IsRunningExpression()) {
7276 if (is_expression_fork) {
7277 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
7278 "to parent during expression evaluation");
7279 } else {
7280 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
7281 "to parent during expression evaluation. Child process "
7282 "{0} is available for manual attachment.",
7283 child_pid);
7284 }
7285 follow_fork_mode = eFollowParent;
7286 overrode_follow_mode = true;
7287 }
7288
7289 // Disable all software breakpoints for the duration of vfork.
7290 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7291 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
7292
7293 lldb::pid_t detach_pid;
7294 lldb::tid_t detach_tid;
7295
7296 switch (follow_fork_mode) {
7297 case eFollowParent:
7298 detach_pid = child_pid;
7299 detach_tid = child_tid;
7300 break;
7301 case eFollowChild:
7302 detach_pid = m_gdb_comm.GetCurrentProcessID();
7303 // Any valid TID will suffice, thread-relevant actions will set a proper TID
7304 // anyway.
7305 detach_tid = m_thread_ids.front();
7306
7307 // Switch to the parent process before detaching it.
7308 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
7309 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to set pid/tid");
7310 return;
7311 }
7312
7313 // Remove hardware breakpoints / watchpoints from the parent process.
7315
7316 // Switch to the child process.
7317 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
7318 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
7319 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to reset pid/tid");
7320 return;
7321 }
7322 break;
7323 }
7324
7325 LLDB_LOG(log, "Detaching process {0}", detach_pid);
7326 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
7327 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
7328 if (error.Fail() && keep_stopped) {
7329 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() detach-and-stay-stopped not "
7330 "supported, falling back to normal detach");
7331 keep_stopped = false;
7332 error = m_gdb_comm.Detach(false, detach_pid);
7333 }
7334 if (error.Fail()) {
7335 LLDB_LOG(log,
7336 "ProcessGDBRemote::DidVFork() detach packet send failed: {0}",
7337 error.AsCString() ? error.AsCString() : "<unknown error>");
7338 return;
7339 }
7340
7341 if (overrode_follow_mode && !is_expression_fork) {
7342 StreamUP output_up =
7344 if (output_up) {
7345 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
7346 "'parent' because an expression is being evaluated.\n"
7347 "Child process %" PRIu64
7348 " has been detached%s.\n"
7349 "You can attach to it with: process attach -p %" PRIu64
7350 "\n",
7351 child_pid,
7352 keep_stopped ? " and stopped" : " (running)",
7353 child_pid);
7354 output_up->Flush();
7355 }
7356 }
7357
7358 if (follow_fork_mode == eFollowChild) {
7359 // Update our PID
7360 SetID(child_pid);
7361 }
7362}
7363
7365 assert(m_vfork_in_progress_count > 0);
7367
7368 // Reenable all software breakpoints that were enabled before vfork.
7369 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7371}
7372
7374 // If we are following children, vfork is finished by exec (rather than
7375 // vforkdone that is submitted for parent).
7379 }
7381}
7382
7384 const BreakpointSiteToActionMap &site_to_action) {
7385 llvm::Error joined = llvm::Error::success();
7386 for (auto &[site, action] : site_to_action) {
7387 llvm::Error error = action == Process::BreakpointAction::Enable
7388 ? DoEnableBreakpointSite(*site)
7389 : DoDisableBreakpointSite(*site);
7390 joined = llvm::joinErrors(std::move(joined), std::move(error));
7391 }
7392 return joined;
7393}
7394
7395/// Parse a MultiBreakpoint response into per-request results.
7396/// Returns a vector of results: std::nullopt means OK, a uint8_t value is the
7397/// error code from an Exx response.
7398static llvm::SmallVector<std::optional<uint8_t>>
7399ParseMultiBreakpointResponse(llvm::StringRef response_str) {
7400 llvm::SmallVector<std::optional<uint8_t>> results;
7401
7404 parsed ? parsed->GetAsDictionary() : nullptr;
7405 StructuredData::Array *array = nullptr;
7406 if (dict)
7407 dict->GetValueForKeyAsArray("results", array);
7408 if (!array)
7409 return results;
7410
7411 array->ForEach([&results](StructuredData::Object *object) -> bool {
7412 llvm::StringRef token;
7413 if (auto *string = object->GetAsString())
7414 token = string->GetValue();
7415 if (token == "OK") {
7416 results.push_back(std::nullopt);
7417 return true;
7418 }
7419 if (token.size() != 3 || !token.starts_with("E")) {
7420 results.push_back(uint8_t(0xff));
7421 return true;
7422 }
7423 uint8_t error_code = 0;
7424 if (token.drop_front(1).getAsInteger(BASE_16, error_code))
7425 results.push_back(0xff);
7426 else
7427 results.push_back(error_code);
7428 return true;
7429 });
7430 return results;
7431}
7432
7433/// Determine the GDB stoppoint type for a breakpoint site by checking which
7434/// packet types the remote supports (for insertions), or by checking the site
7435/// type (for deletions).
7436static std::optional<GDBStoppointType>
7438 GDBRemoteCommunicationClient &gdb_comm) {
7439 if (insert) {
7440 if (!site.HardwareRequired() &&
7442 return eBreakpointSoftware;
7444 return eBreakpointHardware;
7445 return std::nullopt;
7446 }
7447
7448 switch (site.GetType()) {
7450 return eBreakpointSoftware;
7452 return eBreakpointHardware;
7454 return std::nullopt;
7455 }
7456 llvm_unreachable("unhandled BreakpointSite type");
7457}
7458
7459namespace {
7460struct BreakpointPacketInfo {
7461 BreakpointSite &site;
7462 size_t trap_opcode_size;
7463 GDBStoppointType type;
7464 bool is_enable;
7465};
7466
7467std::string to_string(const BreakpointPacketInfo &info) {
7468 char packet = info.is_enable ? 'Z' : 'z';
7469 return llvm::formatv("{0}{1},{2:x-},{3:x-}", packet,
7470 static_cast<int>(info.type), info.site.GetLoadAddress(),
7471 info.trap_opcode_size)
7472 .str();
7473}
7474} // namespace
7475
7477 const BreakpointSiteToActionMap &site_to_action) {
7478 if (site_to_action.empty())
7479 return llvm::Error::success();
7480 if (!m_gdb_comm.GetMultiBreakpointSupported())
7481 return UpdateBreakpointSitesNotBatched(site_to_action);
7482
7484
7485 std::vector<BreakpointPacketInfo> breakpoint_infos;
7486 for (auto [site, action] : site_to_action) {
7487 size_t trap_opcode_size = GetSoftwareBreakpointTrapOpcode(site.get());
7488 std::optional<GDBStoppointType> type =
7490
7491 if (!type) {
7492 LLDB_LOG(log, "MultiBreakpoint: site {0} at {1:x} can't be batched",
7493 site->GetID(), site->GetLoadAddress());
7494 return UpdateBreakpointSitesNotBatched(site_to_action);
7495 }
7496
7497 breakpoint_infos.push_back(
7498 {*site, trap_opcode_size, *type, action == BreakpointAction::Enable});
7499 }
7500
7501 StreamString stream;
7502 stream << "jMultiBreakpoint:";
7503
7504 auto args_array = std::make_shared<StructuredData::Array>();
7505 for (auto &bp_info : breakpoint_infos)
7506 args_array->AddStringItem(to_string(bp_info));
7507
7508 StructuredData::Dictionary packet_dict;
7509 packet_dict.AddItem("breakpoint_requests", args_array);
7510 packet_dict.Dump(stream, false);
7511
7512 StreamGDBRemote escaped_stream;
7513 escaped_stream.PutEscapedBytes(stream.GetString());
7514 llvm::Expected<StringExtractorGDBRemote> response =
7515 m_gdb_comm.SendPacketAndExpectResponse(escaped_stream.GetString(),
7517
7518 if (!response) {
7519 LLDB_LOG_ERROR(log, response.takeError(), "jMultiBreakpoint failed: {0}");
7520 return UpdateBreakpointSitesNotBatched(site_to_action);
7521 }
7522
7523 llvm::SmallVector<std::optional<uint8_t>> results =
7524 ParseMultiBreakpointResponse(response->GetStringRef());
7525
7526 // This is a protocol violation, do nothing.
7527 if (results.size() != breakpoint_infos.size())
7528 return llvm::createStringErrorV(
7529 "MultiBreakpoint response count mismatch (expected {0}, got {1})",
7530 site_to_action.size(), results.size());
7531
7532 llvm::Error joined = llvm::Error::success();
7533 for (auto [error_code, bp_info] :
7534 llvm::zip_equal(results, breakpoint_infos)) {
7535 BreakpointSite &site = bp_info.site;
7536 if (error_code) {
7537 auto error = llvm::createStringErrorV(
7538 "MultiBreakpoint: site {0} at {1:x} failed with E{2}",
7539 bp_info.site.GetID(), bp_info.site.GetLoadAddress(), error_code);
7540 joined = llvm::joinErrors(std::move(joined), std::move(error));
7541 continue;
7542 }
7543 SetBreakpointSiteEnabled(site, bp_info.is_enable);
7544 if (bp_info.is_enable)
7545 site.SetType(bp_info.type == eBreakpointHardware
7548 }
7549
7550 return joined;
7551}
static llvm::raw_ostream & error(Stream &strm)
static PluginProperties & GetGlobalPluginProperties()
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF_VERBOSE(log,...)
Definition Log.h:396
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_LOG_VERBOSE(log,...)
Definition Log.h:382
#define LLDB_PLUGIN_DEFINE(PluginName)
static PluginProperties & GetGlobalPluginProperties()
static const char *const s_async_json_packet_prefix
#define DEBUGSERVER_BASENAME
static size_t SplitCommaSeparatedRegisterNumberString(const llvm::StringRef &comma_separated_register_numbers, std::vector< uint32_t > &regnums, int base)
static const char * end_delimiter
static GDBStoppointType GetGDBStoppointType(const WatchpointResourceSP &wp_res_sp)
static StructuredData::ObjectSP ParseStructuredDataPacket(llvm::StringRef packet)
static std::string BinaryInformationLevelToJSONKey(BinaryInformationLevel info_level)
static uint64_t ComputeNumRangesMultiMemRead(uint64_t max_packet_size, llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges)
Returns the number of ranges that is safe to request using MultiMemRead while respecting max_packet_s...
static Status MemoryAccessError(llvm::StringRef access, lldb::addr_t addr, StringExtractorGDBRemote &response)
Returns the error for a failed memory access.
static std::optional< GDBStoppointType > GetStoppointType(BreakpointSite &site, bool insert, GDBRemoteCommunicationClient &gdb_comm)
Determine the GDB stoppoint type for a breakpoint site by checking which packet types the remote supp...
static FileSpec GetDebugserverPath(Platform &platform)
static llvm::SmallVector< std::optional< uint8_t > > ParseMultiBreakpointResponse(llvm::StringRef response_str)
Parse a MultiBreakpoint response into per-request results.
static const int end_delimiter_len
void * HANDLE
CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter)
~CommandObjectMultiwordProcessGDBRemote() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectProcessGDBRemotePacketHistory() override=default
CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter)
~CommandObjectProcessGDBRemotePacketMonitor() override=default
void DoExecute(llvm::StringRef command, CommandReturnObject &result) override
CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter)
CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter)
~CommandObjectProcessGDBRemotePacketSend() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectProcessGDBRemotePacketXferSize() override=default
void DoExecute(Args &command, CommandReturnObject &result) override
CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter)
~CommandObjectProcessGDBRemotePacket() override=default
CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter)
void DoExecute(Args &command, CommandReturnObject &result) override
~CommandObjectProcessGDBRemoteSpeedTest() override=default
CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter)
static constexpr lldb::pid_t AllProcesses
bool IsStopReply(uint32_t mask=StopReplyMask::Any) const
Classify packets from the stop-reply section of the GDB remote protocol.
std::optional< std::pair< lldb::pid_t, lldb::tid_t > > GetPidTid(lldb::pid_t default_pid)
void SetFilePos(uint32_t idx)
uint64_t GetHexMaxU64(bool little_endian, uint64_t fail_value)
bool GetNameColonValue(llvm::StringRef &name, llvm::StringRef &value)
uint64_t GetU64(uint64_t fail_value, int base=0)
size_t GetHexByteString(std::string &str)
uint8_t GetHexU8(uint8_t fail_value=0, bool set_eof_on_fail=true)
char GetChar(char fail_value='\0')
size_t GetHexBytes(llvm::MutableArrayRef< uint8_t > dest, uint8_t fail_fill_value)
uint64_t GetFilePos() const
llvm::StringRef GetStringRef() const
static lldb::ABISP FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch)
Definition ABI.cpp:27
A class which holds the metadata from a remote stub/corefile note about how many bits are used for ad...
void SetHighmemAddressableBits(uint32_t highmem_addressing_bits)
void SetAddressableBits(uint32_t addressing_bits)
When a single value is available for the number of bits.
void SetLowmemAddressableBits(uint32_t lowmem_addressing_bits)
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:375
void Clear()
Clears the object state.
Definition ArchSpec.cpp:558
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:465
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:768
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition ArchSpec.h:517
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:702
Core GetCore() const
Definition ArchSpec.h:456
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:568
A command line argument class.
Definition Args.h:33
static lldb::Encoding StringToEncoding(llvm::StringRef s, lldb::Encoding fail_value=lldb::eEncodingInvalid)
Definition Args.cpp:431
static uint32_t StringToGenericRegister(llvm::StringRef s)
Definition Args.cpp:441
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str, char quote_char='\0')
Replaces the argument value at index idx to arg_str if idx is a valid argument index.
Definition Args.cpp:347
const char * GetArgumentAtIndex(size_t idx) const
Gets the null-terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
Class that manages the actual breakpoint that will be inserted into the running program.
BreakpointSite::Type GetType() const
void SetType(BreakpointSite::Type type)
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandObjectMultiword(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectParsed(CommandInterpreter &interpreter, const char *name, const char *help=nullptr, const char *syntax=nullptr, uint32_t flags=0)
CommandObjectRaw(CommandInterpreter &interpreter, llvm::StringRef name, llvm::StringRef help="", llvm::StringRef syntax="", uint32_t flags=0)
void AddSimpleArgumentList(lldb::CommandArgumentType arg_type, ArgumentRepetitionType repetition_type=eArgRepeatPlain)
CommandInterpreter & m_interpreter
void SetStatus(lldb::ReturnStatus status)
void SetImmediateOutputStream(const lldb::StreamSP &stream_sp)
void AppendErrorWithFormat(const char *format,...) __attribute__((format(printf
lldb::StreamSP GetImmediateOutputStream() const
A subclass of DataBuffer that stores a data buffer on the heap.
An data extractor class.
lldb::StreamUP GetAsyncErrorStream()
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:230
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report warning events.
TargetGroupList & GetTargetGroupList()
Definition Debugger.h:232
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
lldb::StreamUP GetAsyncOutputStream()
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
ArtifactProviderID AddArtifactProvider(std::string name, ArtifactProvider provider)
Register provider to contribute file name.
void RemoveArtifactProvider(ArtifactProviderID id)
Unregister a provider. Thread-safe.
static Diagnostics & Instance()
static llvm::Expected< lldb::ModuleSP > LocateAndLoadBinary(Process *process, BinarySpec &bin_spec)
Find a binary and load it into a Target.
virtual lldb::ModuleSP LoadModuleAtAddress(const lldb_private::FileSpec &file, lldb::addr_t link_map_addr, lldb::addr_t base_addr, bool base_addr_is_offset)
Locates or creates a module given by file and updates/loads the resulting module at the virtual base ...
static DynamicLoader * FindPlugin(Process *process, llvm::StringRef plugin_name)
Find a dynamic loader plugin for a given process.
const void * GetBytes() const
Definition Event.cpp:140
static const EventDataBytes * GetEventDataFromEvent(const Event *event_ptr)
Definition Event.cpp:161
size_t GetByteSize() const
Definition Event.cpp:144
lldb::ProcessSP GetProcessSP() const
Get accessor that creates a strong reference from the weak process reference contained in this object...
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
Action GetAction() const
Get the type of action.
Definition FileAction.h:59
const FileSpec & GetFileSpec() const
Get the file specification for open actions.
A file collection class.
void Append(const FileSpec &file)
Append a FileSpec object to the list.
size_t GetSize() const
Get the number of files in the file list.
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void Clear()
Clears the object state.
Definition FileSpec.cpp:265
static const char * DEV_NULL
Definition FileSystem.h:32
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
ValueType Get() const
Get accessor for all flags.
Definition Flags.h:40
static Environment GetEnvironment()
static void Kill(lldb::pid_t pid, int signo)
static lldb::ListenerSP MakeListener(llvm::StringRef name)
Definition Listener.cpp:373
void add(const LoadedModuleInfo &mod)
std::vector< LoadedModuleInfo > m_list
void PutCString(const char *cstr)
Definition Log.cpp:162
lldb::offset_t GetBlocksize() const
lldb::SymbolSharedCacheUse GetSharedCacheBinaryLoading() const
A collection class for Module objects.
Definition ModuleList.h:139
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
static ModuleListProperties & GetGlobalModuleListProperties()
bool Remove(const lldb::ModuleSP &module_sp, bool notify=true)
Remove a module from the module list.
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
void FindSymbolsWithNameAndType(llvm::StringRef name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
void FindFunctions(llvm::StringRef name, lldb::FunctionNameType name_type_mask, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list) const
size_t GetSize() const
Gets the size of the module list.
void ForEach(std::function< IterationAction(const lldb::ModuleSP &module_sp)> const &callback) const
Applies 'callback' to each module in this ModuleList.
void Dump(Stream &strm) const
Definition ModuleSpec.h:200
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:92
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1235
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:448
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:47
@ eTypeExecutable
A normal executable.
Definition ObjectFile.h:56
@ eTypeDebugInfo
An object file that contains only debug information.
Definition ObjectFile.h:58
@ eTypeStubLibrary
A library that can be linked against but not used for execution.
Definition ObjectFile.h:66
@ eTypeObjectFile
An intermediate object file.
Definition ObjectFile.h:62
@ eTypeDynamicLinker
The platform's dynamic linker executable.
Definition ObjectFile.h:60
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition ObjectFile.h:54
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition ObjectFile.h:64
@ eTypeJIT
JIT code that has symbols, sections and possibly debug info.
Definition ObjectFile.h:68
void SetPlatformName(const char *platform_name)
A command line option parsing protocol class.
Definition Options.h:58
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition Platform.h:81
virtual FileSpec LocateExecutable(const char *basename)
Find a support executable that may not live within in the standard locations related to LLDB.
Definition Platform.h:868
virtual Status Unlink(const FileSpec &file_spec)
bool IsRemote() const
Definition Platform.h:560
virtual Status GetFile(const FileSpec &source, const FileSpec &destination)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool CreateSettingForProcessPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static lldb::OptionValuePropertiesSP GetSettingForProcessPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool UnregisterPlugin(ABICreateInstance create_callback)
An address in a process, qualified by an address space.
lldb::addr_t GetValue() const
std::optional< lldb::tid_t > GetThreadID() const
lldb::addr_space_t GetAddressSpace() const
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
uint32_t GetUserID() const
Definition ProcessInfo.h:48
Environment & GetEnvironment()
Definition ProcessInfo.h:86
void SetUserID(uint32_t uid)
Definition ProcessInfo.h:56
const char * GetLaunchEventData() const
const FileAction * GetFileActionForFD(int fd) const
void SetMonitorProcessCallback(Host::MonitorChildProcessCallback callback)
void SetLaunchInSeparateProcessGroup(bool separate)
const FileSpec & GetWorkingDirectory() const
FollowForkMode GetFollowForkMode() const
Definition Process.cpp:431
std::chrono::seconds GetInterruptTimeout() const
Definition Process.cpp:388
A plug-in interface definition class for debugging a process.
Definition Process.h:370
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3605
std::mutex m_process_input_reader_mutex
Definition Process.h:3606
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1609
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1987
lldb::pid_t GetID() const
Returns the pid of the process or LLDB_INVALID_PROCESS_ID if there is no known pid.
Definition Process.h:555
ThreadList & GetThreadList()
Definition Process.h:2398
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7343
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:487
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:4080
void SetSTDIOFileDescriptor(int file_descriptor, std::optional< int > secondary_fd=std::nullopt)
Associates a file descriptor with the process' STDIO handling and configures an asynchronous reading ...
Definition Process.cpp:5152
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6555
virtual llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > DoReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buffer)
Reads each range individually via ReadMemoryFromInferior, bypassing the memory cache.
Definition Process.cpp:2174
void ResumePrivateStateThread()
Definition Process.cpp:4338
void MapSupportedStructuredDataPlugins(const StructuredData::Array &supported_type_names)
Loads any plugins associated with asynchronous structured data and maps the relevant supported type n...
Definition Process.cpp:6798
std::map< lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp > BreakpointSiteToActionMap
Definition Process.h:2309
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3267
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition Process.h:3555
lldb::StateType GetPrivateState() const
Definition Process.h:3512
void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled=true)
Definition Process.h:3816
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3593
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition Process.cpp:2728
StopPointSiteList< lldb_private::WatchpointResource > m_watchpoint_resource_list
Watchpoint resources currently in use.
Definition Process.h:3585
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
Definition Process.cpp:1714
std::vector< AddressSpaceInfo > m_address_spaces
A list of address spaces for this process.
Definition Process.h:3576
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:5046
std::shared_ptr< void > InferiorInterruptGuard
Definition Process.h:2316
bool HasAssignedIndexIDToThread(uint64_t sb_thread_id)
Definition Process.cpp:1306
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:4090
void UpdateThreadListIfNeeded()
Definition Process.cpp:1168
bool IsValid() const
Return whether this object is valid (i.e.
Definition Process.h:590
virtual void DidExec()
Called after a process re-execs itself.
Definition Process.cpp:6488
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:5060
lldb::UnixSignalsSP m_unix_signals_sp
Definition Process.h:3603
lldb::tid_t m_interrupt_tid
Definition Process.h:3635
void AddCacheData(lldb::addr_t addr, const lldb::WritableDataBufferSP &data_buffer_sp)
Cache memory, restoring the original bytes under any breakpoint.
Definition Process.cpp:1890
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1907
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
Definition Process.cpp:6865
virtual bool IsAlive()
Check if a process is still alive.
Definition Process.cpp:1143
ThreadList m_thread_list_real
The threads for this process as are known to the protocol we are debugging with.
Definition Process.h:3561
lldb::StateType m_last_broadcast_state
Definition Process.h:3667
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:560
friend class Target
Definition Process.h:376
uint32_t AssignIndexIDToThread(uint64_t thread_id)
Definition Process.cpp:1311
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition Process.cpp:1085
uint32_t GetAddressByteSize() const
Definition Process.cpp:4094
uint32_t GetStopID() const
Definition Process.h:1526
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1449
llvm::Expected< AddressSpaceInfo > GetAddressSpaceInfo(llvm::StringRef address_space_name)
Definition Process.cpp:7366
lldb::StateType GetPublicState() const
Definition Process.h:3506
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:601
void SetSTDIOPseudoTerminal(PseudoTerminal &pty)
Associates the primary side of pty with the process' STDIO handling.
Definition Process.cpp:5182
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3563
const lldb::UnixSignalsSP & GetUnixSignals()
Definition Process.cpp:4085
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition Process.h:3530
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
Locate the memory region that contains load_addr.
Definition Process.cpp:6729
friend class DynamicLoader
Definition Process.h:373
size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site)
Definition Process.cpp:1900
friend class Debugger
Definition Process.h:372
const ProcessModID & GetModIDRef() const
Definition Process.h:1524
ThreadedCommunication m_stdio_communication
Definition Process.h:3607
friend class ThreadList
Definition Process.h:377
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1271
lldb::OptionValuePropertiesSP GetValueProperties() const
A pseudo terminal helper class.
llvm::Error OpenFirstAvailablePrimary(int oflag)
Open the first available pseudo terminal.
@ invalid_fd
Invalid file descriptor value.
int GetPrimaryFileDescriptor() const
The primary file descriptor accessor.
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
std::string GetSecondaryName() const
Get the name of the secondary pseudo terminal.
std::vector< Enumerator > Enumerators
const Enumerators & GetEnumerators() const
unsigned GetSizeInBits() const
Get size of the field in bits. Will always be at least 1.
uint64_t GetMaxValue() const
The maximum unsigned value that could be contained in this field.
virtual std::optional< uint64_t > GetByteSize() const
Return this type's fixed size in bytes, if it has one.
virtual StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, lldb_private::Status &error)
virtual StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, lldb_private::Status &error)
Status CompleteSending(lldb::pid_t child_pid)
Definition Socket.cpp:83
shared_fd_t GetSendableFD()
Definition Socket.h:54
static llvm::Expected< Pair > CreatePair(std::optional< SocketProtocol > protocol=std::nullopt)
Definition Socket.cpp:238
An error handling class.
Definition Status.h:118
llvm::Error takeError()
Definition Status.h:170
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
static lldb::StopInfoSP CreateStopReasonWithMachException(Thread &thread, uint32_t exc_type, uint32_t exc_data_count, uint64_t exc_code, uint64_t exc_sub_code, uint64_t exc_sub_sub_code, bool pc_already_adjusted=true, bool adjust_pc_if_needed=false)
static lldb::StopInfoSP CreateStopReasonToTrace(Thread &thread)
static lldb::StopInfoSP CreateStopReasonVFork(Thread &thread, lldb::pid_t child_pid, lldb::tid_t child_tid)
static lldb::StopInfoSP CreateStopReasonWithInterrupt(Thread &thread, int signo, const char *description)
static lldb::StopInfoSP CreateStopReasonWithSignal(Thread &thread, int signo, const char *description=nullptr, std::optional< int > code=std::nullopt)
static lldb::StopInfoSP CreateStopReasonFork(Thread &thread, lldb::pid_t child_pid, lldb::tid_t child_tid)
static lldb::StopInfoSP CreateStopReasonVForkDone(Thread &thread)
static lldb::StopInfoSP CreateStopReasonWithWatchpointID(Thread &thread, lldb::break_id_t watch_id, bool silently_continue=false)
static lldb::StopInfoSP CreateStopReasonWithException(Thread &thread, const char *description)
static lldb::StopInfoSP CreateStopReasonWithBreakpointSiteID(Thread &thread, lldb::break_id_t break_id)
static lldb::StopInfoSP CreateStopReasonHistoryBoundary(Thread &thread, const char *description)
static lldb::StopInfoSP CreateStopReasonDyld(Thread &thread, const char *description=nullptr)
static lldb::StopInfoSP CreateStopReasonProcessorTrace(Thread &thread, const char *description)
static lldb::StopInfoSP CreateStopReasonWithExec(Thread &thread)
void ForEach(std::function< void(StopPointSite *)> const &callback)
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
lldb::break_id_t GetID() const
virtual lldb::addr_t GetLoadAddress() const
int PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition GDBRemote.cpp:31
const char * GetData() const
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition Stream.cpp:418
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
size_t PutBytesAsRawHex8(const void *src, size_t src_len, lldb::ByteOrder src_byte_order=lldb::eByteOrderInvalid, lldb::ByteOrder dst_byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:391
ObjectSP GetItemAtIndex(size_t idx) const
bool ForEach(std::function< bool(Object *object)> const &foreach_callback) const
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
ObjectSP GetValueForKey(llvm::StringRef key) const
bool HasKey(llvm::StringRef key) const
void AddItem(llvm::StringRef key, ObjectSP value_sp)
bool GetValueForKeyAsArray(llvm::StringRef key, Array *&result) const
void ForEach(std::function< bool(llvm::StringRef key, Object *object)> const &callback) const
void Dump(lldb_private::Stream &s, bool pretty_print=true) const
uint64_t GetUnsignedIntegerValue(uint64_t fail_value=0)
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
static ObjectSP ParseJSON(llvm::StringRef json_text)
std::shared_ptr< Array > ArraySP
Integer< uint64_t > UnsignedInteger
Defines a list of symbol context objects.
Defines a symbol context baton that can be handed other debug core functions.
A plug-in interface definition class for system runtimes.
virtual void AddThreadExtendedInfoPacketHints(lldb_private::StructuredData::ObjectSP dict)
Add key-value pairs to the StructuredData dictionary object with information debugserver may need whe...
A group that accepts a CPU target as its first member, followed by accelerator targets.
Definition TargetGroup.h:97
lldb::TargetGroupSP CreateTargetGroup(llvm::StringRef description)
Create and register a target group.
bool DeleteTargetGroup(const lldb::TargetGroupSP &group_sp)
Remove group_sp from this list.
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
bool DeleteTarget(lldb::TargetSP &target_sp)
Delete a Target object from the list.
Module * GetExecutableModulePointer()
Definition Target.cpp:1668
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:457
Debugger & GetDebugger() const
Definition Target.h:1378
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1825
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1648
lldb::PlatformSP GetPlatform()
Definition Target.h:2053
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition Target.cpp:528
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1295
const ArchSpec & GetArchitecture() const
Definition Target.h:1337
@ eBroadcastBitNewTargetCreated
Definition Target.h:618
void RebuildModuleListWithExecutable(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Clear the module list and rebuild it around a new main executable.
Definition Target.cpp:1691
bool MergeArchitecture(const ArchSpec &arch_spec)
Definition Target.cpp:1916
void AddThreadSortedByIndexID(const lldb::ThreadSP &thread_sp)
static llvm::Expected< HostThread > LaunchThread(llvm::StringRef name, std::function< lldb::thread_result_t()> thread_function, size_t min_stack_byte_size=0)
uint32_t GetSize(bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
lldb::ThreadSP RemoveThreadByProtocolID(lldb::tid_t tid, bool can_update=true)
Represents UUID's of various sizes.
Definition UUID.h:27
bool SetFromStringRef(llvm::StringRef str)
Definition UUID.cpp:101
bool IsValid() const
Definition UUID.h:69
static lldb::UnixSignalsSP Create(const ArchSpec &arch)
static std::vector< lldb::WatchpointResourceSP > AtomizeWatchpointRequest(lldb::addr_t addr, size_t size, bool read, bool write, WatchpointHardwareFeature supported_features, ArchSpec &arch)
Convert a user's watchpoint request into an array of memory regions, each region watched by one hardw...
static bool XMLEnabled()
Definition XML.cpp:83
XMLNode GetRootElement(const char *required_name=nullptr)
Definition XML.cpp:65
bool ParseMemory(const char *xml, size_t xml_length, const char *url="untitled.xml")
Definition XML.cpp:54
void ForEachChildElement(NodeCallback const &callback) const
Definition XML.cpp:169
llvm::StringRef GetName() const
Definition XML.cpp:268
bool GetElementText(std::string &text) const
Definition XML.cpp:278
std::string GetAttributeValue(const char *name, const char *fail_value=nullptr) const
Definition XML.cpp:135
bool NameIs(const char *name) const
Definition XML.cpp:314
void ForEachChildElementWithName(const char *name, NodeCallback const &callback) const
Definition XML.cpp:177
XMLNode FindFirstChildElementWithName(const char *name) const
Definition XML.cpp:328
void ForEachAttribute(AttributeCallback const &callback) const
Definition XML.cpp:186
PacketResult SendPacketAndReceiveResponseWithOutputSupport(llvm::StringRef payload, StringExtractorGDBRemote &response, std::chrono::seconds interrupt_timeout, llvm::function_ref< void(llvm::StringRef)> output_callback)
PacketResult SendPacketAndWaitForResponse(llvm::StringRef payload, StringExtractorGDBRemote &response, std::chrono::seconds interrupt_timeout=std::chrono::seconds(0), bool sync_on_timeout=true)
lldb::StateType SendContinuePacketAndWaitForResponse(ContinueDelegate &delegate, const UnixSignals &signals, llvm::StringRef payload, std::chrono::seconds interrupt_timeout, StringExtractorGDBRemote &response)
llvm::Expected< std::string > ReadExtFeature(llvm::StringRef object, llvm::StringRef annex)
void TestPacketSpeed(const uint32_t num_packets, uint32_t max_send, uint32_t max_recv, uint64_t recv_amount, bool json, Stream &strm)
std::unordered_map< lldb::tid_t, StructuredData::Dictionary * > m_thread_dicts
Each thread's dictionary in m_json_sp, by thread ID.
StructuredData::Dictionary * FindThread(lldb::tid_t tid) const
The dictionary of thread tid, or null if the reply has none.
ThreadInfos(StructuredData::ObjectSP json_sp)
Index json_sp, which must not be null, by thread ID.
Status FlashErase(lldb::addr_t addr, size_t size)
Status DisableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true) override
llvm::SmallVector< llvm::MutableArrayRef< uint8_t > > DoReadMemoryRanges(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges, llvm::MutableArrayRef< uint8_t > buf) override
Override of DoReadMemoryRanges that uses MultiMemRead to perform this operation in a single packet.
static ThreadInfosSP IndexThreadInfos(StructuredData::ObjectSP json_sp)
Index a "jstopinfo" or "jThreadsInfo" reply by thread ID.
static bool AcceleratorBreakpointHitCallback(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
Breakpoint callback invoked when an accelerator-plugin-requested breakpoint is hit.
Status DoConnectRemote(llvm::StringRef remote_url) override
Attach to a remote system via a URL.
void HandleAsyncStructuredDataPacket(llvm::StringRef data) override
Process asynchronously-received structured data.
llvm::Error DoDisableBreakpointSite(BreakpointSite &bp_site)
Disable a single breakpoint site directly by sending the appropriate z packet or restoring the origin...
std::vector< std::unique_ptr< RegisterType > > m_register_types
Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info)
virtual std::shared_ptr< ThreadGDBRemote > CreateThread(lldb::tid_t tid)
StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address, lldb::addr_t image_count) override
Retrieve the list of shared libraries that are loaded for this process This method is used on pre-mac...
llvm::Error HandleAcceleratorActions(const AcceleratorActions &actions)
Handle a set of actions requested by an accelerator plugin.
lldb::StateType SetThreadStopInfo(StringExtractor &stop_packet)
static void MonitorDebugserverProcess(std::weak_ptr< ProcessGDBRemote > process_wp, lldb::pid_t pid, int signo, int exit_status)
StructuredData::ObjectSP GetSharedCacheInfo() override
Status DisableBreakpointSite(BreakpointSite *bp_site) override
Status EnableWatchpoint(lldb::WatchpointSP wp_sp, bool notify=true) override
Status DoSignal(int signal) override
Sends a process a UNIX signal signal.
Status DoDeallocateMemory(lldb::addr_t ptr) override
Actually deallocate memory in the process.
bool ParsePythonTargetDefinition(const FileSpec &target_definition_fspec)
llvm::Error UpdateBreakpointSitesNotBatched(const BreakpointSiteToActionMap &site_to_action)
bool StopNoticingNewThreads() override
Call this to turn off the stop & notice new threads mode.
static bool NewThreadNotifyBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid, bool is_expression_fork=false) override
Called after a reported fork.
void DumpPluginHistory(Stream &s) override
The underlying plugin might store the low-level communication history for this session.
Guarded< StructuredData::ObjectSP, std::mutex > m_shared_cache_info
Shared cache image list from the "jGetSharedCacheInfo" packet.
Status DoDetach(bool keep_stopped) override
Detaches from a running or stopped process.
lldb::addr_t DoAllocateMemory(size_t size, uint32_t permissions, Status &error) override
Actually allocate memory in the process.
std::optional< bool > DoGetWatchpointReportedAfter() override
Provide an override value in the subclass for lldb's CPU-based logic for whether watchpoint exception...
void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid, bool is_expression_fork=false) override
Called after a reported vfork.
std::optional< uint32_t > GetWatchpointSlotCount() override
Get the number of watchpoints supported by this target.
llvm::Expected< std::vector< uint8_t > > DoReadMemoryTags(lldb::addr_t addr, size_t len, int32_t type) override
Does the final operation to read memory tags.
llvm::DenseMap< ModuleCacheKey, ModuleSpec, ModuleCacheInfo > m_cached_module_specs
Status DoWillAttachToProcessWithID(lldb::pid_t pid) override
Called before attaching to a process.
void DidForkSwitchSoftwareBreakpoints(bool enable, bool is_expression_fork=false)
Guarded< ThreadInfosSP, std::mutex > m_jthreadsinfo
Full stop info, expedited registers and memory for all threads, from the "jThreadsInfo" packet.
Status DoResume(lldb::RunDirection direction) override
Resumes all of a process's threads as configured using the Thread run control functions.
std::unordered_map< lldb::tid_t, size_t > m_thread_id_positions
The position of each ID in m_thread_ids, for FindThreadIDIndex.
Status DoGetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &region_info) override
DoGetMemoryRegionInfo is called by GetMemoryRegionInfo after it has removed non address bits from loa...
size_t UpdateThreadIDsFromStopReplyThreadsValue(llvm::StringRef value)
Status GetFileLoadAddress(const FileSpec &file, bool &is_loaded, lldb::addr_t &load_addr) override
Try to find the load address of a file.
void DidLaunch() override
Called after launching a process.
void SetUserSpecifiedMaxMemoryTransferSize(uint64_t user_specified_max)
void AddRemoteRegisters(std::vector< DynamicRegisterInfo::Register > &registers, const ArchSpec &arch_to_use)
void HandleAsyncStdout(llvm::StringRef out) override
std::map< uint32_t, std::string > ExpeditedRegisterMap
llvm::Error TraceStop(const TraceStopRequest &request) override
Stop tracing a live process or its threads.
StructuredData::ObjectSP GetExtendedInfoForThread(lldb::tid_t tid)
llvm::Error DoEnableBreakpointSite(BreakpointSite &bp_site)
Enable a single breakpoint site by trying Z0 (software), then Z1 (hardware), then manual memory write...
lldb::ThreadSP HandleThreadAsyncInterrupt(uint8_t signo, const std::string &description) override
Handle thread specific async interrupt and return the original thread that requested the async interr...
llvm::Expected< LoadedModuleInfoList > GetLoadedModuleList() override
Query remote GDBServer for a detailed loaded library list.
bool AcceleratorBreakpointHit(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
llvm::Error HandleAcceleratorConnection(const AcceleratorActions &actions)
Create a new target for an accelerator and connect it to the GDB server described by the action's con...
Status DoAttachToProcessWithID(lldb::pid_t pid, const ProcessAttachInfo &attach_info) override
Attach to an existing process using a process ID.
InferiorInterruptGuard InterruptInferior() override
Interrupt the inferior and return a guard that lets it resume when the last reference is released.
Status EstablishConnectionIfNeeded(const ProcessInfo &process_info)
llvm::Error UpdateBreakpointSites(const BreakpointSiteToActionMap &site_to_action) override
bool GetThreadStopInfoFromJSON(ThreadGDBRemote *thread, const ThreadInfosSP &thread_infos_sp)
std::shared_ptr< const ThreadInfos > ThreadInfosSP
Status DoHalt(bool &caused_stop) override
Halts a running process.
llvm::Expected< TraceSupportedResponse > TraceSupported() override
Get the processor tracing type supported for this process.
std::map< std::string, int64_t > m_processed_accelerator_actions
Tracks the last action identifier handled per accelerator plugin so the same actions are not processe...
llvm::Error TraceStart(const llvm::json::Value &request) override
Start tracing a process or its threads.
void ParseExpeditedRegisters(ExpeditedRegisterMap &expedited_register_map, lldb::ThreadSP thread_sp)
size_t DoReadMemory(const ProcessAddress &process_addr, void *buf, size_t size, Status &error) override
Actually do the reading of memory from a process.
void WillPublicStop() override
Called when the process is about to broadcast a public stop.
void SetExitStatusFromStopReply(StringExtractorGDBRemote &response)
std::optional< size_t > FindThreadIDIndex(lldb::tid_t tid)
bool StartNoticingNewThreads() override
Call this to set the lldb in the mode where it breaks on new thread creations, and then auto-restarts...
DynamicLoader * GetDynamicLoader() override
Get the dynamic loader plug-in for this process.
void RemoveNewThreadBreakpoints()
Remove the breakpoints associated with thread creation from the Target.
ArchSpec GetSystemArchitecture() override
Get the system architecture for this process.
Status ConfigureStructuredData(llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) override
Configure asynchronous structured data feature.
bool SupportsReverseDirection() override
Reports whether this process supports reverse execution.
void DidExec() override
Called after a process re-execs itself.
size_t PutSTDIN(const char *buf, size_t buf_size, Status &error) override
Puts data into this process's STDIN.
Status DoAttachToProcessWithName(const char *process_name, const ProcessAttachInfo &attach_info) override
Attach to an existing process using a partial process name.
StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos_sender(StructuredData::ObjectSP args)
bool CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) override
Check if a plug-in instance can debug the file in module.
void SetThreadPc(const lldb::ThreadSP &thread_sp, uint64_t index)
bool DoCanAllocateMemory() override
Determines whether DoAllocateMemory is expected to succeed, without running code in the process.
Status ConnectToDebugserver(llvm::StringRef host_port)
void SetUnixSignals(const lldb::UnixSignalsSP &signals_sp)
void RefreshStateAfterStop() override
Currently called as part of ShouldStop.
std::optional< StringExtractorGDBRemote > m_last_stop_packet
CommandObject * GetPluginCommandObject() override
Return a multi-word command object that can be used to expose plug-in specific commands.
size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, Status &error) override
Actually do the writing of memory to a process.
Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override
Launch a new process.
void DidVForkDone() override
Called after reported vfork completion.
std::string HarmonizeThreadIdsForProfileData(StringExtractorGDBRemote &inputStringExtractor)
bool GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use, std::string xml_filename, std::vector< DynamicRegisterInfo::Register > &registers)
Status DoWillAttachToProcessWithName(const char *process_name, bool wait_for_launch) override
Called before attaching to a process.
std::pair< std::string, std::string > ModuleCacheKey
bool SupportsMemoryTagging() override
Check whether the process supports memory tagging.
size_t UpdateThreadPCsFromStopReplyThreadsValue(llvm::StringRef value)
llvm::VersionTuple GetHostOSVersion() override
Sometimes the connection to a process can detect the host OS version that the process is running on.
llvm::Expected< StringExtractorGDBRemote > SendMultiMemReadPacket(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges)
std::map< uint64_t, uint32_t > m_thread_id_to_used_usec_map
Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type, const std::vector< uint8_t > &tags) override
Does the final operation to write memory tags.
Guarded< ThreadInfosSP, std::mutex > m_jstopinfo
Stop info caches filled at a stop and reset by WillResume, which runs on another thread.
llvm::Error ParseMultiMemReadPacket(llvm::StringRef response_str, llvm::MutableArrayRef< uint8_t > buffer, unsigned expected_num_ranges, llvm::SmallVectorImpl< llvm::MutableArrayRef< uint8_t > > &memory_regions)
llvm::Expected< std::vector< uint8_t > > TraceGetBinaryData(const TraceGetBinaryDataRequest &request) override
Get binary data given a trace technology and a data identifier.
llvm::Error HandleAcceleratorBreakpoints(const AcceleratorActions &actions)
Set the breakpoints requested by an accelerator plugin as internal breakpoints with a callback that n...
Status EnableBreakpointSite(BreakpointSite *bp_site) override
void ModulesDidLoad(ModuleList &module_list) override
ProcessGDBRemote(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Status WillResume() override
Called before resuming to a process.
lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file, lldb::addr_t link_map, lldb::addr_t base_addr, bool value_is_offset)
void SetLastStopPacket(const StringExtractorGDBRemote &response)
Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries) override
static std::chrono::milliseconds GetPacketTestDelay()
llvm::Error LoadModules() override
Sometimes processes know how to retrieve and load shared libraries.
void HandleAsyncMisc(llvm::StringRef data) override
lldb::addr_t GetImageInfoAddress() override
Get the image information address for the current process.
bool DoUpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) override
Update the thread list following process plug-in's specific logic.
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
void PrefetchModuleSpecs(llvm::ArrayRef< FileSpec > module_file_specs, const llvm::Triple &triple) override
StructuredData::ObjectSP GetDynamicLoaderProcessState() override
bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec) override
Try to fetch the module specification for a module with the given file name and architecture.
Status DoWillLaunch(Module *module) override
Called before launching to a process.
void DidAttach(ArchSpec &process_arch) override
Called after attaching a process.
llvm::Expected< bool > SaveCore(llvm::StringRef outfile) override
Save core dump into the specified file.
std::optional< Diagnostics::ArtifactProviderID > m_diagnostics_artifact_id
Registration for the packet-history diagnostics provider, if enabled.
llvm::Expected< std::string > TraceGetState(llvm::StringRef type) override
Get the current tracing state of the process and its threads.
bool IsAlive() override
Check if a process is still alive.
void SetQueueLibdispatchQueueAddress(lldb::addr_t dispatch_queue_t) override
void SetQueueInfo(std::string &&queue_name, lldb::QueueKind queue_kind, uint64_t queue_serial, lldb::addr_t dispatch_queue_t, lldb_private::LazyBool associated_with_libdispatch_queue)
void SetNewlyAddedBinaries(const std::vector< lldb::addr_t > &added_binaries)
void SetThreadDispatchQAddr(lldb::addr_t thread_dispatch_qaddr)
lldb::RegisterContextSP GetRegisterContext() override
void SetDetailedBinariesInfo(StructuredData::ObjectSP &detailed_info)
void SetAssociatedWithLibdispatchQueue(lldb_private::LazyBool associated_with_libdispatch_queue) override
bool PrivateSetRegisterValue(uint32_t reg, llvm::ArrayRef< uint8_t > data)
#define LLDB_INVALID_SITE_ID
#define LLDB_OPT_SET_1
#define UINT64_MAX
#define LLDB_INVALID_WATCH_ID
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_THREAD_ID
#define LLDB_OPT_SET_ALL
#define UNUSED_IF_ASSERT_DISABLED(x)
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
#define LLDB_INVALID_REGNUM
#define LLDB_INVALID_PROCESS_ID
#define LLDB_DEFAULT_ADDRESS_SPACE_ID
#define LLDB_REGNUM_GENERIC_PC
lldb::ByteOrder InlHostByteOrder()
Definition Endian.h:25
std::vector< DynamicRegisterInfo::Register > GetFallbackRegisters(const ArchSpec &arch_to_use)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
bool InferiorCallMunmap(Process *proc, lldb::addr_t addr, lldb::addr_t length)
bool StateIsRunningState(lldb::StateType state)
Check if a state represents a state where the process or thread is running.
Definition State.cpp:68
@ eMmapFlagsPrivate
Definition Platform.h:46
bool InferiorCallMmap(Process *proc, lldb::addr_t &allocated_addr, lldb::addr_t addr, lldb::addr_t length, unsigned prot, unsigned flags, lldb::addr_t fd, lldb::addr_t offset)
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
const char * GetPermissionsAsCString(uint32_t permissions)
Definition State.cpp:44
void DumpProcessGDBRemotePacketHistory(void *p, const char *path)
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::BreakpointSite > BreakpointSiteSP
RunDirection
Execution directions.
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::CommandObject > CommandObjectSP
void * thread_result_t
Definition lldb-types.h:62
ConnectionStatus
Connection Status Types.
@ eConnectionStatusSuccess
Success.
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
@ eFormatCString
Null-terminated C strings.
@ eFormatCharArray
Print characters with no single quotes, used for character arrays that can contain non printable char...
@ eFormatInstruction
Disassemble an opcode.
@ eFormatVectorOfChar
@ eFormatVectorOfUInt64
@ eFormatVoid
Do not print this.
@ eFormatVectorOfFloat16
@ eFormatVectorOfSInt64
@ eFormatComplex
Floating point complex type.
@ eFormatHexFloat
ISO C99 hex float string.
@ eFormatBytesWithASCII
@ eFormatOSType
OS character codes encoded into an integer 'PICT' 'text' etc...
@ eFormatAddressInfo
Describe what an address points to (func + offset with file/line, symbol + offset,...
@ eFormatVectorOfUInt128
@ eFormatVectorOfUInt8
@ eFormatVectorOfFloat32
@ eFormatVectorOfSInt32
@ eFormatVectorOfSInt8
@ eFormatVectorOfUInt16
@ eFormatHexUppercase
@ eFormatVectorOfFloat64
@ eFormatCharPrintable
Only printable characters, '.' if not printable.
@ eFormatComplexInteger
Integer complex type.
@ eFormatVectorOfSInt16
@ eFormatFloat128
Disambiguate between 128-bit long double (which uses eFormatFloat) and __float128 (which uses eFormat...
@ eFormatVectorOfUInt32
std::shared_ptr< lldb_private::Platform > PlatformSP
StateType
Process and Thread States.
@ eStateUnloaded
Process is object is valid, but not currently loaded.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateDetached
Process has been detached and can't be examined.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateSuspended
Process or thread is in a suspended state as far as the debugger is concerned while other processes o...
@ eStateRunning
Process or thread is running and can't be examined.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
@ eStateStepping
Process or thread is in the process of stepping and can not be examined.
@ eStateCrashed
Process or thread has crashed and can be examined.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eSymbolSharedCacheUseInferiorSharedCacheOnly
@ eSymbolSharedCacheUseHostAndInferiorSharedCache
std::shared_ptr< lldb_private::Stream > StreamSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
Encoding
Register encoding definitions.
@ eEncodingIEEE754
float
@ eEncodingVector
vector registers
@ eEncodingUint
unsigned integer
@ eEncodingSint
signed integer
std::shared_ptr< lldb_private::Event > EventSP
@ eReturnStatusFailed
@ eReturnStatusSuccessFinishResult
uint64_t pid_t
Definition lldb-types.h:84
QueueKind
Queue type.
@ eArgTypeUnsignedInteger
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::Listener > ListenerSP
int32_t watch_id_t
Definition lldb-types.h:89
std::shared_ptr< lldb_private::WatchpointResource > WatchpointResourceSP
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::StopInfo > StopInfoSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
BinaryInformationLevel
When the Process plugin can retrieve information about all binaries loaded in the target process,...
@ eBinaryInformationLevelAddrName
@ eBinaryInformationLevelAddrNameUUID
@ eBinaryInformationLevelFull
@ eBinaryInformationLevelAddrOnly
uint64_t addr_space_t
Definition lldb-types.h:81
std::shared_ptr< lldb_private::Target > TargetSP
std::unique_ptr< lldb_private::Stream > StreamUP
std::shared_ptr< lldb_private::RegisterContext > RegisterContextSP
uint64_t tid_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Module > ModuleSP
@ eRegisterKindGeneric
insn ptr reg, stack ptr reg, etc not specific to any particular target
@ eRegisterKindProcessPlugin
num used by the process plugin - e.g.
Actions to be performed in the native process on behalf of an accelerator plugin.
std::vector< AcceleratorBreakpointInfo > breakpoints
New breakpoints to set. Nothing to set if this is empty.
int64_t identifier
Unique identifier for this action within the plugin.
std::string plugin_name
Unique name identifying the accelerator plugin.
std::optional< AcceleratorConnectionInfo > connect_info
If set, the client should create a new target and connect to the accelerator GDB server described her...
std::string session_name
Human-readable label for the accelerator target.
Sent by the client when a plugin-requested breakpoint is hit.
int64_t identifier
Unique breakpoint ID used to identify this breakpoint in the BreakpointWasHit callback.
std::vector< std::string > symbol_names
Symbol names whose values should be supplied when the breakpoint is hit.
std::optional< AcceleratorBreakpointByAddress > by_address
Breakpoint by load address.
std::optional< AcceleratorBreakpointByName > by_name
Breakpoint by function name.
Information the client needs to connect to an accelerator GDB server.
std::string triple
Target triple for the accelerator target.
bool synchronous
If true, connect synchronously: the client blocks until the accelerator process is connected and stop...
std::optional< std::string > exe_path
Path to the executable to use when creating the accelerator target.
std::string connect_url
Connection URL the client should connect to (as in "process connect<url>").
std::string platform_name
Name of the platform to select when creating the accelerator target.
A binary to find and load into a Target.
lldb::addr_t value
Address where the binary should be loaded, or read out of memory.
UUID uuid
UUID of the binary to be loaded.
bool is_main_executable
Whether this is the process' main executable.
bool force_symbol_search
Allow the search to do a possibly expensive external search for the ObjectFile and/or SymbolFile.
bool set_address_in_target
Whether the address of the binary should be set in the Target if it is added.
bool notify
Whether ModulesDidLoad should be called once the binary has been added to the Target.
bool value_is_offset
A flag indicating that value is an address, or an offset to be applied to the file addresses.
Options used by Module::FindFunctions.
Definition Module.h:68
bool include_inlines
Include inlined functions.
Definition Module.h:72
bool include_symbols
Include the symbol table.
Definition Module.h:70
static Status ToFormat(const char *s, lldb::Format &format, size_t *byte_size_ptr)
BaseType GetRangeBase() const
Definition RangeMap.h:45
SizeType GetByteSize() const
Definition RangeMap.h:87
void SetRangeBase(BaseType b)
Set the start value for the range, and keep the same size.
Definition RangeMap.h:48
BaseType GetRangeEnd() const
Definition RangeMap.h:78
void SetByteSize(SizeType s)
Definition RangeMap.h:89
jLLDBTraceGetBinaryData gdb-remote packet
jLLDBTraceStop gdb-remote packet
#define O_NOCTTY
#define SIGTRAP