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.SetString(value);
544 } else if (name == "alt-name") {
545 reg_info.alt_name.SetString(value);
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.SetString(value);
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
896 {
897 // Scope for the scoped timeout object
899 std::chrono::seconds(10));
900
901 // Since we can't send argv0 separate from the executable path, we need to
902 // make sure to use the actual executable path found in the launch_info...
903 Args args = launch_info.GetArguments();
904 if (FileSpec exe_file = launch_info.GetExecutableFile()) {
905 const llvm::Triple &remote_triple =
907 if (remote_triple.getOS() != llvm::Triple::UnknownOS) {
908 FileSpec remote_exe_file(exe_file.GetPath(/*denormalize=*/false),
909 remote_triple);
911 0, remote_exe_file.GetPath(/*denormalize=*/true));
912 } else {
914 exe_file.GetPath(/*denormalize=*/true));
915 }
916 }
917 if (llvm::Error err = m_gdb_comm.LaunchProcess(args)) {
919 "Cannot launch '{0}': {1}", args.GetArgumentAtIndex(0),
920 llvm::fmt_consume(std::move(err)));
921 } else {
922 SetID(m_gdb_comm.GetCurrentProcessID());
923 }
924 }
925
927 LLDB_LOGF(log, "failed to connect to debugserver: %s",
928 error.AsCString());
930 return error;
931 }
932
934 if (m_gdb_comm.GetStopReply(response)) {
935 SetLastStopPacket(response);
936
937 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
938
939 if (process_arch.IsValid()) {
940 GetTarget().MergeArchitecture(process_arch);
941 } else {
942 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
943 if (host_arch.IsValid())
944 GetTarget().MergeArchitecture(host_arch);
945 }
946
948
949 if (!disable_stdio) {
951#ifdef _WIN32
953#else
955#endif
956 }
957#ifdef _WIN32
958 else if (m_stdin_forward) {
959 // No client-side PTY FD on Windows.
960 std::lock_guard<std::mutex> guard(m_process_input_reader_mutex);
963 std::make_shared<IOHandlerProcessSTDIOWindows>(this);
964 }
965#endif
966 }
967 }
968 } else {
969 LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
970 }
971 return error;
972}
973
974Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
976 // Only connect if we have a valid connect URL
978
979 if (!connect_url.empty()) {
980 LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
981 connect_url.str().c_str());
982 std::unique_ptr<ConnectionFileDescriptor> conn_up(
984 if (conn_up) {
985 const uint32_t max_retry_count = 50;
986 uint32_t retry_count = 0;
987 while (!m_gdb_comm.IsConnected()) {
988 if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
989 m_gdb_comm.SetConnection(std::move(conn_up));
990 break;
991 }
992
993 retry_count++;
994
995 if (retry_count >= max_retry_count)
996 break;
997
998 std::this_thread::sleep_for(std::chrono::milliseconds(100));
999 }
1000 }
1001 }
1002
1003 if (!m_gdb_comm.IsConnected()) {
1004 if (error.Success())
1005 error = Status::FromErrorString("not connected to remote gdb server");
1006 return error;
1007 }
1008
1009 // We always seem to be able to open a connection to a local port so we need
1010 // to make sure we can then send data to it. If we can't then we aren't
1011 // actually connected to anything, so try and do the handshake with the
1012 // remote GDB server and make sure that goes alright.
1013 if (!m_gdb_comm.HandshakeWithServer(&error)) {
1014 m_gdb_comm.Disconnect();
1015 if (error.Success())
1016 error = Status::FromErrorString("not connected to remote gdb server");
1017 return error;
1018 }
1019
1020 m_gdb_comm.GetEchoSupported();
1021 m_gdb_comm.GetThreadSuffixSupported();
1022 m_gdb_comm.GetListThreadsInStopReplySupported();
1023 m_gdb_comm.GetHostInfo();
1024 m_gdb_comm.GetVContSupported("c");
1025 m_gdb_comm.GetVAttachOrWaitSupported();
1026 m_gdb_comm.EnableErrorStringInPacket();
1027
1028 // Empty unless the server advertised "address-spaces+" in qSupported.
1029 m_address_spaces = m_gdb_comm.GetAddressSpaces();
1030
1031 // First dispatch any commands from the platform:
1032 auto handle_cmds = [&] (const Args &args) -> void {
1033 for (const Args::ArgEntry &entry : args) {
1034 StringExtractorGDBRemote response;
1035 m_gdb_comm.SendPacketAndWaitForResponse(
1036 entry.c_str(), response);
1037 }
1038 };
1039
1040 PlatformSP platform_sp = GetTarget().GetPlatform();
1041 if (platform_sp) {
1042 handle_cmds(platform_sp->GetExtraStartupCommands());
1043 }
1044
1045 // Then dispatch any process commands:
1046 handle_cmds(GetExtraStartupCommands());
1047
1048 return error;
1049}
1050
1052 Log *log = GetLog(GDBRLog::Process);
1054
1055 // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
1056 // qProcessInfo as it will be more specific to our process.
1057
1058 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
1059 if (remote_process_arch.IsValid()) {
1060 process_arch = remote_process_arch;
1061 LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
1062 process_arch.GetArchitectureName(),
1063 process_arch.GetTriple().getTriple());
1064 } else {
1065 process_arch = m_gdb_comm.GetHostArchitecture();
1066 LLDB_LOG(log,
1067 "gdb-remote did not have process architecture, using gdb-remote "
1068 "host architecture {0} {1}",
1069 process_arch.GetArchitectureName(),
1070 process_arch.GetTriple().getTriple());
1071 }
1072
1073 AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits();
1074 SetAddressableBitMasks(addressable_bits);
1075
1076 if (process_arch.IsValid()) {
1077 const ArchSpec &target_arch = GetTarget().GetArchitecture();
1078 if (target_arch.IsValid()) {
1079 LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
1080 target_arch.GetArchitectureName(),
1081 target_arch.GetTriple().getTriple());
1082
1083 // If the remote host is ARM and we have apple as the vendor, then
1084 // ARM executables and shared libraries can have mixed ARM
1085 // architectures.
1086 // You can have an armv6 executable, and if the host is armv7, then the
1087 // system will load the best possible architecture for all shared
1088 // libraries it has, so we really need to take the remote host
1089 // architecture as our defacto architecture in this case.
1090
1091 if ((process_arch.GetMachine() == llvm::Triple::arm ||
1092 process_arch.GetMachine() == llvm::Triple::thumb) &&
1093 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
1094 GetTarget().SetArchitecture(process_arch);
1095 LLDB_LOG(log,
1096 "remote process is ARM/Apple, "
1097 "setting target arch to {0} {1}",
1098 process_arch.GetArchitectureName(),
1099 process_arch.GetTriple().getTriple());
1100 } else {
1101 // Fill in what is missing in the triple
1102 const llvm::Triple &remote_triple = process_arch.GetTriple();
1103 llvm::Triple new_target_triple = target_arch.GetTriple();
1104 if (new_target_triple.getVendorName().size() == 0) {
1105 new_target_triple.setVendor(remote_triple.getVendor());
1106
1107 if (new_target_triple.getOSName().size() == 0) {
1108 new_target_triple.setOS(remote_triple.getOS());
1109
1110 if (new_target_triple.getEnvironmentName().size() == 0)
1111 new_target_triple.setEnvironment(remote_triple.getEnvironment());
1112 }
1113
1114 ArchSpec new_target_arch = target_arch;
1115 new_target_arch.SetTriple(new_target_triple);
1116 GetTarget().SetArchitecture(new_target_arch);
1117 }
1118 }
1119
1120 LLDB_LOG(log,
1121 "final target arch after adjustments for remote architecture: "
1122 "{0} {1}",
1123 target_arch.GetArchitectureName(),
1124 target_arch.GetTriple().getTriple());
1125 } else {
1126 // The target doesn't have a valid architecture yet, set it from the
1127 // architecture we got from the remote GDB server
1128 GetTarget().SetArchitecture(process_arch);
1129 }
1130 }
1131
1132 // Target and Process are reasonably initailized;
1133 // load any binaries we have metadata for / set load address.
1136
1137 // Find out which StructuredDataPlugins are supported by the debug monitor.
1138 // These plugins transmit data over async $J packets.
1139 if (StructuredData::Array *supported_packets =
1140 m_gdb_comm.GetSupportedStructuredDataPlugins())
1141 MapSupportedStructuredDataPlugins(*supported_packets);
1142
1143 // If connected to LLDB ("native-signals+"), use signal defs for
1144 // the remote platform. If connected to GDB, just use the standard set.
1145 if (!m_gdb_comm.UsesNativeSignals()) {
1146 SetUnixSignals(std::make_shared<GDBRemoteSignals>());
1147 } else {
1148 PlatformSP platform_sp = GetTarget().GetPlatform();
1149 if (platform_sp && platform_sp->IsConnected())
1150 SetUnixSignals(platform_sp->GetUnixSignals());
1151 else
1152 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
1153 }
1154
1155 // Ask any accelerator plugins installed in lldb-server for their initial
1156 // actions (e.g. breakpoints to set in the native process).
1157 llvm::Expected<std::vector<AcceleratorActions>> init_actions =
1158 m_gdb_comm.GetAcceleratorInitializeActions();
1159 if (!init_actions) {
1160 LLDB_LOG_ERROR(log, init_actions.takeError(),
1161 "failed to get accelerator initialize actions: {0}");
1162 } else {
1163 for (const AcceleratorActions &actions : *init_actions) {
1164 if (llvm::Error error = HandleAcceleratorActions(actions))
1165 LLDB_LOG_ERROR(log, std::move(error),
1166 "failed to handle accelerator actions: {0}");
1167 }
1168 }
1169}
1170
1172 // The remote stub may know about the "main binary" in
1173 // the context of a firmware debug session, and can
1174 // give us a UUID and an address/slide of where the
1175 // binary is loaded in memory.
1176 UUID standalone_uuid;
1177 addr_t standalone_value;
1178 bool standalone_value_is_offset;
1179 if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value,
1180 standalone_value_is_offset)) {
1181 if (standalone_uuid.IsValid()) {
1183 bin_spec.uuid = standalone_uuid;
1184 bin_spec.value = standalone_value;
1185 bin_spec.value_is_offset = standalone_value_is_offset;
1186 bin_spec.force_symbol_search = true;
1187 bin_spec.notify = true;
1188 bin_spec.set_address_in_target = true;
1189 bin_spec.is_main_executable = true;
1190 llvm::Expected<ModuleSP> module =
1191 DynamicLoader::LocateAndLoadBinary(this, bin_spec);
1192 if (!module)
1194 << llvm::toString(module.takeError()) << "\n";
1195 }
1196 }
1197
1198 // The remote stub may know about a list of binaries to
1199 // force load into the process -- a firmware type situation
1200 // where multiple binaries are present in virtual memory,
1201 // and we are only given the addresses of the binaries.
1202 // Not intended for use with userland debugging, when we use
1203 // a DynamicLoader plugin that knows how to find the loaded
1204 // binaries, and will track updates as binaries are added.
1205
1206 std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
1207 if (bin_addrs.size()) {
1208 for (addr_t addr : bin_addrs) {
1209 const bool notify = true;
1210 // First see if this is a special platform
1211 // binary that may determine the DynamicLoader and
1212 // Platform to be used in this Process and Target.
1213 if (GetTarget()
1214 .GetDebugger()
1215 .GetPlatformList()
1216 .LoadPlatformBinaryAndSetup(this, addr, notify))
1217 continue;
1218
1219 // Second manually load this binary into the Target.
1221 bin_spec.value = addr;
1222 bin_spec.force_symbol_search = true;
1223 bin_spec.notify = notify;
1224 bin_spec.set_address_in_target = true;
1225 llvm::Expected<ModuleSP> module =
1226 DynamicLoader::LocateAndLoadBinary(this, bin_spec);
1227 if (!module)
1229 << llvm::toString(module.takeError()) << "\n";
1230 }
1231 }
1232}
1233
1235 ModuleSP module_sp = GetTarget().GetExecutableModule();
1236 if (!module_sp)
1237 return;
1238
1239 std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1240 if (!offsets)
1241 return;
1242
1243 bool is_uniform =
1244 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1245 offsets->offsets.size();
1246 if (!is_uniform)
1247 return; // TODO: Handle non-uniform responses.
1248
1249 bool changed = false;
1250 module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1251 /*value_is_offset=*/true, changed);
1252 if (changed) {
1253 ModuleList list;
1254 list.Append(module_sp);
1255 m_process->GetTarget().ModulesDidLoad(list);
1256 }
1257}
1258
1260 ArchSpec process_arch;
1261 DidLaunchOrAttach(process_arch);
1262}
1263
1265 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1266 Log *log = GetLog(GDBRLog::Process);
1267 Status error;
1268
1269 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1270
1271 // Clear out and clean up from any current state
1272 Clear();
1273 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1274 error = EstablishConnectionIfNeeded(attach_info);
1275 if (error.Success()) {
1276 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1277
1278 char packet[64];
1279 const int packet_len =
1280 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1281 SetID(attach_pid);
1282 auto data_sp =
1283 std::make_shared<EventDataBytes>(llvm::StringRef(packet, packet_len));
1284 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1285 } else
1286 SetExitStatus(-1, error.AsCString());
1287 }
1288
1289 return error;
1290}
1291
1293 const char *process_name, const ProcessAttachInfo &attach_info) {
1294 Status error;
1295 // Clear out and clean up from any current state
1296 Clear();
1297
1298 if (process_name && process_name[0]) {
1299 error = EstablishConnectionIfNeeded(attach_info);
1300 if (error.Success()) {
1301 StreamString packet;
1302
1303 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1304
1305 if (attach_info.GetWaitForLaunch()) {
1306 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1307 packet.PutCString("vAttachWait");
1308 } else {
1309 if (attach_info.GetIgnoreExisting())
1310 packet.PutCString("vAttachWait");
1311 else
1312 packet.PutCString("vAttachOrWait");
1313 }
1314 } else
1315 packet.PutCString("vAttachName");
1316 packet.PutChar(';');
1317 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1320
1321 auto data_sp = std::make_shared<EventDataBytes>(packet.GetString());
1322 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1323
1324 } else
1325 SetExitStatus(-1, error.AsCString());
1326 }
1327 return error;
1328}
1329
1330llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1331 return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
1332}
1333
1335 return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1336}
1337
1338llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1339 return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1340}
1341
1342llvm::Expected<std::string>
1343ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1344 return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
1345}
1346
1347llvm::Expected<std::vector<uint8_t>>
1349 return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1350}
1351
1353 // When we exit, disconnect from the GDB server communications
1354 m_gdb_comm.Disconnect();
1355}
1356
1358 // If you can figure out what the architecture is, fill it in here.
1359 process_arch.Clear();
1360 DidLaunchOrAttach(process_arch);
1361}
1362
1364 m_continue_c_tids.clear();
1365 m_continue_C_tids.clear();
1366 m_continue_s_tids.clear();
1367 m_continue_S_tids.clear();
1368 m_jstopinfo.Lock()->reset();
1369 m_jthreadsinfo.Lock()->reset();
1370 m_shared_cache_info.Lock()->reset();
1371 return Status();
1372}
1373
1375 return m_gdb_comm.GetReverseStepSupported() ||
1376 m_gdb_comm.GetReverseContinueSupported();
1377}
1378
1380 Status error;
1381 Log *log = GetLog(GDBRLog::Process);
1382 LLDB_LOGF(log, "ProcessGDBRemote::Resume(%s)",
1383 direction == RunDirection::eRunForward ? "" : "reverse");
1384
1385 ListenerSP listener_sp(
1386 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1387 if (listener_sp->StartListeningForEvents(
1389 listener_sp->StartListeningForEvents(
1392
1393 const size_t num_threads = GetThreadList().GetSize();
1394
1395 StreamString continue_packet;
1396 bool continue_packet_error = false;
1397 // Number of threads continuing with "c", i.e. continuing without a signal
1398 // to deliver.
1399 const size_t num_continue_c_tids = m_continue_c_tids.size();
1400 // Number of threads continuing with "C", i.e. continuing with a signal to
1401 // deliver.
1402 const size_t num_continue_C_tids = m_continue_C_tids.size();
1403 // Number of threads continuing with "s", i.e. single-stepping.
1404 const size_t num_continue_s_tids = m_continue_s_tids.size();
1405 // Number of threads continuing with "S", i.e. single-stepping with a signal
1406 // to deliver.
1407 const size_t num_continue_S_tids = m_continue_S_tids.size();
1408 if (direction == RunDirection::eRunForward &&
1409 m_gdb_comm.HasAnyVContSupport()) {
1410 std::string pid_prefix;
1411 if (m_gdb_comm.GetMultiprocessSupported())
1412 pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1413
1414 if (num_continue_c_tids == num_threads ||
1415 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1416 m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1417 // All threads are continuing
1418 if (m_gdb_comm.GetMultiprocessSupported())
1419 continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1420 else
1421 continue_packet.PutCString("c");
1422 } else {
1423 continue_packet.PutCString("vCont");
1424
1425 if (!m_continue_c_tids.empty()) {
1426 if (m_gdb_comm.GetVContSupported("c")) {
1427 for (tid_collection::const_iterator
1428 t_pos = m_continue_c_tids.begin(),
1429 t_end = m_continue_c_tids.end();
1430 t_pos != t_end; ++t_pos)
1431 continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1432 } else
1433 continue_packet_error = true;
1434 }
1435
1436 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1437 if (m_gdb_comm.GetVContSupported("C")) {
1438 for (tid_sig_collection::const_iterator
1439 s_pos = m_continue_C_tids.begin(),
1440 s_end = m_continue_C_tids.end();
1441 s_pos != s_end; ++s_pos)
1442 continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1443 pid_prefix, s_pos->first);
1444 } else
1445 continue_packet_error = true;
1446 }
1447
1448 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1449 if (m_gdb_comm.GetVContSupported("s")) {
1450 for (tid_collection::const_iterator
1451 t_pos = m_continue_s_tids.begin(),
1452 t_end = m_continue_s_tids.end();
1453 t_pos != t_end; ++t_pos)
1454 continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1455 } else
1456 continue_packet_error = true;
1457 }
1458
1459 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1460 if (m_gdb_comm.GetVContSupported("S")) {
1461 for (tid_sig_collection::const_iterator
1462 s_pos = m_continue_S_tids.begin(),
1463 s_end = m_continue_S_tids.end();
1464 s_pos != s_end; ++s_pos)
1465 continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1466 pid_prefix, s_pos->first);
1467 } else
1468 continue_packet_error = true;
1469 }
1470
1471 if (continue_packet_error)
1472 continue_packet.Clear();
1473 }
1474 } else
1475 continue_packet_error = true;
1476
1477 if (direction == RunDirection::eRunForward && continue_packet_error) {
1478 // Either no vCont support, or we tried to use part of the vCont packet
1479 // that wasn't supported by the remote GDB server. We need to try and
1480 // make a simple packet that can do our continue.
1481 if (num_continue_c_tids > 0) {
1482 if (num_continue_c_tids == num_threads) {
1483 // All threads are resuming...
1484 m_gdb_comm.SetCurrentThreadForRun(-1);
1485 continue_packet.PutChar('c');
1486 continue_packet_error = false;
1487 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1488 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1489 // Only one thread is continuing
1490 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1491 continue_packet.PutChar('c');
1492 continue_packet_error = false;
1493 }
1494 }
1495
1496 if (continue_packet_error && num_continue_C_tids > 0) {
1497 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1498 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1499 num_continue_S_tids == 0) {
1500 const int continue_signo = m_continue_C_tids.front().second;
1501 // Only one thread is continuing
1502 if (num_continue_C_tids > 1) {
1503 // More that one thread with a signal, yet we don't have vCont
1504 // support and we are being asked to resume each thread with a
1505 // signal, we need to make sure they are all the same signal, or we
1506 // can't issue the continue accurately with the current support...
1507 if (num_continue_C_tids > 1) {
1508 continue_packet_error = false;
1509 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1510 if (m_continue_C_tids[i].second != continue_signo)
1511 continue_packet_error = true;
1512 }
1513 }
1514 if (!continue_packet_error)
1515 m_gdb_comm.SetCurrentThreadForRun(-1);
1516 } else {
1517 // Set the continue thread ID
1518 continue_packet_error = false;
1519 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1520 }
1521 if (!continue_packet_error) {
1522 // Add threads continuing with the same signo...
1523 continue_packet.Printf("C%2.2x", continue_signo);
1524 }
1525 }
1526 }
1527
1528 if (continue_packet_error && num_continue_s_tids > 0) {
1529 if (num_continue_s_tids == num_threads) {
1530 // All threads are resuming...
1531 m_gdb_comm.SetCurrentThreadForRun(-1);
1532
1533 continue_packet.PutChar('s');
1534
1535 continue_packet_error = false;
1536 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1537 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1538 // Only one thread is stepping
1539 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1540 continue_packet.PutChar('s');
1541 continue_packet_error = false;
1542 }
1543 }
1544
1545 if (!continue_packet_error && num_continue_S_tids > 0) {
1546 if (num_continue_S_tids == num_threads) {
1547 const int step_signo = m_continue_S_tids.front().second;
1548 // Are all threads trying to step with the same signal?
1549 continue_packet_error = false;
1550 if (num_continue_S_tids > 1) {
1551 for (size_t i = 1; i < num_threads; ++i) {
1552 if (m_continue_S_tids[i].second != step_signo)
1553 continue_packet_error = true;
1554 }
1555 }
1556 if (!continue_packet_error) {
1557 // Add threads stepping with the same signo...
1558 m_gdb_comm.SetCurrentThreadForRun(-1);
1559 continue_packet.Printf("S%2.2x", step_signo);
1560 }
1561 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1562 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1563 // Only one thread is stepping with signal
1564 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1565 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1566 continue_packet_error = false;
1567 }
1568 }
1569 }
1570
1571 if (direction == RunDirection::eRunReverse) {
1572 if (num_continue_s_tids > 0 || num_continue_S_tids > 0) {
1573 if (!m_gdb_comm.GetReverseStepSupported()) {
1574 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1575 "support reverse-stepping");
1577 "target does not support reverse-stepping");
1578 }
1579
1580 if (num_continue_S_tids > 0) {
1581 LLDB_LOGF(
1582 log,
1583 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1585 "can't deliver signals while running in reverse");
1586 }
1587
1588 if (num_continue_s_tids > 1) {
1589 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: can't step multiple "
1590 "threads in reverse");
1592 "can't step multiple threads while reverse-stepping");
1593 }
1594
1595 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1596 continue_packet.PutCString("bs");
1597 } else {
1598 if (!m_gdb_comm.GetReverseContinueSupported()) {
1599 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1600 "support reverse-continue");
1602 "target does not support reverse execution of processes");
1603 }
1604
1605 if (num_continue_C_tids > 0) {
1606 LLDB_LOGF(
1607 log,
1608 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1610 "can't deliver signals while running in reverse");
1611 }
1612
1613 // All threads continue whether requested or not ---
1614 // we can't change how threads ran in the past.
1615 continue_packet.PutCString("bc");
1616 }
1617
1618 continue_packet_error = false;
1619 }
1620
1621 if (continue_packet_error) {
1623 "can't make continue packet for this resume");
1624 } else {
1625 EventSP event_sp;
1626 if (!m_async_thread.IsJoinable()) {
1628 "Trying to resume but the async thread is dead.");
1629 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1630 "async thread is dead.");
1631 return error;
1632 }
1633
1634 auto data_sp =
1635 std::make_shared<EventDataBytes>(continue_packet.GetString());
1636 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1637
1638 if (!listener_sp->GetEvent(event_sp, ResumeTimeout())) {
1639 error = Status::FromErrorString("Resume timed out.");
1640 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1641 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1643 "Broadcast continue, but the async thread was "
1644 "killed before we got an ack back.");
1645 LLDB_LOGF(log,
1646 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1647 "async thread was killed before we got an ack back.");
1648 return error;
1649 }
1650 }
1651 }
1652
1653 return error;
1654}
1655
1657 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1658 m_thread_ids.clear();
1659 m_thread_pcs.clear();
1660}
1661
1663 llvm::StringRef value) {
1664 m_thread_ids.clear();
1665 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1666 StringExtractorGDBRemote thread_ids{value};
1667
1668 do {
1669 auto pid_tid = thread_ids.GetPidTid(pid);
1670 if (pid_tid && pid_tid->first == pid) {
1671 lldb::tid_t tid = pid_tid->second;
1672 if (tid != LLDB_INVALID_THREAD_ID &&
1674 m_thread_ids.push_back(tid);
1675 }
1676 } while (thread_ids.GetChar() == ',');
1677
1678 return m_thread_ids.size();
1679}
1680
1682 llvm::StringRef value) {
1683 m_thread_pcs.clear();
1684 for (llvm::StringRef x : llvm::split(value, ',')) {
1686 if (llvm::to_integer(x, pc, 16))
1687 m_thread_pcs.push_back(pc);
1688 }
1689 return m_thread_pcs.size();
1690}
1691
1693 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1694
1695 StructuredData::ObjectSP threads_info_sp = *m_jthreadsinfo.Lock();
1696 if (threads_info_sp) {
1697 // If we have the JSON threads info, we can get the thread list from that
1698 StructuredData::Array *thread_infos = threads_info_sp->GetAsArray();
1699 if (thread_infos && thread_infos->GetSize() > 0) {
1700 m_thread_ids.clear();
1701 m_thread_pcs.clear();
1702 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1703 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1704 if (thread_dict) {
1705 // Set the thread stop info from the JSON dictionary
1706 SetThreadStopInfo(thread_dict);
1708 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1709 m_thread_ids.push_back(tid);
1710 }
1711 return true; // Keep iterating through all thread_info objects
1712 });
1713 }
1714 if (!m_thread_ids.empty())
1715 return true;
1716 } else {
1717 // See if we can get the thread IDs from the current stop reply packets
1718 // that might contain a "threads" key/value pair
1719
1720 if (m_last_stop_packet) {
1721 // Get the thread stop info
1723 const llvm::StringRef stop_info_str = stop_info.GetStringRef();
1724
1725 m_thread_pcs.clear();
1726 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1727 if (thread_pcs_pos != llvm::StringRef::npos) {
1728 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1729 const size_t end = stop_info_str.find(';', start);
1730 if (end != llvm::StringRef::npos) {
1731 llvm::StringRef value = stop_info_str.substr(start, end - start);
1733 }
1734 }
1735
1736 const size_t threads_pos = stop_info_str.find(";threads:");
1737 if (threads_pos != llvm::StringRef::npos) {
1738 const size_t start = threads_pos + strlen(";threads:");
1739 const size_t end = stop_info_str.find(';', start);
1740 if (end != llvm::StringRef::npos) {
1741 llvm::StringRef value = stop_info_str.substr(start, end - start);
1743 return true;
1744 }
1745 }
1746 }
1747 }
1748
1749 bool sequence_mutex_unavailable = false;
1750 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1751 if (sequence_mutex_unavailable) {
1752 return false; // We just didn't get the list
1753 }
1754 return true;
1755}
1756
1758 ThreadList &new_thread_list) {
1759 // locker will keep a mutex locked until it goes out of scope
1760 Log *log = GetLog(GDBRLog::Thread);
1761 LLDB_LOG_VERBOSE(log, "pid = {0}", GetID());
1762
1763 size_t num_thread_ids = m_thread_ids.size();
1764 // The "m_thread_ids" thread ID list should always be updated after each stop
1765 // reply packet, but in case it isn't, update it here.
1766 if (num_thread_ids == 0) {
1767 if (!UpdateThreadIDList())
1768 return false;
1769 num_thread_ids = m_thread_ids.size();
1770 }
1771
1772 ThreadList old_thread_list_copy(old_thread_list);
1773 if (num_thread_ids > 0) {
1774 for (size_t i = 0; i < num_thread_ids; ++i) {
1775 lldb::tid_t tid = m_thread_ids[i];
1776 ThreadSP thread_sp(
1777 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1778 if (!thread_sp) {
1779 thread_sp = CreateThread(tid);
1780 LLDB_LOG_VERBOSE(log, "Making new thread: {0} for thread ID: {1:x}.",
1781 thread_sp.get(), thread_sp->GetID());
1782 } else {
1783 LLDB_LOG_VERBOSE(log, "Found old thread: {0} for thread ID: {1:x}.",
1784 thread_sp.get(), thread_sp->GetID());
1785 }
1786
1787 SetThreadPc(thread_sp, i);
1788 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1789 }
1790 }
1791
1792 // Whatever that is left in old_thread_list_copy are not present in
1793 // new_thread_list. Remove non-existent threads from internal id table.
1794 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1795 for (size_t i = 0; i < old_num_thread_ids; i++) {
1796 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1797 if (old_thread_sp) {
1798 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1799 m_thread_id_to_index_id_map.erase(old_thread_id);
1800 }
1801 }
1802
1803 return true;
1804}
1805
1806void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1807 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1809 ThreadGDBRemote *gdb_thread =
1810 static_cast<ThreadGDBRemote *>(thread_sp.get());
1811 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1812 if (reg_ctx_sp) {
1813 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1815 if (pc_regnum != LLDB_INVALID_REGNUM) {
1816 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1817 }
1818 }
1819 }
1820}
1821
1823 // This runs for every thread at a stop, so searching m_thread_ids would make
1824 // the stop quadratic in the number of threads. m_thread_ids is rewritten in
1825 // several places that leave m_thread_id_positions alone, so trust a cached
1826 // position only if m_thread_ids still has tid there, and rebuild otherwise.
1827 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1828 auto it = m_thread_id_positions.find(tid);
1829 if (it != m_thread_id_positions.end() && it->second < m_thread_ids.size() &&
1830 m_thread_ids[it->second] == tid)
1831 return it->second;
1832
1833 m_thread_id_positions.clear();
1834 for (auto [i, id] : llvm::enumerate(m_thread_ids))
1835 m_thread_id_positions.try_emplace(id, i);
1836 it = m_thread_id_positions.find(tid);
1837 if (it == m_thread_id_positions.end())
1838 return std::nullopt;
1839 return it->second;
1840}
1841
1843 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1844 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1845 // packet
1846 if (thread_infos_sp) {
1847 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1848 if (thread_infos) {
1849 lldb::tid_t tid;
1850 const size_t n = thread_infos->GetSize();
1851 for (size_t i = 0; i < n; ++i) {
1852 StructuredData::Dictionary *thread_dict =
1853 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1854 if (thread_dict) {
1855 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1856 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1857 if (tid == thread->GetID())
1858 return (bool)SetThreadStopInfo(thread_dict,
1859 thread->shared_from_this());
1860 }
1861 }
1862 }
1863 }
1864 }
1865 return false;
1866}
1867
1869 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1870 // packet (we're at a public stop).
1871 StructuredData::ObjectSP threads_info_sp = *m_jthreadsinfo.Lock();
1872 if (GetThreadStopInfoFromJSON(thread, threads_info_sp))
1873 return true;
1874
1875 // See if the stop-reply packet (T05 etc) included a `jstopinfo` key
1876 // with a mach exception description for any thread that has a stop reason.
1877 StructuredData::ObjectSP stop_info_sp = *m_jstopinfo.Lock();
1878 if (stop_info_sp) {
1879 // Any thread not described in `jstopinfo` has no stop reason.
1880 // If a no-stop-reason thread is stopped at a breakpoint site (but
1881 // hasn't yet hit the breakpoint instruction), note that in the
1882 // Thread state so we will hit the breakpoint when we resume execution.
1883 if (!GetThreadStopInfoFromJSON(thread, stop_info_sp)) {
1884 addr_t pc = thread->GetRegisterContext()->GetPC();
1885 BreakpointSiteSP bp_site_sp =
1886 thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1887 if (bp_site_sp && IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
1888 thread->SetThreadStoppedAtUnexecutedBP(pc);
1889 thread->SetStopInfo(StopInfoSP());
1890 }
1891 return true;
1892 }
1893
1894 // Fall back to using the qThreadStopInfo packet
1895 StringExtractorGDBRemote stop_packet;
1896 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1897 return SetThreadStopInfo(stop_packet) == eStateStopped;
1898 return false;
1899}
1900
1902 ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) {
1903 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1904 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1905
1906 for (const auto &pair : expedited_register_map) {
1907 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1908 eRegisterKindProcessPlugin, pair.first);
1909 if (lldb_regnum != LLDB_INVALID_REGNUM) {
1910 StringExtractor reg_value_extractor(pair.second);
1911 if (reg_value_extractor.GetStringRef().empty()) {
1912 gdb_thread->PrivateSetRegisterUnavailable(lldb_regnum);
1913 continue;
1914 }
1915 WritableDataBufferSP buffer_sp(
1916 new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1917 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1918 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1919 }
1920 }
1921}
1922
1924 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1925 uint8_t signo, const std::string &thread_name, const std::string &reason,
1926 const std::string &description, uint32_t exc_type,
1927 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1928 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1929 // queue_serial are valid
1930 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1931 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial,
1932 std::vector<lldb::addr_t> &added_binaries,
1933 StructuredData::ObjectSP &detailed_binaries_info, ThreadSP thread_sp) {
1934
1935 if (tid == LLDB_INVALID_THREAD_ID)
1936 return nullptr;
1937
1938 // Stop info is set for every thread at a stop, so a search of the thread
1939 // list for each would take time quadratic in the number of threads.
1940 if (!thread_sp || thread_sp->GetProtocolID() != tid) {
1941 // m_thread_list_real does have its own mutex, but we need to hold onto the
1942 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1943 // m_thread_list_real.AddThread(...) so it doesn't change on us
1944 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1945 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1946
1947 if (!thread_sp) {
1948 // Create the thread if we need to
1949 thread_sp = CreateThread(tid);
1950 m_thread_list_real.AddThread(thread_sp);
1951 }
1952 }
1953
1954 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1955 RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext());
1956
1957 reg_ctx_sp->InvalidateIfNeeded(true);
1958
1959 if (std::optional<size_t> index = FindThreadIDIndex(tid))
1960 SetThreadPc(thread_sp, *index);
1961
1962 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1963
1964 if (reg_ctx_sp->ReconfigureRegisterInfo()) {
1965 // Now we have changed the offsets of all the registers, so the values
1966 // will be corrupted.
1967 reg_ctx_sp->InvalidateAllRegisters();
1968 // Expedited registers values will never contain registers that would be
1969 // resized by a reconfigure. So we are safe to continue using these
1970 // values.
1971 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1972 }
1973
1974 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1975
1976 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1977 // Check if the GDB server was able to provide the queue name, kind and serial
1978 // number
1979 if (queue_vars_valid)
1980 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1981 dispatch_queue_t, associated_with_dispatch_queue);
1982 else
1983 gdb_thread->ClearQueueInfo();
1984
1985 gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);
1986
1987 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1988 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1989
1990 gdb_thread->SetNewlyAddedBinaries(added_binaries);
1991 gdb_thread->SetDetailedBinariesInfo(detailed_binaries_info);
1992
1993 // Make sure we update our thread stop reason just once, but don't overwrite
1994 // the stop info for threads that haven't moved:
1995 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1996 if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1997 current_stop_info_sp) {
1998 thread_sp->SetStopInfo(current_stop_info_sp);
1999 return thread_sp;
2000 }
2001
2002 if (!thread_sp->StopInfoIsUpToDate()) {
2003 thread_sp->SetStopInfo(StopInfoSP());
2004
2005 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
2006 BreakpointSiteSP bp_site_sp =
2007 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
2008 if (bp_site_sp && IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
2009 thread_sp->SetThreadStoppedAtUnexecutedBP(pc);
2010
2011 if (exc_type != 0) {
2012 // For thread plan async interrupt, creating stop info on the
2013 // original async interrupt request thread instead. If interrupt thread
2014 // does not exist anymore we fallback to current signal receiving thread
2015 // instead.
2016 ThreadSP interrupt_thread;
2018 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
2019 if (interrupt_thread)
2020 thread_sp = interrupt_thread;
2021 else {
2022 const size_t exc_data_size = exc_data.size();
2023 thread_sp->SetStopInfo(
2025 *thread_sp, exc_type, exc_data_size,
2026 exc_data_size >= 1 ? exc_data[0] : 0,
2027 exc_data_size >= 2 ? exc_data[1] : 0,
2028 exc_data_size >= 3 ? exc_data[2] : 0));
2029 }
2030 } else {
2031 bool handled = false;
2032 bool did_exec = false;
2033 // debugserver can send reason = "none" which is equivalent
2034 // to no reason.
2035 if (!reason.empty() && reason != "none") {
2036 if (reason == "trace") {
2037 thread_sp->SetStopInfo(StopInfo::CreateStopReasonToTrace(*thread_sp));
2038 handled = true;
2039 } else if (reason == "breakpoint") {
2040 thread_sp->SetThreadHitBreakpointSite();
2041 if (bp_site_sp) {
2042 // If the breakpoint is for this thread, then we'll report the hit,
2043 // but if it is for another thread, we can just report no reason.
2044 // We don't need to worry about stepping over the breakpoint here,
2045 // that will be taken care of when the thread resumes and notices
2046 // that there's a breakpoint under the pc.
2047 handled = true;
2048 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2049 thread_sp->SetStopInfo(
2051 *thread_sp, bp_site_sp->GetID()));
2052 } else {
2053 StopInfoSP invalid_stop_info_sp;
2054 thread_sp->SetStopInfo(invalid_stop_info_sp);
2055 }
2056 }
2057 } else if (reason == "trap") {
2058 // Let the trap just use the standard signal stop reason below...
2059 } else if (reason == "watchpoint") {
2060 // We will have between 1 and 3 fields in the description.
2061 //
2062 // \a wp_addr which is the original start address that
2063 // lldb requested be watched, or an address that the
2064 // hardware reported. This address should be within the
2065 // range of a currently active watchpoint region - lldb
2066 // should be able to find a watchpoint with this address.
2067 //
2068 // \a wp_index is the hardware watchpoint register number.
2069 //
2070 // \a wp_hit_addr is the actual address reported by the hardware,
2071 // which may be outside the range of a region we are watching.
2072 //
2073 // On MIPS, we may get a false watchpoint exception where an
2074 // access to the same 8 byte granule as a watchpoint will trigger,
2075 // even if the access was not within the range of the watched
2076 // region. When we get a \a wp_hit_addr outside the range of any
2077 // set watchpoint, continue execution without making it visible to
2078 // the user.
2079 //
2080 // On ARM, a related issue where a large access that starts
2081 // before the watched region (and extends into the watched
2082 // region) may report a hit address before the watched region.
2083 // lldb will not find the "nearest" watchpoint to
2084 // disable/step/re-enable it, so one of the valid watchpoint
2085 // addresses should be provided as \a wp_addr.
2086 StringExtractor desc_extractor(description.c_str());
2087 // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this
2088 // up as
2089 // <address within wp range> <wp hw index> <actual accessed addr>
2090 // but this is not reading the <wp hw index>. Seems like it
2091 // wouldn't work on MIPS, where that third field is important.
2092 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2093 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2095 bool silently_continue = false;
2096 WatchpointResourceSP wp_resource_sp;
2097 if (wp_hit_addr != LLDB_INVALID_ADDRESS) {
2098 wp_resource_sp =
2099 m_watchpoint_resource_list.FindByAddress(wp_hit_addr);
2100 // On MIPS, \a wp_hit_addr outside the range of a watched
2101 // region means we should silently continue, it is a false hit.
2103 if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first &&
2105 silently_continue = true;
2106 }
2107 if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS)
2108 wp_resource_sp = m_watchpoint_resource_list.FindByAddress(wp_addr);
2109 if (!wp_resource_sp) {
2111 LLDB_LOGF(log, "failed to find watchpoint");
2112 watch_id = LLDB_INVALID_SITE_ID;
2113 } else {
2114 // LWP_TODO: This is hardcoding a single Watchpoint in a
2115 // Resource, need to add
2116 // StopInfo::CreateStopReasonWithWatchpointResource which
2117 // represents all watchpoints that were tripped at this stop.
2118 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();
2119 }
2120 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
2121 *thread_sp, watch_id, silently_continue));
2122 handled = true;
2123 } else if (reason == "exception") {
2124 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2125 *thread_sp, description.c_str()));
2126 handled = true;
2127 } else if (reason == "history boundary") {
2128 thread_sp->SetStopInfo(StopInfo::CreateStopReasonHistoryBoundary(
2129 *thread_sp, description.c_str()));
2130 handled = true;
2131 } else if (reason == "exec") {
2132 did_exec = true;
2133 thread_sp->SetStopInfo(
2135 handled = true;
2136 } else if (reason == "processor trace") {
2137 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
2138 *thread_sp, description.c_str()));
2139 } else if (reason == "fork") {
2140 StringExtractor desc_extractor(description.c_str());
2141 lldb::pid_t child_pid =
2142 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
2143 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
2144 thread_sp->SetStopInfo(
2145 StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));
2146 handled = true;
2147 } else if (reason == "vfork") {
2148 StringExtractor desc_extractor(description.c_str());
2149 lldb::pid_t child_pid =
2150 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
2151 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
2152 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
2153 *thread_sp, child_pid, child_tid));
2154 handled = true;
2155 } else if (reason == "vforkdone") {
2156 thread_sp->SetStopInfo(
2158 handled = true;
2159 } else if (reason == "dyld") {
2160 if (llvm::Error error = LoadModules()) {
2161 Log *log = GetLog(GDBRLog::Process);
2162 LLDB_LOG_ERROR(log, std::move(error),
2163 "failed to load modules: {0}");
2164 }
2165 thread_sp->SetStopInfo(
2166 StopInfo::CreateStopReasonDyld(*thread_sp, description.c_str()));
2167 handled = true;
2168 }
2169 }
2170
2171 if (!handled && signo && !did_exec) {
2172 if (signo == SIGTRAP) {
2173 // Currently we are going to assume SIGTRAP means we are either
2174 // hitting a breakpoint or hardware single stepping.
2175
2176 // We can't disambiguate between stepping-to-a-breakpointsite and
2177 // hitting-a-breakpointsite.
2178 //
2179 // A user can instruction-step, and be stopped at a BreakpointSite.
2180 // Or a user can be sitting at a BreakpointSite,
2181 // instruction-step which hits the breakpoint and the pc does not
2182 // advance.
2183 //
2184 // In both cases, we're at a BreakpointSite when stopped, and
2185 // the resume state was eStateStepping.
2186
2187 // Assume if we're at a BreakpointSite, we hit it.
2188 handled = true;
2189 addr_t pc =
2190 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2191 BreakpointSiteSP bp_site_sp =
2192 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
2193 pc);
2194
2195 // We can't know if we hit it or not. So if we are stopped at
2196 // a BreakpointSite, assume we hit it, and should step past the
2197 // breakpoint when we resume. This is contrary to how we handle
2198 // BreakpointSites in any other location, but we can't know for
2199 // sure what happened so it's a reasonable default.
2200 if (bp_site_sp) {
2201 if (IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
2202 thread_sp->SetThreadHitBreakpointSite();
2203
2204 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2205 if (m_breakpoint_pc_offset != 0)
2206 thread_sp->GetRegisterContext()->SetPC(pc);
2207 thread_sp->SetStopInfo(
2209 *thread_sp, bp_site_sp->GetID()));
2210 } else {
2211 StopInfoSP invalid_stop_info_sp;
2212 thread_sp->SetStopInfo(invalid_stop_info_sp);
2213 }
2214 } else {
2215 // If we were stepping then assume the stop was the result of the
2216 // trace. If we were not stepping then report the SIGTRAP.
2217 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2218 thread_sp->SetStopInfo(
2220 else
2221 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2222 *thread_sp, signo, description.c_str()));
2223 }
2224 }
2225 if (!handled) {
2226 // For thread plan async interrupt, creating stop info on the
2227 // original async interrupt request thread instead. If interrupt
2228 // thread does not exist anymore we fallback to current signal
2229 // receiving thread instead.
2230 ThreadSP interrupt_thread;
2232 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
2233 if (interrupt_thread)
2234 thread_sp = interrupt_thread;
2235 else
2236 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2237 *thread_sp, signo, description.c_str()));
2238 }
2239 }
2240
2241 if (!description.empty()) {
2242 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2243 if (stop_info_sp) {
2244 const char *stop_info_desc = stop_info_sp->GetDescription();
2245 if (!stop_info_desc || !stop_info_desc[0])
2246 stop_info_sp->SetDescription(description.c_str());
2247 } else {
2248 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2249 *thread_sp, description.c_str()));
2250 }
2251 }
2252 }
2253 }
2254 return thread_sp;
2255}
2256
2259 const std::string &description) {
2260 ThreadSP thread_sp;
2261 {
2262 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2263 thread_sp = m_thread_list_real.FindThreadByProtocolID(m_interrupt_tid,
2264 /*can_update=*/false);
2265 }
2266 if (thread_sp)
2267 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(
2268 *thread_sp, signo, description.c_str()));
2269 // Clear m_interrupt_tid regardless we can find original interrupt thread or
2270 // not.
2272 return thread_sp;
2273}
2274
2277 lldb::ThreadSP thread_sp) {
2278 static constexpr llvm::StringLiteral g_key_tid("tid");
2279 static constexpr llvm::StringLiteral g_key_name("name");
2280 static constexpr llvm::StringLiteral g_key_reason("reason");
2281 static constexpr llvm::StringLiteral g_key_metype("metype");
2282 static constexpr llvm::StringLiteral g_key_medata("medata");
2283 static constexpr llvm::StringLiteral g_key_qaddr("qaddr");
2284 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2285 "dispatch_queue_t");
2286 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2287 "associated_with_dispatch_queue");
2288 static constexpr llvm::StringLiteral g_key_queue_name("qname");
2289 static constexpr llvm::StringLiteral g_key_queue_kind("qkind");
2290 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");
2291 static constexpr llvm::StringLiteral g_key_registers("registers");
2292 static constexpr llvm::StringLiteral g_key_memory("memory");
2293 static constexpr llvm::StringLiteral g_key_description("description");
2294 static constexpr llvm::StringLiteral g_key_signal("signal");
2295 static constexpr llvm::StringLiteral g_key_added_binaries("added-binaries");
2296 static constexpr llvm::StringLiteral g_key_detailed_binaries_info(
2297 "detailed-binaries-info");
2298
2299 // Stop with signal and thread info
2301 uint8_t signo = 0;
2302 std::string thread_name;
2303 std::string reason;
2304 std::string description;
2305 uint32_t exc_type = 0;
2306 std::vector<addr_t> exc_data;
2307 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2308 ExpeditedRegisterMap expedited_register_map;
2309 bool queue_vars_valid = false;
2310 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2311 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2312 std::string queue_name;
2313 QueueKind queue_kind = eQueueKindUnknown;
2314 uint64_t queue_serial_number = 0;
2315 std::vector<addr_t> added_binaries;
2316 StructuredData::ObjectSP detailed_binaries_info;
2317 // Iterate through all of the thread dictionary key/value pairs from the
2318 // structured data dictionary
2319
2320 // FIXME: we're silently ignoring invalid data here
2321 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2322 &signo, &reason, &description, &exc_type, &exc_data,
2323 &thread_dispatch_qaddr, &queue_vars_valid,
2324 &associated_with_dispatch_queue, &dispatch_queue_t,
2325 &queue_name, &queue_kind, &queue_serial_number,
2326 &added_binaries, &detailed_binaries_info](
2327 llvm::StringRef key,
2328 StructuredData::Object *object) -> bool {
2329 if (key == g_key_tid) {
2330 // thread in big endian hex
2331 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
2332 } else if (key == g_key_metype) {
2333 // exception type in big endian hex
2334 exc_type = object->GetUnsignedIntegerValue(0);
2335 } else if (key == g_key_medata) {
2336 // exception data in big endian hex
2337 StructuredData::Array *array = object->GetAsArray();
2338 if (array) {
2339 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2340 exc_data.push_back(object->GetUnsignedIntegerValue());
2341 return true; // Keep iterating through all array items
2342 });
2343 }
2344 } else if (key == g_key_name) {
2345 thread_name = std::string(object->GetStringValue());
2346 } else if (key == g_key_qaddr) {
2347 thread_dispatch_qaddr =
2348 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
2349 } else if (key == g_key_queue_name) {
2350 queue_vars_valid = true;
2351 queue_name = std::string(object->GetStringValue());
2352 } else if (key == g_key_queue_kind) {
2353 std::string queue_kind_str = std::string(object->GetStringValue());
2354 if (queue_kind_str == "serial") {
2355 queue_vars_valid = true;
2356 queue_kind = eQueueKindSerial;
2357 } else if (queue_kind_str == "concurrent") {
2358 queue_vars_valid = true;
2359 queue_kind = eQueueKindConcurrent;
2360 }
2361 } else if (key == g_key_queue_serial_number) {
2362 queue_serial_number = object->GetUnsignedIntegerValue(0);
2363 if (queue_serial_number != 0)
2364 queue_vars_valid = true;
2365 } else if (key == g_key_dispatch_queue_t) {
2366 dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2367 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2368 queue_vars_valid = true;
2369 } else if (key == g_key_associated_with_dispatch_queue) {
2370 queue_vars_valid = true;
2371 bool associated = object->GetBooleanValue();
2372 if (associated)
2373 associated_with_dispatch_queue = eLazyBoolYes;
2374 else
2375 associated_with_dispatch_queue = eLazyBoolNo;
2376 } else if (key == g_key_reason) {
2377 reason = std::string(object->GetStringValue());
2378 } else if (key == g_key_description) {
2379 description = std::string(object->GetStringValue());
2380 } else if (key == g_key_registers) {
2381 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2382
2383 if (registers_dict) {
2384 registers_dict->ForEach(
2385 [&expedited_register_map](llvm::StringRef key,
2386 StructuredData::Object *object) -> bool {
2387 uint32_t reg;
2388 if (llvm::to_integer(key, reg))
2389 expedited_register_map[reg] =
2390 std::string(object->GetStringValue());
2391 return true; // Keep iterating through all array items
2392 });
2393 }
2394 } else if (key == g_key_memory) {
2395 StructuredData::Array *array = object->GetAsArray();
2396 if (array) {
2397 array->ForEach([this](StructuredData::Object *object) -> bool {
2398 StructuredData::Dictionary *mem_cache_dict =
2399 object->GetAsDictionary();
2400 if (mem_cache_dict) {
2401 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2402 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2403 "address", mem_cache_addr)) {
2404 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2405 llvm::StringRef str;
2406 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2407 StringExtractor bytes(str);
2408 bytes.SetFilePos(0);
2409
2410 const size_t byte_size = bytes.GetStringRef().size() / 2;
2411 WritableDataBufferSP data_buffer_sp(
2412 new DataBufferHeap(byte_size, 0));
2413 const size_t bytes_copied =
2414 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2415 if (bytes_copied == byte_size)
2416 AddCacheData(mem_cache_addr, data_buffer_sp);
2417 }
2418 }
2419 }
2420 }
2421 return true; // Keep iterating through all array items
2422 });
2423 }
2424 } else if (key == g_key_signal)
2425 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2426 else if (key == g_key_added_binaries) {
2427 StructuredData::Array *array = object->GetAsArray();
2428 if (array) {
2429 array->ForEach([&added_binaries](
2430 StructuredData::Object *object) -> bool {
2432 object->GetAsUnsignedInteger();
2433 if (addr) {
2435 if (value != LLDB_INVALID_ADDRESS)
2436 added_binaries.push_back(value);
2437 }
2438 return true; // Keep iterating through all array items
2439 });
2440 }
2441 } else if (key == g_key_detailed_binaries_info) {
2442 // Get a string representation and then parse it into
2443 // StructuredData to get a separate copy of this part of
2444 // the response. We only have an Object* here, not the
2445 // original shared pointer, to increase the ref count.
2446 if (object->GetAsDictionary()) {
2447 StreamString json_str;
2448 object->Dump(json_str);
2449 detailed_binaries_info =
2451 }
2452 }
2453 return true; // Keep iterating through all dictionary key/value pairs
2454 });
2455
2456 return SetThreadStopInfo(
2457 tid, expedited_register_map, signo, thread_name, reason, description,
2458 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2459 associated_with_dispatch_queue, dispatch_queue_t, queue_name, queue_kind,
2460 queue_serial_number, added_binaries, detailed_binaries_info,
2461 std::move(thread_sp));
2462}
2463
2465 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2466 stop_packet.SetFilePos(0);
2467 const char stop_type = stop_packet.GetChar();
2468 switch (stop_type) {
2469 case 'T':
2470 case 'S': {
2471 // This is a bit of a hack, but it is required. If we did exec, we need to
2472 // clear our thread lists and also know to rebuild our dynamic register
2473 // info before we lookup and threads and populate the expedited register
2474 // values so we need to know this right away so we can cleanup and update
2475 // our registers.
2476 const uint32_t stop_id = GetStopID();
2477 if (stop_id == 0) {
2478 // Our first stop, make sure we have a process ID, and also make sure we
2479 // know about our registers
2481 SetID(pid);
2483 }
2484 // Stop with signal and thread info
2487 const uint8_t signo = stop_packet.GetHexU8();
2488 llvm::StringRef key;
2489 llvm::StringRef value;
2490 std::string thread_name;
2491 std::string reason;
2492 std::string description;
2493 std::vector<addr_t> added_binaries;
2494 StructuredData::ObjectSP detailed_binaries_info;
2495 uint32_t exc_type = 0;
2496 std::vector<addr_t> exc_data;
2497 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2498 bool queue_vars_valid =
2499 false; // says if locals below that start with "queue_" are valid
2500 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2501 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2502 std::string queue_name;
2503 QueueKind queue_kind = eQueueKindUnknown;
2504 uint64_t queue_serial_number = 0;
2505 ExpeditedRegisterMap expedited_register_map;
2506 AddressableBits addressable_bits;
2507 while (stop_packet.GetNameColonValue(key, value)) {
2508 if (key.compare("metype") == 0) {
2509 // exception type in big endian hex
2510 value.getAsInteger(BASE_16, exc_type);
2511 } else if (key.compare("medata") == 0) {
2512 // exception data in big endian hex
2513 uint64_t x;
2514 value.getAsInteger(BASE_16, x);
2515 exc_data.push_back(x);
2516 } else if (key.compare("thread") == 0) {
2517 // thread-id
2518 StringExtractorGDBRemote thread_id{value};
2519 auto pid_tid = thread_id.GetPidTid(pid);
2520 if (pid_tid) {
2521 stop_pid = pid_tid->first;
2522 tid = pid_tid->second;
2523 } else
2525 } else if (key.compare("threads") == 0) {
2526 std::lock_guard<std::recursive_mutex> guard(
2527 m_thread_list_real.GetMutex());
2529 } else if (key.compare("thread-pcs") == 0) {
2530 m_thread_pcs.clear();
2531 // A comma separated list of all threads in the current
2532 // process that includes the thread for this stop reply packet
2534 while (!value.empty()) {
2535 llvm::StringRef pc_str;
2536 std::tie(pc_str, value) = value.split(',');
2537 if (pc_str.getAsInteger(BASE_16, pc))
2539 m_thread_pcs.push_back(pc);
2540 }
2541 } else if (key.compare("jstopinfo") == 0) {
2542 StringExtractor json_extractor(value);
2543 std::string json;
2544 // Now convert the HEX bytes into a string value
2545 json_extractor.GetHexByteString(json);
2546
2547 // This JSON contains thread IDs and thread stop info for all threads.
2548 // It doesn't contain expedited registers, memory or queue info.
2549 *m_jstopinfo.Lock() = StructuredData::ParseJSON(json);
2550 } else if (key.compare("hexname") == 0) {
2551 StringExtractor name_extractor(value);
2552 // Now convert the HEX bytes into a string value
2553 name_extractor.GetHexByteString(thread_name);
2554 } else if (key.compare("name") == 0) {
2555 thread_name = std::string(value);
2556 } else if (key.compare("qaddr") == 0) {
2557 value.getAsInteger(BASE_16, thread_dispatch_qaddr);
2558 } else if (key.compare("dispatch_queue_t") == 0) {
2559 queue_vars_valid = true;
2560 value.getAsInteger(BASE_16, dispatch_queue_t);
2561 } else if (key.compare("qname") == 0) {
2562 queue_vars_valid = true;
2563 StringExtractor name_extractor(value);
2564 // Now convert the HEX bytes into a string value
2565 name_extractor.GetHexByteString(queue_name);
2566 } else if (key.compare("qkind") == 0) {
2567 queue_kind = llvm::StringSwitch<QueueKind>(value)
2568 .Case("serial", eQueueKindSerial)
2569 .Case("concurrent", eQueueKindConcurrent)
2570 .Default(eQueueKindUnknown);
2571 queue_vars_valid = queue_kind != eQueueKindUnknown;
2572 } else if (key.compare("qserialnum") == 0) {
2573 if (!value.getAsInteger(BASE_10, queue_serial_number))
2574 queue_vars_valid = true;
2575 } else if (key.compare("reason") == 0) {
2576 reason = std::string(value);
2577 } else if (key.compare("description") == 0) {
2578 StringExtractor desc_extractor(value);
2579 // Now convert the HEX bytes into a string value
2580 desc_extractor.GetHexByteString(description);
2581 } else if (key.compare("memory") == 0) {
2582 // Expedited memory. GDB servers can choose to send back expedited
2583 // memory that can populate the L1 memory cache in the process so that
2584 // things like the frame pointer backchain can be expedited. This will
2585 // help stack backtracing be more efficient by not having to send as
2586 // many memory read requests down the remote GDB server.
2587
2588 // Key/value pair format: memory:<addr>=<bytes>;
2589 // <addr> is a number whose base will be interpreted by the prefix:
2590 // "0x[0-9a-fA-F]+" for hex
2591 // "0[0-7]+" for octal
2592 // "[1-9]+" for decimal
2593 // <bytes> is native endian ASCII hex bytes just like the register
2594 // values
2595 llvm::StringRef addr_str, bytes_str;
2596 std::tie(addr_str, bytes_str) = value.split('=');
2597 if (!addr_str.empty() && !bytes_str.empty()) {
2598 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2599 if (!addr_str.getAsInteger(BASE_AUTOSENSE, mem_cache_addr)) {
2600 StringExtractor bytes(bytes_str);
2601 const size_t byte_size = bytes.GetBytesLeft() / 2;
2602 WritableDataBufferSP data_buffer_sp(
2603 new DataBufferHeap(byte_size, 0));
2604 const size_t bytes_copied =
2605 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2606 if (bytes_copied == byte_size)
2607 AddCacheData(mem_cache_addr, data_buffer_sp);
2608 }
2609 }
2610 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2611 key.compare("awatch") == 0) {
2612 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2614 value.getAsInteger(BASE_16, wp_addr);
2615
2616 WatchpointResourceSP wp_resource_sp =
2617 m_watchpoint_resource_list.FindByAddress(wp_addr);
2618
2619 // Rewrite gdb standard watch/rwatch/awatch to
2620 // "reason:watchpoint" + "description:ADDR",
2621 // which is parsed in SetThreadStopInfo.
2622 reason = "watchpoint";
2623 StreamString ostr;
2624 ostr.Printf("%" PRIu64, wp_addr);
2625 description = std::string(ostr.GetString());
2626 } else if (key.compare("swbreak") == 0 || key.compare("hwbreak") == 0) {
2627 reason = "breakpoint";
2628 } else if (key.compare("replaylog") == 0) {
2629 reason = "history boundary";
2630 } else if (key.compare("library") == 0) {
2631 auto error = LoadModules();
2632 if (error) {
2634 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2635 }
2636 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2637 // fork includes child pid/tid in thread-id format
2638 StringExtractorGDBRemote thread_id{value};
2639 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2640 if (!pid_tid) {
2642 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2644 }
2645
2646 reason = key.str();
2647 StreamString ostr;
2648 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2649 description = std::string(ostr.GetString());
2650 } else if (key.compare("addressing_bits") == 0) {
2651 uint64_t addressing_bits;
2652 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2653 addressable_bits.SetAddressableBits(addressing_bits);
2654 }
2655 } else if (key.compare("low_mem_addressing_bits") == 0) {
2656 uint64_t addressing_bits;
2657 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2658 addressable_bits.SetLowmemAddressableBits(addressing_bits);
2659 }
2660 } else if (key.compare("high_mem_addressing_bits") == 0) {
2661 uint64_t addressing_bits;
2662 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2663 addressable_bits.SetHighmemAddressableBits(addressing_bits);
2664 }
2665 } else if (key == "added-binaries") {
2666 // A comma separated list of all threads in the current
2667 // process that includes the thread for this stop reply packet
2669 while (!value.empty()) {
2670 llvm::StringRef pc_str;
2671 std::tie(pc_str, value) = value.split(',');
2672 if (pc_str.getAsInteger(BASE_16, pc))
2674 added_binaries.push_back(pc);
2675 }
2676 } else if (key == "detailed-binaries-info") {
2677 StringExtractor json_extractor(value);
2678 std::string json;
2679 // Now convert the HEX bytes into a string value.
2680 json_extractor.GetHexByteString(json);
2681
2682 // This JSON contains detailed information about binares.
2683 detailed_binaries_info = StructuredData::ParseJSON(json);
2684 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2685 uint32_t reg = UINT32_MAX;
2686 if (!key.getAsInteger(BASE_16, reg))
2687 expedited_register_map[reg] = std::string(std::move(value));
2688 }
2689 // swbreak and hwbreak are also expected keys, but we don't need to
2690 // change our behaviour for them because lldb always expects the remote
2691 // to adjust the program counter (if relevant, e.g., for x86 targets)
2692 }
2693
2694 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2695 Log *log = GetLog(GDBRLog::Process);
2696 LLDB_LOG(log,
2697 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2698 stop_pid, pid);
2699 return eStateInvalid;
2700 }
2701
2702 if (tid == LLDB_INVALID_THREAD_ID) {
2703 // A thread id may be invalid if the response is old style 'S' packet
2704 // which does not provide the
2705 // thread information. So update the thread list and choose the first
2706 // one.
2708
2709 if (!m_thread_ids.empty()) {
2710 tid = m_thread_ids.front();
2711 }
2712 }
2713
2714 SetAddressableBitMasks(addressable_bits);
2715
2717
2718 ThreadSP thread_sp = SetThreadStopInfo(
2719 tid, expedited_register_map, signo, thread_name, reason, description,
2720 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2721 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2722 queue_kind, queue_serial_number, added_binaries,
2723 detailed_binaries_info);
2724
2725 return eStateStopped;
2726 } break;
2727
2728 case 'W':
2729 case 'X':
2730 // process exited
2731 return eStateExited;
2732
2733 default:
2734 break;
2735 }
2736 return eStateInvalid;
2737}
2738
2740 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2741
2742 m_thread_ids.clear();
2743 m_thread_pcs.clear();
2744
2745 // Set the thread stop info. It might have a "threads" key whose value is a
2746 // list of all thread IDs in the current process, so m_thread_ids might get
2747 // set.
2748 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2749 if (m_thread_ids.empty()) {
2750 // No, we need to fetch the thread list manually
2752 }
2753
2754 // We might set some stop info's so make sure the thread list is up to
2755 // date before we do that or we might overwrite what was computed here.
2757
2760 m_last_stop_packet.reset();
2761
2762 // If we have queried for a default thread id
2764 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2768 if (ThreadSP primary_thread_sp = m_thread_list.FindThreadByProtocolID(
2769 m_last_stop_primary_tid, /*can_update=*/false)) {
2770 ThreadSP selected_thread_sp = m_thread_list.GetSelectedThread();
2771 if (!selected_thread_sp ||
2772 selected_thread_sp->GetID() != primary_thread_sp->GetID())
2773 m_thread_list.SetSelectedThreadByID(primary_thread_sp->GetID());
2774 }
2775 }
2777
2778 // Let all threads recover from stopping and do any clean up based on the
2779 // previous thread state (if any).
2780 m_thread_list_real.RefreshStateAfterStop();
2781}
2782
2784 Status error;
2785
2787 // We are being asked to halt during an attach. We used to just close our
2788 // file handle and debugserver will go away, but with remote proxies, it
2789 // is better to send a positive signal, so let's send the interrupt first...
2790 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2791 m_gdb_comm.Disconnect();
2792 } else
2793 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2794 return error;
2795}
2796
2798 Status error;
2799 Log *log = GetLog(GDBRLog::Process);
2800 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2801
2802 error = m_gdb_comm.Detach(keep_stopped);
2803 if (log) {
2804 if (error.Success())
2805 log->PutCString(
2806 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2807 else
2808 LLDB_LOGF(log,
2809 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2810 error.AsCString() ? error.AsCString() : "<unknown error>");
2811 }
2812
2813 if (!error.Success())
2814 return error;
2815
2816 // Sleep for one second to let the process get all detached...
2818
2821
2822 // KillDebugserverProcess ();
2823 return error;
2824}
2825
2827 Log *log = GetLog(GDBRLog::Process);
2828 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2829
2830 // Interrupt if our inferior is running...
2831 int exit_status = SIGABRT;
2832 std::string exit_string;
2833
2834 if (m_gdb_comm.IsConnected()) {
2836 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2837
2838 if (kill_res) {
2839 exit_status = kill_res.get();
2840#if defined(__APPLE__)
2841 // For Native processes on Mac OS X, we launch through the Host
2842 // Platform, then hand the process off to debugserver, which becomes
2843 // the parent process through "PT_ATTACH". Then when we go to kill
2844 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2845 // we call waitpid which returns with no error and the correct
2846 // status. But amusingly enough that doesn't seem to actually reap
2847 // the process, but instead it is left around as a Zombie. Probably
2848 // the kernel is in the process of switching ownership back to lldb
2849 // which was the original parent, and gets confused in the handoff.
2850 // Anyway, so call waitpid here to finally reap it.
2851 PlatformSP platform_sp(GetTarget().GetPlatform());
2852 if (platform_sp && platform_sp->IsHost()) {
2853 int status;
2854 ::pid_t reap_pid;
2855 reap_pid = waitpid(GetID(), &status, WNOHANG);
2856 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2857 }
2858#endif
2860 exit_string.assign("killed");
2861 } else {
2862 exit_string.assign(llvm::toString(kill_res.takeError()));
2863 }
2864 } else {
2865 exit_string.assign("killed or interrupted while attaching.");
2866 }
2867 } else {
2868 // If we missed setting the exit status on the way out, do it here.
2869 // NB set exit status can be called multiple times, the first one sets the
2870 // status.
2871 exit_string.assign("destroying when not connected to debugserver");
2872 }
2873
2874 SetExitStatus(exit_status, exit_string.c_str());
2875
2879 return Status();
2880}
2881
2884 if (TargetSP target_sp = m_target_wp.lock())
2885 target_sp->RemoveBreakpointByID(m_thread_create_bp_sp->GetID());
2886 m_thread_create_bp_sp.reset();
2887 }
2888}
2889
2891 const StringExtractorGDBRemote &response) {
2892 const bool did_exec =
2893 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2894 if (did_exec) {
2895 Log *log = GetLog(GDBRLog::Process);
2896 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2897
2898 m_thread_list_real.Clear();
2899 m_thread_list.Clear();
2901 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2902 }
2903
2904 m_last_stop_packet = response;
2905}
2906
2908 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2909}
2910
2911// Process Queries
2912
2914 return m_gdb_comm.IsConnected() && Process::IsAlive();
2915}
2916
2918 // request the link map address via the $qShlibInfoAddr packet
2919 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2920
2921 // the loaded module list can also provides a link map address
2922 if (addr == LLDB_INVALID_ADDRESS) {
2923 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2924 if (!list) {
2925 Log *log = GetLog(GDBRLog::Process);
2926 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2927 } else {
2928 addr = list->m_link_map;
2929 }
2930 }
2931
2932 return addr;
2933}
2934
2936 // See if the GDB remote client supports the JSON threads info. If so, we
2937 // gather stop info for all threads, expedited registers, expedited memory,
2938 // runtime queue information (iOS and MacOSX only), and more. Expediting
2939 // memory will help stack backtracing be much faster. Expediting registers
2940 // will make sure we don't have to read the thread registers for GPRs.
2941 StructuredData::ObjectSP threads_info_sp = m_gdb_comm.GetThreadsInfo();
2942 *m_jthreadsinfo.Lock() = threads_info_sp;
2943
2944 if (threads_info_sp) {
2945 // Now set the stop info for each thread and also expedite any registers
2946 // and memory that was in the jThreadsInfo response.
2947 StructuredData::Array *thread_infos = threads_info_sp->GetAsArray();
2948 if (thread_infos) {
2949 std::unordered_map<lldb::tid_t, ThreadSP> threads;
2950 for (const ThreadSP &thread_sp : m_thread_list_real.Threads())
2951 threads.try_emplace(thread_sp->GetProtocolID(), thread_sp);
2952 const size_t n = thread_infos->GetSize();
2953 for (size_t i = 0; i < n; ++i) {
2954 StructuredData::Dictionary *thread_dict =
2955 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2956 if (!thread_dict)
2957 continue;
2959 thread_dict->GetValueForKeyAsInteger("tid", tid);
2960 auto thread = threads.find(tid);
2961 SetThreadStopInfo(thread_dict,
2962 thread == threads.end() ? nullptr : thread->second);
2963 }
2964 }
2965 }
2966}
2967
2968// Process Memory
2970 void *buf, size_t size, Status &error) {
2971 using xPacketState = GDBRemoteCommunicationClient::xPacketState;
2972
2973 lldb::addr_t addr = process_addr.GetValue();
2974 lldb::addr_space_t addr_space = process_addr.GetAddressSpace();
2975 if (addr_space != LLDB_DEFAULT_ADDRESS_SPACE_ID &&
2976 !m_gdb_comm.GetAddressSpacesSupported()) {
2977 error = Status::FromErrorString("address spaces are not supported");
2978 return 0;
2979 }
2980
2982 xPacketState x_state = m_gdb_comm.GetxPacketState();
2983
2984 // M and m packets take 2 bytes for 1 byte of memory
2985 size_t max_memory_size = x_state != xPacketState::Unimplemented
2987 : m_max_memory_size / 2;
2988 if (size > max_memory_size) {
2989 // Keep memory read sizes down to a sane limit. This function will be
2990 // called multiple times in order to complete the task by
2991 // lldb_private::Process so it is ok to do this.
2992 size = max_memory_size;
2993 }
2994
2995 // A non-default address space rides on an "address_space:<hex-id>;" suffix,
2996 // followed by "thread:<hex-tid>;" when that space is thread specific.
2997 std::string suffix;
2998 if (addr_space != LLDB_DEFAULT_ADDRESS_SPACE_ID) {
2999 llvm::Expected<AddressSpaceInfo> info = GetAddressSpaceInfo(addr_space);
3000 if (!info) {
3001 error = Status::FromError(info.takeError());
3002 return 0;
3003 }
3004 suffix =
3005 llvm::formatv(";address_space:{0};", llvm::utohexstr(addr_space, true));
3006 if (info->is_thread_specific) {
3007 std::optional<lldb::tid_t> tid = process_addr.GetThreadID();
3008 if (!tid) {
3010 "address space \"%s\" is thread specific, but no thread was "
3011 "specified",
3012 info->name.c_str());
3013 return 0;
3014 }
3015 suffix += llvm::formatv("thread:{0};", llvm::utohexstr(*tid, true));
3016 }
3017 }
3018
3019 char packet[128];
3020 int packet_len =
3021 ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64 "%s",
3022 x_state != xPacketState::Unimplemented ? 'x' : 'm',
3023 (uint64_t)addr, (uint64_t)size, suffix.c_str());
3024 assert(packet_len + 1 < (int)sizeof(packet));
3025 UNUSED_IF_ASSERT_DISABLED(packet_len);
3026 StringExtractorGDBRemote response;
3027 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
3030 if (response.IsNormalResponse()) {
3031 error.Clear();
3032 if (x_state != xPacketState::Unimplemented) {
3033 // The lower level GDBRemoteCommunication packet receive layer has
3034 // already de-quoted any 0x7d character escaping that was present in
3035 // the packet
3036
3037 llvm::StringRef data_received = response.GetStringRef();
3038 if (x_state == xPacketState::Prefixed &&
3039 !data_received.consume_front("b")) {
3041 "unexpected response to GDB server memory read packet '{0}': "
3042 "'{1}'",
3043 packet, data_received);
3044 return 0;
3045 }
3046 // Don't write past the end of BUF if the remote debug server gave us
3047 // too much data for some reason.
3048 size_t memcpy_size = std::min(size, data_received.size());
3049 memcpy(buf, data_received.data(), memcpy_size);
3050 return memcpy_size;
3051 } else {
3052 return response.GetHexBytes(
3053 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
3054 }
3055 } else if (response.IsErrorResponse())
3057 "memory read failed for 0x%" PRIx64, addr);
3058 else if (response.IsUnsupportedResponse())
3060 "GDB server does not support reading memory");
3061 else
3063 "unexpected response to GDB server memory read packet '%s': '%s'",
3064 packet, response.GetStringRef().data());
3065 } else {
3066 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3067 packet);
3068 }
3069 return 0;
3070}
3071
3072/// Returns the number of ranges that is safe to request using MultiMemRead
3073/// while respecting max_packet_size.
3075 uint64_t max_packet_size,
3076 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
3077 // Each range is specified by two numbers (up to 16 ASCII characters) and one
3078 // comma.
3079 constexpr uint64_t range_overhead = 33;
3080 uint64_t current_size = 0;
3081 for (auto [idx, range] : llvm::enumerate(ranges)) {
3082 uint64_t potential_size = current_size + range.size + range_overhead;
3083 if (potential_size > max_packet_size) {
3084 if (idx == 0)
3086 "MultiMemRead input has a range (base = {0:x}, size = {1}) "
3087 "bigger than the maximum allowed by remote",
3088 range.base, range.size);
3089 return idx;
3090 }
3091 }
3092 return ranges.size();
3093}
3094
3095llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
3097 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
3098 llvm::MutableArrayRef<uint8_t> buffer) {
3099 if (!m_gdb_comm.GetMultiMemReadSupported())
3100 return Process::DoReadMemoryRanges(ranges, buffer);
3101
3102 const llvm::ArrayRef<Range<lldb::addr_t, size_t>> original_ranges = ranges;
3103 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory_regions;
3104
3105 while (!ranges.empty()) {
3106 uint64_t num_ranges =
3108 if (num_ranges == 0)
3109 return Process::DoReadMemoryRanges(original_ranges, buffer);
3110
3111 auto ranges_for_request = ranges.take_front(num_ranges);
3112 ranges = ranges.drop_front(num_ranges);
3113
3114 llvm::Expected<StringExtractorGDBRemote> response =
3115 SendMultiMemReadPacket(ranges_for_request);
3116 if (!response) {
3117 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(),
3118 "MultiMemRead error response: {0}");
3119 return Process::DoReadMemoryRanges(original_ranges, buffer);
3120 }
3121
3122 llvm::StringRef response_str = response->GetStringRef();
3123 const unsigned expected_num_ranges = ranges_for_request.size();
3124 if (llvm::Error error = ParseMultiMemReadPacket(
3125 response_str, buffer, expected_num_ranges, memory_regions)) {
3127 "MultiMemRead error parsing response: {0}");
3128 return Process::DoReadMemoryRanges(original_ranges, buffer);
3129 }
3130 }
3131 return memory_regions;
3132}
3133
3134llvm::Expected<StringExtractorGDBRemote>
3136 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
3137 std::string packet_str;
3138 llvm::raw_string_ostream stream(packet_str);
3139 stream << "MultiMemRead:ranges:";
3140
3141 auto range_to_stream = [&](auto range) {
3142 // the "-" marker omits the '0x' prefix.
3143 stream << llvm::formatv("{0:x-},{1:x-}", range.base, range.size);
3144 };
3145 llvm::interleave(ranges, stream, range_to_stream, ",");
3146 stream << ";";
3147
3148 StringExtractorGDBRemote response;
3150 m_gdb_comm.SendPacketAndWaitForResponse(packet_str.data(), response,
3153 return llvm::createStringErrorV("MultiMemRead failed to send packet: '{0}'",
3154 packet_str);
3155
3156 if (response.IsErrorResponse())
3157 return llvm::createStringErrorV("MultiMemRead failed: '{0}'",
3158 response.GetStringRef());
3159
3160 if (!response.IsNormalResponse())
3161 return llvm::createStringErrorV("MultiMemRead unexpected response: '{0}'",
3162 response.GetStringRef());
3163
3164 return response;
3165}
3166
3168 llvm::StringRef response_str, llvm::MutableArrayRef<uint8_t> buffer,
3169 unsigned expected_num_ranges,
3170 llvm::SmallVectorImpl<llvm::MutableArrayRef<uint8_t>> &memory_regions) {
3171 // The sizes and the data are separated by a `;`.
3172 auto [sizes_str, memory_data] = response_str.split(';');
3173 if (sizes_str.size() == response_str.size())
3174 return llvm::createStringErrorV(
3175 "MultiMemRead response missing field separator ';' in: '{0}'",
3176 response_str);
3177
3178 // Sizes are separated by a `,`.
3179 unsigned num_sizes = 0;
3180 for (llvm::StringRef size_str : llvm::split(sizes_str, ',')) {
3181 uint64_t read_size;
3182 if (size_str.getAsInteger(BASE_16, read_size))
3183 return llvm::createStringErrorV(
3184 "MultiMemRead response has invalid size string: {0}", size_str);
3185
3186 if (memory_data.size() < read_size)
3187 return llvm::createStringErrorV("MultiMemRead response did not have "
3188 "enough data, requested sizes: {0}",
3189 sizes_str);
3190
3191 if (read_size > buffer.size())
3192 return llvm::createStringErrorV(
3193 "MultiMemRead response size {0} exceeds remaining buffer {1}",
3194 read_size, buffer.size());
3195
3196 llvm::StringRef region_to_read = memory_data.take_front(read_size);
3197 memory_data = memory_data.drop_front(read_size);
3198
3199 llvm::MutableArrayRef<uint8_t> region_to_write =
3200 buffer.take_front(read_size);
3201 buffer = buffer.drop_front(read_size);
3202
3203 memcpy(region_to_write.data(), region_to_read.data(), read_size);
3204 memory_regions.push_back(region_to_write);
3205 ++num_sizes;
3206 }
3207
3208 if (num_sizes != expected_num_ranges)
3209 return llvm::createStringErrorV(
3210 "MultiMemRead response had {0} sizes, expected {1}", num_sizes,
3211 expected_num_ranges);
3212
3213 return llvm::Error::success();
3214}
3215
3217 return m_gdb_comm.GetMemoryTaggingSupported();
3218}
3219
3220llvm::Expected<std::vector<uint8_t>>
3222 int32_t type) {
3223 // By this point ReadMemoryTags has validated that tagging is enabled
3224 // for this target/process/address.
3225 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
3226 if (!buffer_sp) {
3227 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3228 "Error reading memory tags from remote");
3229 }
3230
3231 // Return the raw tag data
3232 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
3233 std::vector<uint8_t> got;
3234 got.reserve(tag_data.size());
3235 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
3236 return got;
3237}
3238
3240 int32_t type,
3241 const std::vector<uint8_t> &tags) {
3242 // By now WriteMemoryTags should have validated that tagging is enabled
3243 // for this target/process.
3244 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
3245}
3246
3248 std::vector<ObjectFile::LoadableData> entries) {
3249 Status error;
3250 // Sort the entries by address because some writes, like those to flash
3251 // memory, must happen in order of increasing address.
3252 llvm::stable_sort(entries, [](const ObjectFile::LoadableData a,
3253 const ObjectFile::LoadableData b) {
3254 return a.Dest < b.Dest;
3255 });
3256 m_allow_flash_writes = true;
3258 if (error.Success())
3259 error = FlashDone();
3260 else
3261 // Even though some of the writing failed, try to send a flash done if some
3262 // of the writing succeeded so the flash state is reset to normal, but
3263 // don't stomp on the error status that was set in the write failure since
3264 // that's the one we want to report back.
3265 FlashDone();
3266 m_allow_flash_writes = false;
3267 return error;
3268}
3269
3271 auto size = m_erased_flash_ranges.GetSize();
3272 for (size_t i = 0; i < size; ++i)
3273 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
3274 return true;
3275 return false;
3276}
3277
3279 Status status;
3280
3281 MemoryRegionInfo region;
3282 status = GetMemoryRegionInfo(addr, region);
3283 if (!status.Success())
3284 return status;
3285
3286 // The gdb spec doesn't say if erasures are allowed across multiple regions,
3287 // but we'll disallow it to be safe and to keep the logic simple by worring
3288 // about only one region's block size. DoMemoryWrite is this function's
3289 // primary user, and it can easily keep writes within a single memory region
3290 if (addr + size > region.GetRange().GetRangeEnd()) {
3291 status =
3292 Status::FromErrorString("Unable to erase flash in multiple regions");
3293 return status;
3294 }
3295
3296 uint64_t blocksize = region.GetBlocksize();
3297 if (blocksize == 0) {
3298 status =
3299 Status::FromErrorString("Unable to erase flash because blocksize is 0");
3300 return status;
3301 }
3302
3303 // Erasures can only be done on block boundary adresses, so round down addr
3304 // and round up size
3305 lldb::addr_t block_start_addr = addr - (addr % blocksize);
3306 size += (addr - block_start_addr);
3307 if ((size % blocksize) != 0)
3308 size += (blocksize - size % blocksize);
3309
3310 FlashRange range(block_start_addr, size);
3311
3312 if (HasErased(range))
3313 return status;
3314
3315 // We haven't erased the entire range, but we may have erased part of it.
3316 // (e.g., block A is already erased and range starts in A and ends in B). So,
3317 // adjust range if necessary to exclude already erased blocks.
3318 if (!m_erased_flash_ranges.IsEmpty()) {
3319 // Assuming that writes and erasures are done in increasing addr order,
3320 // because that is a requirement of the vFlashWrite command. Therefore, we
3321 // only need to look at the last range in the list for overlap.
3322 const auto &last_range = *m_erased_flash_ranges.Back();
3323 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
3324 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
3325 // overlap will be less than range.GetByteSize() or else HasErased()
3326 // would have been true
3327 range.SetByteSize(range.GetByteSize() - overlap);
3328 range.SetRangeBase(range.GetRangeBase() + overlap);
3329 }
3330 }
3331
3332 StreamString packet;
3333 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
3334 (uint64_t)range.GetByteSize());
3335
3336 StringExtractorGDBRemote response;
3337 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3340 if (response.IsOKResponse()) {
3341 m_erased_flash_ranges.Insert(range, true);
3342 } else {
3343 if (response.IsErrorResponse())
3345 "flash erase failed for 0x%" PRIx64, addr);
3346 else if (response.IsUnsupportedResponse())
3348 "GDB server does not support flashing");
3349 else
3351 "unexpected response to GDB server flash erase packet '%s': '%s'",
3352 packet.GetData(), response.GetStringRef().data());
3353 }
3354 } else {
3355 status = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3356 packet.GetData());
3357 }
3358 return status;
3359}
3360
3362 Status status;
3363 // If we haven't erased any blocks, then we must not have written anything
3364 // either, so there is no need to actually send a vFlashDone command
3365 if (m_erased_flash_ranges.IsEmpty())
3366 return status;
3367 StringExtractorGDBRemote response;
3368 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
3371 if (response.IsOKResponse()) {
3372 m_erased_flash_ranges.Clear();
3373 } else {
3374 if (response.IsErrorResponse())
3375 status = Status::FromErrorStringWithFormat("flash done failed");
3376 else if (response.IsUnsupportedResponse())
3378 "GDB server does not support flashing");
3379 else
3381 "unexpected response to GDB server flash done packet: '%s'",
3382 response.GetStringRef().data());
3383 }
3384 } else {
3385 status =
3386 Status::FromErrorStringWithFormat("failed to send flash done packet");
3387 }
3388 return status;
3389}
3390
3391size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
3392 size_t size, Status &error) {
3394 // M and m packets take 2 bytes for 1 byte of memory
3395 size_t max_memory_size = m_max_memory_size / 2;
3396 if (size > max_memory_size) {
3397 // Keep memory read sizes down to a sane limit. This function will be
3398 // called multiple times in order to complete the task by
3399 // lldb_private::Process so it is ok to do this.
3400 size = max_memory_size;
3401 }
3402
3403 StreamGDBRemote packet;
3404
3405 MemoryRegionInfo region;
3406 Status region_status = GetMemoryRegionInfo(addr, region);
3407
3408 bool is_flash = region_status.Success() && region.GetFlash() == eLazyBoolYes;
3409
3410 if (is_flash) {
3411 if (!m_allow_flash_writes) {
3412 error = Status::FromErrorString("Writing to flash memory is not allowed");
3413 return 0;
3414 }
3415 // Keep the write within a flash memory region
3416 if (addr + size > region.GetRange().GetRangeEnd())
3417 size = region.GetRange().GetRangeEnd() - addr;
3418 // Flash memory must be erased before it can be written
3419 error = FlashErase(addr, size);
3420 if (!error.Success())
3421 return 0;
3422 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
3423 packet.PutEscapedBytes(buf, size);
3424 } else {
3425 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
3426 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
3428 }
3429 StringExtractorGDBRemote response;
3430 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3433 if (response.IsOKResponse()) {
3434 error.Clear();
3435 return size;
3436 } else if (response.IsErrorResponse())
3438 "memory write failed for 0x%" PRIx64, addr);
3439 else if (response.IsUnsupportedResponse())
3441 "GDB server does not support writing memory");
3442 else
3444 "unexpected response to GDB server memory write packet '%s': '%s'",
3445 packet.GetData(), response.GetStringRef().data());
3446 } else {
3447 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3448 packet.GetData());
3449 }
3450 return 0;
3451}
3452
3454 // Probe the _M packet. Falling back to mmap() only needs its symbol.
3455 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolCalculate) {
3456 addr_t addr = m_gdb_comm.AllocateMemory(8, ePermissionsReadable |
3457 ePermissionsWritable |
3458 ePermissionsExecutable);
3459 if (addr != LLDB_INVALID_ADDRESS)
3460 m_gdb_comm.DeallocateMemory(addr);
3461 }
3462 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3463 return true;
3464
3466 options.include_symbols = true;
3467 options.include_inlines = false;
3468 SymbolContextList sc_list;
3470 ConstString("mmap"), eFunctionNameTypeFull, options, sc_list);
3471 return !sc_list.IsEmpty();
3472}
3473
3475 uint32_t permissions,
3476 Status &error) {
3478 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3479
3480 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3481 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3482 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3483 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3484 return allocated_addr;
3485 }
3486
3487 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3488 // Call mmap() to create memory in the inferior..
3489 unsigned prot = 0;
3490 if (permissions & lldb::ePermissionsReadable)
3491 prot |= eMmapProtRead;
3492 if (permissions & lldb::ePermissionsWritable)
3493 prot |= eMmapProtWrite;
3494 if (permissions & lldb::ePermissionsExecutable)
3495 prot |= eMmapProtExec;
3496
3497 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3499 m_addr_to_mmap_size[allocated_addr] = size;
3500 else {
3501 allocated_addr = LLDB_INVALID_ADDRESS;
3502 LLDB_LOGF(log,
3503 "ProcessGDBRemote::%s no direct stub support for memory "
3504 "allocation, and InferiorCallMmap also failed - is stub "
3505 "missing register context save/restore capability?",
3506 __FUNCTION__);
3507 }
3508 }
3509
3510 if (allocated_addr == LLDB_INVALID_ADDRESS)
3512 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3513 (uint64_t)size, GetPermissionsAsCString(permissions));
3514 else
3515 error.Clear();
3516 return allocated_addr;
3517}
3518
3520 MemoryRegionInfo &region_info) {
3521
3522 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
3523 return error;
3524}
3525
3527 return m_gdb_comm.GetWatchpointSlotCount();
3528}
3529
3531 return m_gdb_comm.GetWatchpointReportedAfter();
3532}
3533
3535 Status error;
3536 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3537
3538 switch (supported) {
3539 case eLazyBoolCalculate:
3540 // We should never be deallocating memory without allocating memory first
3541 // so we should never get eLazyBoolCalculate
3543 "tried to deallocate memory without ever allocating memory");
3544 break;
3545
3546 case eLazyBoolYes:
3547 if (!m_gdb_comm.DeallocateMemory(addr))
3549 "unable to deallocate memory at 0x%" PRIx64, addr);
3550 break;
3551
3552 case eLazyBoolNo:
3553 // Call munmap() to deallocate memory in the inferior..
3554 {
3555 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3556 if (pos != m_addr_to_mmap_size.end() &&
3557 InferiorCallMunmap(this, addr, pos->second))
3558 m_addr_to_mmap_size.erase(pos);
3559 else
3561 "unable to deallocate memory at 0x%" PRIx64, addr);
3562 }
3563 break;
3564 }
3565
3566 return error;
3567}
3568
3569// Process STDIO
3570size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3571 Status &error) {
3572 if (m_stdio_communication.IsConnected()) {
3573 ConnectionStatus status;
3574 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
3575 } else if (m_stdin_forward) {
3576 m_gdb_comm.SendStdinNotification(src, src_len, GetInterruptTimeout());
3577 }
3578 return 0;
3579}
3580
3581/// Enable a single breakpoint site by trying Z0 (software), then Z1
3582/// (hardware), then manual memory write as a last resort.
3585 const addr_t addr = bp_site.GetLoadAddress();
3586 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3587 auto &gdb_comm = GetGDBRemote();
3588
3589 // SupportsGDBStoppointPacket always returns true unless a previously sent
3590 // packet failed. As such, query the function before AND after sending the
3591 // packet.
3592 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3593 !bp_site.HardwareRequired()) {
3594 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3595 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
3596 if (error_no == 0) {
3597 SetBreakpointSiteEnabled(bp_site);
3599 return llvm::Error::success();
3600 }
3601 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3602 if (error_no != UINT8_MAX)
3603 return llvm::createStringErrorV(
3604 "error sending the breakpoint request: {0}", error_no);
3605 return llvm::createStringError("error sending the breakpoint request");
3606 }
3607 LLDB_LOG(log, "Software breakpoints are unsupported");
3608 }
3609
3610 // Like above, this is also queried twice.
3611 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3612 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3613 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3614 if (error_no == 0) {
3615 SetBreakpointSiteEnabled(bp_site);
3617 return llvm::Error::success();
3618 }
3619 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3620 if (error_no != UINT8_MAX)
3621 return llvm::createStringErrorV(
3622 "error sending the hardware breakpoint request: {0} "
3623 "(hardware breakpoint resources might be exhausted or unavailable)",
3624 error_no);
3625 return llvm::createStringError(
3626 "error sending the hardware breakpoint request "
3627 "(hardware breakpoint resources might be exhausted or unavailable)");
3628 }
3629 LLDB_LOG(log, "Hardware breakpoints are unsupported");
3630 }
3631
3632 if (bp_site.HardwareRequired())
3633 return llvm::createStringError("hardware breakpoints are not supported");
3634
3635 return EnableSoftwareBreakpoint(&bp_site).takeError();
3636}
3637
3638/// Disable a single breakpoint site directly by sending the appropriate
3639/// z packet or restoring the original instruction.
3641 const addr_t addr = bp_site.GetLoadAddress();
3642 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3643 auto &gdb_comm = GetGDBRemote();
3644
3645 switch (bp_site.GetType()) {
3648 if (error.Fail())
3649 return error.takeError();
3650 break;
3651 }
3653 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr,
3654 bp_op_size, GetInterruptTimeout()))
3655 return llvm::createStringError("unknown error");
3656 break;
3658 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr,
3659 bp_op_size, GetInterruptTimeout()))
3660 return llvm::createStringError("unknown error");
3661 break;
3662 }
3663 SetBreakpointSiteEnabled(bp_site, false);
3664 return llvm::Error::success();
3665}
3666
3668 assert(bp_site != nullptr);
3669
3670 // Get logging info
3672 user_id_t site_id = bp_site->GetID();
3673
3674 // Get the breakpoint address
3675 const addr_t addr = bp_site->GetLoadAddress();
3676
3677 // Log that a breakpoint was requested
3678 LLDB_LOGF(log,
3679 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3680 ") address = 0x%" PRIx64,
3681 site_id, (uint64_t)addr);
3682
3683 // Breakpoint already exists and is enabled
3684 if (IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3685 LLDB_LOGF(log,
3686 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3687 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3688 site_id, (uint64_t)addr);
3689 return Status();
3690 }
3691
3692 return Status::FromError(DoEnableBreakpointSite(*bp_site));
3693}
3694
3696 assert(bp_site != nullptr);
3697 addr_t addr = bp_site->GetLoadAddress();
3698 user_id_t site_id = bp_site->GetID();
3700 LLDB_LOGF(log,
3701 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3702 ") addr = 0x%8.8" PRIx64,
3703 site_id, (uint64_t)addr);
3704
3705 if (!IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3706 LLDB_LOGF(log,
3707 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3708 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3709 site_id, (uint64_t)addr);
3710 return Status();
3711 }
3712
3714}
3715
3716// Pre-requisite: wp != NULL.
3717static GDBStoppointType
3719 assert(wp_res_sp);
3720 bool read = wp_res_sp->WatchpointResourceRead();
3721 bool write = wp_res_sp->WatchpointResourceWrite();
3722
3723 assert((read || write) &&
3724 "WatchpointResource type is neither read nor write");
3725 if (read && write)
3726 return eWatchpointReadWrite;
3727 else if (read)
3728 return eWatchpointRead;
3729 else
3730 return eWatchpointWrite;
3731}
3732
3734 Status error;
3735 if (!wp_sp) {
3736 error = Status::FromErrorString("No watchpoint specified");
3737 return error;
3738 }
3739 user_id_t watchID = wp_sp->GetID();
3740 addr_t addr = wp_sp->GetLoadAddress();
3742 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3743 watchID);
3744 if (wp_sp->IsEnabled()) {
3745 LLDB_LOGF(log,
3746 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3747 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3748 watchID, (uint64_t)addr);
3749 return error;
3750 }
3751
3752 bool read = wp_sp->WatchpointRead();
3753 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3754 size_t size = wp_sp->GetByteSize();
3755
3756 ArchSpec target_arch = GetTarget().GetArchitecture();
3757 WatchpointHardwareFeature supported_features =
3758 m_gdb_comm.GetSupportedWatchpointTypes();
3759
3760 std::vector<WatchpointResourceSP> resources =
3762 addr, size, read, write, supported_features, target_arch);
3763
3764 // LWP_TODO: Now that we know the WP Resources needed to implement this
3765 // Watchpoint, we need to look at currently allocated Resources in the
3766 // Process and if they match, or are within the same memory granule, or
3767 // overlapping memory ranges, then we need to combine them. e.g. one
3768 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1
3769 // byte at 0x1003, they must use the same hardware watchpoint register
3770 // (Resource) to watch them.
3771
3772 // This may mean that an existing resource changes its type (read to
3773 // read+write) or address range it is watching, in which case the old
3774 // watchpoint needs to be disabled and the new Resource addr/size/type
3775 // watchpoint enabled.
3776
3777 // If we modify a shared Resource to accomodate this newly added Watchpoint,
3778 // and we are unable to set all of the Resources for it in the inferior, we
3779 // will return an error for this Watchpoint and the shared Resource should
3780 // be restored. e.g. this Watchpoint requires three Resources, one which
3781 // is shared with another Watchpoint. We extend the shared Resouce to
3782 // handle both Watchpoints and we try to set two new ones. But if we don't
3783 // have sufficient watchpoint register for all 3, we need to show an error
3784 // for creating this Watchpoint and we should reset the shared Resource to
3785 // its original configuration because it is no longer shared.
3786
3787 bool set_all_resources = true;
3788 std::vector<WatchpointResourceSP> succesfully_set_resources;
3789 for (const auto &wp_res_sp : resources) {
3790 addr_t addr = wp_res_sp->GetLoadAddress();
3791 size_t size = wp_res_sp->GetByteSize();
3792 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3793 if (!m_gdb_comm.SupportsGDBStoppointPacket(type) ||
3794 m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size,
3796 set_all_resources = false;
3797 break;
3798 } else {
3799 succesfully_set_resources.push_back(wp_res_sp);
3800 }
3801 }
3802 if (set_all_resources) {
3803 wp_sp->SetEnabled(true, notify);
3804 for (const auto &wp_res_sp : resources) {
3805 // LWP_TODO: If we expanded/reused an existing Resource,
3806 // it's already in the WatchpointResourceList.
3807 wp_res_sp->AddConstituent(wp_sp);
3808 m_watchpoint_resource_list.Add(wp_res_sp);
3809 }
3810 return error;
3811 } else {
3812 // We failed to allocate one of the resources. Unset all
3813 // of the new resources we did successfully set in the
3814 // process.
3815 for (const auto &wp_res_sp : succesfully_set_resources) {
3816 addr_t addr = wp_res_sp->GetLoadAddress();
3817 size_t size = wp_res_sp->GetByteSize();
3818 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3819 m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3821 }
3823 "Setting one of the watchpoint resources failed");
3824 }
3825 return error;
3826}
3827
3829 Status error;
3830 if (!wp_sp) {
3831 error = Status::FromErrorString("Watchpoint argument was NULL.");
3832 return error;
3833 }
3834
3835 user_id_t watchID = wp_sp->GetID();
3836
3838
3839 addr_t addr = wp_sp->GetLoadAddress();
3840
3841 LLDB_LOGF(log,
3842 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3843 ") addr = 0x%8.8" PRIx64,
3844 watchID, (uint64_t)addr);
3845
3846 if (!wp_sp->IsEnabled()) {
3847 LLDB_LOGF(log,
3848 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3849 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3850 watchID, (uint64_t)addr);
3851 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3852 // attempt might come from the user-supplied actions, we'll route it in
3853 // order for the watchpoint object to intelligently process this action.
3854 wp_sp->SetEnabled(false, notify);
3855 return error;
3856 }
3857
3858 if (wp_sp->IsHardware()) {
3859 bool disabled_all = true;
3860
3861 std::vector<WatchpointResourceSP> unused_resources;
3862 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
3863 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3864 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3865 addr_t addr = wp_res_sp->GetLoadAddress();
3866 size_t size = wp_res_sp->GetByteSize();
3867 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3869 disabled_all = false;
3870 } else {
3871 wp_res_sp->RemoveConstituent(wp_sp);
3872 if (wp_res_sp->GetNumberOfConstituents() == 0)
3873 unused_resources.push_back(wp_res_sp);
3874 }
3875 }
3876 }
3877 for (auto &wp_res_sp : unused_resources)
3878 m_watchpoint_resource_list.Remove(wp_res_sp->GetID());
3879
3880 wp_sp->SetEnabled(false, notify);
3881 if (!disabled_all)
3883 "Failure disabling one of the watchpoint locations");
3884 }
3885 return error;
3886}
3887
3889 m_thread_list_real.Clear();
3890 m_thread_list.Clear();
3891}
3892
3894 Status error;
3895 Log *log = GetLog(GDBRLog::Process);
3896 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3897
3898 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3899 error =
3900 Status::FromErrorStringWithFormat("failed to send signal %i", signo);
3901 return error;
3902}
3903
3904Status
3906 // Make sure we aren't already connected?
3907 if (m_gdb_comm.IsConnected())
3908 return Status();
3909
3910 PlatformSP platform_sp(GetTarget().GetPlatform());
3911 if (platform_sp && !platform_sp->IsHost())
3912 return Status::FromErrorString("Lost debug server connection");
3913
3914 auto error = LaunchAndConnectToDebugserver(process_info);
3915 if (error.Fail()) {
3916 const char *error_string = error.AsCString();
3917 if (error_string == nullptr)
3918 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3919 }
3920 return error;
3921}
3922
3924 Log *log = GetLog(GDBRLog::Process);
3925 // If we locate debugserver, keep that located version around
3926 static FileSpec g_debugserver_file_spec;
3927 FileSpec debugserver_file_spec;
3928
3929 Environment host_env = Host::GetEnvironment();
3930
3931 // Always check to see if we have an environment override for the path to the
3932 // debugserver to use and use it if we do.
3933 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
3934 if (!env_debugserver_path.empty()) {
3935 debugserver_file_spec.SetFile(env_debugserver_path,
3936 FileSpec::Style::native);
3937 LLDB_LOG(log, "gdb-remote stub exe path set from environment variable: {0}",
3938 env_debugserver_path);
3939 } else
3940 debugserver_file_spec = g_debugserver_file_spec;
3941 if (FileSystem::Instance().Exists(debugserver_file_spec))
3942 return debugserver_file_spec;
3943
3944 // The debugserver binary is in the LLDB.framework/Resources directory.
3945 debugserver_file_spec = HostInfo::GetSupportExeDir();
3946 if (debugserver_file_spec) {
3947 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
3948 if (FileSystem::Instance().Exists(debugserver_file_spec)) {
3949 LLDB_LOG(log, "found gdb-remote stub exe '{0}'", debugserver_file_spec);
3950
3951 g_debugserver_file_spec = debugserver_file_spec;
3952 } else {
3953 debugserver_file_spec = platform.LocateExecutable(DEBUGSERVER_BASENAME);
3954 if (!debugserver_file_spec) {
3955 // Platform::LocateExecutable() wouldn't return a path if it doesn't
3956 // exist
3957 LLDB_LOG(log, "could not find gdb-remote stub exe '{0}'",
3958 debugserver_file_spec);
3959 }
3960 // Don't cache the platform specific GDB server binary as it could
3961 // change from platform to platform
3962 g_debugserver_file_spec.Clear();
3963 }
3964 }
3965 return debugserver_file_spec;
3966}
3967
3969 const ProcessInfo &process_info) {
3970 using namespace std::placeholders; // For _1, _2, etc.
3971
3973 return Status();
3974
3975 ProcessLaunchInfo debugserver_launch_info;
3976 // Make debugserver run in its own session so signals generated by special
3977 // terminal key sequences (^C) don't affect debugserver.
3978 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3979
3980 const std::weak_ptr<ProcessGDBRemote> this_wp =
3981 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3982 debugserver_launch_info.SetMonitorProcessCallback(
3983 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3984 debugserver_launch_info.SetUserID(process_info.GetUserID());
3985
3986 FileSpec debugserver_path = GetDebugserverPath(*GetTarget().GetPlatform());
3987
3988#if defined(__APPLE__)
3989 // On macOS 11, we need to support x86_64 applications translated to
3990 // arm64. We check whether a binary is translated and spawn the correct
3991 // debugserver accordingly.
3992 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID,
3993 static_cast<int>(process_info.GetProcessID())};
3994 struct kinfo_proc processInfo;
3995 size_t bufsize = sizeof(processInfo);
3996 if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize,
3997 NULL, 0) == 0 &&
3998 bufsize > 0) {
3999 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
4000 debugserver_path = FileSpec("/Library/Apple/usr/libexec/oah/debugserver");
4001 }
4002 }
4003#endif
4004
4005 if (!FileSystem::Instance().Exists(debugserver_path))
4006 return Status::FromErrorString("could not find '" DEBUGSERVER_BASENAME
4007 "'. Please ensure it is properly installed "
4008 "and available in your PATH");
4009
4010 debugserver_launch_info.SetExecutableFile(debugserver_path,
4011 /*add_exe_file_as_first_arg=*/true);
4012
4013 llvm::Expected<Socket::Pair> socket_pair = Socket::CreatePair();
4014 if (!socket_pair)
4015 return Status::FromError(socket_pair.takeError());
4016
4017 Status error;
4018 SharedSocket shared_socket(socket_pair->first.get(), error);
4019 if (error.Fail())
4020 return error;
4021
4022 error = m_gdb_comm.StartDebugserverProcess(shared_socket.GetSendableFD(),
4023 debugserver_launch_info, nullptr);
4024
4025 if (error.Fail()) {
4026 Log *log = GetLog(GDBRLog::Process);
4027
4028 LLDB_LOGF(log, "failed to start debugserver process: %s",
4029 error.AsCString());
4030 return error;
4031 }
4032
4033 m_debugserver_pid = debugserver_launch_info.GetProcessID();
4034 shared_socket.CompleteSending(m_debugserver_pid);
4035
4036 // Our process spawned correctly, we can now set our connection to use
4037 // our end of the socket pair
4038 m_gdb_comm.SetConnection(std::make_unique<ConnectionFileDescriptor>(
4039 std::move(socket_pair->second)));
4041
4042 if (m_gdb_comm.IsConnected()) {
4043 // Finish the connection process by doing the handshake without
4044 // connecting (send NULL URL)
4046 } else {
4047 error = Status::FromErrorString("connection failed");
4048 }
4049 return error;
4050}
4051
4053 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
4054 int signo, // Zero for no signal
4055 int exit_status // Exit value of process if signal is zero
4056) {
4057 // "debugserver_pid" argument passed in is the process ID for debugserver
4058 // that we are tracking...
4059 Log *log = GetLog(GDBRLog::Process);
4060
4061 LLDB_LOGF(log,
4062 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
4063 ", signo=%i (0x%x), exit_status=%i)",
4064 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
4065
4066 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
4067 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
4068 static_cast<void *>(process_sp.get()));
4069 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
4070 return;
4071
4072 // Sleep for a half a second to make sure our inferior process has time to
4073 // set its exit status before we set it incorrectly when both the debugserver
4074 // and the inferior process shut down.
4075 std::this_thread::sleep_for(std::chrono::milliseconds(500));
4076
4077 // If our process hasn't yet exited, debugserver might have died. If the
4078 // process did exit, then we are reaping it.
4079 const StateType state = process_sp->GetState();
4080
4081 if (state != eStateInvalid && state != eStateUnloaded &&
4082 state != eStateExited && state != eStateDetached) {
4083 StreamString stream;
4084 if (signo == 0)
4085 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",
4086 exit_status);
4087 else {
4088 llvm::StringRef signal_name =
4089 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
4090 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";
4091 if (!signal_name.empty())
4092 stream.Format(format_str, signal_name);
4093 else
4094 stream.Format(format_str, signo);
4095 }
4096 process_sp->SetExitStatus(-1, stream.GetString());
4097 }
4098 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
4099 // longer has a debugserver instance
4100 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
4101}
4102
4110
4116
4119 debugger, PluginProperties::GetSettingName())) {
4120 const bool is_global_setting = true;
4123 "Properties for the gdb-remote process plug-in.", is_global_setting);
4124 }
4125}
4126
4128 Log *log = GetLog(GDBRLog::Process);
4129
4130 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4131
4132 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4133 if (!m_async_thread.IsJoinable()) {
4134 // Create a thread that watches our internal state and controls which
4135 // events make it to clients (into the DCProcess event queue).
4136
4137 llvm::Expected<HostThread> async_thread =
4138 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
4140 });
4141 if (!async_thread) {
4142 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
4143 "failed to launch host thread: {0}");
4144 return false;
4145 }
4146 m_async_thread = *async_thread;
4147 } else
4148 LLDB_LOGF(log,
4149 "ProcessGDBRemote::%s () - Called when Async thread was "
4150 "already running.",
4151 __FUNCTION__);
4152
4153 return m_async_thread.IsJoinable();
4154}
4155
4157 Log *log = GetLog(GDBRLog::Process);
4158
4159 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4160
4161 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4162 if (m_async_thread.IsJoinable()) {
4164
4165 // This will shut down the async thread.
4166 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
4167
4168 // Stop the stdio thread
4169 m_async_thread.Join(nullptr);
4170 m_async_thread.Reset();
4171 } else
4172 LLDB_LOGF(
4173 log,
4174 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
4175 __FUNCTION__);
4176}
4177
4179 Log *log = GetLog(GDBRLog::Process);
4180 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
4181 __FUNCTION__, GetID());
4182
4183 EventSP event_sp;
4184
4185 // We need to ignore any packets that come in after we have
4186 // have decided the process has exited. There are some
4187 // situations, for instance when we try to interrupt a running
4188 // process and the interrupt fails, where another packet might
4189 // get delivered after we've decided to give up on the process.
4190 // But once we've decided we are done with the process we will
4191 // not be in a state to do anything useful with new packets.
4192 // So it is safer to simply ignore any remaining packets by
4193 // explicitly checking for eStateExited before reentering the
4194 // fetch loop.
4195
4196 bool done = false;
4197 while (!done && GetPrivateState() != eStateExited) {
4198 LLDB_LOGF(log,
4199 "ProcessGDBRemote::%s(pid = %" PRIu64
4200 ") listener.WaitForEvent (NULL, event_sp)...",
4201 __FUNCTION__, GetID());
4202
4203 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
4204 const uint32_t event_type = event_sp->GetType();
4205 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
4206 LLDB_LOGF(log,
4207 "ProcessGDBRemote::%s(pid = %" PRIu64
4208 ") Got an event of type: %d...",
4209 __FUNCTION__, GetID(), event_type);
4210
4211 switch (event_type) {
4213 const EventDataBytes *continue_packet =
4215
4216 if (continue_packet) {
4217 const char *continue_cstr =
4218 (const char *)continue_packet->GetBytes();
4219 const size_t continue_cstr_len = continue_packet->GetByteSize();
4220 LLDB_LOGF(log,
4221 "ProcessGDBRemote::%s(pid = %" PRIu64
4222 ") got eBroadcastBitAsyncContinue: %s",
4223 __FUNCTION__, GetID(), continue_cstr);
4224
4225 if (::strstr(continue_cstr, "vAttach") == nullptr)
4227 StringExtractorGDBRemote response;
4228
4229 StateType stop_state =
4231 *this, *GetUnixSignals(),
4232 llvm::StringRef(continue_cstr, continue_cstr_len),
4233 GetInterruptTimeout(), response);
4234
4235 // We need to immediately clear the thread ID list so we are sure
4236 // to get a valid list of threads. The thread ID list might be
4237 // contained within the "response", or the stop reply packet that
4238 // caused the stop. So clear it now before we give the stop reply
4239 // packet to the process using the
4240 // SetLastStopPacket()...
4242
4243 switch (stop_state) {
4244 case eStateStopped:
4245 case eStateCrashed:
4246 case eStateSuspended:
4247 SetLastStopPacket(response);
4248 SetPrivateState(stop_state);
4249 break;
4250
4251 case eStateExited: {
4252 SetLastStopPacket(response);
4254 response.SetFilePos(1);
4255
4256 int exit_status = response.GetHexU8();
4257 std::string desc_string;
4258 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
4259 llvm::StringRef desc_str;
4260 llvm::StringRef desc_token;
4261 while (response.GetNameColonValue(desc_token, desc_str)) {
4262 if (desc_token != "description")
4263 continue;
4264 StringExtractor extractor(desc_str);
4265 extractor.GetHexByteString(desc_string);
4266 }
4267 }
4268 SetExitStatus(exit_status, desc_string.c_str());
4269 done = true;
4270 break;
4271 }
4272 case eStateInvalid: {
4273 // Check to see if we were trying to attach and if we got back
4274 // the "E87" error code from debugserver -- this indicates that
4275 // the process is not debuggable. Return a slightly more
4276 // helpful error message about why the attach failed.
4277 if (::strstr(continue_cstr, "vAttach") != nullptr &&
4278 response.GetError() == 0x87) {
4279 SetExitStatus(-1, "cannot attach to process due to "
4280 "System Integrity Protection");
4281 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
4282 response.GetStatus().Fail()) {
4283 SetExitStatus(-1, response.GetStatus().AsCString());
4284 } else {
4285 SetExitStatus(-1, "lost connection");
4286 }
4287 done = true;
4288 break;
4289 }
4290
4291 default:
4292 SetPrivateState(stop_state);
4293 break;
4294 } // switch(stop_state)
4295 } // if (continue_packet)
4296 } // case eBroadcastBitAsyncContinue
4297 break;
4298
4300 LLDB_LOGF(log,
4301 "ProcessGDBRemote::%s(pid = %" PRIu64
4302 ") got eBroadcastBitAsyncThreadShouldExit...",
4303 __FUNCTION__, GetID());
4304 done = true;
4305 break;
4306
4307 default:
4308 LLDB_LOGF(log,
4309 "ProcessGDBRemote::%s(pid = %" PRIu64
4310 ") got unknown event 0x%8.8x",
4311 __FUNCTION__, GetID(), event_type);
4312 done = true;
4313 break;
4314 }
4315 }
4316 } else {
4317 LLDB_LOGF(log,
4318 "ProcessGDBRemote::%s(pid = %" PRIu64
4319 ") listener.WaitForEvent (NULL, event_sp) => false",
4320 __FUNCTION__, GetID());
4321 done = true;
4322 }
4323 }
4324
4325 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
4326 __FUNCTION__, GetID());
4327
4328 return {};
4329}
4330
4331// uint32_t
4332// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
4333// &matches, std::vector<lldb::pid_t> &pids)
4334//{
4335// // If we are planning to launch the debugserver remotely, then we need to
4336// fire up a debugserver
4337// // process and ask it for the list of processes. But if we are local, we
4338// can let the Host do it.
4339// if (m_local_debugserver)
4340// {
4341// return Host::ListProcessesMatchingName (name, matches, pids);
4342// }
4343// else
4344// {
4345// // FIXME: Implement talking to the remote debugserver.
4346// return 0;
4347// }
4348//
4349//}
4350//
4352 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4353 lldb::user_id_t break_loc_id) {
4354 // I don't think I have to do anything here, just make sure I notice the new
4355 // thread when it starts to
4356 // run so I can stop it if that's what I want to do.
4357 Log *log = GetLog(LLDBLog::Step);
4358 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
4359 return false;
4360}
4361
4362namespace {
4363/// Baton that carries the breakpoint hit arguments to the accelerator plugin
4364/// breakpoint callback.
4365class AcceleratorBreakpointCallbackBaton
4366 : public TypedBaton<AcceleratorBreakpointHitArgs> {
4367public:
4368 explicit AcceleratorBreakpointCallbackBaton(
4369 std::unique_ptr<AcceleratorBreakpointHitArgs> data)
4370 : TypedBaton(std::move(data)) {}
4371};
4372} // namespace
4373
4374llvm::Error
4376 Log *log = GetLog(GDBRLog::Process);
4377
4378 // The same set of actions can be delivered to the client more than once: a
4379 // plugin may keep reporting the same actions (with the same identifier) on
4380 // subsequent native stops until its state advances. The identifier uniquely
4381 // names a set of actions for a plugin, so skip any set we have already
4382 // processed to avoid re-running its side effects (e.g. setting the same
4383 // breakpoints again).
4384 auto it = m_processed_accelerator_actions.find(actions.plugin_name);
4385 if (it != m_processed_accelerator_actions.end() &&
4386 it->second == actions.identifier) {
4387 LLDB_LOG(log,
4388 "ProcessGDBRemote::HandleAcceleratorActions skipping already "
4389 "processed actions for plugin '{0}' with identifier {1}",
4390 actions.plugin_name, actions.identifier);
4391 return llvm::Error::success();
4392 }
4394
4395 // Handle each kind of action. More action kinds will be handled here in the
4396 // future, so only return early on error; otherwise fall through so the next
4397 // kind of action still gets a chance to run.
4398 if (!actions.breakpoints.empty()) {
4399 if (llvm::Error error = HandleAcceleratorBreakpoints(actions))
4400 return error;
4401 }
4402
4403 if (actions.connect_info) {
4404 if (llvm::Error error = HandleAcceleratorConnection(actions))
4405 return error;
4406 }
4407
4408 return llvm::Error::success();
4409}
4410
4412 const AcceleratorActions &actions) {
4413 const AcceleratorConnectionInfo &connect_info = *actions.connect_info;
4414 Debugger &debugger = GetTarget().GetDebugger();
4415
4416 OptionGroupPlatform platform_options(/*include_platform_option=*/false);
4417 platform_options.SetPlatformName(connect_info.platform_name.c_str());
4418 std::string exe_path = connect_info.exe_path.value_or("");
4419 TargetSP accelerator_target_sp;
4421 debugger, exe_path, connect_info.triple, eLoadDependentsNo,
4422 &platform_options, accelerator_target_sp);
4423 if (error.Fail())
4424 return error.takeError();
4425 if (!accelerator_target_sp)
4426 return llvm::createStringError("failed to create accelerator target");
4427
4428 llvm::scope_exit delete_accelerator_target([&] {
4429 debugger.GetTargetList().DeleteTarget(accelerator_target_sp);
4430 accelerator_target_sp->Destroy();
4431 });
4432
4433 PlatformSP platform_sp = accelerator_target_sp->GetPlatform();
4434 if (!platform_sp)
4435 return llvm::createStringErrorV(
4436 "no platform '{0}' compatible with triple '{1}' for the accelerator "
4437 "target",
4438 connect_info.platform_name, connect_info.triple);
4439
4440 TargetSP native_target_sp = GetTarget().shared_from_this();
4441 std::shared_ptr<TargetGroupCPUAndAccelerators> group_sp =
4442 native_target_sp
4443 ->GetFirstTargetGroupOfType<TargetGroupCPUAndAccelerators>();
4444
4445 bool created_group = !group_sp;
4446 if (created_group) {
4447 group_sp = debugger.GetTargetGroupList()
4449 "CPU and accelerator targets");
4450 }
4451
4452 llvm::scope_exit restore_target_group([&] {
4453 group_sp->RemoveTarget(accelerator_target_sp);
4454 if (created_group) {
4455 group_sp->RemoveTarget(native_target_sp);
4456 debugger.GetTargetGroupList().DeleteTargetGroup(group_sp);
4457 }
4458 });
4459
4460 if (llvm::Error membership_error =
4461 group_sp->AddTarget(native_target_sp, TargetGroup::Role::CPU))
4462 return membership_error;
4463 if (llvm::Error membership_error = group_sp->AddTarget(
4464 accelerator_target_sp, TargetGroup::Role::Accelerator))
4465 return membership_error;
4466
4467 ProcessSP process_sp =
4468 connect_info.synchronous
4469 ? platform_sp->ConnectProcessSynchronous(
4470 connect_info.connect_url, GetPluginNameStatic(), debugger,
4471 *debugger.GetAsyncOutputStream(), accelerator_target_sp.get(),
4472 error)
4473 : platform_sp->ConnectProcess(connect_info.connect_url,
4474 GetPluginNameStatic(), debugger,
4475 accelerator_target_sp.get(), error);
4476 if (error.Fail())
4477 return error.takeError();
4478 if (!process_sp)
4479 return llvm::createStringError("failed to connect to the accelerator");
4480
4481 restore_target_group.release();
4482 delete_accelerator_target.release();
4483 accelerator_target_sp->SetTargetSessionName(actions.session_name);
4484
4485 // Broadcast the new-target event so API clients can detect it.
4486 auto event_sp = std::make_shared<Event>(
4488 new Target::TargetEventData(GetTarget().shared_from_this(),
4489 accelerator_target_sp));
4490 GetTarget().BroadcastEvent(event_sp);
4491 return llvm::Error::success();
4492}
4493
4495 const AcceleratorActions &actions) {
4496 Target &target = GetTarget();
4497 llvm::Error error = llvm::Error::success();
4498 for (const AcceleratorBreakpointInfo &bp : actions.breakpoints) {
4499 // Carry data with the breakpoint so the callback can notify the plugin
4500 // when the breakpoint is hit.
4501 auto args_up = std::make_unique<AcceleratorBreakpointHitArgs>();
4502 args_up->plugin_name = actions.plugin_name;
4503 args_up->breakpoint = bp;
4504
4505 // Each breakpoint must specify exactly one of by_name or by_address. Bad
4506 // breakpoints are collected as errors but don't stop the remaining ones
4507 // from being set.
4508 BreakpointSP bp_sp;
4509 if (bp.by_name && bp.by_address) {
4510 error = llvm::joinErrors(
4511 std::move(error),
4512 llvm::createStringErrorV(
4513 "accelerator breakpoint {0} specifies both a by_name and a "
4514 "by_address specification",
4515 bp.identifier));
4516 continue;
4517 } else if (bp.by_name) {
4518 FileSpecList bp_modules;
4519 if (bp.by_name->shlib && !bp.by_name->shlib->empty())
4520 bp_modules.Append(FileSpec(*bp.by_name->shlib));
4521 bp_sp = target.CreateBreakpoint(
4522 bp_modules.GetSize() ? &bp_modules : nullptr, // Containing modules.
4523 nullptr, // Containing source.
4524 bp.by_name->function_name.c_str(), // Function name.
4525 eFunctionNameTypeFull, // Function name type.
4526 eLanguageTypeUnknown, // Language type.
4527 0, // Byte offset.
4528 false, // Offset is insn count.
4529 eLazyBoolNo, // Skip prologue.
4530 true, // Internal breakpoint.
4531 false); // Request hardware.
4532 } else if (bp.by_address) {
4533 bp_sp = target.CreateBreakpoint(bp.by_address->load_address,
4534 /*internal=*/true,
4535 /*request_hardware=*/false);
4536 } else {
4537 error = llvm::joinErrors(
4538 std::move(error),
4539 llvm::createStringErrorV(
4540 "accelerator breakpoint {0} has neither a by_name nor a "
4541 "by_address specification",
4542 bp.identifier));
4543 continue;
4544 }
4545
4546 if (!bp_sp) {
4547 error = llvm::joinErrors(
4548 std::move(error),
4549 llvm::createStringErrorV("failed to set accelerator breakpoint {0}",
4550 bp.identifier));
4551 continue;
4552 }
4553
4554 // Give the internal breakpoint a meaningful description for stop reasons,
4555 // including the plugin that requested it.
4556 std::string kind =
4557 llvm::formatv("accelerator-plugin ({0})", actions.plugin_name);
4558 bp_sp->SetBreakpointKind(kind.c_str());
4559 auto baton_sp = std::make_shared<AcceleratorBreakpointCallbackBaton>(
4560 std::move(args_up));
4561 bp_sp->SetCallback(AcceleratorBreakpointHitCallback, baton_sp,
4562 /*is_synchronous=*/true);
4563 }
4564 return error;
4565}
4566
4568 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4569 lldb::user_id_t break_loc_id) {
4570 ProcessSP process_sp = context->exe_ctx_ref.GetProcessSP();
4571 ProcessGDBRemote *process = static_cast<ProcessGDBRemote *>(process_sp.get());
4572 return process->AcceleratorBreakpointHit(baton, context, break_id,
4573 break_loc_id);
4574}
4575
4577 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4578 lldb::user_id_t break_loc_id) {
4579 AcceleratorBreakpointHitArgs *callback_data =
4580 static_cast<AcceleratorBreakpointHitArgs *>(baton);
4581 // Copy the args so we can fill in requested symbol values before notifying
4582 // lldb-server.
4583 AcceleratorBreakpointHitArgs args = *callback_data;
4584 Target &target = GetTarget();
4585
4586 const std::vector<std::string> &symbol_names = args.breakpoint.symbol_names;
4587 args.symbol_values.resize(symbol_names.size());
4588 for (size_t i = 0; i < symbol_names.size(); ++i) {
4589 args.symbol_values[i].name = symbol_names[i];
4590 SymbolContextList sc_list;
4591 target.GetImages().FindSymbolsWithNameAndType(ConstString(symbol_names[i]),
4592 eSymbolTypeAny, sc_list);
4593 for (const SymbolContext &sc : sc_list) {
4594 if (!sc.symbol)
4595 continue;
4596 addr_t load_addr = sc.symbol->GetAddress().GetLoadAddress(&target);
4597 if (load_addr != LLDB_INVALID_ADDRESS) {
4598 args.symbol_values[i].value = load_addr;
4599 break;
4600 }
4601 }
4602 }
4603
4604 Log *log = GetLog(GDBRLog::Process);
4605 llvm::Expected<AcceleratorBreakpointHitResponse> response =
4606 m_gdb_comm.AcceleratorBreakpointHit(args);
4607 if (!response) {
4608 LLDB_LOG_ERROR(log, response.takeError(),
4609 "accelerator breakpoint hit notification failed: {0}");
4610 // We could not reach the plugin, so auto-resume rather than stopping the
4611 // native process at an internal breakpoint the user can't see.
4612 return false;
4613 }
4614
4615 // Disable the breakpoint if requested, but keep it around so its hit count
4616 // and other stats remain visible.
4617 if (response->disable_bp) {
4618 if (BreakpointSP bp_sp = target.GetBreakpointByID(break_id))
4619 bp_sp->SetEnabled(false);
4620 }
4621
4622 // The plugin may request new actions (e.g. additional breakpoints) in
4623 // response to this breakpoint being hit.
4624 if (response->actions) {
4625 if (llvm::Error error = HandleAcceleratorActions(*response->actions)) {
4626 // Also print the failure to the user; during a stop, logging alone is
4627 // invisible.
4628 std::string message = llvm::toString(std::move(error));
4629 LLDB_LOG(log, "failed to handle accelerator actions: {0}", message);
4630 target.GetDebugger().GetAsyncErrorStream()->Printf(
4631 "error: accelerator plugin '%s': %s\n",
4632 response->actions->plugin_name.c_str(), message.c_str());
4633 }
4634 }
4635
4636 // Returning true stops the native process; false auto-resumes it.
4637 return !response->auto_resume_native;
4638}
4639
4641 Log *log = GetLog(GDBRLog::Process);
4642 LLDB_LOG(log, "Check if need to update ignored signals");
4643
4644 // QPassSignals package is not supported by the server, there is no way we
4645 // can ignore any signals on server side.
4646 if (!m_gdb_comm.GetQPassSignalsSupported())
4647 return Status();
4648
4649 // No signals, nothing to send.
4650 if (m_unix_signals_sp == nullptr)
4651 return Status();
4652
4653 // Signals' version hasn't changed, no need to send anything.
4654 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
4655 if (new_signals_version == m_last_signals_version) {
4656 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
4658 return Status();
4659 }
4660
4661 auto signals_to_ignore =
4662 m_unix_signals_sp->GetFilteredSignals(false, false, false);
4663 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
4664
4665 LLDB_LOG(log,
4666 "Signals' version changed. old version={0}, new version={1}, "
4667 "signals ignored={2}, update result={3}",
4668 m_last_signals_version, new_signals_version,
4669 signals_to_ignore.size(), error);
4670
4671 if (error.Success())
4672 m_last_signals_version = new_signals_version;
4673
4674 return error;
4675}
4676
4678 Log *log = GetLog(LLDBLog::Step);
4680 LLDB_LOGF_VERBOSE(log, "Enabled noticing new thread breakpoint.");
4681 m_thread_create_bp_sp->SetEnabled(true);
4682 } else {
4683 PlatformSP platform_sp(GetTarget().GetPlatform());
4684 if (platform_sp) {
4686 platform_sp->SetThreadCreationBreakpoint(GetTarget());
4689 log, "Successfully created new thread notification breakpoint %i",
4690 m_thread_create_bp_sp->GetID());
4691 m_thread_create_bp_sp->SetCallback(
4693 } else {
4694 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
4695 }
4696 }
4697 }
4698 return m_thread_create_bp_sp.get() != nullptr;
4699}
4700
4702 Log *log = GetLog(LLDBLog::Step);
4703 LLDB_LOGF_VERBOSE(log, "Disabling new thread notification breakpoint.");
4704
4706 m_thread_create_bp_sp->SetEnabled(false);
4707
4708 return true;
4709}
4710
4712 if (m_dyld_up.get() == nullptr) {
4713 std::string plugin_name;
4714 if (std::optional<LLDBSettings> settings = m_gdb_comm.GetLLDBSettings())
4715 plugin_name = settings->dyld_plugin_name;
4716 m_dyld_up.reset(DynamicLoader::FindPlugin(this, plugin_name));
4717 }
4718 return m_dyld_up.get();
4719}
4720
4722 int return_value;
4723 bool was_supported;
4724
4725 Status error;
4726
4727 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4728 if (return_value != 0) {
4729 if (!was_supported)
4731 "Sending events is not supported for this process.");
4732 else
4733 error = Status::FromErrorStringWithFormat("Error sending event data: %d.",
4734 return_value);
4735 }
4736 return error;
4737}
4738
4740 DataBufferSP buf;
4741 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4742 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
4743 if (response)
4744 buf = std::make_shared<DataBufferHeap>(response->c_str(),
4745 response->length());
4746 else
4747 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
4748 }
4750}
4751
4754 StructuredData::ObjectSP object_sp;
4755
4756 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
4758 SystemRuntime *runtime = GetSystemRuntime();
4759 if (runtime) {
4760 runtime->AddThreadExtendedInfoPacketHints(args_dict);
4761 }
4762 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
4763
4764 StreamString packet;
4765 packet << "jThreadExtendedInfo:";
4766 args_dict->Dump(packet, false);
4767
4768 // FIXME the final character of a JSON dictionary, '}', is the escape
4769 // character in gdb-remote binary mode. lldb currently doesn't escape
4770 // these characters in its packet output -- so we add the quoted version of
4771 // the } character here manually in case we talk to a debugserver which un-
4772 // escapes the characters at packet read time.
4773 packet << (char)(0x7d ^ 0x20);
4774
4775 StringExtractorGDBRemote response;
4776 response.SetResponseValidatorToJSON();
4777 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4780 response.GetResponseType();
4781 if (response_type == StringExtractorGDBRemote::eResponse) {
4782 if (!response.Empty()) {
4783 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4784 }
4785 }
4786 }
4787 }
4788 return object_sp;
4789}
4790
4792 lldb::addr_t image_list_address, lldb::addr_t image_count) {
4793
4795 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4796 image_list_address);
4797 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4798
4799 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4800}
4801
4802static std::string
4804 std::string info_level_str;
4805 if (info_level == eBinaryInformationLevelAddrOnly)
4806 info_level_str = "address-only";
4807 else if (info_level == eBinaryInformationLevelAddrName)
4808 info_level_str = "address-name";
4809 else if (info_level == eBinaryInformationLevelAddrNameUUID)
4810 info_level_str = "address-name-uuid";
4811 else if (info_level == eBinaryInformationLevelFull)
4812 info_level_str = "full";
4813
4814 return info_level_str;
4815}
4816
4818 BinaryInformationLevel info_level) {
4820
4821 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4822 if (info_level != eBinaryInformationLevelFull)
4823 args_dict->GetAsDictionary()->AddBooleanItem("report_load_commands", false);
4824 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4825 if (!info_level_str.empty())
4826 args_dict->GetAsDictionary()->AddStringItem("information-level",
4827 info_level_str.c_str());
4828
4829 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4830}
4831
4833 BinaryInformationLevel info_level,
4834 const std::vector<lldb::addr_t> &load_addresses) {
4837
4838 for (auto addr : load_addresses)
4839 addresses->AddIntegerItem(addr);
4840
4841 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4842
4843 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4844 if (!info_level_str.empty())
4845 args_dict->GetAsDictionary()->AddStringItem("information-level",
4846 info_level_str.c_str());
4847
4848 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4849}
4850
4853 StructuredData::ObjectSP args_dict) {
4854 StructuredData::ObjectSP object_sp;
4855
4856 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4857 // Scope for the scoped timeout object
4859 std::chrono::seconds(10));
4860
4861 StreamString packet;
4862 packet << "jGetLoadedDynamicLibrariesInfos:";
4863 args_dict->Dump(packet, false);
4864
4865 // FIXME the final character of a JSON dictionary, '}', is the escape
4866 // character in gdb-remote binary mode. lldb currently doesn't escape
4867 // these characters in its packet output -- so we add the quoted version of
4868 // the } character here manually in case we talk to a debugserver which un-
4869 // escapes the characters at packet read time.
4870 packet << (char)(0x7d ^ 0x20);
4871
4872 StringExtractorGDBRemote response;
4873 response.SetResponseValidatorToJSON();
4874 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4877 response.GetResponseType();
4878 if (response_type == StringExtractorGDBRemote::eResponse) {
4879 if (!response.Empty()) {
4880 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4881 }
4882 }
4883 }
4884 }
4885 return object_sp;
4886}
4887
4889 StructuredData::ObjectSP object_sp;
4891
4892 if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
4893 StringExtractorGDBRemote response;
4894 response.SetResponseValidatorToJSON();
4895 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
4896 response) ==
4899 response.GetResponseType();
4900 if (response_type == StringExtractorGDBRemote::eResponse) {
4901 if (!response.Empty()) {
4902 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4903 }
4904 }
4905 }
4906 }
4907 return object_sp;
4908}
4909
4911 // Held across the query so a second caller waits for the answer instead of
4912 // sending the packet again.
4913 auto shared_cache_info = m_shared_cache_info.Lock();
4915
4916 if (*shared_cache_info || !m_gdb_comm.GetSharedCacheInfoSupported())
4917 return *shared_cache_info;
4918
4919 StreamString packet;
4920 packet << "jGetSharedCacheInfo:";
4921 args_dict->Dump(packet, false);
4922
4923 StringExtractorGDBRemote response;
4924 response.SetResponseValidatorToJSON();
4925 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4928 response.GetResponseType();
4929 if (response_type == StringExtractorGDBRemote::eResponse) {
4930 if (response.Empty())
4931 return {};
4932 StructuredData::ObjectSP response_sp =
4934 if (!response_sp)
4935 return {};
4936 StructuredData::Dictionary *dict = response_sp->GetAsDictionary();
4937 if (!dict)
4938 return {};
4939 if (!dict->HasKey("shared_cache_uuid"))
4940 return {};
4941 llvm::StringRef uuid_str;
4942 if (!dict->GetValueForKeyAsString("shared_cache_uuid", uuid_str, "") ||
4943 uuid_str == "00000000-0000-0000-0000-000000000000")
4944 return {};
4945 if (dict->HasKey("shared_cache_path")) {
4946 UUID uuid;
4947 uuid.SetFromStringRef(uuid_str);
4948 FileSpec sc_path(
4949 dict->GetValueForKey("shared_cache_path")->GetStringValue());
4950
4951 SymbolSharedCacheUse sc_mode =
4954
4957 // Attempt to open the shared cache at sc_path, and
4958 // if the uuid matches, index all the files.
4959 HostInfo::SharedCacheIndexFiles(sc_path, uuid, sc_mode);
4960 }
4961 }
4962 *shared_cache_info = response_sp;
4963 }
4964 }
4965 return *shared_cache_info;
4966}
4967
4969 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4970 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4971}
4972
4973// Establish the largest memory read/write payloads we should use. If the
4974// remote stub has a max packet size, stay under that size.
4975//
4976// If the remote stub's max packet size is crazy large, use a reasonable
4977// largeish default.
4978//
4979// If the remote stub doesn't advertise a max packet size, use a conservative
4980// default.
4981
4983 const uint64_t reasonable_largeish_default = 128 * 1024;
4984 const uint64_t conservative_default = 512;
4985
4986 if (m_max_memory_size == 0) {
4987 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4988 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4989 // Save the stub's claimed maximum packet size
4990 m_remote_stub_max_memory_size = stub_max_size;
4991
4992 // Even if the stub says it can support ginormous packets, don't exceed
4993 // our reasonable largeish default packet size.
4994 if (stub_max_size > reasonable_largeish_default) {
4995 stub_max_size = reasonable_largeish_default;
4996 }
4997
4998 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4999 // calculating the bytes taken by size and addr every time, we take a
5000 // maximum guess here.
5001 if (stub_max_size > 70)
5002 stub_max_size -= 32 + 32 + 6;
5003 else {
5004 // In unlikely scenario that max packet size is less then 70, we will
5005 // hope that data being written is small enough to fit.
5007 LLDB_LOG(log, "warning: Packet size is too small. "
5008 "LLDB may face problems while writing memory");
5009 }
5010
5011 m_max_memory_size = stub_max_size;
5012 } else {
5013 m_max_memory_size = conservative_default;
5014 }
5015 }
5016}
5017
5019 uint64_t user_specified_max) {
5020 if (user_specified_max != 0) {
5022
5024 if (m_remote_stub_max_memory_size < user_specified_max) {
5026 // packet size too
5027 // big, go as big
5028 // as the remote stub says we can go.
5029 } else {
5030 m_max_memory_size = user_specified_max; // user's packet size is good
5031 }
5032 } else {
5034 user_specified_max; // user's packet size is probably fine
5035 }
5036 }
5037}
5038
5039bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
5040 const ArchSpec &arch,
5041 ModuleSpec &module_spec) {
5043
5044 const ModuleCacheKey key(module_file_spec.GetPath(),
5045 arch.GetTriple().getTriple());
5046 auto cached = m_cached_module_specs.find(key);
5047 if (cached != m_cached_module_specs.end()) {
5048 module_spec = cached->second;
5049 return bool(module_spec);
5050 }
5051
5052 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
5053 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
5054 __FUNCTION__, module_file_spec.GetPath().c_str(),
5055 arch.GetTriple().getTriple().c_str());
5056 return false;
5057 }
5058
5059 if (log) {
5060 StreamString stream;
5061 module_spec.Dump(stream);
5062 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
5063 __FUNCTION__, module_file_spec.GetPath().c_str(),
5064 arch.GetTriple().getTriple().c_str(), stream.GetData());
5065 }
5066
5067 m_cached_module_specs[key] = module_spec;
5068 return true;
5069}
5070
5072 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
5073 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
5074 if (module_specs) {
5075 for (const FileSpec &spec : module_file_specs)
5077 triple.getTriple())] = ModuleSpec();
5078 for (const ModuleSpec &spec : *module_specs)
5079 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
5080 triple.getTriple())] = spec;
5081 }
5082}
5083
5085 return m_gdb_comm.GetOSVersion();
5086}
5087
5089 return m_gdb_comm.GetMacCatalystVersion();
5090}
5091
5092namespace {
5093
5094typedef std::vector<std::string> stringVec;
5095
5096typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
5097struct RegisterSetInfo {
5098 ConstString name;
5099};
5100
5101typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
5102
5103struct GdbServerTargetInfo {
5104 std::string arch;
5105 std::string osabi;
5106 stringVec includes;
5107 RegisterSetMap reg_set_map;
5108};
5109
5110using RegisterTypeMap = llvm::StringMap<const RegisterType *>;
5111
5113ParseEnumEvalues(const XMLNode &enum_node) {
5115 // We will use the last instance of each value. Also we preserve the order
5116 // of declaration in the XML, as it may not be numerical.
5117 // For example, hardware may initially release with two states that software
5118 // can read from a register field:
5119 // 0 = startup, 1 = running
5120 // If in a future hardware release, the designers added a pre-startup state:
5121 // 0 = startup, 1 = running, 2 = pre-startup
5122 // Now it makes more sense to list them in this logical order as opposed to
5123 // numerical order:
5124 // 2 = pre-startup, 1 = startup, 0 = startup
5125 // This only matters for "register info" but let's trust what the server
5126 // chose regardless.
5127 std::map<uint64_t, RegisterTypeEnum::Enumerator> enumerators;
5128
5130 "evalue", [&enumerators, &log](const XMLNode &enumerator_node) {
5131 std::optional<llvm::StringRef> name;
5132 std::optional<uint64_t> value;
5133
5134 enumerator_node.ForEachAttribute(
5135 [&name, &value, &log](const llvm::StringRef &attr_name,
5136 const llvm::StringRef &attr_value) {
5137 if (attr_name == "name") {
5138 if (attr_value.size())
5139 name = attr_value;
5140 else
5141 LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues "
5142 "Ignoring empty name in evalue");
5143 } else if (attr_name == "value") {
5144 uint64_t parsed_value = 0;
5145 if (llvm::to_integer(attr_value, parsed_value))
5146 value = parsed_value;
5147 else
5148 LLDB_LOG(log,
5149 "ProcessGDBRemote::ParseEnumEvalues "
5150 "Invalid value \"{0}\" in "
5151 "evalue",
5152 attr_value.data());
5153 } else
5154 LLDB_LOG(log,
5155 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
5156 "unknown attribute "
5157 "\"{0}\" in evalue",
5158 attr_name.data());
5159
5160 // Keep walking attributes.
5161 return true;
5162 });
5163
5164 if (value && name)
5165 enumerators.insert_or_assign(
5166 *value, RegisterTypeEnum::Enumerator(*value, name->str()));
5167
5168 // Find all evalue elements.
5169 return true;
5170 });
5171
5172 RegisterTypeEnum::Enumerators final_enumerators;
5173 for (auto [_, enumerator] : enumerators)
5174 final_enumerators.push_back(enumerator);
5175
5176 return final_enumerators;
5177}
5178
5179static void
5180ParseEnums(XMLNode feature_node, RegisterTypeMap &feature_register_types,
5181 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5182 Log *log(GetLog(GDBRLog::Process));
5183
5184 // The top level element is "<enum...".
5185 feature_node.ForEachChildElementWithName(
5186 "enum", [log, &feature_register_types,
5187 &owned_register_types](const XMLNode &enum_node) {
5188 std::string id;
5189
5190 enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name,
5191 const llvm::StringRef &attr_value) {
5192 if (attr_name == "id")
5193 id = attr_value;
5194
5195 // There is also a "size" attribute that is supposed to be the size in
5196 // bytes of the register this applies to. However:
5197 // * LLDB doesn't need this information.
5198 // * It is difficult to verify because you have to wait until the
5199 // enum is applied to a field.
5200 //
5201 // So we will emit this attribute in XML for GDB's sake, but will not
5202 // bother ingesting it.
5203
5204 // Walk all attributes.
5205 return true;
5206 });
5207
5208 if (!id.empty()) {
5209 RegisterTypeEnum::Enumerators enumerators =
5210 ParseEnumEvalues(enum_node);
5211 if (!enumerators.empty()) {
5212 LLDB_LOG(log,
5213 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
5214 id);
5215 auto enum_type =
5216 std::make_unique<RegisterTypeEnum>(id, enumerators);
5217 const RegisterTypeEnum *enum_type_ptr = enum_type.get();
5218 auto [it, inserted] =
5219 feature_register_types.try_emplace(id, enum_type_ptr);
5220 if (inserted) {
5221 owned_register_types.push_back(std::move(enum_type));
5222 } else if (llvm::isa<RegisterTypeEnum>(it->second)) {
5223 // Preserve the existing behavior where the last valid enum with
5224 // a repeated ID wins. All enums are parsed before flags, so no
5225 // fields can reference the enum being replaced yet. The earlier
5226 // object remains owned; only the feature lookup is updated.
5227 owned_register_types.push_back(std::move(enum_type));
5228 it->second = enum_type_ptr;
5229 } else {
5230 LLDB_LOG(
5231 log,
5232 "ProcessGDBRemote::ParseEnums Ignoring enum type \"{0}\" "
5233 "because another type with that id already exists",
5234 id);
5235 }
5236 }
5237 }
5238
5239 // Find all <enum> elements.
5240 return true;
5241 });
5242}
5243
5244static std::vector<RegisterTypeFlags::Field>
5245ParseFlagsFields(XMLNode flags_node, unsigned size,
5246 const RegisterTypeMap &feature_register_types) {
5247 Log *log(GetLog(GDBRLog::Process));
5248 const unsigned max_start_bit = size * 8 - 1;
5249
5250 // Process the fields of this set of flags.
5251 std::vector<RegisterTypeFlags::Field> fields;
5252 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log,
5253 &feature_register_types](
5254 const XMLNode
5255 &field_node) {
5256 std::optional<llvm::StringRef> name;
5257 std::optional<unsigned> start;
5258 std::optional<unsigned> end;
5259 std::optional<llvm::StringRef> type;
5260
5261 field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit,
5262 &log](const llvm::StringRef &attr_name,
5263 const llvm::StringRef &attr_value) {
5264 // Note that XML in general requires that each of these attributes only
5265 // appears once, so we don't have to handle that here.
5266 if (attr_name == "name") {
5267 LLDB_LOG(
5268 log,
5269 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
5270 attr_value.data());
5271 name = attr_value;
5272 } else if (attr_name == "start") {
5273 unsigned parsed_start = 0;
5274 if (llvm::to_integer(attr_value, parsed_start)) {
5275 if (parsed_start > max_start_bit) {
5276 LLDB_LOG(log,
5277 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
5278 "field node, "
5279 "cannot be > {1}",
5280 parsed_start, max_start_bit);
5281 } else
5282 start = parsed_start;
5283 } else {
5284 LLDB_LOG(
5285 log,
5286 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
5287 "field node",
5288 attr_value.data());
5289 }
5290 } else if (attr_name == "end") {
5291 unsigned parsed_end = 0;
5292 if (llvm::to_integer(attr_value, parsed_end))
5293 if (parsed_end > max_start_bit) {
5294 LLDB_LOG(log,
5295 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
5296 "field node, "
5297 "cannot be > {1}",
5298 parsed_end, max_start_bit);
5299 } else
5300 end = parsed_end;
5301 else {
5302 LLDB_LOG(log,
5303 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
5304 "field node",
5305 attr_value.data());
5306 }
5307 } else if (attr_name == "type") {
5308 type = attr_value;
5309 } else {
5310 LLDB_LOG(
5311 log,
5312 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
5313 "\"{0}\" in field node",
5314 attr_name.data());
5315 }
5316
5317 return true; // Walk all attributes of the field.
5318 });
5319
5320 if (name && start && end) {
5321 if (*start > *end)
5322 LLDB_LOG(
5323 log,
5324 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
5325 "\"{2}\", ignoring",
5326 *start, *end, name->data());
5327 else {
5328 if (RegisterTypeFlags::Field::GetSizeInBits(*start, *end) > 64)
5329 LLDB_LOG(log,
5330 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{}\" "
5331 "that has size > 64 bits, this is not supported",
5332 name->data());
5333 else {
5334 // A field's type may be set to the name of an enum type.
5335 const RegisterTypeEnum *enum_type = nullptr;
5336 if (type && !type->empty()) {
5337 auto found = feature_register_types.find(*type);
5338 if (found != feature_register_types.end()) {
5339 enum_type = llvm::dyn_cast<RegisterTypeEnum>(found->second);
5340
5341 if (!enum_type) {
5342 LLDB_LOG(log,
5343 "ProcessGDBRemote::ParseFlagsFields Type \"{0}\" for "
5344 "field \"{1}\" is not an enum, ignoring",
5345 type->data(), name->data());
5346 }
5347
5348 // No enumerator can exceed the range of the field itself.
5349 if (enum_type) {
5350 uint64_t max_value =
5352 for (const auto &enumerator : enum_type->GetEnumerators()) {
5353 if (enumerator.m_value > max_value) {
5354 enum_type = nullptr;
5355 LLDB_LOG(
5356 log,
5357 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
5358 "evalue \"{1}\" with value {2} exceeds the maximum "
5359 "value of field \"{3}\" ({4}), ignoring enum",
5360 type->data(), enumerator.m_name, enumerator.m_value,
5361 name->data(), max_value);
5362 break;
5363 }
5364 }
5365 }
5366 } else {
5367 LLDB_LOG(log,
5368 "ProcessGDBRemote::ParseFlagsFields Could not find type "
5369 "\"{0}\" "
5370 "for field \"{1}\", ignoring",
5371 type->data(), name->data());
5372 }
5373 }
5374
5375 fields.push_back(
5376 RegisterTypeFlags::Field(name->str(), *start, *end, enum_type));
5377 }
5378 }
5379 }
5380
5381 return true; // Iterate all "field" nodes.
5382 });
5383 return fields;
5384}
5385
5386void ParseFlags(
5387 XMLNode feature_node, RegisterTypeMap &feature_register_types,
5388 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5389 Log *log(GetLog(GDBRLog::Process));
5390
5391 feature_node.ForEachChildElementWithName(
5392 "flags",
5393 [&log, &feature_register_types,
5394 &owned_register_types](const XMLNode &flags_node) -> bool {
5395 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
5396 flags_node.GetAttributeValue("id").c_str());
5397
5398 std::optional<llvm::StringRef> id;
5399 std::optional<unsigned> size;
5400 flags_node.ForEachAttribute(
5401 [&id, &size, &log](const llvm::StringRef &name,
5402 const llvm::StringRef &value) {
5403 if (name == "id") {
5404 id = value;
5405 } else if (name == "size") {
5406 unsigned parsed_size = 0;
5407 if (llvm::to_integer(value, parsed_size))
5408 size = parsed_size;
5409 else {
5410 LLDB_LOG(log,
5411 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
5412 "in flags node",
5413 value.data());
5414 }
5415 } else {
5416 LLDB_LOG(log,
5417 "ProcessGDBRemote::ParseFlags Ignoring unknown "
5418 "attribute \"{0}\" in flags node",
5419 name.data());
5420 }
5421 return true; // Walk all attributes.
5422 });
5423
5424 if (id && size) {
5425 // Process the fields of this set of flags.
5426 std::vector<RegisterTypeFlags::Field> fields =
5427 ParseFlagsFields(flags_node, *size, feature_register_types);
5428 if (fields.size()) {
5429 // Sort so that the fields with the MSBs are first.
5430 std::sort(fields.rbegin(), fields.rend());
5431 std::vector<RegisterTypeFlags::Field>::const_iterator overlap =
5432 std::adjacent_find(fields.begin(), fields.end(),
5433 [](const RegisterTypeFlags::Field &lhs,
5434 const RegisterTypeFlags::Field &rhs) {
5435 return lhs.Overlaps(rhs);
5436 });
5437
5438 // If no fields overlap, use them.
5439 if (overlap == fields.end()) {
5440 if (feature_register_types.contains(*id)) {
5441 // Type IDs must be unique within a feature. Keep the type that
5442 // was already registered by the enum and flags parsing passes.
5443 LLDB_LOG(
5444 log,
5445 "ProcessGDBRemote::ParseFlags Definition of flags \"{0}\" "
5446 "conflicts with an existing type, ignoring this "
5447 "definition.",
5448 id->data());
5449 } else {
5450 auto flags_type = std::make_unique<RegisterTypeFlags>(
5451 id->str(), *size, std::move(fields));
5452 feature_register_types.try_emplace(*id, flags_type.get());
5453 owned_register_types.push_back(std::move(flags_type));
5454 }
5455 } else {
5456 // If any fields overlap, ignore the whole set of flags.
5457 std::vector<RegisterTypeFlags::Field>::const_iterator next =
5458 std::next(overlap);
5459 LLDB_LOG(
5460 log,
5461 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
5462 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
5463 "overlap.",
5464 overlap->GetName().c_str(), overlap->GetStart(),
5465 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
5466 next->GetEnd());
5467 }
5468 } else {
5469 LLDB_LOG(
5470 log,
5471 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
5472 "\"{0}\" because it contains no fields.",
5473 id->data());
5474 }
5475 }
5476
5477 return true; // Keep iterating through all "flags" elements.
5478 });
5479}
5480
5481static const RegisterTypeBuiltin *
5482ResolveGDBBuiltinType(llvm::StringRef type_name) {
5483 // These names and sizes follow GDB's predefined target-description types in
5484 // gdbsupport/tdesc.cc. ARM FPA is intentionally omitted because GCC removed
5485 // support for it in 2012.
5486 static const RegisterTypeBuiltin bool_type("bool", eEncodingUint,
5487 eFormatBoolean, 1);
5488 static const RegisterTypeBuiltin int8_type("int8", eEncodingSint,
5489 eFormatDecimal, 1);
5490 static const RegisterTypeBuiltin int16_type("int16", eEncodingSint,
5491 eFormatDecimal, 2);
5492 static const RegisterTypeBuiltin int32_type("int32", eEncodingSint,
5493 eFormatDecimal, 4);
5494 static const RegisterTypeBuiltin int64_type("int64", eEncodingSint,
5495 eFormatDecimal, 8);
5496 static const RegisterTypeBuiltin int128_type("int128", eEncodingSint,
5497 eFormatDecimal, 16);
5498 static const RegisterTypeBuiltin uint8_type("uint8", eEncodingUint,
5499 eFormatHex, 1);
5500 static const RegisterTypeBuiltin uint16_type("uint16", eEncodingUint,
5501 eFormatHex, 2);
5502 static const RegisterTypeBuiltin uint32_type("uint32", eEncodingUint,
5503 eFormatHex, 4);
5504 static const RegisterTypeBuiltin uint64_type("uint64", eEncodingUint,
5505 eFormatHex, 8);
5506 static const RegisterTypeBuiltin uint128_type("uint128", eEncodingUint,
5507 eFormatHex, 16);
5508 static const RegisterTypeBuiltin code_ptr_type(
5509 "code_ptr", eEncodingUint, eFormatAddressInfo, std::nullopt);
5510 static const RegisterTypeBuiltin data_ptr_type(
5511 "data_ptr", eEncodingUint, eFormatAddressInfo, std::nullopt);
5512 static const RegisterTypeBuiltin ieee_half_type("ieee_half", eEncodingIEEE754,
5513 eFormatFloat, 2);
5514 static const RegisterTypeBuiltin ieee_single_type(
5515 "ieee_single", eEncodingIEEE754, eFormatFloat, 4);
5516 static const RegisterTypeBuiltin ieee_double_type(
5517 "ieee_double", eEncodingIEEE754, eFormatFloat, 8);
5518 static const RegisterTypeBuiltin i387_ext_type("i387_ext", eEncodingIEEE754,
5519 eFormatFloat, 10);
5520 static const RegisterTypeBuiltin bfloat16_type("bfloat16", eEncodingIEEE754,
5521 eFormatFloat, 2);
5522
5523 return llvm::StringSwitch<const RegisterTypeBuiltin *>(type_name)
5524 .Case("bool", &bool_type)
5525 .Case("int8", &int8_type)
5526 .Case("int16", &int16_type)
5527 .Case("int32", &int32_type)
5528 .Case("int64", &int64_type)
5529 .Case("int128", &int128_type)
5530 .Case("uint8", &uint8_type)
5531 .Case("uint16", &uint16_type)
5532 .Case("uint32", &uint32_type)
5533 .Case("uint64", &uint64_type)
5534 .Case("uint128", &uint128_type)
5535 .Case("code_ptr", &code_ptr_type)
5536 .Case("data_ptr", &data_ptr_type)
5537 .Case("ieee_half", &ieee_half_type)
5538 .Case("ieee_single", &ieee_single_type)
5539 .Case("ieee_double", &ieee_double_type)
5540 .Case("i387_ext", &i387_ext_type)
5541 .Case("bfloat16", &bfloat16_type)
5542 .Default(nullptr);
5543}
5544
5545static const RegisterType *
5546ResolveGDBType(llvm::StringRef type_name,
5547 const RegisterTypeMap &feature_register_types) {
5548 auto type_it = feature_register_types.find(type_name);
5549 if (type_it != feature_register_types.end())
5550 return type_it->second;
5551 return ResolveGDBBuiltinType(type_name);
5552}
5553
5554static void
5555ParseVector(const XMLNode &vector_node, RegisterTypeMap &feature_register_types,
5556 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5557 Log *log(GetLog(GDBRLog::Process));
5558 std::optional<llvm::StringRef> id;
5559 std::optional<llvm::StringRef> element_type_name;
5560 std::optional<uint32_t> count;
5561
5562 vector_node.ForEachAttribute(
5563 [&id, &element_type_name, &count, log](llvm::StringRef name,
5564 llvm::StringRef value) {
5565 if (name == "id") {
5566 id = value;
5567 } else if (name == "type") {
5568 element_type_name = value;
5569 } else if (name == "count") {
5570 uint32_t parsed_count = 0;
5571 if (llvm::to_integer(value, parsed_count))
5572 count = parsed_count;
5573 else
5574 LLDB_LOG(log, "ProcessGDBRemote::ParseVector Invalid count \"{0}\"",
5575 value);
5576 } else {
5577 LLDB_LOG(log,
5578 "ProcessGDBRemote::ParseVector Ignoring unknown attribute "
5579 "\"{0}\"",
5580 name);
5581 }
5582 return true;
5583 });
5584
5585 // GDB limits vectors to 65536 elements. This is also LLDB's maximum
5586 // register size in bytes, so use the existing named limit.
5587 constexpr uint32_t max_vector_count = RegisterValue::kMaxRegisterByteSize;
5588 if (!id || id->empty() || !element_type_name || element_type_name->empty() ||
5589 !count || *count == 0 || *count > max_vector_count) {
5590 LLDB_LOG(log, "ProcessGDBRemote::ParseVector Ignoring vector with invalid "
5591 "id, type, or count");
5592 return;
5593 }
5594
5595 if (feature_register_types.contains(*id)) {
5596 LLDB_LOG(log,
5597 "ProcessGDBRemote::ParseVector Ignoring duplicate type \"{0}\"",
5598 *id);
5599 return;
5600 }
5601
5602 const RegisterType *element_type =
5603 ResolveGDBType(*element_type_name, feature_register_types);
5604 if (!element_type) {
5605 LLDB_LOG(log,
5606 "ProcessGDBRemote::ParseVector Could not resolve element type "
5607 "\"{0}\" for vector \"{1}\"",
5608 *element_type_name, *id);
5609 return;
5610 }
5611
5612 if (!llvm::isa<RegisterTypeBuiltin, RegisterTypeVector, RegisterTypeUnion>(
5613 element_type)) {
5614 LLDB_LOG(log,
5615 "ProcessGDBRemote::ParseVector Found element type \"{0}\" for "
5616 "vector \"{1}\", but it is not a builtin, vector, or union "
5617 "type",
5618 *element_type_name, *id);
5619 return;
5620 }
5621
5622 std::optional<uint64_t> element_size = element_type->GetByteSize();
5623 if (element_size &&
5624 *element_size > RegisterValue::kMaxRegisterByteSize / *count) {
5625 LLDB_LOG(log,
5626 "ProcessGDBRemote::ParseVector Size of vector \"{0}\" is too "
5627 "large",
5628 *id);
5629 return;
5630 }
5631
5632 auto vector_type =
5633 std::make_unique<RegisterTypeVector>(id->str(), element_type, *count);
5634 feature_register_types.try_emplace(*id, vector_type.get());
5635 owned_register_types.push_back(std::move(vector_type));
5636}
5637
5638static std::vector<RegisterTypeUnion::Field>
5639ParseUnionFields(const XMLNode &union_node, llvm::StringRef union_id,
5640 const RegisterTypeMap &feature_register_types) {
5641 Log *log(GetLog(GDBRLog::Process));
5642 std::vector<RegisterTypeUnion::Field> fields;
5643 bool invalid_field = false;
5644
5645 union_node.ForEachChildElementWithName(
5646 "field", [&fields, &invalid_field, log, &feature_register_types,
5647 union_id](const XMLNode &field_node) {
5648 std::optional<llvm::StringRef> name;
5649 std::optional<llvm::StringRef> type_name;
5650
5651 field_node.ForEachAttribute(
5652 [&name, &type_name, log, union_id](llvm::StringRef attribute,
5653 llvm::StringRef value) {
5654 if (attribute == "name")
5655 name = value;
5656 else if (attribute == "type")
5657 type_name = value;
5658 else
5659 LLDB_LOG(log,
5660 "ProcessGDBRemote::ParseUnionFields Ignoring unknown "
5661 "attribute \"{0}\" in a field of union \"{1}\"",
5662 attribute, union_id);
5663 return true;
5664 });
5665
5666 if (!name || name->empty() || !type_name || type_name->empty()) {
5667 LLDB_LOG(log,
5668 "ProcessGDBRemote::ParseUnionFields Union \"{0}\" has a "
5669 "field missing a non-empty name or type",
5670 union_id);
5671 invalid_field = true;
5672 return true;
5673 }
5674
5675 const RegisterType *field_type =
5676 ResolveGDBType(*type_name, feature_register_types);
5677 if (!field_type) {
5678 LLDB_LOG(log,
5679 "ProcessGDBRemote::ParseUnionFields Could not resolve type "
5680 "\"{0}\" for field \"{1}\" of union \"{2}\"",
5681 *type_name, *name, union_id);
5682 invalid_field = true;
5683 return true;
5684 }
5685
5686 if (!llvm::isa<RegisterTypeBuiltin, RegisterTypeVector,
5687 RegisterTypeUnion>(field_type)) {
5688 LLDB_LOG(log,
5689 "ProcessGDBRemote::ParseUnionFields Found type \"{0}\" "
5690 "for field \"{1}\", but it is not a builtin, vector, or "
5691 "union type. Union \"{2}\" will be ignored.",
5692 *type_name, *name, union_id);
5693 invalid_field = true;
5694 return true;
5695 }
5696
5697 fields.emplace_back(name->str(), field_type);
5698 return true;
5699 });
5700
5701 // Reject the whole union if any field is invalid. Retaining only valid fields
5702 // would misrepresent the target's type definition.
5703 if (invalid_field) {
5704 LLDB_LOG(log,
5705 "ProcessGDBRemote::ParseUnionFields Ignoring union \"{0}\" "
5706 "because it contains an invalid field",
5707 union_id);
5708 fields.clear();
5709 } else if (fields.empty()) {
5710 LLDB_LOG(log,
5711 "ProcessGDBRemote::ParseUnionFields Ignoring union \"{0}\" "
5712 "because it has no fields",
5713 union_id);
5714 }
5715 return fields;
5716}
5717
5718static void
5719ParseUnion(const XMLNode &union_node, RegisterTypeMap &feature_register_types,
5720 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5721 Log *log(GetLog(GDBRLog::Process));
5722 std::optional<llvm::StringRef> id;
5723
5724 union_node.ForEachAttribute(
5725 [&id, log](llvm::StringRef name, llvm::StringRef value) {
5726 if (name == "id")
5727 id = value;
5728 else
5729 LLDB_LOG(log,
5730 "ProcessGDBRemote::ParseUnion Ignoring unknown attribute "
5731 "\"{0}\"",
5732 name);
5733 return true;
5734 });
5735
5736 if (!id || id->empty()) {
5737 LLDB_LOG(log, "ProcessGDBRemote::ParseUnion Ignoring union without an id");
5738 return;
5739 }
5740
5741 if (feature_register_types.contains(*id)) {
5742 LLDB_LOG(log,
5743 "ProcessGDBRemote::ParseUnion Ignoring duplicate type \"{0}\"",
5744 *id);
5745 return;
5746 }
5747
5748 std::vector<RegisterTypeUnion::Field> fields =
5749 ParseUnionFields(union_node, *id, feature_register_types);
5750 if (fields.empty())
5751 return;
5752
5753 auto union_type =
5754 std::make_unique<RegisterTypeUnion>(id->str(), std::move(fields));
5755 feature_register_types.try_emplace(*id, union_type.get());
5756 owned_register_types.push_back(std::move(union_type));
5757}
5758
5759static void ParseCompositeTypes(
5760 XMLNode feature_node, RegisterTypeMap &feature_register_types,
5761 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5762 feature_node.ForEachChildElement(
5763 [&feature_register_types,
5764 &owned_register_types](const XMLNode &type_node) {
5765 if (type_node.NameIs("vector"))
5766 ParseVector(type_node, feature_register_types, owned_register_types);
5767 else if (type_node.NameIs("union"))
5768 ParseUnion(type_node, feature_register_types, owned_register_types);
5769 return true;
5770 });
5771}
5772
5773bool ParseRegisters(
5774 XMLNode feature_node, GdbServerTargetInfo &target_info,
5775 std::vector<DynamicRegisterInfo::Register> &registers,
5776 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5777 if (!feature_node)
5778 return false;
5779
5780 Log *log(GetLog(GDBRLog::Process));
5781 RegisterTypeMap feature_register_types;
5782
5783 // Enums first because they are referenced by fields in the flags.
5784 ParseEnums(feature_node, feature_register_types, owned_register_types);
5785 for (const auto &register_type : feature_register_types)
5786 if (const auto *enum_type =
5787 llvm::dyn_cast<RegisterTypeEnum>(register_type.second))
5788 enum_type->DumpToLog(log);
5789
5790 ParseFlags(feature_node, feature_register_types, owned_register_types);
5791 for (const auto &register_type : feature_register_types)
5792 if (const auto *flags_type =
5793 llvm::dyn_cast<RegisterTypeFlags>(register_type.second))
5794 flags_type->DumpToLog(log);
5795
5796 // Enums and flags retain their dedicated passes above. Vectors and unions
5797 // can reference one another, so parse them together in document order. A
5798 // referenced composite type must precede its user.
5799 ParseCompositeTypes(feature_node, feature_register_types,
5800 owned_register_types);
5801 for (const auto &register_type : feature_register_types)
5802 if (const auto *vector_type =
5803 llvm::dyn_cast<RegisterTypeVector>(register_type.second))
5804 vector_type->DumpToLog(log);
5805 for (const auto &register_type : feature_register_types)
5806 if (const auto *union_type =
5807 llvm::dyn_cast<RegisterTypeUnion>(register_type.second))
5808 union_type->DumpToLog(log);
5809
5810 feature_node.ForEachChildElementWithName(
5811 "reg",
5812 [&target_info, &registers, &feature_register_types,
5813 log](const XMLNode &reg_node) -> bool {
5814 std::string gdb_group;
5815 std::string gdb_type;
5816 DynamicRegisterInfo::Register reg_info;
5817 bool encoding_set = false;
5818 bool format_set = false;
5819
5820 // FIXME: we're silently ignoring invalid data here
5821 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
5822 &encoding_set, &format_set, &reg_info,
5823 log](const llvm::StringRef &name,
5824 const llvm::StringRef &value) -> bool {
5825 if (name == "name") {
5826 reg_info.name.SetString(value);
5827 } else if (name == "bitsize") {
5828 if (llvm::to_integer(value, reg_info.byte_size))
5829 reg_info.byte_size =
5830 llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
5831 } else if (name == "type") {
5832 gdb_type = value.str();
5833 } else if (name == "group") {
5834 gdb_group = value.str();
5835 } else if (name == "regnum") {
5836 llvm::to_integer(value, reg_info.regnum_remote);
5837 } else if (name == "offset") {
5838 llvm::to_integer(value, reg_info.byte_offset);
5839 } else if (name == "altname") {
5840 reg_info.alt_name.SetString(value);
5841 } else if (name == "encoding") {
5842 encoding_set = true;
5844 } else if (name == "format") {
5845 format_set = true;
5846 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
5847 nullptr)
5848 .Success())
5849 reg_info.format =
5850 llvm::StringSwitch<lldb::Format>(value)
5851 .Case("vector-sint8", eFormatVectorOfSInt8)
5852 .Case("vector-uint8", eFormatVectorOfUInt8)
5853 .Case("vector-sint16", eFormatVectorOfSInt16)
5854 .Case("vector-uint16", eFormatVectorOfUInt16)
5855 .Case("vector-sint32", eFormatVectorOfSInt32)
5856 .Case("vector-uint32", eFormatVectorOfUInt32)
5857 .Case("vector-float32", eFormatVectorOfFloat32)
5858 .Case("vector-uint64", eFormatVectorOfUInt64)
5859 .Case("vector-uint128", eFormatVectorOfUInt128)
5860 .Default(eFormatInvalid);
5861 } else if (name == "group_id") {
5862 uint32_t set_id = UINT32_MAX;
5863 llvm::to_integer(value, set_id);
5864 RegisterSetMap::const_iterator pos =
5865 target_info.reg_set_map.find(set_id);
5866 if (pos != target_info.reg_set_map.end())
5867 reg_info.set_name = pos->second.name;
5868 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
5869 llvm::to_integer(value, reg_info.regnum_ehframe);
5870 } else if (name == "dwarf_regnum") {
5871 llvm::to_integer(value, reg_info.regnum_dwarf);
5872 } else if (name == "generic") {
5874 } else if (name == "value_regnums") {
5876 0);
5877 } else if (name == "invalidate_regnums") {
5879 value, reg_info.invalidate_regs, 0);
5880 } else {
5881 LLDB_LOGF(log,
5882 "ProcessGDBRemote::ParseRegisters unhandled reg "
5883 "attribute %s = %s",
5884 name.data(), value.data());
5885 }
5886 return true; // Keep iterating through all attributes
5887 });
5888
5889 if (!gdb_type.empty()) {
5890 // gdb_type could reference a type defined in this feature.
5891 auto it = feature_register_types.find(gdb_type);
5892 if (it != feature_register_types.end()) {
5893 if (const auto *vector_type =
5894 llvm::dyn_cast<RegisterTypeVector>(it->second)) {
5895 std::optional<uint64_t> type_size = vector_type->GetByteSize();
5897 LLDB_LOG(log,
5898 "ProcessGDBRemote::ParseRegisters Register {0} is "
5899 "too large for vector type {1}",
5900 reg_info.name, vector_type->GetID());
5901 } else if (!vector_type->IsByteSizeCompatible(
5902 reg_info.byte_size)) {
5903 if (!type_size) {
5904 LLDB_LOG(log,
5905 "ProcessGDBRemote::ParseRegisters Size of register "
5906 "{0} is incompatible with vector type {1}",
5907 reg_info.name, vector_type->GetID());
5908 } else {
5909 LLDB_LOG(
5910 log,
5911 "ProcessGDBRemote::ParseRegisters Size of register type "
5912 "{0} ({1} bytes) for register {2} does not match the "
5913 "register size ({3} bytes). Ignoring this type.",
5914 vector_type->GetID(), *type_size, reg_info.name,
5915 reg_info.byte_size);
5916 }
5917 } else {
5918 reg_info.register_type = vector_type;
5919 if (!encoding_set) {
5920 reg_info.encoding = eEncodingVector;
5921 encoding_set = true;
5922 }
5923 if (!format_set) {
5924 reg_info.format = eFormatVectorOfUInt8;
5925 format_set = true;
5926 }
5927 }
5928 } else if (const auto *union_type =
5929 llvm::dyn_cast<RegisterTypeUnion>(it->second)) {
5931 LLDB_LOG(log,
5932 "ProcessGDBRemote::ParseRegisters Register {0} is "
5933 "too large for union type {1}",
5934 reg_info.name, union_type->GetID());
5935 } else if (!union_type->IsByteSizeCompatible(
5936 reg_info.byte_size)) {
5937 LLDB_LOG(log,
5938 "ProcessGDBRemote::ParseRegisters Size of register "
5939 "{0} is incompatible with union type {1}",
5940 reg_info.name, union_type->GetID());
5941 } else {
5942 reg_info.register_type = union_type;
5943 if (!encoding_set) {
5944 reg_info.encoding = eEncodingUint;
5945 encoding_set = true;
5946 }
5947 if (!format_set) {
5948 reg_info.format = eFormatHex;
5949 format_set = true;
5950 }
5951 }
5952 } else if (const auto *flags_type =
5953 llvm::dyn_cast<RegisterTypeFlags>(it->second)) {
5954 if (reg_info.byte_size == flags_type->GetSize())
5955 reg_info.register_type = flags_type;
5956 else
5957 LLDB_LOG(
5958 log,
5959 "ProcessGDBRemote::ParseRegisters Size of register flags "
5960 "{0} ({1} bytes) for register {2} does not match the "
5961 "register size ({3} bytes). Ignoring this set of flags.",
5962 flags_type->GetID().c_str(), flags_type->GetSize(),
5963 reg_info.name, reg_info.byte_size);
5964 }
5965 }
5966
5967 // There's a slim chance that the gdb_type name is both a flags type
5968 // and a simple type. Just in case, look for that too (setting both
5969 // does no harm).
5970 if (!gdb_type.empty() && !(encoding_set || format_set)) {
5971 if (llvm::StringRef(gdb_type).starts_with("int")) {
5972 reg_info.format = eFormatHex;
5973 reg_info.encoding = eEncodingUint;
5974 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
5975 reg_info.format = eFormatAddressInfo;
5976 reg_info.encoding = eEncodingUint;
5977 } else if (gdb_type == "float" || gdb_type == "ieee_single" ||
5978 gdb_type == "ieee_double") {
5979 reg_info.format = eFormatFloat;
5980 reg_info.encoding = eEncodingIEEE754;
5981 } else if (gdb_type == "aarch64v" ||
5982 llvm::StringRef(gdb_type).starts_with("vec") ||
5983 gdb_type == "i387_ext" || gdb_type == "uint128" ||
5984 reg_info.byte_size > 16) {
5985 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
5986 // treat them as vector (similarly to xmm/ymm).
5987 // We can fall back to handling anything else <= 128 bit as an
5988 // unsigned integer, more than that, call it a vector of bytes.
5989 // This can happen if we don't recognise the type for AArc64 SVE
5990 // registers.
5991 reg_info.format = eFormatVectorOfUInt8;
5992 reg_info.encoding = eEncodingVector;
5993 } else {
5994 LLDB_LOGF(
5995 log,
5996 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
5997 "format and encoding for gdb type %s",
5998 gdb_type.c_str());
5999 }
6000 }
6001 }
6002
6003 // Only update the register set name if we didn't get a "reg_set"
6004 // attribute. "set_name" will be empty if we didn't have a "reg_set"
6005 // attribute.
6006 if (!reg_info.set_name) {
6007 if (!gdb_group.empty()) {
6008 reg_info.set_name.SetCString(gdb_group.c_str());
6009 } else {
6010 // If no register group name provided anywhere,
6011 // we'll create a 'general' register set
6012 reg_info.set_name.SetCString("general");
6013 }
6014 }
6015
6016 if (reg_info.byte_size == 0) {
6017 LLDB_LOG(log,
6018 "ProcessGDBRemote::{0} Skipping zero bitsize register {1}",
6019 __FUNCTION__, reg_info.name);
6020 } else
6021 registers.push_back(reg_info);
6022
6023 return true; // Keep iterating through all "reg" elements
6024 });
6025 return true;
6026}
6027
6028} // namespace
6029
6030// This method fetches a register description feature xml file from
6031// the remote stub and adds registers/register groupsets/architecture
6032// information to the current process. It will call itself recursively
6033// for nested register definition files. It returns true if it was able
6034// to fetch and parse an xml file.
6036 ArchSpec &arch_to_use, std::string xml_filename,
6037 std::vector<DynamicRegisterInfo::Register> &registers) {
6038 // request the target xml file
6039 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
6040 if (errorToBool(raw.takeError()))
6041 return false;
6042
6043 XMLDocument xml_document;
6044
6045 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
6046 xml_filename.c_str())) {
6047 GdbServerTargetInfo target_info;
6048 std::vector<XMLNode> feature_nodes;
6049
6050 // The top level feature XML file will start with a <target> tag.
6051 XMLNode target_node = xml_document.GetRootElement("target");
6052 if (target_node) {
6053 target_node.ForEachChildElement([&target_info, &feature_nodes](
6054 const XMLNode &node) -> bool {
6055 llvm::StringRef name = node.GetName();
6056 if (name == "architecture") {
6057 node.GetElementText(target_info.arch);
6058 } else if (name == "osabi") {
6059 node.GetElementText(target_info.osabi);
6060 } else if (name == "xi:include" || name == "include") {
6061 std::string href = node.GetAttributeValue("href");
6062 if (!href.empty())
6063 target_info.includes.push_back(href);
6064 } else if (name == "feature") {
6065 feature_nodes.push_back(node);
6066 } else if (name == "groups") {
6068 "group", [&target_info](const XMLNode &node) -> bool {
6069 uint32_t set_id = UINT32_MAX;
6070 RegisterSetInfo set_info;
6071
6072 node.ForEachAttribute(
6073 [&set_id, &set_info](const llvm::StringRef &name,
6074 const llvm::StringRef &value) -> bool {
6075 // FIXME: we're silently ignoring invalid data here
6076 if (name == "id")
6077 llvm::to_integer(value, set_id);
6078 if (name == "name")
6079 set_info.name = ConstString(value);
6080 return true; // Keep iterating through all attributes
6081 });
6082
6083 if (set_id != UINT32_MAX)
6084 target_info.reg_set_map[set_id] = set_info;
6085 return true; // Keep iterating through all "group" elements
6086 });
6087 }
6088 return true; // Keep iterating through all children of the target_node
6089 });
6090 } else {
6091 // In an included XML feature file, we're already "inside" the <target>
6092 // tag of the initial XML file; this included file will likely only have
6093 // a <feature> tag. Need to check for any more included files in this
6094 // <feature> element.
6095 XMLNode feature_node = xml_document.GetRootElement("feature");
6096 if (feature_node) {
6097 feature_nodes.push_back(feature_node);
6098 feature_node.ForEachChildElement([&target_info](
6099 const XMLNode &node) -> bool {
6100 llvm::StringRef name = node.GetName();
6101 if (name == "xi:include" || name == "include") {
6102 std::string href = node.GetAttributeValue("href");
6103 if (!href.empty())
6104 target_info.includes.push_back(href);
6105 }
6106 return true;
6107 });
6108 }
6109 }
6110
6111 // gdbserver does not implement the LLDB packets used to determine host
6112 // or process architecture. If that is the case, attempt to use
6113 // the <architecture/> field from target.xml, e.g.:
6114 //
6115 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
6116 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
6117 // arm board)
6118 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
6119 // We don't have any information about vendor or OS.
6120 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
6121 .Case("i386:x86-64", "x86_64")
6122 .Case("riscv:rv64", "riscv64")
6123 .Case("riscv:rv32", "riscv32")
6124 .Default(target_info.arch) +
6125 "--");
6126
6127 if (arch_to_use.IsValid())
6128 GetTarget().MergeArchitecture(arch_to_use);
6129 }
6130
6131 if (arch_to_use.IsValid()) {
6132 for (auto &feature_node : feature_nodes) {
6133 ParseRegisters(feature_node, target_info, registers, m_register_types);
6134 }
6135
6136 for (const auto &include : target_info.includes) {
6137 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
6138 registers);
6139 }
6140 }
6141 } else {
6142 return false;
6143 }
6144 return true;
6145}
6146
6148 std::vector<DynamicRegisterInfo::Register> &registers,
6149 const ArchSpec &arch_to_use) {
6150 std::map<uint32_t, uint32_t> remote_to_local_map;
6151 uint32_t remote_regnum = 0;
6152 for (auto it : llvm::enumerate(registers)) {
6153 DynamicRegisterInfo::Register &remote_reg_info = it.value();
6154
6155 // Assign successive remote regnums if missing.
6156 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
6157 remote_reg_info.regnum_remote = remote_regnum;
6158
6159 // Create a mapping from remote to local regnos.
6160 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
6161
6162 remote_regnum = remote_reg_info.regnum_remote + 1;
6163 }
6164
6165 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
6166 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
6167 auto lldb_regit = remote_to_local_map.find(process_regnum);
6168 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
6170 };
6171
6172 llvm::transform(remote_reg_info.value_regs,
6173 remote_reg_info.value_regs.begin(), proc_to_lldb);
6174 llvm::transform(remote_reg_info.invalidate_regs,
6175 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
6176 }
6177
6178 // Don't use Process::GetABI, this code gets called from DidAttach, and
6179 // in that context we haven't set the Target's architecture yet, so the
6180 // ABI is also potentially incorrect.
6181 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
6182 abi_sp->AugmentRegisterInfo(registers);
6183
6184 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
6185}
6186
6187// query the target of gdb-remote for extended target information returns
6188// true on success (got register definitions), false on failure (did not).
6190 // If the remote does not offer XML, does not matter if we would have been
6191 // able to parse it.
6192 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
6193 return llvm::createStringError(
6194 llvm::inconvertibleErrorCode(),
6195 "the debug server does not support \"qXfer:features:read\"");
6196
6198 return llvm::createStringError(
6199 llvm::inconvertibleErrorCode(),
6200 "the debug server supports \"qXfer:features:read\", but LLDB does not "
6201 "have XML parsing enabled (check LLLDB_ENABLE_LIBXML2)");
6202
6203 std::vector<DynamicRegisterInfo::Register> registers;
6204 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
6205 registers) &&
6206 // Target XML is not required to include register information.
6207 !registers.empty())
6208 AddRemoteRegisters(registers, arch_to_use);
6209
6210 return m_register_info_sp->GetNumRegisters() > 0
6211 ? llvm::ErrorSuccess()
6212 : llvm::createStringError(
6213 llvm::inconvertibleErrorCode(),
6214 "the debug server did not describe any registers");
6215}
6216
6217llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
6218 // Make sure LLDB has an XML parser it can use first
6220 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6221 "XML parsing not available");
6222
6223 Log *log = GetLog(LLDBLog::Process);
6224 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
6225
6228 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
6229
6230 // check that we have extended feature read support
6231 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
6232 // request the loaded library list
6233 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
6234 if (!raw)
6235 return raw.takeError();
6236
6237 // parse the xml file in memory
6238 LLDB_LOGF(log, "parsing: %s", raw->c_str());
6239 XMLDocument doc;
6240
6241 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
6242 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6243 "Error reading noname.xml");
6244
6245 XMLNode root_element = doc.GetRootElement("library-list-svr4");
6246 if (!root_element)
6247 return llvm::createStringError(
6248 llvm::inconvertibleErrorCode(),
6249 "Error finding library-list-svr4 xml element");
6250
6251 // main link map structure
6252 std::string main_lm = root_element.GetAttributeValue("main-lm");
6253 // FIXME: we're silently ignoring invalid data here
6254 if (!main_lm.empty())
6255 llvm::to_integer(main_lm, list.m_link_map);
6256
6257 root_element.ForEachChildElementWithName(
6258 "library", [log, &list](const XMLNode &library) -> bool {
6260
6261 // FIXME: we're silently ignoring invalid data here
6262 library.ForEachAttribute(
6263 [&module](const llvm::StringRef &name,
6264 const llvm::StringRef &value) -> bool {
6265 uint64_t uint_value = LLDB_INVALID_ADDRESS;
6266 if (name == "name")
6267 module.set_name(value.str());
6268 else if (name == "lm") {
6269 // the address of the link_map struct.
6270 llvm::to_integer(value, uint_value);
6271 module.set_link_map(uint_value);
6272 } else if (name == "l_addr") {
6273 // the displacement as read from the field 'l_addr' of the
6274 // link_map struct.
6275 llvm::to_integer(value, uint_value);
6276 module.set_base(uint_value);
6277 // base address is always a displacement, not an absolute
6278 // value.
6279 module.set_base_is_offset(true);
6280 } else if (name == "l_ld") {
6281 // the memory address of the libraries PT_DYNAMIC section.
6282 llvm::to_integer(value, uint_value);
6283 module.set_dynamic(uint_value);
6284 }
6285
6286 return true; // Keep iterating over all properties of "library"
6287 });
6288
6289 if (log) {
6290 std::string name;
6291 lldb::addr_t lm = 0, base = 0, ld = 0;
6292 bool base_is_offset;
6293
6294 module.get_name(name);
6295 module.get_link_map(lm);
6296 module.get_base(base);
6297 module.get_base_is_offset(base_is_offset);
6298 module.get_dynamic(ld);
6299
6300 LLDB_LOGF(log,
6301 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
6302 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
6303 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
6304 name.c_str());
6305 }
6306
6307 list.add(module);
6308 return true; // Keep iterating over all "library" elements in the root
6309 // node
6310 });
6311
6312 LLDB_LOGF(log, "found %" PRId32 " modules in total",
6313 (int)list.m_list.size());
6314 return list;
6315 } else if (comm.GetQXferLibrariesReadSupported()) {
6316 // request the loaded library list
6317 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
6318
6319 if (!raw)
6320 return raw.takeError();
6321
6322 LLDB_LOGF(log, "parsing: %s", raw->c_str());
6323 XMLDocument doc;
6324
6325 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
6326 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6327 "Error reading noname.xml");
6328
6329 XMLNode root_element = doc.GetRootElement("library-list");
6330 if (!root_element)
6331 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6332 "Error finding library-list xml element");
6333
6334 // FIXME: we're silently ignoring invalid data here
6335 root_element.ForEachChildElementWithName(
6336 "library", [log, &list](const XMLNode &library) -> bool {
6338
6339 std::string name = library.GetAttributeValue("name");
6340 module.set_name(name);
6341
6342 // The base address of a given library will be the address of its
6343 // first section. Most remotes send only one section for Windows
6344 // targets for example.
6345 const XMLNode &section =
6346 library.FindFirstChildElementWithName("section");
6347 std::string address = section.GetAttributeValue("address");
6348 uint64_t address_value = LLDB_INVALID_ADDRESS;
6349 llvm::to_integer(address, address_value);
6350 module.set_base(address_value);
6351 // These addresses are absolute values.
6352 module.set_base_is_offset(false);
6353
6354 if (log) {
6355 std::string name;
6356 lldb::addr_t base = 0;
6357 bool base_is_offset;
6358 module.get_name(name);
6359 module.get_base(base);
6360 module.get_base_is_offset(base_is_offset);
6361
6362 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
6363 (base_is_offset ? "offset" : "absolute"), 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 {
6375 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6376 "Remote libraries not supported");
6377 }
6378}
6379
6381 lldb::addr_t link_map,
6382 lldb::addr_t base_addr,
6383 bool value_is_offset) {
6384 DynamicLoader *loader = GetDynamicLoader();
6385 if (!loader)
6386 return nullptr;
6387
6388 return loader->LoadModuleAtAddress(file, link_map, base_addr,
6389 value_is_offset);
6390}
6391
6394
6395 if (m_dyld_up && m_dyld_up->HandleStopReasonDynamicLoader())
6396 return llvm::ErrorSuccess();
6397
6398 // request a list of loaded libraries from GDBServer
6399 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
6400 if (!module_list)
6401 return module_list.takeError();
6402
6403 // get a list of all the modules
6404 ModuleList new_modules;
6405
6406 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
6407 std::string mod_name;
6408 lldb::addr_t mod_base;
6409 lldb::addr_t link_map;
6410 bool mod_base_is_offset;
6411
6412 bool valid = true;
6413 valid &= modInfo.get_name(mod_name);
6414 valid &= modInfo.get_base(mod_base);
6415 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
6416 if (!valid)
6417 continue;
6418
6419 if (!modInfo.get_link_map(link_map))
6420 link_map = LLDB_INVALID_ADDRESS;
6421
6422 FileSpec file(mod_name);
6424 lldb::ModuleSP module_sp =
6425 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
6426
6427 if (module_sp.get())
6428 new_modules.Append(module_sp);
6429 }
6430
6431 if (new_modules.GetSize() > 0) {
6432 ModuleList removed_modules;
6433 Target &target = GetTarget();
6434 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
6435
6436 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
6437 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
6438
6439 bool found = false;
6440 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
6441 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
6442 found = true;
6443 }
6444
6445 // The main executable will never be included in libraries-svr4, don't
6446 // remove it
6447 if (!found &&
6448 loaded_module.get() != target.GetExecutableModulePointer()) {
6449 removed_modules.Append(loaded_module);
6450 }
6451 }
6452
6453 loaded_modules.Remove(removed_modules);
6454 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
6455
6456 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) {
6457 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
6458 if (!obj)
6460
6463
6464 if (target.GetExecutableModulePointer() == module_sp.get())
6465 return IterationAction::Stop;
6466
6467 lldb::ModuleSP module_copy_sp = module_sp;
6468 target.RebuildModuleListWithExecutable(module_copy_sp, eLoadDependentsNo);
6469 return IterationAction::Stop;
6470 });
6471
6472 loaded_modules.AppendIfNeeded(new_modules);
6473 m_process->GetTarget().ModulesDidLoad(new_modules);
6474 }
6475
6476 return llvm::ErrorSuccess();
6477}
6478
6480 bool &is_loaded,
6481 lldb::addr_t &load_addr) {
6482 is_loaded = false;
6483 load_addr = LLDB_INVALID_ADDRESS;
6484
6485 std::string file_path = file.GetPath(false);
6486 if (file_path.empty())
6487 return Status::FromErrorString("Empty file name specified");
6488
6489 StreamString packet;
6490 packet.PutCString("qFileLoadAddress:");
6491 packet.PutStringAsRawHex8(file_path);
6492
6493 StringExtractorGDBRemote response;
6494 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
6496 return Status::FromErrorString("Sending qFileLoadAddress packet failed");
6497
6498 if (response.IsErrorResponse()) {
6499 if (response.GetError() == 1) {
6500 // The file is not loaded into the inferior
6501 is_loaded = false;
6502 load_addr = LLDB_INVALID_ADDRESS;
6503 return Status();
6504 }
6505
6507 "Fetching file load address from remote server returned an error");
6508 }
6509
6510 if (response.IsNormalResponse()) {
6511 is_loaded = true;
6512 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
6513 return Status();
6514 }
6515
6517 "Unknown error happened during sending the load address packet");
6518}
6519
6521 // We must call the lldb_private::Process::ModulesDidLoad () first before we
6522 // do anything
6523 Process::ModulesDidLoad(module_list);
6524
6525 // After loading shared libraries, we can ask our remote GDB server if it
6526 // needs any symbols.
6527 m_gdb_comm.ServeSymbolLookups(this);
6528}
6529
6530void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
6531 AppendSTDOUT(out.data(), out.size());
6532}
6533
6534static const char *end_delimiter = "--end--;";
6535static const int end_delimiter_len = 8;
6536
6537void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
6538 std::string input = data.str(); // '1' to move beyond 'A'
6539 if (m_partial_profile_data.length() > 0) {
6540 m_partial_profile_data.append(input);
6541 input = m_partial_profile_data;
6542 m_partial_profile_data.clear();
6543 }
6544
6545 size_t found, pos = 0, len = input.length();
6546 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
6547 StringExtractorGDBRemote profileDataExtractor(
6548 input.substr(pos, found).c_str());
6549 std::string profile_data =
6550 HarmonizeThreadIdsForProfileData(profileDataExtractor);
6551 BroadcastAsyncProfileData(profile_data);
6552
6553 pos = found + end_delimiter_len;
6554 }
6555
6556 if (pos < len) {
6557 // Last incomplete chunk.
6558 m_partial_profile_data = input.substr(pos);
6559 }
6560}
6561
6563 StringExtractorGDBRemote &profileDataExtractor) {
6564 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
6565 std::string output;
6566 llvm::raw_string_ostream output_stream(output);
6567 llvm::StringRef name, value;
6568
6569 // Going to assuming thread_used_usec comes first, else bail out.
6570 while (profileDataExtractor.GetNameColonValue(name, value)) {
6571 if (name.compare("thread_used_id") == 0) {
6572 StringExtractor threadIDHexExtractor(value);
6573 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
6574
6575 bool has_used_usec = false;
6576 uint32_t curr_used_usec = 0;
6577 llvm::StringRef usec_name, usec_value;
6578 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
6579 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
6580 if (usec_name == "thread_used_usec") {
6581 has_used_usec = true;
6582 usec_value.getAsInteger(BASE_10, curr_used_usec);
6583 } else {
6584 // We didn't find what we want, it is probably an older version. Bail
6585 // out.
6586 profileDataExtractor.SetFilePos(input_file_pos);
6587 }
6588 }
6589
6590 if (has_used_usec) {
6591 uint32_t prev_used_usec = 0;
6592 std::map<uint64_t, uint32_t>::iterator iterator =
6593 m_thread_id_to_used_usec_map.find(thread_id);
6594 if (iterator != m_thread_id_to_used_usec_map.end())
6595 prev_used_usec = iterator->second;
6596
6597 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
6598 // A good first time record is one that runs for at least 0.25 sec
6599 bool good_first_time =
6600 (prev_used_usec == 0) && (real_used_usec > 250000);
6601 bool good_subsequent_time =
6602 (prev_used_usec > 0) &&
6603 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
6604
6605 if (good_first_time || good_subsequent_time) {
6606 // We try to avoid doing too many index id reservation, resulting in
6607 // fast increase of index ids.
6608
6609 output_stream << name << ":";
6610 int32_t index_id = AssignIndexIDToThread(thread_id);
6611 output_stream << index_id << ";";
6612
6613 output_stream << usec_name << ":" << usec_value << ";";
6614 } else {
6615 // Skip past 'thread_used_name'.
6616 llvm::StringRef local_name, local_value;
6617 profileDataExtractor.GetNameColonValue(local_name, local_value);
6618 }
6619
6620 // Store current time as previous time so that they can be compared
6621 // later.
6622 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
6623 } else {
6624 // Bail out and use old string.
6625 output_stream << name << ":" << value << ";";
6626 }
6627 } else {
6628 output_stream << name << ":" << value << ";";
6629 }
6630 }
6631 output_stream << end_delimiter;
6632 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
6633
6634 return output;
6635}
6636
6638 if (GetStopID() != 0)
6639 return;
6640
6641 if (GetID() == LLDB_INVALID_PROCESS_ID) {
6642 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
6643 if (pid != LLDB_INVALID_PROCESS_ID)
6644 SetID(pid);
6645 }
6647}
6648
6649llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
6650 if (!m_gdb_comm.GetSaveCoreSupported())
6651 return false;
6652
6653 StreamString packet;
6654 packet.PutCString("qSaveCore;path-hint:");
6655 packet.PutStringAsRawHex8(outfile);
6656
6657 StringExtractorGDBRemote response;
6658 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
6660 // TODO: grab error message from the packet? StringExtractor seems to
6661 // be missing a method for that
6662 if (response.IsErrorResponse())
6663 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6664 "qSaveCore returned an error");
6665
6666 std::string path;
6667
6668 // process the response
6669 for (auto x : llvm::split(response.GetStringRef(), ';')) {
6670 if (x.consume_front("core-path:"))
6672 }
6673
6674 // verify that we've gotten what we need
6675 if (path.empty())
6676 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6677 "qSaveCore returned no core path");
6678
6679 FileSpec remote_core{llvm::StringRef(path)};
6680 FileSpec local_core{outfile};
6681 Platform &platform = *GetTarget().GetPlatform();
6682
6683 if (!platform.IsRemote() && remote_core == local_core)
6684 return true;
6685
6686 // now transfer the core file
6687 Status error = platform.GetFile(remote_core, local_core);
6688 // NB: we unlink the file on error too
6689 platform.Unlink(remote_core);
6690 if (error.Fail())
6691 return error.ToError();
6692
6693 return true;
6694 }
6695
6696 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6697 "Unable to send qSaveCore");
6698}
6699
6700static const char *const s_async_json_packet_prefix = "JSON-async:";
6701
6703ParseStructuredDataPacket(llvm::StringRef packet) {
6704 Log *log = GetLog(GDBRLog::Process);
6705
6706 if (!packet.consume_front(s_async_json_packet_prefix)) {
6707 LLDB_LOGF(
6708 log,
6709 "GDBRemoteCommunicationClientBase::%s() received $J packet "
6710 "but was not a StructuredData packet: packet starts with "
6711 "%s",
6712 __FUNCTION__,
6713 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
6714 return StructuredData::ObjectSP();
6715 }
6716
6717 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
6719 if (log) {
6720 if (json_sp) {
6721 StreamString json_str;
6722 json_sp->Dump(json_str, true);
6723 json_str.Flush();
6724 LLDB_LOGF(log,
6725 "ProcessGDBRemote::%s() "
6726 "received Async StructuredData packet: %s",
6727 __FUNCTION__, json_str.GetData());
6728 } else {
6729 LLDB_LOGF(log,
6730 "ProcessGDBRemote::%s"
6731 "() received StructuredData packet:"
6732 " parse failure",
6733 __FUNCTION__);
6734 }
6735 }
6736 return json_sp;
6737}
6738
6740 auto structured_data_sp = ParseStructuredDataPacket(data);
6741 if (structured_data_sp)
6742 RouteAsyncStructuredData(structured_data_sp);
6743}
6744
6746public:
6748 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
6749 "Tests packet speeds of various sizes to determine "
6750 "the performance characteristics of the GDB remote "
6751 "connection. ",
6752 nullptr),
6754 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
6755 "The number of packets to send of each varying size "
6756 "(default is 1000).",
6757 1000),
6758 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
6759 "The maximum number of bytes to send in a packet. Sizes "
6760 "increase in powers of 2 while the size is less than or "
6761 "equal to this option value. (default 1024).",
6762 1024),
6763 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
6764 "The maximum number of bytes to receive in a packet. Sizes "
6765 "increase in powers of 2 while the size is less than or "
6766 "equal to this option value. (default 1024).",
6767 1024),
6768 m_json(LLDB_OPT_SET_1, false, "json", 'j',
6769 "Print the output as JSON data for easy parsing.", false, true) {
6774 m_option_group.Finalize();
6775 }
6776
6778
6779 Options *GetOptions() override { return &m_option_group; }
6780
6781 void DoExecute(Args &command, CommandReturnObject &result) override {
6782 const size_t argc = command.GetArgumentCount();
6783 if (argc == 0) {
6784 ProcessGDBRemote *process =
6785 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
6786 .GetProcessPtr();
6787 if (process) {
6788 StreamSP output_stream_sp = result.GetImmediateOutputStream();
6789 if (!output_stream_sp)
6790 output_stream_sp = m_interpreter.GetDebugger().GetAsyncOutputStream();
6791 result.SetImmediateOutputStream(output_stream_sp);
6792
6793 const uint32_t num_packets =
6794 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
6795 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
6796 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
6797 const bool json = m_json.GetOptionValue().GetCurrentValue();
6798 const uint64_t k_recv_amount =
6799 4 * 1024 * 1024; // Receive amount in bytes
6800 process->GetGDBRemote().TestPacketSpeed(
6801 num_packets, max_send, max_recv, k_recv_amount, json,
6802 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
6804 return;
6805 }
6806 } else {
6807 result.AppendErrorWithFormat("'%s' takes no arguments",
6808 m_cmd_name.c_str());
6809 }
6811 }
6812
6813protected:
6819};
6820
6822private:
6823public:
6825 : CommandObjectParsed(interpreter, "process plugin packet history",
6826 "Dumps the packet history buffer. ", nullptr) {}
6827
6829
6830 void DoExecute(Args &command, CommandReturnObject &result) override {
6831 ProcessGDBRemote *process =
6832 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6833 if (process) {
6834 process->DumpPluginHistory(result.GetOutputStream());
6836 return;
6837 }
6839 }
6840};
6841
6843private:
6844public:
6847 interpreter, "process plugin packet xfer-size",
6848 "Maximum size that lldb will try to read/write one one chunk.",
6849 nullptr) {
6851 }
6852
6854
6855 void DoExecute(Args &command, CommandReturnObject &result) override {
6856 const size_t argc = command.GetArgumentCount();
6857 if (argc == 0) {
6858 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
6859 "amount to be transferred when "
6860 "reading/writing",
6861 m_cmd_name.c_str());
6862 return;
6863 }
6864
6865 ProcessGDBRemote *process =
6866 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6867 if (process) {
6868 const char *packet_size = command.GetArgumentAtIndex(0);
6869 errno = 0;
6870 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
6871 if (errno == 0 && user_specified_max != 0) {
6872 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
6874 return;
6875 }
6876 }
6878 }
6879};
6880
6882private:
6883public:
6885 : CommandObjectParsed(interpreter, "process plugin packet send",
6886 "Send a custom packet through the GDB remote "
6887 "protocol and print the answer. "
6888 "The packet header and footer will automatically "
6889 "be added to the packet prior to sending and "
6890 "stripped from the result.",
6891 nullptr) {
6893 }
6894
6896
6897 void DoExecute(Args &command, CommandReturnObject &result) override {
6898 const size_t argc = command.GetArgumentCount();
6899 if (argc == 0) {
6900 result.AppendErrorWithFormat(
6901 "'%s' takes a one or more packet content arguments",
6902 m_cmd_name.c_str());
6903 return;
6904 }
6905
6906 ProcessGDBRemote *process =
6907 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6908 if (process) {
6909 for (size_t i = 0; i < argc; ++i) {
6910 const char *packet_cstr = command.GetArgumentAtIndex(0);
6911 StringExtractorGDBRemote response;
6913 packet_cstr, response, process->GetInterruptTimeout());
6915 Stream &output_strm = result.GetOutputStream();
6916 output_strm.Printf(" packet: %s\n", packet_cstr);
6917 std::string response_str = std::string(response.GetStringRef());
6918
6919 if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
6920 response_str = process->HarmonizeThreadIdsForProfileData(response);
6921 }
6922
6923 if (response_str.empty())
6924 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6925 else
6926 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6927 }
6928 }
6929 }
6930};
6931
6933private:
6934public:
6936 : CommandObjectRaw(interpreter, "process plugin packet monitor",
6937 "Send a qRcmd packet through the GDB remote protocol "
6938 "and print the response. "
6939 "The argument passed to this command will be hex "
6940 "encoded into a valid 'qRcmd' packet, sent and the "
6941 "response will be printed.") {}
6942
6944
6945 void DoExecute(llvm::StringRef command,
6946 CommandReturnObject &result) override {
6947 if (command.empty()) {
6948 result.AppendErrorWithFormat("'%s' takes a command string argument",
6949 m_cmd_name.c_str());
6950 return;
6951 }
6952
6953 ProcessGDBRemote *process =
6954 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6955 if (process) {
6956 StreamString packet;
6957 packet.PutCString("qRcmd,");
6958 packet.PutBytesAsRawHex8(command.data(), command.size());
6959
6960 StringExtractorGDBRemote response;
6961 Stream &output_strm = result.GetOutputStream();
6963 packet.GetString(), response, process->GetInterruptTimeout(),
6964 [&output_strm](llvm::StringRef output) { output_strm << output; });
6966 output_strm.Printf(" packet: %s\n", packet.GetData());
6967 const std::string &response_str = std::string(response.GetStringRef());
6968
6969 if (response_str.empty())
6970 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6971 else
6972 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6973 }
6974 }
6975};
6976
6978private:
6979public:
6981 : CommandObjectMultiword(interpreter, "process plugin packet",
6982 "Commands that deal with GDB remote packets.",
6983 nullptr) {
6985 "history",
6989 "send", CommandObjectSP(
6990 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
6992 "monitor",
6996 "xfer-size",
6999 LoadSubCommand("speed-test",
7001 interpreter)));
7002 }
7003
7005};
7006
7008public:
7011 interpreter, "process plugin",
7012 "Commands for operating on a ProcessGDBRemote process.",
7013 "process plugin <subcommand> [<subcommand-options>]") {
7015 "packet",
7017 }
7018
7020};
7021
7023 if (!m_command_sp)
7024 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
7025 GetTarget().GetDebugger().GetCommandInterpreter());
7026 return m_command_sp.get();
7027}
7028
7030 bool enable, bool is_expression_fork) {
7031 Log *log = GetLog(GDBRLog::Process);
7032
7033 // Resolve the expression-return sentinel address (_start) once. This is
7034 // the same address ThreadPlanCallFunction uses as the return trap.
7036 if (!enable && is_expression_fork) {
7037 if (auto entry = GetTarget().GetEntryPointAddress())
7038 entry_addr = entry->GetOpcodeLoadAddress(&GetTarget());
7039 }
7040
7041 GetBreakpointSiteList().ForEach([this, enable, entry_addr,
7042 log](BreakpointSite *bp_site) {
7043 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
7044 (bp_site->GetType() == BreakpointSite::eSoftware ||
7045 bp_site->GetType() == BreakpointSite::eExternal)) {
7046 // During expression evaluation, retain the expression-return trap
7047 // at _start in the forked child so it dies deterministically on
7048 // SIGTRAP rather than executing _start with a corrupted stack.
7049 if (entry_addr != LLDB_INVALID_ADDRESS &&
7050 bp_site->GetLoadAddress() == entry_addr) {
7051 LLDB_LOG(log,
7052 "DidForkSwitchSoftwareBreakpoints: retaining expression-"
7053 "return trap at {0:x} in forked child",
7054 bp_site->GetLoadAddress());
7055 return;
7056 }
7057 m_gdb_comm.SendGDBStoppointTypePacket(
7058 eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
7060 }
7061 });
7062}
7063
7065 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
7066 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
7067 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
7068 bp_site->GetType() == BreakpointSite::eHardware) {
7069 m_gdb_comm.SendGDBStoppointTypePacket(
7070 eBreakpointHardware, enable, bp_site->GetLoadAddress(),
7072 }
7073 });
7074 }
7075
7076 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
7077 addr_t addr = wp_res_sp->GetLoadAddress();
7078 size_t size = wp_res_sp->GetByteSize();
7079 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
7080 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, addr, size,
7082 }
7083}
7084
7086 bool is_expression_fork) {
7087 Log *log = GetLog(GDBRLog::Process);
7088
7089 // During expression evaluation, force follow-parent regardless of which
7090 // thread forked. The expression is running on the parent and following the
7091 // child would cause the expression thread to vanish (the child has different
7092 // thread IDs). Even if a *different* thread forks, switching to the child
7093 // would destroy the expression thread's process context.
7094 FollowForkMode follow_fork_mode = GetFollowForkMode();
7095 bool overrode_follow_mode = false;
7096 if (follow_fork_mode == eFollowChild &&
7097 GetModIDRef().IsRunningExpression()) {
7098 if (is_expression_fork) {
7099 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
7100 "to parent during expression evaluation");
7101 } else {
7102 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
7103 "to parent during expression evaluation. Child process "
7104 "{0} is available for manual attachment.",
7105 child_pid);
7106 }
7107 follow_fork_mode = eFollowParent;
7108 overrode_follow_mode = true;
7109 }
7110
7111 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
7112 // Any valid TID will suffice, thread-relevant actions will set a proper TID
7113 // anyway.
7114 lldb::tid_t parent_tid = m_thread_ids.front();
7115
7116 lldb::pid_t follow_pid, detach_pid;
7117 lldb::tid_t follow_tid, detach_tid;
7118
7119 switch (follow_fork_mode) {
7120 case eFollowParent:
7121 follow_pid = parent_pid;
7122 follow_tid = parent_tid;
7123 detach_pid = child_pid;
7124 detach_tid = child_tid;
7125 break;
7126 case eFollowChild:
7127 follow_pid = child_pid;
7128 follow_tid = child_tid;
7129 detach_pid = parent_pid;
7130 detach_tid = parent_tid;
7131 break;
7132 }
7133
7134 // Switch to the process that is going to be detached.
7135 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
7136 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
7137 return;
7138 }
7139
7140 // Disable all software breakpoints in the forked process.
7141 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7142 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
7143
7144 // Remove hardware breakpoints / watchpoints from parent process if we're
7145 // following child.
7146 if (follow_fork_mode == eFollowChild)
7148
7149 // Switch to the process that is going to be followed
7150 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
7151 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
7152 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
7153 return;
7154 }
7155
7156 LLDB_LOG(log, "Detaching process {0}", detach_pid);
7157 // When we overrode follow-child because of a concurrent expression, try to
7158 // keep the child stopped so the user can attach to it manually.
7159 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
7160 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
7161 if (error.Fail() && keep_stopped) {
7162 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach-and-stay-stopped not "
7163 "supported, falling back to normal detach");
7164 keep_stopped = false;
7165 error = m_gdb_comm.Detach(false, detach_pid);
7166 }
7167 if (error.Fail()) {
7168 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
7169 error.AsCString() ? error.AsCString() : "<unknown error>");
7170 return;
7171 }
7172
7173 // Notify the user via the async output channel when we overrode
7174 // follow-fork-mode for a non-expression fork during expression evaluation.
7175 if (overrode_follow_mode && !is_expression_fork) {
7176 StreamUP output_up =
7178 if (output_up) {
7179 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
7180 "'parent' because an expression is being evaluated.\n"
7181 "Child process %" PRIu64
7182 " has been detached%s.\n"
7183 "You can attach to it with: process attach -p %" PRIu64
7184 "\n",
7185 child_pid,
7186 keep_stopped ? " and stopped" : " (running)",
7187 child_pid);
7188 output_up->Flush();
7189 }
7190 }
7191
7192 // Hardware breakpoints/watchpoints are not inherited implicitly,
7193 // so we need to readd them if we're following child.
7194 if (follow_fork_mode == eFollowChild) {
7196 // Update our PID
7197 SetID(child_pid);
7198 }
7199}
7200
7202 bool is_expression_fork) {
7203 Log *log = GetLog(GDBRLog::Process);
7204
7205 LLDB_LOG(
7206 log,
7207 "ProcessGDBRemote::DidVFork() called for child_pid: {0}, child_tid {1}",
7208 child_pid, child_tid);
7210
7211 // See comment in DidFork(): force follow-parent during expression evaluation
7212 // regardless of which thread triggered the vfork.
7213 FollowForkMode follow_fork_mode = GetFollowForkMode();
7214 bool overrode_follow_mode = false;
7215 if (follow_fork_mode == eFollowChild &&
7216 GetModIDRef().IsRunningExpression()) {
7217 if (is_expression_fork) {
7218 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
7219 "to parent during expression evaluation");
7220 } else {
7221 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
7222 "to parent during expression evaluation. Child process "
7223 "{0} is available for manual attachment.",
7224 child_pid);
7225 }
7226 follow_fork_mode = eFollowParent;
7227 overrode_follow_mode = true;
7228 }
7229
7230 // Disable all software breakpoints for the duration of vfork.
7231 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7232 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
7233
7234 lldb::pid_t detach_pid;
7235 lldb::tid_t detach_tid;
7236
7237 switch (follow_fork_mode) {
7238 case eFollowParent:
7239 detach_pid = child_pid;
7240 detach_tid = child_tid;
7241 break;
7242 case eFollowChild:
7243 detach_pid = m_gdb_comm.GetCurrentProcessID();
7244 // Any valid TID will suffice, thread-relevant actions will set a proper TID
7245 // anyway.
7246 detach_tid = m_thread_ids.front();
7247
7248 // Switch to the parent process before detaching it.
7249 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
7250 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to set pid/tid");
7251 return;
7252 }
7253
7254 // Remove hardware breakpoints / watchpoints from the parent process.
7256
7257 // Switch to the child process.
7258 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
7259 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
7260 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to reset pid/tid");
7261 return;
7262 }
7263 break;
7264 }
7265
7266 LLDB_LOG(log, "Detaching process {0}", detach_pid);
7267 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
7268 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
7269 if (error.Fail() && keep_stopped) {
7270 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() detach-and-stay-stopped not "
7271 "supported, falling back to normal detach");
7272 keep_stopped = false;
7273 error = m_gdb_comm.Detach(false, detach_pid);
7274 }
7275 if (error.Fail()) {
7276 LLDB_LOG(log,
7277 "ProcessGDBRemote::DidVFork() detach packet send failed: {0}",
7278 error.AsCString() ? error.AsCString() : "<unknown error>");
7279 return;
7280 }
7281
7282 if (overrode_follow_mode && !is_expression_fork) {
7283 StreamUP output_up =
7285 if (output_up) {
7286 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
7287 "'parent' because an expression is being evaluated.\n"
7288 "Child process %" PRIu64
7289 " has been detached%s.\n"
7290 "You can attach to it with: process attach -p %" PRIu64
7291 "\n",
7292 child_pid,
7293 keep_stopped ? " and stopped" : " (running)",
7294 child_pid);
7295 output_up->Flush();
7296 }
7297 }
7298
7299 if (follow_fork_mode == eFollowChild) {
7300 // Update our PID
7301 SetID(child_pid);
7302 }
7303}
7304
7306 assert(m_vfork_in_progress_count > 0);
7308
7309 // Reenable all software breakpoints that were enabled before vfork.
7310 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7312}
7313
7315 // If we are following children, vfork is finished by exec (rather than
7316 // vforkdone that is submitted for parent).
7320 }
7322}
7323
7325 const BreakpointSiteToActionMap &site_to_action) {
7326 llvm::Error joined = llvm::Error::success();
7327 for (auto &[site, action] : site_to_action) {
7328 llvm::Error error = action == Process::BreakpointAction::Enable
7329 ? DoEnableBreakpointSite(*site)
7330 : DoDisableBreakpointSite(*site);
7331 joined = llvm::joinErrors(std::move(joined), std::move(error));
7332 }
7333 return joined;
7334}
7335
7336/// Parse a MultiBreakpoint response into per-request results.
7337/// Returns a vector of results: std::nullopt means OK, a uint8_t value is the
7338/// error code from an Exx response.
7339static llvm::SmallVector<std::optional<uint8_t>>
7340ParseMultiBreakpointResponse(llvm::StringRef response_str) {
7341 llvm::SmallVector<std::optional<uint8_t>> results;
7342
7345 parsed ? parsed->GetAsDictionary() : nullptr;
7346 StructuredData::Array *array = nullptr;
7347 if (dict)
7348 dict->GetValueForKeyAsArray("results", array);
7349 if (!array)
7350 return results;
7351
7352 array->ForEach([&results](StructuredData::Object *object) -> bool {
7353 llvm::StringRef token;
7354 if (auto *string = object->GetAsString())
7355 token = string->GetValue();
7356 if (token == "OK") {
7357 results.push_back(std::nullopt);
7358 return true;
7359 }
7360 if (token.size() != 3 || !token.starts_with("E")) {
7361 results.push_back(uint8_t(0xff));
7362 return true;
7363 }
7364 uint8_t error_code = 0;
7365 if (token.drop_front(1).getAsInteger(BASE_16, error_code))
7366 results.push_back(0xff);
7367 else
7368 results.push_back(error_code);
7369 return true;
7370 });
7371 return results;
7372}
7373
7374/// Determine the GDB stoppoint type for a breakpoint site by checking which
7375/// packet types the remote supports (for insertions), or by checking the site
7376/// type (for deletions).
7377static std::optional<GDBStoppointType>
7379 GDBRemoteCommunicationClient &gdb_comm) {
7380 if (insert) {
7381 if (!site.HardwareRequired() &&
7383 return eBreakpointSoftware;
7385 return eBreakpointHardware;
7386 return std::nullopt;
7387 }
7388
7389 switch (site.GetType()) {
7391 return eBreakpointSoftware;
7393 return eBreakpointHardware;
7395 return std::nullopt;
7396 }
7397 llvm_unreachable("unhandled BreakpointSite type");
7398}
7399
7400namespace {
7401struct BreakpointPacketInfo {
7402 BreakpointSite &site;
7403 size_t trap_opcode_size;
7404 GDBStoppointType type;
7405 bool is_enable;
7406};
7407
7408std::string to_string(const BreakpointPacketInfo &info) {
7409 char packet = info.is_enable ? 'Z' : 'z';
7410 return llvm::formatv("{0}{1},{2:x-},{3:x-}", packet,
7411 static_cast<int>(info.type), info.site.GetLoadAddress(),
7412 info.trap_opcode_size)
7413 .str();
7414}
7415} // namespace
7416
7418 const BreakpointSiteToActionMap &site_to_action) {
7419 if (site_to_action.empty())
7420 return llvm::Error::success();
7421 if (!m_gdb_comm.GetMultiBreakpointSupported())
7422 return UpdateBreakpointSitesNotBatched(site_to_action);
7423
7425
7426 std::vector<BreakpointPacketInfo> breakpoint_infos;
7427 for (auto [site, action] : site_to_action) {
7428 size_t trap_opcode_size = GetSoftwareBreakpointTrapOpcode(site.get());
7429 std::optional<GDBStoppointType> type =
7431
7432 if (!type) {
7433 LLDB_LOG(log, "MultiBreakpoint: site {0} at {1:x} can't be batched",
7434 site->GetID(), site->GetLoadAddress());
7435 return UpdateBreakpointSitesNotBatched(site_to_action);
7436 }
7437
7438 breakpoint_infos.push_back(
7439 {*site, trap_opcode_size, *type, action == BreakpointAction::Enable});
7440 }
7441
7442 StreamString stream;
7443 stream << "jMultiBreakpoint:";
7444
7445 auto args_array = std::make_shared<StructuredData::Array>();
7446 for (auto &bp_info : breakpoint_infos)
7447 args_array->AddStringItem(to_string(bp_info));
7448
7449 StructuredData::Dictionary packet_dict;
7450 packet_dict.AddItem("breakpoint_requests", args_array);
7451 packet_dict.Dump(stream, false);
7452
7453 StreamGDBRemote escaped_stream;
7454 escaped_stream.PutEscapedBytes(stream.GetString());
7455 llvm::Expected<StringExtractorGDBRemote> response =
7456 m_gdb_comm.SendPacketAndExpectResponse(escaped_stream.GetString(),
7458
7459 if (!response) {
7460 LLDB_LOG_ERROR(log, response.takeError(), "jMultiBreakpoint failed: {0}");
7461 return UpdateBreakpointSitesNotBatched(site_to_action);
7462 }
7463
7464 llvm::SmallVector<std::optional<uint8_t>> results =
7465 ParseMultiBreakpointResponse(response->GetStringRef());
7466
7467 // This is a protocol violation, do nothing.
7468 if (results.size() != breakpoint_infos.size())
7469 return llvm::createStringErrorV(
7470 "MultiBreakpoint response count mismatch (expected {0}, got {1})",
7471 site_to_action.size(), results.size());
7472
7473 llvm::Error joined = llvm::Error::success();
7474 for (auto [error_code, bp_info] :
7475 llvm::zip_equal(results, breakpoint_infos)) {
7476 BreakpointSite &site = bp_info.site;
7477 if (error_code) {
7478 auto error = llvm::createStringErrorV(
7479 "MultiBreakpoint: site {0} at {1:x} failed with E{2}",
7480 bp_info.site.GetID(), bp_info.site.GetLoadAddress(), error_code);
7481 joined = llvm::joinErrors(std::move(joined), std::move(error));
7482 continue;
7483 }
7484 SetBreakpointSiteEnabled(site, bp_info.is_enable);
7485 if (bp_info.is_enable)
7486 site.SetType(bp_info.type == eBreakpointHardware
7489 }
7490
7491 return joined;
7492}
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 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
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 uniqued constant string class.
Definition ConstString.h:40
void SetCString(const char *cstr)
Set the C string value.
void SetString(llvm::StringRef s)
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:127
void FindFunctions(ConstString name, lldb::FunctionNameType name_type_mask, const ModuleFunctionSearchOptions &options, SymbolContextList &sc_list) const
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
void FindSymbolsWithNameAndType(ConstString name, lldb::SymbolType symbol_type, SymbolContextList &sc_list) const
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.
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:1208
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:46
@ eTypeExecutable
A normal executable.
Definition ObjectFile.h:55
@ eTypeDebugInfo
An object file that contains only debug information.
Definition ObjectFile.h:57
@ eTypeStubLibrary
A library that can be linked against but not used for execution.
Definition ObjectFile.h:65
@ eTypeObjectFile
An intermediate object file.
Definition ObjectFile.h:61
@ eTypeDynamicLinker
The platform's dynamic linker executable.
Definition ObjectFile.h:59
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition ObjectFile.h:53
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition ObjectFile.h:63
@ eTypeJIT
JIT code that has symbols, sections and possibly debug info.
Definition ObjectFile.h:67
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:430
std::chrono::seconds GetInterruptTimeout() const
Definition Process.cpp:387
A plug-in interface definition class for debugging a process.
Definition Process.h:369
lldb::IOHandlerSP m_process_input_reader
Definition Process.h:3556
std::mutex m_process_input_reader_mutex
Definition Process.h:3557
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1608
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1986
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:554
ThreadList & GetThreadList()
Definition Process.h:2372
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7218
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:486
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:3959
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:5031
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6434
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:2173
void ResumePrivateStateThread()
Definition Process.cpp:4217
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:6677
std::map< lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp > BreakpointSiteToActionMap
Definition Process.h:2292
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3158
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition Process.h:3506
lldb::StateType GetPrivateState() const
Definition Process.h:3463
void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled=true)
Definition Process.h:3757
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3544
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition Process.cpp:2727
StopPointSiteList< lldb_private::WatchpointResource > m_watchpoint_resource_list
Watchpoint resources currently in use.
Definition Process.h:3536
bool IsBreakpointSitePhysicallyEnabled(const BreakpointSite &site)
Definition Process.cpp:1713
std::vector< AddressSpaceInfo > m_address_spaces
A list of address spaces for this process.
Definition Process.h:3527
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4925
bool HasAssignedIndexIDToThread(uint64_t sb_thread_id)
Definition Process.cpp:1305
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3969
void UpdateThreadListIfNeeded()
Definition Process.cpp:1167
bool IsValid() const
Return whether this object is valid (i.e.
Definition Process.h:589
virtual void DidExec()
Called after a process re-execs itself.
Definition Process.cpp:6367
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:4939
lldb::UnixSignalsSP m_unix_signals_sp
Definition Process.h:3554
lldb::tid_t m_interrupt_tid
Definition Process.h:3586
void AddCacheData(lldb::addr_t addr, const lldb::WritableDataBufferSP &data_buffer_sp)
Cache memory, restoring the original bytes under any breakpoint.
Definition Process.cpp:1889
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1906
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
Definition Process.cpp:6744
virtual bool IsAlive()
Check if a process is still alive.
Definition Process.cpp:1142
ThreadList m_thread_list_real
The threads for this process as are known to the protocol we are debugging with.
Definition Process.h:3512
lldb::StateType m_last_broadcast_state
Definition Process.h:3618
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:559
friend class Target
Definition Process.h:375
uint32_t AssignIndexIDToThread(uint64_t thread_id)
Definition Process.cpp:1310
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition Process.cpp:1084
uint32_t GetAddressByteSize() const
Definition Process.cpp:3973
uint32_t GetStopID() const
Definition Process.h:1517
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1448
llvm::Expected< AddressSpaceInfo > GetAddressSpaceInfo(llvm::StringRef address_space_name)
Definition Process.cpp:7241
lldb::StateType GetPublicState() const
Definition Process.h:3457
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:600
void SetSTDIOPseudoTerminal(PseudoTerminal &pty)
Associates the primary side of pty with the process' STDIO handling.
Definition Process.cpp:5061
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3514
const lldb::UnixSignalsSP & GetUnixSignals()
Definition Process.cpp:3964
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition Process.h:3481
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
Locate the memory region that contains load_addr.
Definition Process.cpp:6608
friend class DynamicLoader
Definition Process.h:372
size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site)
Definition Process.cpp:1899
friend class Debugger
Definition Process.h:371
const ProcessModID & GetModIDRef() const
Definition Process.h:1515
ThreadedCommunication m_stdio_communication
Definition Process.h:3558
friend class ThreadList
Definition Process.h:376
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1270
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:1366
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:2008
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:1283
const ArchSpec & GetArchitecture() const
Definition Target.h:1325
@ eBroadcastBitNewTargetCreated
Definition Target.h:616
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)
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 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)
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.
bool GetThreadStopInfoFromJSON(ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp)
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.
Status EstablishConnectionIfNeeded(const ProcessInfo &process_info)
llvm::Error UpdateBreakpointSites(const BreakpointSiteToActionMap &site_to_action) override
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.
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.
Guarded< StructuredData::ObjectSP, std::mutex > m_jthreadsinfo
Full stop info, expedited registers and memory for all threads, from the "jThreadsInfo" packet.
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
Guarded< StructuredData::ObjectSP, std::mutex > m_jstopinfo
Stop info caches filled at a stop and reset by WillResume, which runs on another thread.
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.
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