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 }
2160 }
2161
2162 if (!handled && signo && !did_exec) {
2163 if (signo == SIGTRAP) {
2164 // Currently we are going to assume SIGTRAP means we are either
2165 // hitting a breakpoint or hardware single stepping.
2166
2167 // We can't disambiguate between stepping-to-a-breakpointsite and
2168 // hitting-a-breakpointsite.
2169 //
2170 // A user can instruction-step, and be stopped at a BreakpointSite.
2171 // Or a user can be sitting at a BreakpointSite,
2172 // instruction-step which hits the breakpoint and the pc does not
2173 // advance.
2174 //
2175 // In both cases, we're at a BreakpointSite when stopped, and
2176 // the resume state was eStateStepping.
2177
2178 // Assume if we're at a BreakpointSite, we hit it.
2179 handled = true;
2180 addr_t pc =
2181 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2182 BreakpointSiteSP bp_site_sp =
2183 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
2184 pc);
2185
2186 // We can't know if we hit it or not. So if we are stopped at
2187 // a BreakpointSite, assume we hit it, and should step past the
2188 // breakpoint when we resume. This is contrary to how we handle
2189 // BreakpointSites in any other location, but we can't know for
2190 // sure what happened so it's a reasonable default.
2191 if (bp_site_sp) {
2192 if (IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
2193 thread_sp->SetThreadHitBreakpointSite();
2194
2195 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2196 if (m_breakpoint_pc_offset != 0)
2197 thread_sp->GetRegisterContext()->SetPC(pc);
2198 thread_sp->SetStopInfo(
2200 *thread_sp, bp_site_sp->GetID()));
2201 } else {
2202 StopInfoSP invalid_stop_info_sp;
2203 thread_sp->SetStopInfo(invalid_stop_info_sp);
2204 }
2205 } else {
2206 // If we were stepping then assume the stop was the result of the
2207 // trace. If we were not stepping then report the SIGTRAP.
2208 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2209 thread_sp->SetStopInfo(
2211 else
2212 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2213 *thread_sp, signo, description.c_str()));
2214 }
2215 }
2216 if (!handled) {
2217 // For thread plan async interrupt, creating stop info on the
2218 // original async interrupt request thread instead. If interrupt
2219 // thread does not exist anymore we fallback to current signal
2220 // receiving thread instead.
2221 ThreadSP interrupt_thread;
2223 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
2224 if (interrupt_thread)
2225 thread_sp = interrupt_thread;
2226 else
2227 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2228 *thread_sp, signo, description.c_str()));
2229 }
2230 }
2231
2232 if (!description.empty()) {
2233 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2234 if (stop_info_sp) {
2235 const char *stop_info_desc = stop_info_sp->GetDescription();
2236 if (!stop_info_desc || !stop_info_desc[0])
2237 stop_info_sp->SetDescription(description.c_str());
2238 } else {
2239 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2240 *thread_sp, description.c_str()));
2241 }
2242 }
2243 }
2244 }
2245 return thread_sp;
2246}
2247
2250 const std::string &description) {
2251 ThreadSP thread_sp;
2252 {
2253 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2254 thread_sp = m_thread_list_real.FindThreadByProtocolID(m_interrupt_tid,
2255 /*can_update=*/false);
2256 }
2257 if (thread_sp)
2258 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(
2259 *thread_sp, signo, description.c_str()));
2260 // Clear m_interrupt_tid regardless we can find original interrupt thread or
2261 // not.
2263 return thread_sp;
2264}
2265
2268 lldb::ThreadSP thread_sp) {
2269 static constexpr llvm::StringLiteral g_key_tid("tid");
2270 static constexpr llvm::StringLiteral g_key_name("name");
2271 static constexpr llvm::StringLiteral g_key_reason("reason");
2272 static constexpr llvm::StringLiteral g_key_metype("metype");
2273 static constexpr llvm::StringLiteral g_key_medata("medata");
2274 static constexpr llvm::StringLiteral g_key_qaddr("qaddr");
2275 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2276 "dispatch_queue_t");
2277 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2278 "associated_with_dispatch_queue");
2279 static constexpr llvm::StringLiteral g_key_queue_name("qname");
2280 static constexpr llvm::StringLiteral g_key_queue_kind("qkind");
2281 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");
2282 static constexpr llvm::StringLiteral g_key_registers("registers");
2283 static constexpr llvm::StringLiteral g_key_memory("memory");
2284 static constexpr llvm::StringLiteral g_key_description("description");
2285 static constexpr llvm::StringLiteral g_key_signal("signal");
2286 static constexpr llvm::StringLiteral g_key_added_binaries("added-binaries");
2287 static constexpr llvm::StringLiteral g_key_detailed_binaries_info(
2288 "detailed-binaries-info");
2289
2290 // Stop with signal and thread info
2292 uint8_t signo = 0;
2293 std::string thread_name;
2294 std::string reason;
2295 std::string description;
2296 uint32_t exc_type = 0;
2297 std::vector<addr_t> exc_data;
2298 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2299 ExpeditedRegisterMap expedited_register_map;
2300 bool queue_vars_valid = false;
2301 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2302 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2303 std::string queue_name;
2304 QueueKind queue_kind = eQueueKindUnknown;
2305 uint64_t queue_serial_number = 0;
2306 std::vector<addr_t> added_binaries;
2307 StructuredData::ObjectSP detailed_binaries_info;
2308 // Iterate through all of the thread dictionary key/value pairs from the
2309 // structured data dictionary
2310
2311 // FIXME: we're silently ignoring invalid data here
2312 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2313 &signo, &reason, &description, &exc_type, &exc_data,
2314 &thread_dispatch_qaddr, &queue_vars_valid,
2315 &associated_with_dispatch_queue, &dispatch_queue_t,
2316 &queue_name, &queue_kind, &queue_serial_number,
2317 &added_binaries, &detailed_binaries_info](
2318 llvm::StringRef key,
2319 StructuredData::Object *object) -> bool {
2320 if (key == g_key_tid) {
2321 // thread in big endian hex
2322 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
2323 } else if (key == g_key_metype) {
2324 // exception type in big endian hex
2325 exc_type = object->GetUnsignedIntegerValue(0);
2326 } else if (key == g_key_medata) {
2327 // exception data in big endian hex
2328 StructuredData::Array *array = object->GetAsArray();
2329 if (array) {
2330 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2331 exc_data.push_back(object->GetUnsignedIntegerValue());
2332 return true; // Keep iterating through all array items
2333 });
2334 }
2335 } else if (key == g_key_name) {
2336 thread_name = std::string(object->GetStringValue());
2337 } else if (key == g_key_qaddr) {
2338 thread_dispatch_qaddr =
2339 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
2340 } else if (key == g_key_queue_name) {
2341 queue_vars_valid = true;
2342 queue_name = std::string(object->GetStringValue());
2343 } else if (key == g_key_queue_kind) {
2344 std::string queue_kind_str = std::string(object->GetStringValue());
2345 if (queue_kind_str == "serial") {
2346 queue_vars_valid = true;
2347 queue_kind = eQueueKindSerial;
2348 } else if (queue_kind_str == "concurrent") {
2349 queue_vars_valid = true;
2350 queue_kind = eQueueKindConcurrent;
2351 }
2352 } else if (key == g_key_queue_serial_number) {
2353 queue_serial_number = object->GetUnsignedIntegerValue(0);
2354 if (queue_serial_number != 0)
2355 queue_vars_valid = true;
2356 } else if (key == g_key_dispatch_queue_t) {
2357 dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2358 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2359 queue_vars_valid = true;
2360 } else if (key == g_key_associated_with_dispatch_queue) {
2361 queue_vars_valid = true;
2362 bool associated = object->GetBooleanValue();
2363 if (associated)
2364 associated_with_dispatch_queue = eLazyBoolYes;
2365 else
2366 associated_with_dispatch_queue = eLazyBoolNo;
2367 } else if (key == g_key_reason) {
2368 reason = std::string(object->GetStringValue());
2369 } else if (key == g_key_description) {
2370 description = std::string(object->GetStringValue());
2371 } else if (key == g_key_registers) {
2372 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2373
2374 if (registers_dict) {
2375 registers_dict->ForEach(
2376 [&expedited_register_map](llvm::StringRef key,
2377 StructuredData::Object *object) -> bool {
2378 uint32_t reg;
2379 if (llvm::to_integer(key, reg))
2380 expedited_register_map[reg] =
2381 std::string(object->GetStringValue());
2382 return true; // Keep iterating through all array items
2383 });
2384 }
2385 } else if (key == g_key_memory) {
2386 StructuredData::Array *array = object->GetAsArray();
2387 if (array) {
2388 array->ForEach([this](StructuredData::Object *object) -> bool {
2389 StructuredData::Dictionary *mem_cache_dict =
2390 object->GetAsDictionary();
2391 if (mem_cache_dict) {
2392 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2393 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2394 "address", mem_cache_addr)) {
2395 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2396 llvm::StringRef str;
2397 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2398 StringExtractor bytes(str);
2399 bytes.SetFilePos(0);
2400
2401 const size_t byte_size = bytes.GetStringRef().size() / 2;
2402 WritableDataBufferSP data_buffer_sp(
2403 new DataBufferHeap(byte_size, 0));
2404 const size_t bytes_copied =
2405 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2406 if (bytes_copied == byte_size)
2407 AddCacheData(mem_cache_addr, data_buffer_sp);
2408 }
2409 }
2410 }
2411 }
2412 return true; // Keep iterating through all array items
2413 });
2414 }
2415 } else if (key == g_key_signal)
2416 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2417 else if (key == g_key_added_binaries) {
2418 StructuredData::Array *array = object->GetAsArray();
2419 if (array) {
2420 array->ForEach([&added_binaries](
2421 StructuredData::Object *object) -> bool {
2423 object->GetAsUnsignedInteger();
2424 if (addr) {
2426 if (value != LLDB_INVALID_ADDRESS)
2427 added_binaries.push_back(value);
2428 }
2429 return true; // Keep iterating through all array items
2430 });
2431 }
2432 } else if (key == g_key_detailed_binaries_info) {
2433 // Get a string representation and then parse it into
2434 // StructuredData to get a separate copy of this part of
2435 // the response. We only have an Object* here, not the
2436 // original shared pointer, to increase the ref count.
2437 if (object->GetAsDictionary()) {
2438 StreamString json_str;
2439 object->Dump(json_str);
2440 detailed_binaries_info =
2442 }
2443 }
2444 return true; // Keep iterating through all dictionary key/value pairs
2445 });
2446
2447 return SetThreadStopInfo(
2448 tid, expedited_register_map, signo, thread_name, reason, description,
2449 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2450 associated_with_dispatch_queue, dispatch_queue_t, queue_name, queue_kind,
2451 queue_serial_number, added_binaries, detailed_binaries_info,
2452 std::move(thread_sp));
2453}
2454
2456 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2457 stop_packet.SetFilePos(0);
2458 const char stop_type = stop_packet.GetChar();
2459 switch (stop_type) {
2460 case 'T':
2461 case 'S': {
2462 // This is a bit of a hack, but it is required. If we did exec, we need to
2463 // clear our thread lists and also know to rebuild our dynamic register
2464 // info before we lookup and threads and populate the expedited register
2465 // values so we need to know this right away so we can cleanup and update
2466 // our registers.
2467 const uint32_t stop_id = GetStopID();
2468 if (stop_id == 0) {
2469 // Our first stop, make sure we have a process ID, and also make sure we
2470 // know about our registers
2472 SetID(pid);
2474 }
2475 // Stop with signal and thread info
2478 const uint8_t signo = stop_packet.GetHexU8();
2479 llvm::StringRef key;
2480 llvm::StringRef value;
2481 std::string thread_name;
2482 std::string reason;
2483 std::string description;
2484 std::vector<addr_t> added_binaries;
2485 StructuredData::ObjectSP detailed_binaries_info;
2486 uint32_t exc_type = 0;
2487 std::vector<addr_t> exc_data;
2488 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2489 bool queue_vars_valid =
2490 false; // says if locals below that start with "queue_" are valid
2491 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2492 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2493 std::string queue_name;
2494 QueueKind queue_kind = eQueueKindUnknown;
2495 uint64_t queue_serial_number = 0;
2496 ExpeditedRegisterMap expedited_register_map;
2497 AddressableBits addressable_bits;
2498 while (stop_packet.GetNameColonValue(key, value)) {
2499 if (key.compare("metype") == 0) {
2500 // exception type in big endian hex
2501 value.getAsInteger(BASE_16, exc_type);
2502 } else if (key.compare("medata") == 0) {
2503 // exception data in big endian hex
2504 uint64_t x;
2505 value.getAsInteger(BASE_16, x);
2506 exc_data.push_back(x);
2507 } else if (key.compare("thread") == 0) {
2508 // thread-id
2509 StringExtractorGDBRemote thread_id{value};
2510 auto pid_tid = thread_id.GetPidTid(pid);
2511 if (pid_tid) {
2512 stop_pid = pid_tid->first;
2513 tid = pid_tid->second;
2514 } else
2516 } else if (key.compare("threads") == 0) {
2517 std::lock_guard<std::recursive_mutex> guard(
2518 m_thread_list_real.GetMutex());
2520 } else if (key.compare("thread-pcs") == 0) {
2521 m_thread_pcs.clear();
2522 // A comma separated list of all threads in the current
2523 // process that includes the thread for this stop reply packet
2525 while (!value.empty()) {
2526 llvm::StringRef pc_str;
2527 std::tie(pc_str, value) = value.split(',');
2528 if (pc_str.getAsInteger(BASE_16, pc))
2530 m_thread_pcs.push_back(pc);
2531 }
2532 } else if (key.compare("jstopinfo") == 0) {
2533 StringExtractor json_extractor(value);
2534 std::string json;
2535 // Now convert the HEX bytes into a string value
2536 json_extractor.GetHexByteString(json);
2537
2538 // This JSON contains thread IDs and thread stop info for all threads.
2539 // It doesn't contain expedited registers, memory or queue info.
2540 *m_jstopinfo.Lock() = StructuredData::ParseJSON(json);
2541 } else if (key.compare("hexname") == 0) {
2542 StringExtractor name_extractor(value);
2543 // Now convert the HEX bytes into a string value
2544 name_extractor.GetHexByteString(thread_name);
2545 } else if (key.compare("name") == 0) {
2546 thread_name = std::string(value);
2547 } else if (key.compare("qaddr") == 0) {
2548 value.getAsInteger(BASE_16, thread_dispatch_qaddr);
2549 } else if (key.compare("dispatch_queue_t") == 0) {
2550 queue_vars_valid = true;
2551 value.getAsInteger(BASE_16, dispatch_queue_t);
2552 } else if (key.compare("qname") == 0) {
2553 queue_vars_valid = true;
2554 StringExtractor name_extractor(value);
2555 // Now convert the HEX bytes into a string value
2556 name_extractor.GetHexByteString(queue_name);
2557 } else if (key.compare("qkind") == 0) {
2558 queue_kind = llvm::StringSwitch<QueueKind>(value)
2559 .Case("serial", eQueueKindSerial)
2560 .Case("concurrent", eQueueKindConcurrent)
2561 .Default(eQueueKindUnknown);
2562 queue_vars_valid = queue_kind != eQueueKindUnknown;
2563 } else if (key.compare("qserialnum") == 0) {
2564 if (!value.getAsInteger(BASE_10, queue_serial_number))
2565 queue_vars_valid = true;
2566 } else if (key.compare("reason") == 0) {
2567 reason = std::string(value);
2568 } else if (key.compare("description") == 0) {
2569 StringExtractor desc_extractor(value);
2570 // Now convert the HEX bytes into a string value
2571 desc_extractor.GetHexByteString(description);
2572 } else if (key.compare("memory") == 0) {
2573 // Expedited memory. GDB servers can choose to send back expedited
2574 // memory that can populate the L1 memory cache in the process so that
2575 // things like the frame pointer backchain can be expedited. This will
2576 // help stack backtracing be more efficient by not having to send as
2577 // many memory read requests down the remote GDB server.
2578
2579 // Key/value pair format: memory:<addr>=<bytes>;
2580 // <addr> is a number whose base will be interpreted by the prefix:
2581 // "0x[0-9a-fA-F]+" for hex
2582 // "0[0-7]+" for octal
2583 // "[1-9]+" for decimal
2584 // <bytes> is native endian ASCII hex bytes just like the register
2585 // values
2586 llvm::StringRef addr_str, bytes_str;
2587 std::tie(addr_str, bytes_str) = value.split('=');
2588 if (!addr_str.empty() && !bytes_str.empty()) {
2589 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2590 if (!addr_str.getAsInteger(BASE_AUTOSENSE, mem_cache_addr)) {
2591 StringExtractor bytes(bytes_str);
2592 const size_t byte_size = bytes.GetBytesLeft() / 2;
2593 WritableDataBufferSP data_buffer_sp(
2594 new DataBufferHeap(byte_size, 0));
2595 const size_t bytes_copied =
2596 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2597 if (bytes_copied == byte_size)
2598 AddCacheData(mem_cache_addr, data_buffer_sp);
2599 }
2600 }
2601 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2602 key.compare("awatch") == 0) {
2603 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2605 value.getAsInteger(BASE_16, wp_addr);
2606
2607 WatchpointResourceSP wp_resource_sp =
2608 m_watchpoint_resource_list.FindByAddress(wp_addr);
2609
2610 // Rewrite gdb standard watch/rwatch/awatch to
2611 // "reason:watchpoint" + "description:ADDR",
2612 // which is parsed in SetThreadStopInfo.
2613 reason = "watchpoint";
2614 StreamString ostr;
2615 ostr.Printf("%" PRIu64, wp_addr);
2616 description = std::string(ostr.GetString());
2617 } else if (key.compare("swbreak") == 0 || key.compare("hwbreak") == 0) {
2618 reason = "breakpoint";
2619 } else if (key.compare("replaylog") == 0) {
2620 reason = "history boundary";
2621 } else if (key.compare("library") == 0) {
2622 auto error = LoadModules();
2623 if (error) {
2625 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2626 }
2627 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2628 // fork includes child pid/tid in thread-id format
2629 StringExtractorGDBRemote thread_id{value};
2630 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2631 if (!pid_tid) {
2633 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2635 }
2636
2637 reason = key.str();
2638 StreamString ostr;
2639 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2640 description = std::string(ostr.GetString());
2641 } else if (key.compare("addressing_bits") == 0) {
2642 uint64_t addressing_bits;
2643 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2644 addressable_bits.SetAddressableBits(addressing_bits);
2645 }
2646 } else if (key.compare("low_mem_addressing_bits") == 0) {
2647 uint64_t addressing_bits;
2648 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2649 addressable_bits.SetLowmemAddressableBits(addressing_bits);
2650 }
2651 } else if (key.compare("high_mem_addressing_bits") == 0) {
2652 uint64_t addressing_bits;
2653 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2654 addressable_bits.SetHighmemAddressableBits(addressing_bits);
2655 }
2656 } else if (key == "added-binaries") {
2657 // A comma separated list of all threads in the current
2658 // process that includes the thread for this stop reply packet
2660 while (!value.empty()) {
2661 llvm::StringRef pc_str;
2662 std::tie(pc_str, value) = value.split(',');
2663 if (pc_str.getAsInteger(BASE_16, pc))
2665 added_binaries.push_back(pc);
2666 }
2667 } else if (key == "detailed-binaries-info") {
2668 StringExtractor json_extractor(value);
2669 std::string json;
2670 // Now convert the HEX bytes into a string value.
2671 json_extractor.GetHexByteString(json);
2672
2673 // This JSON contains detailed information about binares.
2674 detailed_binaries_info = StructuredData::ParseJSON(json);
2675 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2676 uint32_t reg = UINT32_MAX;
2677 if (!key.getAsInteger(BASE_16, reg))
2678 expedited_register_map[reg] = std::string(std::move(value));
2679 }
2680 // swbreak and hwbreak are also expected keys, but we don't need to
2681 // change our behaviour for them because lldb always expects the remote
2682 // to adjust the program counter (if relevant, e.g., for x86 targets)
2683 }
2684
2685 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2686 Log *log = GetLog(GDBRLog::Process);
2687 LLDB_LOG(log,
2688 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2689 stop_pid, pid);
2690 return eStateInvalid;
2691 }
2692
2693 if (tid == LLDB_INVALID_THREAD_ID) {
2694 // A thread id may be invalid if the response is old style 'S' packet
2695 // which does not provide the
2696 // thread information. So update the thread list and choose the first
2697 // one.
2699
2700 if (!m_thread_ids.empty()) {
2701 tid = m_thread_ids.front();
2702 }
2703 }
2704
2705 SetAddressableBitMasks(addressable_bits);
2706
2708
2709 ThreadSP thread_sp = SetThreadStopInfo(
2710 tid, expedited_register_map, signo, thread_name, reason, description,
2711 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2712 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2713 queue_kind, queue_serial_number, added_binaries,
2714 detailed_binaries_info);
2715
2716 return eStateStopped;
2717 } break;
2718
2719 case 'W':
2720 case 'X':
2721 // process exited
2722 return eStateExited;
2723
2724 default:
2725 break;
2726 }
2727 return eStateInvalid;
2728}
2729
2731 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2732
2733 m_thread_ids.clear();
2734 m_thread_pcs.clear();
2735
2736 // Set the thread stop info. It might have a "threads" key whose value is a
2737 // list of all thread IDs in the current process, so m_thread_ids might get
2738 // set.
2739 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2740 if (m_thread_ids.empty()) {
2741 // No, we need to fetch the thread list manually
2743 }
2744
2745 // We might set some stop info's so make sure the thread list is up to
2746 // date before we do that or we might overwrite what was computed here.
2748
2751 m_last_stop_packet.reset();
2752
2753 // If we have queried for a default thread id
2755 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2759 if (ThreadSP primary_thread_sp = m_thread_list.FindThreadByProtocolID(
2760 m_last_stop_primary_tid, /*can_update=*/false)) {
2761 ThreadSP selected_thread_sp = m_thread_list.GetSelectedThread();
2762 if (!selected_thread_sp ||
2763 selected_thread_sp->GetID() != primary_thread_sp->GetID())
2764 m_thread_list.SetSelectedThreadByID(primary_thread_sp->GetID());
2765 }
2766 }
2768
2769 // Let all threads recover from stopping and do any clean up based on the
2770 // previous thread state (if any).
2771 m_thread_list_real.RefreshStateAfterStop();
2772}
2773
2775 Status error;
2776
2778 // We are being asked to halt during an attach. We used to just close our
2779 // file handle and debugserver will go away, but with remote proxies, it
2780 // is better to send a positive signal, so let's send the interrupt first...
2781 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2782 m_gdb_comm.Disconnect();
2783 } else
2784 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2785 return error;
2786}
2787
2789 Status error;
2790 Log *log = GetLog(GDBRLog::Process);
2791 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2792
2793 error = m_gdb_comm.Detach(keep_stopped);
2794 if (log) {
2795 if (error.Success())
2796 log->PutCString(
2797 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2798 else
2799 LLDB_LOGF(log,
2800 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2801 error.AsCString() ? error.AsCString() : "<unknown error>");
2802 }
2803
2804 if (!error.Success())
2805 return error;
2806
2807 // Sleep for one second to let the process get all detached...
2809
2812
2813 // KillDebugserverProcess ();
2814 return error;
2815}
2816
2818 Log *log = GetLog(GDBRLog::Process);
2819 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2820
2821 // Interrupt if our inferior is running...
2822 int exit_status = SIGABRT;
2823 std::string exit_string;
2824
2825 if (m_gdb_comm.IsConnected()) {
2827 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2828
2829 if (kill_res) {
2830 exit_status = kill_res.get();
2831#if defined(__APPLE__)
2832 // For Native processes on Mac OS X, we launch through the Host
2833 // Platform, then hand the process off to debugserver, which becomes
2834 // the parent process through "PT_ATTACH". Then when we go to kill
2835 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2836 // we call waitpid which returns with no error and the correct
2837 // status. But amusingly enough that doesn't seem to actually reap
2838 // the process, but instead it is left around as a Zombie. Probably
2839 // the kernel is in the process of switching ownership back to lldb
2840 // which was the original parent, and gets confused in the handoff.
2841 // Anyway, so call waitpid here to finally reap it.
2842 PlatformSP platform_sp(GetTarget().GetPlatform());
2843 if (platform_sp && platform_sp->IsHost()) {
2844 int status;
2845 ::pid_t reap_pid;
2846 reap_pid = waitpid(GetID(), &status, WNOHANG);
2847 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2848 }
2849#endif
2851 exit_string.assign("killed");
2852 } else {
2853 exit_string.assign(llvm::toString(kill_res.takeError()));
2854 }
2855 } else {
2856 exit_string.assign("killed or interrupted while attaching.");
2857 }
2858 } else {
2859 // If we missed setting the exit status on the way out, do it here.
2860 // NB set exit status can be called multiple times, the first one sets the
2861 // status.
2862 exit_string.assign("destroying when not connected to debugserver");
2863 }
2864
2865 SetExitStatus(exit_status, exit_string.c_str());
2866
2870 return Status();
2871}
2872
2875 if (TargetSP target_sp = m_target_wp.lock())
2876 target_sp->RemoveBreakpointByID(m_thread_create_bp_sp->GetID());
2877 m_thread_create_bp_sp.reset();
2878 }
2879}
2880
2882 const StringExtractorGDBRemote &response) {
2883 const bool did_exec =
2884 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2885 if (did_exec) {
2886 Log *log = GetLog(GDBRLog::Process);
2887 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2888
2889 m_thread_list_real.Clear();
2890 m_thread_list.Clear();
2892 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2893 }
2894
2895 m_last_stop_packet = response;
2896}
2897
2899 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2900}
2901
2902// Process Queries
2903
2905 return m_gdb_comm.IsConnected() && Process::IsAlive();
2906}
2907
2909 // request the link map address via the $qShlibInfoAddr packet
2910 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2911
2912 // the loaded module list can also provides a link map address
2913 if (addr == LLDB_INVALID_ADDRESS) {
2914 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2915 if (!list) {
2916 Log *log = GetLog(GDBRLog::Process);
2917 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2918 } else {
2919 addr = list->m_link_map;
2920 }
2921 }
2922
2923 return addr;
2924}
2925
2927 // See if the GDB remote client supports the JSON threads info. If so, we
2928 // gather stop info for all threads, expedited registers, expedited memory,
2929 // runtime queue information (iOS and MacOSX only), and more. Expediting
2930 // memory will help stack backtracing be much faster. Expediting registers
2931 // will make sure we don't have to read the thread registers for GPRs.
2932 StructuredData::ObjectSP threads_info_sp = m_gdb_comm.GetThreadsInfo();
2933 *m_jthreadsinfo.Lock() = threads_info_sp;
2934
2935 if (threads_info_sp) {
2936 // Now set the stop info for each thread and also expedite any registers
2937 // and memory that was in the jThreadsInfo response.
2938 StructuredData::Array *thread_infos = threads_info_sp->GetAsArray();
2939 if (thread_infos) {
2940 std::unordered_map<lldb::tid_t, ThreadSP> threads;
2941 for (const ThreadSP &thread_sp : m_thread_list_real.Threads())
2942 threads.try_emplace(thread_sp->GetProtocolID(), thread_sp);
2943 const size_t n = thread_infos->GetSize();
2944 for (size_t i = 0; i < n; ++i) {
2945 StructuredData::Dictionary *thread_dict =
2946 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2947 if (!thread_dict)
2948 continue;
2950 thread_dict->GetValueForKeyAsInteger("tid", tid);
2951 auto thread = threads.find(tid);
2952 SetThreadStopInfo(thread_dict,
2953 thread == threads.end() ? nullptr : thread->second);
2954 }
2955 }
2956 }
2957}
2958
2959// Process Memory
2961 void *buf, size_t size, Status &error) {
2962 using xPacketState = GDBRemoteCommunicationClient::xPacketState;
2963
2964 lldb::addr_t addr = process_addr.GetValue();
2965 lldb::addr_space_t addr_space = process_addr.GetAddressSpace();
2966 if (addr_space != LLDB_DEFAULT_ADDRESS_SPACE_ID &&
2967 !m_gdb_comm.GetAddressSpacesSupported()) {
2968 error = Status::FromErrorString("address spaces are not supported");
2969 return 0;
2970 }
2971
2973 xPacketState x_state = m_gdb_comm.GetxPacketState();
2974
2975 // M and m packets take 2 bytes for 1 byte of memory
2976 size_t max_memory_size = x_state != xPacketState::Unimplemented
2978 : m_max_memory_size / 2;
2979 if (size > max_memory_size) {
2980 // Keep memory read sizes down to a sane limit. This function will be
2981 // called multiple times in order to complete the task by
2982 // lldb_private::Process so it is ok to do this.
2983 size = max_memory_size;
2984 }
2985
2986 // A non-default address space rides on an "address_space:<hex-id>;" suffix,
2987 // followed by "thread:<hex-tid>;" when that space is thread specific.
2988 std::string suffix;
2989 if (addr_space != LLDB_DEFAULT_ADDRESS_SPACE_ID) {
2990 llvm::Expected<AddressSpaceInfo> info = GetAddressSpaceInfo(addr_space);
2991 if (!info) {
2992 error = Status::FromError(info.takeError());
2993 return 0;
2994 }
2995 suffix =
2996 llvm::formatv(";address_space:{0};", llvm::utohexstr(addr_space, true));
2997 if (info->is_thread_specific) {
2998 std::optional<lldb::tid_t> tid = process_addr.GetThreadID();
2999 if (!tid) {
3001 "address space \"%s\" is thread specific, but no thread was "
3002 "specified",
3003 info->name.c_str());
3004 return 0;
3005 }
3006 suffix += llvm::formatv("thread:{0};", llvm::utohexstr(*tid, true));
3007 }
3008 }
3009
3010 char packet[128];
3011 int packet_len =
3012 ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64 "%s",
3013 x_state != xPacketState::Unimplemented ? 'x' : 'm',
3014 (uint64_t)addr, (uint64_t)size, suffix.c_str());
3015 assert(packet_len + 1 < (int)sizeof(packet));
3016 UNUSED_IF_ASSERT_DISABLED(packet_len);
3017 StringExtractorGDBRemote response;
3018 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
3021 if (response.IsNormalResponse()) {
3022 error.Clear();
3023 if (x_state != xPacketState::Unimplemented) {
3024 // The lower level GDBRemoteCommunication packet receive layer has
3025 // already de-quoted any 0x7d character escaping that was present in
3026 // the packet
3027
3028 llvm::StringRef data_received = response.GetStringRef();
3029 if (x_state == xPacketState::Prefixed &&
3030 !data_received.consume_front("b")) {
3032 "unexpected response to GDB server memory read packet '{0}': "
3033 "'{1}'",
3034 packet, data_received);
3035 return 0;
3036 }
3037 // Don't write past the end of BUF if the remote debug server gave us
3038 // too much data for some reason.
3039 size_t memcpy_size = std::min(size, data_received.size());
3040 memcpy(buf, data_received.data(), memcpy_size);
3041 return memcpy_size;
3042 } else {
3043 return response.GetHexBytes(
3044 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
3045 }
3046 } else if (response.IsErrorResponse())
3048 "memory read failed for 0x%" PRIx64, addr);
3049 else if (response.IsUnsupportedResponse())
3051 "GDB server does not support reading memory");
3052 else
3054 "unexpected response to GDB server memory read packet '%s': '%s'",
3055 packet, response.GetStringRef().data());
3056 } else {
3057 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3058 packet);
3059 }
3060 return 0;
3061}
3062
3063/// Returns the number of ranges that is safe to request using MultiMemRead
3064/// while respecting max_packet_size.
3066 uint64_t max_packet_size,
3067 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
3068 // Each range is specified by two numbers (up to 16 ASCII characters) and one
3069 // comma.
3070 constexpr uint64_t range_overhead = 33;
3071 uint64_t current_size = 0;
3072 for (auto [idx, range] : llvm::enumerate(ranges)) {
3073 uint64_t potential_size = current_size + range.size + range_overhead;
3074 if (potential_size > max_packet_size) {
3075 if (idx == 0)
3077 "MultiMemRead input has a range (base = {0:x}, size = {1}) "
3078 "bigger than the maximum allowed by remote",
3079 range.base, range.size);
3080 return idx;
3081 }
3082 }
3083 return ranges.size();
3084}
3085
3086llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
3088 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
3089 llvm::MutableArrayRef<uint8_t> buffer) {
3090 if (!m_gdb_comm.GetMultiMemReadSupported())
3091 return Process::DoReadMemoryRanges(ranges, buffer);
3092
3093 const llvm::ArrayRef<Range<lldb::addr_t, size_t>> original_ranges = ranges;
3094 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory_regions;
3095
3096 while (!ranges.empty()) {
3097 uint64_t num_ranges =
3099 if (num_ranges == 0)
3100 return Process::DoReadMemoryRanges(original_ranges, buffer);
3101
3102 auto ranges_for_request = ranges.take_front(num_ranges);
3103 ranges = ranges.drop_front(num_ranges);
3104
3105 llvm::Expected<StringExtractorGDBRemote> response =
3106 SendMultiMemReadPacket(ranges_for_request);
3107 if (!response) {
3108 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(),
3109 "MultiMemRead error response: {0}");
3110 return Process::DoReadMemoryRanges(original_ranges, buffer);
3111 }
3112
3113 llvm::StringRef response_str = response->GetStringRef();
3114 const unsigned expected_num_ranges = ranges_for_request.size();
3115 if (llvm::Error error = ParseMultiMemReadPacket(
3116 response_str, buffer, expected_num_ranges, memory_regions)) {
3118 "MultiMemRead error parsing response: {0}");
3119 return Process::DoReadMemoryRanges(original_ranges, buffer);
3120 }
3121 }
3122 return memory_regions;
3123}
3124
3125llvm::Expected<StringExtractorGDBRemote>
3127 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
3128 std::string packet_str;
3129 llvm::raw_string_ostream stream(packet_str);
3130 stream << "MultiMemRead:ranges:";
3131
3132 auto range_to_stream = [&](auto range) {
3133 // the "-" marker omits the '0x' prefix.
3134 stream << llvm::formatv("{0:x-},{1:x-}", range.base, range.size);
3135 };
3136 llvm::interleave(ranges, stream, range_to_stream, ",");
3137 stream << ";";
3138
3139 StringExtractorGDBRemote response;
3141 m_gdb_comm.SendPacketAndWaitForResponse(packet_str.data(), response,
3144 return llvm::createStringErrorV("MultiMemRead failed to send packet: '{0}'",
3145 packet_str);
3146
3147 if (response.IsErrorResponse())
3148 return llvm::createStringErrorV("MultiMemRead failed: '{0}'",
3149 response.GetStringRef());
3150
3151 if (!response.IsNormalResponse())
3152 return llvm::createStringErrorV("MultiMemRead unexpected response: '{0}'",
3153 response.GetStringRef());
3154
3155 return response;
3156}
3157
3159 llvm::StringRef response_str, llvm::MutableArrayRef<uint8_t> buffer,
3160 unsigned expected_num_ranges,
3161 llvm::SmallVectorImpl<llvm::MutableArrayRef<uint8_t>> &memory_regions) {
3162 // The sizes and the data are separated by a `;`.
3163 auto [sizes_str, memory_data] = response_str.split(';');
3164 if (sizes_str.size() == response_str.size())
3165 return llvm::createStringErrorV(
3166 "MultiMemRead response missing field separator ';' in: '{0}'",
3167 response_str);
3168
3169 // Sizes are separated by a `,`.
3170 unsigned num_sizes = 0;
3171 for (llvm::StringRef size_str : llvm::split(sizes_str, ',')) {
3172 uint64_t read_size;
3173 if (size_str.getAsInteger(BASE_16, read_size))
3174 return llvm::createStringErrorV(
3175 "MultiMemRead response has invalid size string: {0}", size_str);
3176
3177 if (memory_data.size() < read_size)
3178 return llvm::createStringErrorV("MultiMemRead response did not have "
3179 "enough data, requested sizes: {0}",
3180 sizes_str);
3181
3182 if (read_size > buffer.size())
3183 return llvm::createStringErrorV(
3184 "MultiMemRead response size {0} exceeds remaining buffer {1}",
3185 read_size, buffer.size());
3186
3187 llvm::StringRef region_to_read = memory_data.take_front(read_size);
3188 memory_data = memory_data.drop_front(read_size);
3189
3190 llvm::MutableArrayRef<uint8_t> region_to_write =
3191 buffer.take_front(read_size);
3192 buffer = buffer.drop_front(read_size);
3193
3194 memcpy(region_to_write.data(), region_to_read.data(), read_size);
3195 memory_regions.push_back(region_to_write);
3196 ++num_sizes;
3197 }
3198
3199 if (num_sizes != expected_num_ranges)
3200 return llvm::createStringErrorV(
3201 "MultiMemRead response had {0} sizes, expected {1}", num_sizes,
3202 expected_num_ranges);
3203
3204 return llvm::Error::success();
3205}
3206
3208 return m_gdb_comm.GetMemoryTaggingSupported();
3209}
3210
3211llvm::Expected<std::vector<uint8_t>>
3213 int32_t type) {
3214 // By this point ReadMemoryTags has validated that tagging is enabled
3215 // for this target/process/address.
3216 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
3217 if (!buffer_sp) {
3218 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3219 "Error reading memory tags from remote");
3220 }
3221
3222 // Return the raw tag data
3223 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
3224 std::vector<uint8_t> got;
3225 got.reserve(tag_data.size());
3226 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
3227 return got;
3228}
3229
3231 int32_t type,
3232 const std::vector<uint8_t> &tags) {
3233 // By now WriteMemoryTags should have validated that tagging is enabled
3234 // for this target/process.
3235 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
3236}
3237
3239 std::vector<ObjectFile::LoadableData> entries) {
3240 Status error;
3241 // Sort the entries by address because some writes, like those to flash
3242 // memory, must happen in order of increasing address.
3243 llvm::stable_sort(entries, [](const ObjectFile::LoadableData a,
3244 const ObjectFile::LoadableData b) {
3245 return a.Dest < b.Dest;
3246 });
3247 m_allow_flash_writes = true;
3249 if (error.Success())
3250 error = FlashDone();
3251 else
3252 // Even though some of the writing failed, try to send a flash done if some
3253 // of the writing succeeded so the flash state is reset to normal, but
3254 // don't stomp on the error status that was set in the write failure since
3255 // that's the one we want to report back.
3256 FlashDone();
3257 m_allow_flash_writes = false;
3258 return error;
3259}
3260
3262 auto size = m_erased_flash_ranges.GetSize();
3263 for (size_t i = 0; i < size; ++i)
3264 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
3265 return true;
3266 return false;
3267}
3268
3270 Status status;
3271
3272 MemoryRegionInfo region;
3273 status = GetMemoryRegionInfo(addr, region);
3274 if (!status.Success())
3275 return status;
3276
3277 // The gdb spec doesn't say if erasures are allowed across multiple regions,
3278 // but we'll disallow it to be safe and to keep the logic simple by worring
3279 // about only one region's block size. DoMemoryWrite is this function's
3280 // primary user, and it can easily keep writes within a single memory region
3281 if (addr + size > region.GetRange().GetRangeEnd()) {
3282 status =
3283 Status::FromErrorString("Unable to erase flash in multiple regions");
3284 return status;
3285 }
3286
3287 uint64_t blocksize = region.GetBlocksize();
3288 if (blocksize == 0) {
3289 status =
3290 Status::FromErrorString("Unable to erase flash because blocksize is 0");
3291 return status;
3292 }
3293
3294 // Erasures can only be done on block boundary adresses, so round down addr
3295 // and round up size
3296 lldb::addr_t block_start_addr = addr - (addr % blocksize);
3297 size += (addr - block_start_addr);
3298 if ((size % blocksize) != 0)
3299 size += (blocksize - size % blocksize);
3300
3301 FlashRange range(block_start_addr, size);
3302
3303 if (HasErased(range))
3304 return status;
3305
3306 // We haven't erased the entire range, but we may have erased part of it.
3307 // (e.g., block A is already erased and range starts in A and ends in B). So,
3308 // adjust range if necessary to exclude already erased blocks.
3309 if (!m_erased_flash_ranges.IsEmpty()) {
3310 // Assuming that writes and erasures are done in increasing addr order,
3311 // because that is a requirement of the vFlashWrite command. Therefore, we
3312 // only need to look at the last range in the list for overlap.
3313 const auto &last_range = *m_erased_flash_ranges.Back();
3314 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
3315 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
3316 // overlap will be less than range.GetByteSize() or else HasErased()
3317 // would have been true
3318 range.SetByteSize(range.GetByteSize() - overlap);
3319 range.SetRangeBase(range.GetRangeBase() + overlap);
3320 }
3321 }
3322
3323 StreamString packet;
3324 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
3325 (uint64_t)range.GetByteSize());
3326
3327 StringExtractorGDBRemote response;
3328 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3331 if (response.IsOKResponse()) {
3332 m_erased_flash_ranges.Insert(range, true);
3333 } else {
3334 if (response.IsErrorResponse())
3336 "flash erase failed for 0x%" PRIx64, addr);
3337 else if (response.IsUnsupportedResponse())
3339 "GDB server does not support flashing");
3340 else
3342 "unexpected response to GDB server flash erase packet '%s': '%s'",
3343 packet.GetData(), response.GetStringRef().data());
3344 }
3345 } else {
3346 status = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3347 packet.GetData());
3348 }
3349 return status;
3350}
3351
3353 Status status;
3354 // If we haven't erased any blocks, then we must not have written anything
3355 // either, so there is no need to actually send a vFlashDone command
3356 if (m_erased_flash_ranges.IsEmpty())
3357 return status;
3358 StringExtractorGDBRemote response;
3359 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
3362 if (response.IsOKResponse()) {
3363 m_erased_flash_ranges.Clear();
3364 } else {
3365 if (response.IsErrorResponse())
3366 status = Status::FromErrorStringWithFormat("flash done failed");
3367 else if (response.IsUnsupportedResponse())
3369 "GDB server does not support flashing");
3370 else
3372 "unexpected response to GDB server flash done packet: '%s'",
3373 response.GetStringRef().data());
3374 }
3375 } else {
3376 status =
3377 Status::FromErrorStringWithFormat("failed to send flash done packet");
3378 }
3379 return status;
3380}
3381
3382size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
3383 size_t size, Status &error) {
3385 // M and m packets take 2 bytes for 1 byte of memory
3386 size_t max_memory_size = m_max_memory_size / 2;
3387 if (size > max_memory_size) {
3388 // Keep memory read sizes down to a sane limit. This function will be
3389 // called multiple times in order to complete the task by
3390 // lldb_private::Process so it is ok to do this.
3391 size = max_memory_size;
3392 }
3393
3394 StreamGDBRemote packet;
3395
3396 MemoryRegionInfo region;
3397 Status region_status = GetMemoryRegionInfo(addr, region);
3398
3399 bool is_flash = region_status.Success() && region.GetFlash() == eLazyBoolYes;
3400
3401 if (is_flash) {
3402 if (!m_allow_flash_writes) {
3403 error = Status::FromErrorString("Writing to flash memory is not allowed");
3404 return 0;
3405 }
3406 // Keep the write within a flash memory region
3407 if (addr + size > region.GetRange().GetRangeEnd())
3408 size = region.GetRange().GetRangeEnd() - addr;
3409 // Flash memory must be erased before it can be written
3410 error = FlashErase(addr, size);
3411 if (!error.Success())
3412 return 0;
3413 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
3414 packet.PutEscapedBytes(buf, size);
3415 } else {
3416 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
3417 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
3419 }
3420 StringExtractorGDBRemote response;
3421 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3424 if (response.IsOKResponse()) {
3425 error.Clear();
3426 return size;
3427 } else if (response.IsErrorResponse())
3429 "memory write failed for 0x%" PRIx64, addr);
3430 else if (response.IsUnsupportedResponse())
3432 "GDB server does not support writing memory");
3433 else
3435 "unexpected response to GDB server memory write packet '%s': '%s'",
3436 packet.GetData(), response.GetStringRef().data());
3437 } else {
3438 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3439 packet.GetData());
3440 }
3441 return 0;
3442}
3443
3445 // Probe the _M packet. Falling back to mmap() only needs its symbol.
3446 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolCalculate) {
3447 addr_t addr = m_gdb_comm.AllocateMemory(8, ePermissionsReadable |
3448 ePermissionsWritable |
3449 ePermissionsExecutable);
3450 if (addr != LLDB_INVALID_ADDRESS)
3451 m_gdb_comm.DeallocateMemory(addr);
3452 }
3453 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3454 return true;
3455
3457 options.include_symbols = true;
3458 options.include_inlines = false;
3459 SymbolContextList sc_list;
3461 ConstString("mmap"), eFunctionNameTypeFull, options, sc_list);
3462 return !sc_list.IsEmpty();
3463}
3464
3466 uint32_t permissions,
3467 Status &error) {
3469 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3470
3471 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3472 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3473 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3474 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3475 return allocated_addr;
3476 }
3477
3478 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3479 // Call mmap() to create memory in the inferior..
3480 unsigned prot = 0;
3481 if (permissions & lldb::ePermissionsReadable)
3482 prot |= eMmapProtRead;
3483 if (permissions & lldb::ePermissionsWritable)
3484 prot |= eMmapProtWrite;
3485 if (permissions & lldb::ePermissionsExecutable)
3486 prot |= eMmapProtExec;
3487
3488 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3490 m_addr_to_mmap_size[allocated_addr] = size;
3491 else {
3492 allocated_addr = LLDB_INVALID_ADDRESS;
3493 LLDB_LOGF(log,
3494 "ProcessGDBRemote::%s no direct stub support for memory "
3495 "allocation, and InferiorCallMmap also failed - is stub "
3496 "missing register context save/restore capability?",
3497 __FUNCTION__);
3498 }
3499 }
3500
3501 if (allocated_addr == LLDB_INVALID_ADDRESS)
3503 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3504 (uint64_t)size, GetPermissionsAsCString(permissions));
3505 else
3506 error.Clear();
3507 return allocated_addr;
3508}
3509
3511 MemoryRegionInfo &region_info) {
3512
3513 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
3514 return error;
3515}
3516
3518 return m_gdb_comm.GetWatchpointSlotCount();
3519}
3520
3522 return m_gdb_comm.GetWatchpointReportedAfter();
3523}
3524
3526 Status error;
3527 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3528
3529 switch (supported) {
3530 case eLazyBoolCalculate:
3531 // We should never be deallocating memory without allocating memory first
3532 // so we should never get eLazyBoolCalculate
3534 "tried to deallocate memory without ever allocating memory");
3535 break;
3536
3537 case eLazyBoolYes:
3538 if (!m_gdb_comm.DeallocateMemory(addr))
3540 "unable to deallocate memory at 0x%" PRIx64, addr);
3541 break;
3542
3543 case eLazyBoolNo:
3544 // Call munmap() to deallocate memory in the inferior..
3545 {
3546 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3547 if (pos != m_addr_to_mmap_size.end() &&
3548 InferiorCallMunmap(this, addr, pos->second))
3549 m_addr_to_mmap_size.erase(pos);
3550 else
3552 "unable to deallocate memory at 0x%" PRIx64, addr);
3553 }
3554 break;
3555 }
3556
3557 return error;
3558}
3559
3560// Process STDIO
3561size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3562 Status &error) {
3563 if (m_stdio_communication.IsConnected()) {
3564 ConnectionStatus status;
3565 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
3566 } else if (m_stdin_forward) {
3567 m_gdb_comm.SendStdinNotification(src, src_len, GetInterruptTimeout());
3568 }
3569 return 0;
3570}
3571
3572/// Enable a single breakpoint site by trying Z0 (software), then Z1
3573/// (hardware), then manual memory write as a last resort.
3576 const addr_t addr = bp_site.GetLoadAddress();
3577 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3578 auto &gdb_comm = GetGDBRemote();
3579
3580 // SupportsGDBStoppointPacket always returns true unless a previously sent
3581 // packet failed. As such, query the function before AND after sending the
3582 // packet.
3583 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3584 !bp_site.HardwareRequired()) {
3585 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3586 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
3587 if (error_no == 0) {
3588 SetBreakpointSiteEnabled(bp_site);
3590 return llvm::Error::success();
3591 }
3592 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3593 if (error_no != UINT8_MAX)
3594 return llvm::createStringErrorV(
3595 "error sending the breakpoint request: {0}", error_no);
3596 return llvm::createStringError("error sending the breakpoint request");
3597 }
3598 LLDB_LOG(log, "Software breakpoints are unsupported");
3599 }
3600
3601 // Like above, this is also queried twice.
3602 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3603 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3604 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3605 if (error_no == 0) {
3606 SetBreakpointSiteEnabled(bp_site);
3608 return llvm::Error::success();
3609 }
3610 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3611 if (error_no != UINT8_MAX)
3612 return llvm::createStringErrorV(
3613 "error sending the hardware breakpoint request: {0} "
3614 "(hardware breakpoint resources might be exhausted or unavailable)",
3615 error_no);
3616 return llvm::createStringError(
3617 "error sending the hardware breakpoint request "
3618 "(hardware breakpoint resources might be exhausted or unavailable)");
3619 }
3620 LLDB_LOG(log, "Hardware breakpoints are unsupported");
3621 }
3622
3623 if (bp_site.HardwareRequired())
3624 return llvm::createStringError("hardware breakpoints are not supported");
3625
3626 return EnableSoftwareBreakpoint(&bp_site).takeError();
3627}
3628
3629/// Disable a single breakpoint site directly by sending the appropriate
3630/// z packet or restoring the original instruction.
3632 const addr_t addr = bp_site.GetLoadAddress();
3633 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3634 auto &gdb_comm = GetGDBRemote();
3635
3636 switch (bp_site.GetType()) {
3639 if (error.Fail())
3640 return error.takeError();
3641 break;
3642 }
3644 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr,
3645 bp_op_size, GetInterruptTimeout()))
3646 return llvm::createStringError("unknown error");
3647 break;
3649 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr,
3650 bp_op_size, GetInterruptTimeout()))
3651 return llvm::createStringError("unknown error");
3652 break;
3653 }
3654 SetBreakpointSiteEnabled(bp_site, false);
3655 return llvm::Error::success();
3656}
3657
3659 assert(bp_site != nullptr);
3660
3661 // Get logging info
3663 user_id_t site_id = bp_site->GetID();
3664
3665 // Get the breakpoint address
3666 const addr_t addr = bp_site->GetLoadAddress();
3667
3668 // Log that a breakpoint was requested
3669 LLDB_LOGF(log,
3670 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3671 ") address = 0x%" PRIx64,
3672 site_id, (uint64_t)addr);
3673
3674 // Breakpoint already exists and is enabled
3675 if (IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3676 LLDB_LOGF(log,
3677 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3678 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3679 site_id, (uint64_t)addr);
3680 return Status();
3681 }
3682
3683 return Status::FromError(DoEnableBreakpointSite(*bp_site));
3684}
3685
3687 assert(bp_site != nullptr);
3688 addr_t addr = bp_site->GetLoadAddress();
3689 user_id_t site_id = bp_site->GetID();
3691 LLDB_LOGF(log,
3692 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3693 ") addr = 0x%8.8" PRIx64,
3694 site_id, (uint64_t)addr);
3695
3696 if (!IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3697 LLDB_LOGF(log,
3698 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3699 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3700 site_id, (uint64_t)addr);
3701 return Status();
3702 }
3703
3705}
3706
3707// Pre-requisite: wp != NULL.
3708static GDBStoppointType
3710 assert(wp_res_sp);
3711 bool read = wp_res_sp->WatchpointResourceRead();
3712 bool write = wp_res_sp->WatchpointResourceWrite();
3713
3714 assert((read || write) &&
3715 "WatchpointResource type is neither read nor write");
3716 if (read && write)
3717 return eWatchpointReadWrite;
3718 else if (read)
3719 return eWatchpointRead;
3720 else
3721 return eWatchpointWrite;
3722}
3723
3725 Status error;
3726 if (!wp_sp) {
3727 error = Status::FromErrorString("No watchpoint specified");
3728 return error;
3729 }
3730 user_id_t watchID = wp_sp->GetID();
3731 addr_t addr = wp_sp->GetLoadAddress();
3733 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3734 watchID);
3735 if (wp_sp->IsEnabled()) {
3736 LLDB_LOGF(log,
3737 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3738 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3739 watchID, (uint64_t)addr);
3740 return error;
3741 }
3742
3743 bool read = wp_sp->WatchpointRead();
3744 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3745 size_t size = wp_sp->GetByteSize();
3746
3747 ArchSpec target_arch = GetTarget().GetArchitecture();
3748 WatchpointHardwareFeature supported_features =
3749 m_gdb_comm.GetSupportedWatchpointTypes();
3750
3751 std::vector<WatchpointResourceSP> resources =
3753 addr, size, read, write, supported_features, target_arch);
3754
3755 // LWP_TODO: Now that we know the WP Resources needed to implement this
3756 // Watchpoint, we need to look at currently allocated Resources in the
3757 // Process and if they match, or are within the same memory granule, or
3758 // overlapping memory ranges, then we need to combine them. e.g. one
3759 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1
3760 // byte at 0x1003, they must use the same hardware watchpoint register
3761 // (Resource) to watch them.
3762
3763 // This may mean that an existing resource changes its type (read to
3764 // read+write) or address range it is watching, in which case the old
3765 // watchpoint needs to be disabled and the new Resource addr/size/type
3766 // watchpoint enabled.
3767
3768 // If we modify a shared Resource to accomodate this newly added Watchpoint,
3769 // and we are unable to set all of the Resources for it in the inferior, we
3770 // will return an error for this Watchpoint and the shared Resource should
3771 // be restored. e.g. this Watchpoint requires three Resources, one which
3772 // is shared with another Watchpoint. We extend the shared Resouce to
3773 // handle both Watchpoints and we try to set two new ones. But if we don't
3774 // have sufficient watchpoint register for all 3, we need to show an error
3775 // for creating this Watchpoint and we should reset the shared Resource to
3776 // its original configuration because it is no longer shared.
3777
3778 bool set_all_resources = true;
3779 std::vector<WatchpointResourceSP> succesfully_set_resources;
3780 for (const auto &wp_res_sp : resources) {
3781 addr_t addr = wp_res_sp->GetLoadAddress();
3782 size_t size = wp_res_sp->GetByteSize();
3783 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3784 if (!m_gdb_comm.SupportsGDBStoppointPacket(type) ||
3785 m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size,
3787 set_all_resources = false;
3788 break;
3789 } else {
3790 succesfully_set_resources.push_back(wp_res_sp);
3791 }
3792 }
3793 if (set_all_resources) {
3794 wp_sp->SetEnabled(true, notify);
3795 for (const auto &wp_res_sp : resources) {
3796 // LWP_TODO: If we expanded/reused an existing Resource,
3797 // it's already in the WatchpointResourceList.
3798 wp_res_sp->AddConstituent(wp_sp);
3799 m_watchpoint_resource_list.Add(wp_res_sp);
3800 }
3801 return error;
3802 } else {
3803 // We failed to allocate one of the resources. Unset all
3804 // of the new resources we did successfully set in the
3805 // process.
3806 for (const auto &wp_res_sp : succesfully_set_resources) {
3807 addr_t addr = wp_res_sp->GetLoadAddress();
3808 size_t size = wp_res_sp->GetByteSize();
3809 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3810 m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3812 }
3814 "Setting one of the watchpoint resources failed");
3815 }
3816 return error;
3817}
3818
3820 Status error;
3821 if (!wp_sp) {
3822 error = Status::FromErrorString("Watchpoint argument was NULL.");
3823 return error;
3824 }
3825
3826 user_id_t watchID = wp_sp->GetID();
3827
3829
3830 addr_t addr = wp_sp->GetLoadAddress();
3831
3832 LLDB_LOGF(log,
3833 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3834 ") addr = 0x%8.8" PRIx64,
3835 watchID, (uint64_t)addr);
3836
3837 if (!wp_sp->IsEnabled()) {
3838 LLDB_LOGF(log,
3839 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3840 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3841 watchID, (uint64_t)addr);
3842 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3843 // attempt might come from the user-supplied actions, we'll route it in
3844 // order for the watchpoint object to intelligently process this action.
3845 wp_sp->SetEnabled(false, notify);
3846 return error;
3847 }
3848
3849 if (wp_sp->IsHardware()) {
3850 bool disabled_all = true;
3851
3852 std::vector<WatchpointResourceSP> unused_resources;
3853 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
3854 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3855 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3856 addr_t addr = wp_res_sp->GetLoadAddress();
3857 size_t size = wp_res_sp->GetByteSize();
3858 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3860 disabled_all = false;
3861 } else {
3862 wp_res_sp->RemoveConstituent(wp_sp);
3863 if (wp_res_sp->GetNumberOfConstituents() == 0)
3864 unused_resources.push_back(wp_res_sp);
3865 }
3866 }
3867 }
3868 for (auto &wp_res_sp : unused_resources)
3869 m_watchpoint_resource_list.Remove(wp_res_sp->GetID());
3870
3871 wp_sp->SetEnabled(false, notify);
3872 if (!disabled_all)
3874 "Failure disabling one of the watchpoint locations");
3875 }
3876 return error;
3877}
3878
3880 m_thread_list_real.Clear();
3881 m_thread_list.Clear();
3882}
3883
3885 Status error;
3886 Log *log = GetLog(GDBRLog::Process);
3887 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3888
3889 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3890 error =
3891 Status::FromErrorStringWithFormat("failed to send signal %i", signo);
3892 return error;
3893}
3894
3895Status
3897 // Make sure we aren't already connected?
3898 if (m_gdb_comm.IsConnected())
3899 return Status();
3900
3901 PlatformSP platform_sp(GetTarget().GetPlatform());
3902 if (platform_sp && !platform_sp->IsHost())
3903 return Status::FromErrorString("Lost debug server connection");
3904
3905 auto error = LaunchAndConnectToDebugserver(process_info);
3906 if (error.Fail()) {
3907 const char *error_string = error.AsCString();
3908 if (error_string == nullptr)
3909 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3910 }
3911 return error;
3912}
3913
3915 Log *log = GetLog(GDBRLog::Process);
3916 // If we locate debugserver, keep that located version around
3917 static FileSpec g_debugserver_file_spec;
3918 FileSpec debugserver_file_spec;
3919
3920 Environment host_env = Host::GetEnvironment();
3921
3922 // Always check to see if we have an environment override for the path to the
3923 // debugserver to use and use it if we do.
3924 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
3925 if (!env_debugserver_path.empty()) {
3926 debugserver_file_spec.SetFile(env_debugserver_path,
3927 FileSpec::Style::native);
3928 LLDB_LOG(log, "gdb-remote stub exe path set from environment variable: {0}",
3929 env_debugserver_path);
3930 } else
3931 debugserver_file_spec = g_debugserver_file_spec;
3932 if (FileSystem::Instance().Exists(debugserver_file_spec))
3933 return debugserver_file_spec;
3934
3935 // The debugserver binary is in the LLDB.framework/Resources directory.
3936 debugserver_file_spec = HostInfo::GetSupportExeDir();
3937 if (debugserver_file_spec) {
3938 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
3939 if (FileSystem::Instance().Exists(debugserver_file_spec)) {
3940 LLDB_LOG(log, "found gdb-remote stub exe '{0}'", debugserver_file_spec);
3941
3942 g_debugserver_file_spec = debugserver_file_spec;
3943 } else {
3944 debugserver_file_spec = platform.LocateExecutable(DEBUGSERVER_BASENAME);
3945 if (!debugserver_file_spec) {
3946 // Platform::LocateExecutable() wouldn't return a path if it doesn't
3947 // exist
3948 LLDB_LOG(log, "could not find gdb-remote stub exe '{0}'",
3949 debugserver_file_spec);
3950 }
3951 // Don't cache the platform specific GDB server binary as it could
3952 // change from platform to platform
3953 g_debugserver_file_spec.Clear();
3954 }
3955 }
3956 return debugserver_file_spec;
3957}
3958
3960 const ProcessInfo &process_info) {
3961 using namespace std::placeholders; // For _1, _2, etc.
3962
3964 return Status();
3965
3966 ProcessLaunchInfo debugserver_launch_info;
3967 // Make debugserver run in its own session so signals generated by special
3968 // terminal key sequences (^C) don't affect debugserver.
3969 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3970
3971 const std::weak_ptr<ProcessGDBRemote> this_wp =
3972 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3973 debugserver_launch_info.SetMonitorProcessCallback(
3974 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3975 debugserver_launch_info.SetUserID(process_info.GetUserID());
3976
3977 FileSpec debugserver_path = GetDebugserverPath(*GetTarget().GetPlatform());
3978
3979#if defined(__APPLE__)
3980 // On macOS 11, we need to support x86_64 applications translated to
3981 // arm64. We check whether a binary is translated and spawn the correct
3982 // debugserver accordingly.
3983 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID,
3984 static_cast<int>(process_info.GetProcessID())};
3985 struct kinfo_proc processInfo;
3986 size_t bufsize = sizeof(processInfo);
3987 if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize,
3988 NULL, 0) == 0 &&
3989 bufsize > 0) {
3990 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3991 debugserver_path = FileSpec("/Library/Apple/usr/libexec/oah/debugserver");
3992 }
3993 }
3994#endif
3995
3996 if (!FileSystem::Instance().Exists(debugserver_path))
3997 return Status::FromErrorString("could not find '" DEBUGSERVER_BASENAME
3998 "'. Please ensure it is properly installed "
3999 "and available in your PATH");
4000
4001 debugserver_launch_info.SetExecutableFile(debugserver_path,
4002 /*add_exe_file_as_first_arg=*/true);
4003
4004 llvm::Expected<Socket::Pair> socket_pair = Socket::CreatePair();
4005 if (!socket_pair)
4006 return Status::FromError(socket_pair.takeError());
4007
4008 Status error;
4009 SharedSocket shared_socket(socket_pair->first.get(), error);
4010 if (error.Fail())
4011 return error;
4012
4013 error = m_gdb_comm.StartDebugserverProcess(shared_socket.GetSendableFD(),
4014 debugserver_launch_info, nullptr);
4015
4016 if (error.Fail()) {
4017 Log *log = GetLog(GDBRLog::Process);
4018
4019 LLDB_LOGF(log, "failed to start debugserver process: %s",
4020 error.AsCString());
4021 return error;
4022 }
4023
4024 m_debugserver_pid = debugserver_launch_info.GetProcessID();
4025 shared_socket.CompleteSending(m_debugserver_pid);
4026
4027 // Our process spawned correctly, we can now set our connection to use
4028 // our end of the socket pair
4029 m_gdb_comm.SetConnection(std::make_unique<ConnectionFileDescriptor>(
4030 std::move(socket_pair->second)));
4032
4033 if (m_gdb_comm.IsConnected()) {
4034 // Finish the connection process by doing the handshake without
4035 // connecting (send NULL URL)
4037 } else {
4038 error = Status::FromErrorString("connection failed");
4039 }
4040 return error;
4041}
4042
4044 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
4045 int signo, // Zero for no signal
4046 int exit_status // Exit value of process if signal is zero
4047) {
4048 // "debugserver_pid" argument passed in is the process ID for debugserver
4049 // that we are tracking...
4050 Log *log = GetLog(GDBRLog::Process);
4051
4052 LLDB_LOGF(log,
4053 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
4054 ", signo=%i (0x%x), exit_status=%i)",
4055 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
4056
4057 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
4058 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
4059 static_cast<void *>(process_sp.get()));
4060 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
4061 return;
4062
4063 // Sleep for a half a second to make sure our inferior process has time to
4064 // set its exit status before we set it incorrectly when both the debugserver
4065 // and the inferior process shut down.
4066 std::this_thread::sleep_for(std::chrono::milliseconds(500));
4067
4068 // If our process hasn't yet exited, debugserver might have died. If the
4069 // process did exit, then we are reaping it.
4070 const StateType state = process_sp->GetState();
4071
4072 if (state != eStateInvalid && state != eStateUnloaded &&
4073 state != eStateExited && state != eStateDetached) {
4074 StreamString stream;
4075 if (signo == 0)
4076 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",
4077 exit_status);
4078 else {
4079 llvm::StringRef signal_name =
4080 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
4081 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";
4082 if (!signal_name.empty())
4083 stream.Format(format_str, signal_name);
4084 else
4085 stream.Format(format_str, signo);
4086 }
4087 process_sp->SetExitStatus(-1, stream.GetString());
4088 }
4089 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
4090 // longer has a debugserver instance
4091 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
4092}
4093
4101
4107
4110 debugger, PluginProperties::GetSettingName())) {
4111 const bool is_global_setting = true;
4114 "Properties for the gdb-remote process plug-in.", is_global_setting);
4115 }
4116}
4117
4119 Log *log = GetLog(GDBRLog::Process);
4120
4121 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4122
4123 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4124 if (!m_async_thread.IsJoinable()) {
4125 // Create a thread that watches our internal state and controls which
4126 // events make it to clients (into the DCProcess event queue).
4127
4128 llvm::Expected<HostThread> async_thread =
4129 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
4131 });
4132 if (!async_thread) {
4133 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
4134 "failed to launch host thread: {0}");
4135 return false;
4136 }
4137 m_async_thread = *async_thread;
4138 } else
4139 LLDB_LOGF(log,
4140 "ProcessGDBRemote::%s () - Called when Async thread was "
4141 "already running.",
4142 __FUNCTION__);
4143
4144 return m_async_thread.IsJoinable();
4145}
4146
4148 Log *log = GetLog(GDBRLog::Process);
4149
4150 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4151
4152 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4153 if (m_async_thread.IsJoinable()) {
4155
4156 // This will shut down the async thread.
4157 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
4158
4159 // Stop the stdio thread
4160 m_async_thread.Join(nullptr);
4161 m_async_thread.Reset();
4162 } else
4163 LLDB_LOGF(
4164 log,
4165 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
4166 __FUNCTION__);
4167}
4168
4170 Log *log = GetLog(GDBRLog::Process);
4171 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
4172 __FUNCTION__, GetID());
4173
4174 EventSP event_sp;
4175
4176 // We need to ignore any packets that come in after we have
4177 // have decided the process has exited. There are some
4178 // situations, for instance when we try to interrupt a running
4179 // process and the interrupt fails, where another packet might
4180 // get delivered after we've decided to give up on the process.
4181 // But once we've decided we are done with the process we will
4182 // not be in a state to do anything useful with new packets.
4183 // So it is safer to simply ignore any remaining packets by
4184 // explicitly checking for eStateExited before reentering the
4185 // fetch loop.
4186
4187 bool done = false;
4188 while (!done && GetPrivateState() != eStateExited) {
4189 LLDB_LOGF(log,
4190 "ProcessGDBRemote::%s(pid = %" PRIu64
4191 ") listener.WaitForEvent (NULL, event_sp)...",
4192 __FUNCTION__, GetID());
4193
4194 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
4195 const uint32_t event_type = event_sp->GetType();
4196 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
4197 LLDB_LOGF(log,
4198 "ProcessGDBRemote::%s(pid = %" PRIu64
4199 ") Got an event of type: %d...",
4200 __FUNCTION__, GetID(), event_type);
4201
4202 switch (event_type) {
4204 const EventDataBytes *continue_packet =
4206
4207 if (continue_packet) {
4208 const char *continue_cstr =
4209 (const char *)continue_packet->GetBytes();
4210 const size_t continue_cstr_len = continue_packet->GetByteSize();
4211 LLDB_LOGF(log,
4212 "ProcessGDBRemote::%s(pid = %" PRIu64
4213 ") got eBroadcastBitAsyncContinue: %s",
4214 __FUNCTION__, GetID(), continue_cstr);
4215
4216 if (::strstr(continue_cstr, "vAttach") == nullptr)
4218 StringExtractorGDBRemote response;
4219
4220 StateType stop_state =
4222 *this, *GetUnixSignals(),
4223 llvm::StringRef(continue_cstr, continue_cstr_len),
4224 GetInterruptTimeout(), response);
4225
4226 // We need to immediately clear the thread ID list so we are sure
4227 // to get a valid list of threads. The thread ID list might be
4228 // contained within the "response", or the stop reply packet that
4229 // caused the stop. So clear it now before we give the stop reply
4230 // packet to the process using the
4231 // SetLastStopPacket()...
4233
4234 switch (stop_state) {
4235 case eStateStopped:
4236 case eStateCrashed:
4237 case eStateSuspended:
4238 SetLastStopPacket(response);
4239 SetPrivateState(stop_state);
4240 break;
4241
4242 case eStateExited: {
4243 SetLastStopPacket(response);
4245 response.SetFilePos(1);
4246
4247 int exit_status = response.GetHexU8();
4248 std::string desc_string;
4249 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
4250 llvm::StringRef desc_str;
4251 llvm::StringRef desc_token;
4252 while (response.GetNameColonValue(desc_token, desc_str)) {
4253 if (desc_token != "description")
4254 continue;
4255 StringExtractor extractor(desc_str);
4256 extractor.GetHexByteString(desc_string);
4257 }
4258 }
4259 SetExitStatus(exit_status, desc_string.c_str());
4260 done = true;
4261 break;
4262 }
4263 case eStateInvalid: {
4264 // Check to see if we were trying to attach and if we got back
4265 // the "E87" error code from debugserver -- this indicates that
4266 // the process is not debuggable. Return a slightly more
4267 // helpful error message about why the attach failed.
4268 if (::strstr(continue_cstr, "vAttach") != nullptr &&
4269 response.GetError() == 0x87) {
4270 SetExitStatus(-1, "cannot attach to process due to "
4271 "System Integrity Protection");
4272 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
4273 response.GetStatus().Fail()) {
4274 SetExitStatus(-1, response.GetStatus().AsCString());
4275 } else {
4276 SetExitStatus(-1, "lost connection");
4277 }
4278 done = true;
4279 break;
4280 }
4281
4282 default:
4283 SetPrivateState(stop_state);
4284 break;
4285 } // switch(stop_state)
4286 } // if (continue_packet)
4287 } // case eBroadcastBitAsyncContinue
4288 break;
4289
4291 LLDB_LOGF(log,
4292 "ProcessGDBRemote::%s(pid = %" PRIu64
4293 ") got eBroadcastBitAsyncThreadShouldExit...",
4294 __FUNCTION__, GetID());
4295 done = true;
4296 break;
4297
4298 default:
4299 LLDB_LOGF(log,
4300 "ProcessGDBRemote::%s(pid = %" PRIu64
4301 ") got unknown event 0x%8.8x",
4302 __FUNCTION__, GetID(), event_type);
4303 done = true;
4304 break;
4305 }
4306 }
4307 } else {
4308 LLDB_LOGF(log,
4309 "ProcessGDBRemote::%s(pid = %" PRIu64
4310 ") listener.WaitForEvent (NULL, event_sp) => false",
4311 __FUNCTION__, GetID());
4312 done = true;
4313 }
4314 }
4315
4316 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
4317 __FUNCTION__, GetID());
4318
4319 return {};
4320}
4321
4322// uint32_t
4323// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
4324// &matches, std::vector<lldb::pid_t> &pids)
4325//{
4326// // If we are planning to launch the debugserver remotely, then we need to
4327// fire up a debugserver
4328// // process and ask it for the list of processes. But if we are local, we
4329// can let the Host do it.
4330// if (m_local_debugserver)
4331// {
4332// return Host::ListProcessesMatchingName (name, matches, pids);
4333// }
4334// else
4335// {
4336// // FIXME: Implement talking to the remote debugserver.
4337// return 0;
4338// }
4339//
4340//}
4341//
4343 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4344 lldb::user_id_t break_loc_id) {
4345 // I don't think I have to do anything here, just make sure I notice the new
4346 // thread when it starts to
4347 // run so I can stop it if that's what I want to do.
4348 Log *log = GetLog(LLDBLog::Step);
4349 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
4350 return false;
4351}
4352
4353namespace {
4354/// Baton that carries the breakpoint hit arguments to the accelerator plugin
4355/// breakpoint callback.
4356class AcceleratorBreakpointCallbackBaton
4357 : public TypedBaton<AcceleratorBreakpointHitArgs> {
4358public:
4359 explicit AcceleratorBreakpointCallbackBaton(
4360 std::unique_ptr<AcceleratorBreakpointHitArgs> data)
4361 : TypedBaton(std::move(data)) {}
4362};
4363} // namespace
4364
4365llvm::Error
4367 Log *log = GetLog(GDBRLog::Process);
4368
4369 // The same set of actions can be delivered to the client more than once: a
4370 // plugin may keep reporting the same actions (with the same identifier) on
4371 // subsequent native stops until its state advances. The identifier uniquely
4372 // names a set of actions for a plugin, so skip any set we have already
4373 // processed to avoid re-running its side effects (e.g. setting the same
4374 // breakpoints again).
4375 auto it = m_processed_accelerator_actions.find(actions.plugin_name);
4376 if (it != m_processed_accelerator_actions.end() &&
4377 it->second == actions.identifier) {
4378 LLDB_LOG(log,
4379 "ProcessGDBRemote::HandleAcceleratorActions skipping already "
4380 "processed actions for plugin '{0}' with identifier {1}",
4381 actions.plugin_name, actions.identifier);
4382 return llvm::Error::success();
4383 }
4385
4386 // Handle each kind of action. More action kinds will be handled here in the
4387 // future, so only return early on error; otherwise fall through so the next
4388 // kind of action still gets a chance to run.
4389 if (!actions.breakpoints.empty()) {
4390 if (llvm::Error error = HandleAcceleratorBreakpoints(actions))
4391 return error;
4392 }
4393
4394 if (actions.connect_info) {
4395 if (llvm::Error error = HandleAcceleratorConnection(actions))
4396 return error;
4397 }
4398
4399 return llvm::Error::success();
4400}
4401
4403 const AcceleratorActions &actions) {
4404 const AcceleratorConnectionInfo &connect_info = *actions.connect_info;
4405 Debugger &debugger = GetTarget().GetDebugger();
4406
4407 OptionGroupPlatform platform_options(/*include_platform_option=*/false);
4408 platform_options.SetPlatformName(connect_info.platform_name.c_str());
4409 std::string exe_path = connect_info.exe_path.value_or("");
4410 TargetSP accelerator_target_sp;
4412 debugger, exe_path, connect_info.triple, eLoadDependentsNo,
4413 &platform_options, accelerator_target_sp);
4414 if (error.Fail())
4415 return error.takeError();
4416 if (!accelerator_target_sp)
4417 return llvm::createStringError("failed to create accelerator target");
4418
4419 llvm::scope_exit delete_accelerator_target([&] {
4420 debugger.GetTargetList().DeleteTarget(accelerator_target_sp);
4421 accelerator_target_sp->Destroy();
4422 });
4423
4424 PlatformSP platform_sp = accelerator_target_sp->GetPlatform();
4425 if (!platform_sp)
4426 return llvm::createStringErrorV(
4427 "no platform '{0}' compatible with triple '{1}' for the accelerator "
4428 "target",
4429 connect_info.platform_name, connect_info.triple);
4430
4431 TargetSP native_target_sp = GetTarget().shared_from_this();
4432 std::shared_ptr<TargetGroupCPUAndAccelerators> group_sp =
4433 native_target_sp
4434 ->GetFirstTargetGroupOfType<TargetGroupCPUAndAccelerators>();
4435
4436 bool created_group = !group_sp;
4437 if (created_group) {
4438 group_sp = debugger.GetTargetGroupList()
4440 "CPU and accelerator targets");
4441 }
4442
4443 llvm::scope_exit restore_target_group([&] {
4444 group_sp->RemoveTarget(accelerator_target_sp);
4445 if (created_group) {
4446 group_sp->RemoveTarget(native_target_sp);
4447 debugger.GetTargetGroupList().DeleteTargetGroup(group_sp);
4448 }
4449 });
4450
4451 if (llvm::Error membership_error =
4452 group_sp->AddTarget(native_target_sp, TargetGroup::Role::CPU))
4453 return membership_error;
4454 if (llvm::Error membership_error = group_sp->AddTarget(
4455 accelerator_target_sp, TargetGroup::Role::Accelerator))
4456 return membership_error;
4457
4458 ProcessSP process_sp =
4459 connect_info.synchronous
4460 ? platform_sp->ConnectProcessSynchronous(
4461 connect_info.connect_url, GetPluginNameStatic(), debugger,
4462 *debugger.GetAsyncOutputStream(), accelerator_target_sp.get(),
4463 error)
4464 : platform_sp->ConnectProcess(connect_info.connect_url,
4465 GetPluginNameStatic(), debugger,
4466 accelerator_target_sp.get(), error);
4467 if (error.Fail())
4468 return error.takeError();
4469 if (!process_sp)
4470 return llvm::createStringError("failed to connect to the accelerator");
4471
4472 restore_target_group.release();
4473 delete_accelerator_target.release();
4474 accelerator_target_sp->SetTargetSessionName(actions.session_name);
4475
4476 // Broadcast the new-target event so API clients can detect it.
4477 auto event_sp = std::make_shared<Event>(
4479 new Target::TargetEventData(GetTarget().shared_from_this(),
4480 accelerator_target_sp));
4481 GetTarget().BroadcastEvent(event_sp);
4482 return llvm::Error::success();
4483}
4484
4486 const AcceleratorActions &actions) {
4487 Target &target = GetTarget();
4488 llvm::Error error = llvm::Error::success();
4489 for (const AcceleratorBreakpointInfo &bp : actions.breakpoints) {
4490 // Carry data with the breakpoint so the callback can notify the plugin
4491 // when the breakpoint is hit.
4492 auto args_up = std::make_unique<AcceleratorBreakpointHitArgs>();
4493 args_up->plugin_name = actions.plugin_name;
4494 args_up->breakpoint = bp;
4495
4496 // Each breakpoint must specify exactly one of by_name or by_address. Bad
4497 // breakpoints are collected as errors but don't stop the remaining ones
4498 // from being set.
4499 BreakpointSP bp_sp;
4500 if (bp.by_name && bp.by_address) {
4501 error = llvm::joinErrors(
4502 std::move(error),
4503 llvm::createStringErrorV(
4504 "accelerator breakpoint {0} specifies both a by_name and a "
4505 "by_address specification",
4506 bp.identifier));
4507 continue;
4508 } else if (bp.by_name) {
4509 FileSpecList bp_modules;
4510 if (bp.by_name->shlib && !bp.by_name->shlib->empty())
4511 bp_modules.Append(FileSpec(*bp.by_name->shlib));
4512 bp_sp = target.CreateBreakpoint(
4513 bp_modules.GetSize() ? &bp_modules : nullptr, // Containing modules.
4514 nullptr, // Containing source.
4515 bp.by_name->function_name.c_str(), // Function name.
4516 eFunctionNameTypeFull, // Function name type.
4517 eLanguageTypeUnknown, // Language type.
4518 0, // Byte offset.
4519 false, // Offset is insn count.
4520 eLazyBoolNo, // Skip prologue.
4521 true, // Internal breakpoint.
4522 false); // Request hardware.
4523 } else if (bp.by_address) {
4524 bp_sp = target.CreateBreakpoint(bp.by_address->load_address,
4525 /*internal=*/true,
4526 /*request_hardware=*/false);
4527 } else {
4528 error = llvm::joinErrors(
4529 std::move(error),
4530 llvm::createStringErrorV(
4531 "accelerator breakpoint {0} has neither a by_name nor a "
4532 "by_address specification",
4533 bp.identifier));
4534 continue;
4535 }
4536
4537 if (!bp_sp) {
4538 error = llvm::joinErrors(
4539 std::move(error),
4540 llvm::createStringErrorV("failed to set accelerator breakpoint {0}",
4541 bp.identifier));
4542 continue;
4543 }
4544
4545 // Give the internal breakpoint a meaningful description for stop reasons,
4546 // including the plugin that requested it.
4547 std::string kind =
4548 llvm::formatv("accelerator-plugin ({0})", actions.plugin_name);
4549 bp_sp->SetBreakpointKind(kind.c_str());
4550 auto baton_sp = std::make_shared<AcceleratorBreakpointCallbackBaton>(
4551 std::move(args_up));
4552 bp_sp->SetCallback(AcceleratorBreakpointHitCallback, baton_sp,
4553 /*is_synchronous=*/true);
4554 }
4555 return error;
4556}
4557
4559 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4560 lldb::user_id_t break_loc_id) {
4561 ProcessSP process_sp = context->exe_ctx_ref.GetProcessSP();
4562 ProcessGDBRemote *process = static_cast<ProcessGDBRemote *>(process_sp.get());
4563 return process->AcceleratorBreakpointHit(baton, context, break_id,
4564 break_loc_id);
4565}
4566
4568 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4569 lldb::user_id_t break_loc_id) {
4570 AcceleratorBreakpointHitArgs *callback_data =
4571 static_cast<AcceleratorBreakpointHitArgs *>(baton);
4572 // Copy the args so we can fill in requested symbol values before notifying
4573 // lldb-server.
4574 AcceleratorBreakpointHitArgs args = *callback_data;
4575 Target &target = GetTarget();
4576
4577 const std::vector<std::string> &symbol_names = args.breakpoint.symbol_names;
4578 args.symbol_values.resize(symbol_names.size());
4579 for (size_t i = 0; i < symbol_names.size(); ++i) {
4580 args.symbol_values[i].name = symbol_names[i];
4581 SymbolContextList sc_list;
4582 target.GetImages().FindSymbolsWithNameAndType(ConstString(symbol_names[i]),
4583 eSymbolTypeAny, sc_list);
4584 for (const SymbolContext &sc : sc_list) {
4585 if (!sc.symbol)
4586 continue;
4587 addr_t load_addr = sc.symbol->GetAddress().GetLoadAddress(&target);
4588 if (load_addr != LLDB_INVALID_ADDRESS) {
4589 args.symbol_values[i].value = load_addr;
4590 break;
4591 }
4592 }
4593 }
4594
4595 Log *log = GetLog(GDBRLog::Process);
4596 llvm::Expected<AcceleratorBreakpointHitResponse> response =
4597 m_gdb_comm.AcceleratorBreakpointHit(args);
4598 if (!response) {
4599 LLDB_LOG_ERROR(log, response.takeError(),
4600 "accelerator breakpoint hit notification failed: {0}");
4601 // We could not reach the plugin, so auto-resume rather than stopping the
4602 // native process at an internal breakpoint the user can't see.
4603 return false;
4604 }
4605
4606 // Disable the breakpoint if requested, but keep it around so its hit count
4607 // and other stats remain visible.
4608 if (response->disable_bp) {
4609 if (BreakpointSP bp_sp = target.GetBreakpointByID(break_id))
4610 bp_sp->SetEnabled(false);
4611 }
4612
4613 // The plugin may request new actions (e.g. additional breakpoints) in
4614 // response to this breakpoint being hit.
4615 if (response->actions) {
4616 if (llvm::Error error = HandleAcceleratorActions(*response->actions)) {
4617 // Also print the failure to the user; during a stop, logging alone is
4618 // invisible.
4619 std::string message = llvm::toString(std::move(error));
4620 LLDB_LOG(log, "failed to handle accelerator actions: {0}", message);
4621 target.GetDebugger().GetAsyncErrorStream()->Printf(
4622 "error: accelerator plugin '%s': %s\n",
4623 response->actions->plugin_name.c_str(), message.c_str());
4624 }
4625 }
4626
4627 // Returning true stops the native process; false auto-resumes it.
4628 return !response->auto_resume_native;
4629}
4630
4632 Log *log = GetLog(GDBRLog::Process);
4633 LLDB_LOG(log, "Check if need to update ignored signals");
4634
4635 // QPassSignals package is not supported by the server, there is no way we
4636 // can ignore any signals on server side.
4637 if (!m_gdb_comm.GetQPassSignalsSupported())
4638 return Status();
4639
4640 // No signals, nothing to send.
4641 if (m_unix_signals_sp == nullptr)
4642 return Status();
4643
4644 // Signals' version hasn't changed, no need to send anything.
4645 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
4646 if (new_signals_version == m_last_signals_version) {
4647 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
4649 return Status();
4650 }
4651
4652 auto signals_to_ignore =
4653 m_unix_signals_sp->GetFilteredSignals(false, false, false);
4654 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
4655
4656 LLDB_LOG(log,
4657 "Signals' version changed. old version={0}, new version={1}, "
4658 "signals ignored={2}, update result={3}",
4659 m_last_signals_version, new_signals_version,
4660 signals_to_ignore.size(), error);
4661
4662 if (error.Success())
4663 m_last_signals_version = new_signals_version;
4664
4665 return error;
4666}
4667
4669 Log *log = GetLog(LLDBLog::Step);
4671 LLDB_LOGF_VERBOSE(log, "Enabled noticing new thread breakpoint.");
4672 m_thread_create_bp_sp->SetEnabled(true);
4673 } else {
4674 PlatformSP platform_sp(GetTarget().GetPlatform());
4675 if (platform_sp) {
4677 platform_sp->SetThreadCreationBreakpoint(GetTarget());
4680 log, "Successfully created new thread notification breakpoint %i",
4681 m_thread_create_bp_sp->GetID());
4682 m_thread_create_bp_sp->SetCallback(
4684 } else {
4685 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
4686 }
4687 }
4688 }
4689 return m_thread_create_bp_sp.get() != nullptr;
4690}
4691
4693 Log *log = GetLog(LLDBLog::Step);
4694 LLDB_LOGF_VERBOSE(log, "Disabling new thread notification breakpoint.");
4695
4697 m_thread_create_bp_sp->SetEnabled(false);
4698
4699 return true;
4700}
4701
4703 if (m_dyld_up.get() == nullptr)
4704 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
4705 return m_dyld_up.get();
4706}
4707
4709 int return_value;
4710 bool was_supported;
4711
4712 Status error;
4713
4714 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4715 if (return_value != 0) {
4716 if (!was_supported)
4718 "Sending events is not supported for this process.");
4719 else
4720 error = Status::FromErrorStringWithFormat("Error sending event data: %d.",
4721 return_value);
4722 }
4723 return error;
4724}
4725
4727 DataBufferSP buf;
4728 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4729 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
4730 if (response)
4731 buf = std::make_shared<DataBufferHeap>(response->c_str(),
4732 response->length());
4733 else
4734 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
4735 }
4737}
4738
4741 StructuredData::ObjectSP object_sp;
4742
4743 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
4745 SystemRuntime *runtime = GetSystemRuntime();
4746 if (runtime) {
4747 runtime->AddThreadExtendedInfoPacketHints(args_dict);
4748 }
4749 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
4750
4751 StreamString packet;
4752 packet << "jThreadExtendedInfo:";
4753 args_dict->Dump(packet, false);
4754
4755 // FIXME the final character of a JSON dictionary, '}', is the escape
4756 // character in gdb-remote binary mode. lldb currently doesn't escape
4757 // these characters in its packet output -- so we add the quoted version of
4758 // the } character here manually in case we talk to a debugserver which un-
4759 // escapes the characters at packet read time.
4760 packet << (char)(0x7d ^ 0x20);
4761
4762 StringExtractorGDBRemote response;
4763 response.SetResponseValidatorToJSON();
4764 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4767 response.GetResponseType();
4768 if (response_type == StringExtractorGDBRemote::eResponse) {
4769 if (!response.Empty()) {
4770 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4771 }
4772 }
4773 }
4774 }
4775 return object_sp;
4776}
4777
4779 lldb::addr_t image_list_address, lldb::addr_t image_count) {
4780
4782 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4783 image_list_address);
4784 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4785
4786 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4787}
4788
4789static std::string
4791 std::string info_level_str;
4792 if (info_level == eBinaryInformationLevelAddrOnly)
4793 info_level_str = "address-only";
4794 else if (info_level == eBinaryInformationLevelAddrName)
4795 info_level_str = "address-name";
4796 else if (info_level == eBinaryInformationLevelAddrNameUUID)
4797 info_level_str = "address-name-uuid";
4798 else if (info_level == eBinaryInformationLevelFull)
4799 info_level_str = "full";
4800
4801 return info_level_str;
4802}
4803
4805 BinaryInformationLevel info_level) {
4807
4808 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4809 if (info_level != eBinaryInformationLevelFull)
4810 args_dict->GetAsDictionary()->AddBooleanItem("report_load_commands", false);
4811 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4812 if (!info_level_str.empty())
4813 args_dict->GetAsDictionary()->AddStringItem("information-level",
4814 info_level_str.c_str());
4815
4816 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4817}
4818
4820 BinaryInformationLevel info_level,
4821 const std::vector<lldb::addr_t> &load_addresses) {
4824
4825 for (auto addr : load_addresses)
4826 addresses->AddIntegerItem(addr);
4827
4828 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4829
4830 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4831 if (!info_level_str.empty())
4832 args_dict->GetAsDictionary()->AddStringItem("information-level",
4833 info_level_str.c_str());
4834
4835 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4836}
4837
4840 StructuredData::ObjectSP args_dict) {
4841 StructuredData::ObjectSP object_sp;
4842
4843 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4844 // Scope for the scoped timeout object
4846 std::chrono::seconds(10));
4847
4848 StreamString packet;
4849 packet << "jGetLoadedDynamicLibrariesInfos:";
4850 args_dict->Dump(packet, false);
4851
4852 // FIXME the final character of a JSON dictionary, '}', is the escape
4853 // character in gdb-remote binary mode. lldb currently doesn't escape
4854 // these characters in its packet output -- so we add the quoted version of
4855 // the } character here manually in case we talk to a debugserver which un-
4856 // escapes the characters at packet read time.
4857 packet << (char)(0x7d ^ 0x20);
4858
4859 StringExtractorGDBRemote response;
4860 response.SetResponseValidatorToJSON();
4861 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4864 response.GetResponseType();
4865 if (response_type == StringExtractorGDBRemote::eResponse) {
4866 if (!response.Empty()) {
4867 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4868 }
4869 }
4870 }
4871 }
4872 return object_sp;
4873}
4874
4876 StructuredData::ObjectSP object_sp;
4878
4879 if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
4880 StringExtractorGDBRemote response;
4881 response.SetResponseValidatorToJSON();
4882 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
4883 response) ==
4886 response.GetResponseType();
4887 if (response_type == StringExtractorGDBRemote::eResponse) {
4888 if (!response.Empty()) {
4889 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4890 }
4891 }
4892 }
4893 }
4894 return object_sp;
4895}
4896
4898 // Held across the query so a second caller waits for the answer instead of
4899 // sending the packet again.
4900 auto shared_cache_info = m_shared_cache_info.Lock();
4902
4903 if (*shared_cache_info || !m_gdb_comm.GetSharedCacheInfoSupported())
4904 return *shared_cache_info;
4905
4906 StreamString packet;
4907 packet << "jGetSharedCacheInfo:";
4908 args_dict->Dump(packet, false);
4909
4910 StringExtractorGDBRemote response;
4911 response.SetResponseValidatorToJSON();
4912 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4915 response.GetResponseType();
4916 if (response_type == StringExtractorGDBRemote::eResponse) {
4917 if (response.Empty())
4918 return {};
4919 StructuredData::ObjectSP response_sp =
4921 if (!response_sp)
4922 return {};
4923 StructuredData::Dictionary *dict = response_sp->GetAsDictionary();
4924 if (!dict)
4925 return {};
4926 if (!dict->HasKey("shared_cache_uuid"))
4927 return {};
4928 llvm::StringRef uuid_str;
4929 if (!dict->GetValueForKeyAsString("shared_cache_uuid", uuid_str, "") ||
4930 uuid_str == "00000000-0000-0000-0000-000000000000")
4931 return {};
4932 if (dict->HasKey("shared_cache_path")) {
4933 UUID uuid;
4934 uuid.SetFromStringRef(uuid_str);
4935 FileSpec sc_path(
4936 dict->GetValueForKey("shared_cache_path")->GetStringValue());
4937
4938 SymbolSharedCacheUse sc_mode =
4941
4944 // Attempt to open the shared cache at sc_path, and
4945 // if the uuid matches, index all the files.
4946 HostInfo::SharedCacheIndexFiles(sc_path, uuid, sc_mode);
4947 }
4948 }
4949 *shared_cache_info = response_sp;
4950 }
4951 }
4952 return *shared_cache_info;
4953}
4954
4956 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4957 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4958}
4959
4960// Establish the largest memory read/write payloads we should use. If the
4961// remote stub has a max packet size, stay under that size.
4962//
4963// If the remote stub's max packet size is crazy large, use a reasonable
4964// largeish default.
4965//
4966// If the remote stub doesn't advertise a max packet size, use a conservative
4967// default.
4968
4970 const uint64_t reasonable_largeish_default = 128 * 1024;
4971 const uint64_t conservative_default = 512;
4972
4973 if (m_max_memory_size == 0) {
4974 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4975 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4976 // Save the stub's claimed maximum packet size
4977 m_remote_stub_max_memory_size = stub_max_size;
4978
4979 // Even if the stub says it can support ginormous packets, don't exceed
4980 // our reasonable largeish default packet size.
4981 if (stub_max_size > reasonable_largeish_default) {
4982 stub_max_size = reasonable_largeish_default;
4983 }
4984
4985 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4986 // calculating the bytes taken by size and addr every time, we take a
4987 // maximum guess here.
4988 if (stub_max_size > 70)
4989 stub_max_size -= 32 + 32 + 6;
4990 else {
4991 // In unlikely scenario that max packet size is less then 70, we will
4992 // hope that data being written is small enough to fit.
4994 LLDB_LOG(log, "warning: Packet size is too small. "
4995 "LLDB may face problems while writing memory");
4996 }
4997
4998 m_max_memory_size = stub_max_size;
4999 } else {
5000 m_max_memory_size = conservative_default;
5001 }
5002 }
5003}
5004
5006 uint64_t user_specified_max) {
5007 if (user_specified_max != 0) {
5009
5011 if (m_remote_stub_max_memory_size < user_specified_max) {
5013 // packet size too
5014 // big, go as big
5015 // as the remote stub says we can go.
5016 } else {
5017 m_max_memory_size = user_specified_max; // user's packet size is good
5018 }
5019 } else {
5021 user_specified_max; // user's packet size is probably fine
5022 }
5023 }
5024}
5025
5026bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
5027 const ArchSpec &arch,
5028 ModuleSpec &module_spec) {
5030
5031 const ModuleCacheKey key(module_file_spec.GetPath(),
5032 arch.GetTriple().getTriple());
5033 auto cached = m_cached_module_specs.find(key);
5034 if (cached != m_cached_module_specs.end()) {
5035 module_spec = cached->second;
5036 return bool(module_spec);
5037 }
5038
5039 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
5040 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
5041 __FUNCTION__, module_file_spec.GetPath().c_str(),
5042 arch.GetTriple().getTriple().c_str());
5043 return false;
5044 }
5045
5046 if (log) {
5047 StreamString stream;
5048 module_spec.Dump(stream);
5049 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
5050 __FUNCTION__, module_file_spec.GetPath().c_str(),
5051 arch.GetTriple().getTriple().c_str(), stream.GetData());
5052 }
5053
5054 m_cached_module_specs[key] = module_spec;
5055 return true;
5056}
5057
5059 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
5060 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
5061 if (module_specs) {
5062 for (const FileSpec &spec : module_file_specs)
5064 triple.getTriple())] = ModuleSpec();
5065 for (const ModuleSpec &spec : *module_specs)
5066 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
5067 triple.getTriple())] = spec;
5068 }
5069}
5070
5072 return m_gdb_comm.GetOSVersion();
5073}
5074
5076 return m_gdb_comm.GetMacCatalystVersion();
5077}
5078
5079namespace {
5080
5081typedef std::vector<std::string> stringVec;
5082
5083typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
5084struct RegisterSetInfo {
5085 ConstString name;
5086};
5087
5088typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
5089
5090struct GdbServerTargetInfo {
5091 std::string arch;
5092 std::string osabi;
5093 stringVec includes;
5094 RegisterSetMap reg_set_map;
5095};
5096
5097using RegisterTypeMap = llvm::StringMap<const RegisterType *>;
5098
5100ParseEnumEvalues(const XMLNode &enum_node) {
5102 // We will use the last instance of each value. Also we preserve the order
5103 // of declaration in the XML, as it may not be numerical.
5104 // For example, hardware may initially release with two states that software
5105 // can read from a register field:
5106 // 0 = startup, 1 = running
5107 // If in a future hardware release, the designers added a pre-startup state:
5108 // 0 = startup, 1 = running, 2 = pre-startup
5109 // Now it makes more sense to list them in this logical order as opposed to
5110 // numerical order:
5111 // 2 = pre-startup, 1 = startup, 0 = startup
5112 // This only matters for "register info" but let's trust what the server
5113 // chose regardless.
5114 std::map<uint64_t, RegisterTypeEnum::Enumerator> enumerators;
5115
5117 "evalue", [&enumerators, &log](const XMLNode &enumerator_node) {
5118 std::optional<llvm::StringRef> name;
5119 std::optional<uint64_t> value;
5120
5121 enumerator_node.ForEachAttribute(
5122 [&name, &value, &log](const llvm::StringRef &attr_name,
5123 const llvm::StringRef &attr_value) {
5124 if (attr_name == "name") {
5125 if (attr_value.size())
5126 name = attr_value;
5127 else
5128 LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues "
5129 "Ignoring empty name in evalue");
5130 } else if (attr_name == "value") {
5131 uint64_t parsed_value = 0;
5132 if (llvm::to_integer(attr_value, parsed_value))
5133 value = parsed_value;
5134 else
5135 LLDB_LOG(log,
5136 "ProcessGDBRemote::ParseEnumEvalues "
5137 "Invalid value \"{0}\" in "
5138 "evalue",
5139 attr_value.data());
5140 } else
5141 LLDB_LOG(log,
5142 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
5143 "unknown attribute "
5144 "\"{0}\" in evalue",
5145 attr_name.data());
5146
5147 // Keep walking attributes.
5148 return true;
5149 });
5150
5151 if (value && name)
5152 enumerators.insert_or_assign(
5153 *value, RegisterTypeEnum::Enumerator(*value, name->str()));
5154
5155 // Find all evalue elements.
5156 return true;
5157 });
5158
5159 RegisterTypeEnum::Enumerators final_enumerators;
5160 for (auto [_, enumerator] : enumerators)
5161 final_enumerators.push_back(enumerator);
5162
5163 return final_enumerators;
5164}
5165
5166static void
5167ParseEnums(XMLNode feature_node, RegisterTypeMap &feature_register_types,
5168 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5169 Log *log(GetLog(GDBRLog::Process));
5170
5171 // The top level element is "<enum...".
5172 feature_node.ForEachChildElementWithName(
5173 "enum", [log, &feature_register_types,
5174 &owned_register_types](const XMLNode &enum_node) {
5175 std::string id;
5176
5177 enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name,
5178 const llvm::StringRef &attr_value) {
5179 if (attr_name == "id")
5180 id = attr_value;
5181
5182 // There is also a "size" attribute that is supposed to be the size in
5183 // bytes of the register this applies to. However:
5184 // * LLDB doesn't need this information.
5185 // * It is difficult to verify because you have to wait until the
5186 // enum is applied to a field.
5187 //
5188 // So we will emit this attribute in XML for GDB's sake, but will not
5189 // bother ingesting it.
5190
5191 // Walk all attributes.
5192 return true;
5193 });
5194
5195 if (!id.empty()) {
5196 RegisterTypeEnum::Enumerators enumerators =
5197 ParseEnumEvalues(enum_node);
5198 if (!enumerators.empty()) {
5199 LLDB_LOG(log,
5200 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
5201 id);
5202 auto enum_type =
5203 std::make_unique<RegisterTypeEnum>(id, enumerators);
5204 const RegisterTypeEnum *enum_type_ptr = enum_type.get();
5205 auto [it, inserted] =
5206 feature_register_types.try_emplace(id, enum_type_ptr);
5207 if (inserted) {
5208 owned_register_types.push_back(std::move(enum_type));
5209 } else if (llvm::isa<RegisterTypeEnum>(it->second)) {
5210 // Preserve the existing behavior where the last valid enum with
5211 // a repeated ID wins. All enums are parsed before flags, so no
5212 // fields can reference the enum being replaced yet. The earlier
5213 // object remains owned; only the feature lookup is updated.
5214 owned_register_types.push_back(std::move(enum_type));
5215 it->second = enum_type_ptr;
5216 } else {
5217 LLDB_LOG(
5218 log,
5219 "ProcessGDBRemote::ParseEnums Ignoring enum type \"{0}\" "
5220 "because another type with that id already exists",
5221 id);
5222 }
5223 }
5224 }
5225
5226 // Find all <enum> elements.
5227 return true;
5228 });
5229}
5230
5231static std::vector<RegisterTypeFlags::Field>
5232ParseFlagsFields(XMLNode flags_node, unsigned size,
5233 const RegisterTypeMap &feature_register_types) {
5234 Log *log(GetLog(GDBRLog::Process));
5235 const unsigned max_start_bit = size * 8 - 1;
5236
5237 // Process the fields of this set of flags.
5238 std::vector<RegisterTypeFlags::Field> fields;
5239 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log,
5240 &feature_register_types](
5241 const XMLNode
5242 &field_node) {
5243 std::optional<llvm::StringRef> name;
5244 std::optional<unsigned> start;
5245 std::optional<unsigned> end;
5246 std::optional<llvm::StringRef> type;
5247
5248 field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit,
5249 &log](const llvm::StringRef &attr_name,
5250 const llvm::StringRef &attr_value) {
5251 // Note that XML in general requires that each of these attributes only
5252 // appears once, so we don't have to handle that here.
5253 if (attr_name == "name") {
5254 LLDB_LOG(
5255 log,
5256 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
5257 attr_value.data());
5258 name = attr_value;
5259 } else if (attr_name == "start") {
5260 unsigned parsed_start = 0;
5261 if (llvm::to_integer(attr_value, parsed_start)) {
5262 if (parsed_start > max_start_bit) {
5263 LLDB_LOG(log,
5264 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
5265 "field node, "
5266 "cannot be > {1}",
5267 parsed_start, max_start_bit);
5268 } else
5269 start = parsed_start;
5270 } else {
5271 LLDB_LOG(
5272 log,
5273 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
5274 "field node",
5275 attr_value.data());
5276 }
5277 } else if (attr_name == "end") {
5278 unsigned parsed_end = 0;
5279 if (llvm::to_integer(attr_value, parsed_end))
5280 if (parsed_end > max_start_bit) {
5281 LLDB_LOG(log,
5282 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
5283 "field node, "
5284 "cannot be > {1}",
5285 parsed_end, max_start_bit);
5286 } else
5287 end = parsed_end;
5288 else {
5289 LLDB_LOG(log,
5290 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
5291 "field node",
5292 attr_value.data());
5293 }
5294 } else if (attr_name == "type") {
5295 type = attr_value;
5296 } else {
5297 LLDB_LOG(
5298 log,
5299 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
5300 "\"{0}\" in field node",
5301 attr_name.data());
5302 }
5303
5304 return true; // Walk all attributes of the field.
5305 });
5306
5307 if (name && start && end) {
5308 if (*start > *end)
5309 LLDB_LOG(
5310 log,
5311 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
5312 "\"{2}\", ignoring",
5313 *start, *end, name->data());
5314 else {
5315 if (RegisterTypeFlags::Field::GetSizeInBits(*start, *end) > 64)
5316 LLDB_LOG(log,
5317 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{}\" "
5318 "that has size > 64 bits, this is not supported",
5319 name->data());
5320 else {
5321 // A field's type may be set to the name of an enum type.
5322 const RegisterTypeEnum *enum_type = nullptr;
5323 if (type && !type->empty()) {
5324 auto found = feature_register_types.find(*type);
5325 if (found != feature_register_types.end()) {
5326 enum_type = llvm::dyn_cast<RegisterTypeEnum>(found->second);
5327
5328 if (!enum_type) {
5329 LLDB_LOG(log,
5330 "ProcessGDBRemote::ParseFlagsFields Type \"{0}\" for "
5331 "field \"{1}\" is not an enum, ignoring",
5332 type->data(), name->data());
5333 }
5334
5335 // No enumerator can exceed the range of the field itself.
5336 if (enum_type) {
5337 uint64_t max_value =
5339 for (const auto &enumerator : enum_type->GetEnumerators()) {
5340 if (enumerator.m_value > max_value) {
5341 enum_type = nullptr;
5342 LLDB_LOG(
5343 log,
5344 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
5345 "evalue \"{1}\" with value {2} exceeds the maximum "
5346 "value of field \"{3}\" ({4}), ignoring enum",
5347 type->data(), enumerator.m_name, enumerator.m_value,
5348 name->data(), max_value);
5349 break;
5350 }
5351 }
5352 }
5353 } else {
5354 LLDB_LOG(log,
5355 "ProcessGDBRemote::ParseFlagsFields Could not find type "
5356 "\"{0}\" "
5357 "for field \"{1}\", ignoring",
5358 type->data(), name->data());
5359 }
5360 }
5361
5362 fields.push_back(
5363 RegisterTypeFlags::Field(name->str(), *start, *end, enum_type));
5364 }
5365 }
5366 }
5367
5368 return true; // Iterate all "field" nodes.
5369 });
5370 return fields;
5371}
5372
5373void ParseFlags(
5374 XMLNode feature_node, RegisterTypeMap &feature_register_types,
5375 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5376 Log *log(GetLog(GDBRLog::Process));
5377
5378 feature_node.ForEachChildElementWithName(
5379 "flags",
5380 [&log, &feature_register_types,
5381 &owned_register_types](const XMLNode &flags_node) -> bool {
5382 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
5383 flags_node.GetAttributeValue("id").c_str());
5384
5385 std::optional<llvm::StringRef> id;
5386 std::optional<unsigned> size;
5387 flags_node.ForEachAttribute(
5388 [&id, &size, &log](const llvm::StringRef &name,
5389 const llvm::StringRef &value) {
5390 if (name == "id") {
5391 id = value;
5392 } else if (name == "size") {
5393 unsigned parsed_size = 0;
5394 if (llvm::to_integer(value, parsed_size))
5395 size = parsed_size;
5396 else {
5397 LLDB_LOG(log,
5398 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
5399 "in flags node",
5400 value.data());
5401 }
5402 } else {
5403 LLDB_LOG(log,
5404 "ProcessGDBRemote::ParseFlags Ignoring unknown "
5405 "attribute \"{0}\" in flags node",
5406 name.data());
5407 }
5408 return true; // Walk all attributes.
5409 });
5410
5411 if (id && size) {
5412 // Process the fields of this set of flags.
5413 std::vector<RegisterTypeFlags::Field> fields =
5414 ParseFlagsFields(flags_node, *size, feature_register_types);
5415 if (fields.size()) {
5416 // Sort so that the fields with the MSBs are first.
5417 std::sort(fields.rbegin(), fields.rend());
5418 std::vector<RegisterTypeFlags::Field>::const_iterator overlap =
5419 std::adjacent_find(fields.begin(), fields.end(),
5420 [](const RegisterTypeFlags::Field &lhs,
5421 const RegisterTypeFlags::Field &rhs) {
5422 return lhs.Overlaps(rhs);
5423 });
5424
5425 // If no fields overlap, use them.
5426 if (overlap == fields.end()) {
5427 if (feature_register_types.contains(*id)) {
5428 // Type IDs must be unique within a feature. Keep the type that
5429 // was already registered by the enum and flags parsing passes.
5430 LLDB_LOG(
5431 log,
5432 "ProcessGDBRemote::ParseFlags Definition of flags \"{0}\" "
5433 "conflicts with an existing type, ignoring this "
5434 "definition.",
5435 id->data());
5436 } else {
5437 auto flags_type = std::make_unique<RegisterTypeFlags>(
5438 id->str(), *size, std::move(fields));
5439 feature_register_types.try_emplace(*id, flags_type.get());
5440 owned_register_types.push_back(std::move(flags_type));
5441 }
5442 } else {
5443 // If any fields overlap, ignore the whole set of flags.
5444 std::vector<RegisterTypeFlags::Field>::const_iterator next =
5445 std::next(overlap);
5446 LLDB_LOG(
5447 log,
5448 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
5449 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
5450 "overlap.",
5451 overlap->GetName().c_str(), overlap->GetStart(),
5452 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
5453 next->GetEnd());
5454 }
5455 } else {
5456 LLDB_LOG(
5457 log,
5458 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
5459 "\"{0}\" because it contains no fields.",
5460 id->data());
5461 }
5462 }
5463
5464 return true; // Keep iterating through all "flags" elements.
5465 });
5466}
5467
5468static const RegisterTypeBuiltin *
5469ResolveGDBBuiltinType(llvm::StringRef type_name) {
5470 // These names and sizes follow GDB's predefined target-description types in
5471 // gdbsupport/tdesc.cc. ARM FPA is intentionally omitted because GCC removed
5472 // support for it in 2012.
5473 static const RegisterTypeBuiltin bool_type("bool", eEncodingUint,
5474 eFormatBoolean, 1);
5475 static const RegisterTypeBuiltin int8_type("int8", eEncodingSint,
5476 eFormatDecimal, 1);
5477 static const RegisterTypeBuiltin int16_type("int16", eEncodingSint,
5478 eFormatDecimal, 2);
5479 static const RegisterTypeBuiltin int32_type("int32", eEncodingSint,
5480 eFormatDecimal, 4);
5481 static const RegisterTypeBuiltin int64_type("int64", eEncodingSint,
5482 eFormatDecimal, 8);
5483 static const RegisterTypeBuiltin int128_type("int128", eEncodingSint,
5484 eFormatDecimal, 16);
5485 static const RegisterTypeBuiltin uint8_type("uint8", eEncodingUint,
5486 eFormatHex, 1);
5487 static const RegisterTypeBuiltin uint16_type("uint16", eEncodingUint,
5488 eFormatHex, 2);
5489 static const RegisterTypeBuiltin uint32_type("uint32", eEncodingUint,
5490 eFormatHex, 4);
5491 static const RegisterTypeBuiltin uint64_type("uint64", eEncodingUint,
5492 eFormatHex, 8);
5493 static const RegisterTypeBuiltin uint128_type("uint128", eEncodingUint,
5494 eFormatHex, 16);
5495 static const RegisterTypeBuiltin code_ptr_type(
5496 "code_ptr", eEncodingUint, eFormatAddressInfo, std::nullopt);
5497 static const RegisterTypeBuiltin data_ptr_type(
5498 "data_ptr", eEncodingUint, eFormatAddressInfo, std::nullopt);
5499 static const RegisterTypeBuiltin ieee_half_type("ieee_half", eEncodingIEEE754,
5500 eFormatFloat, 2);
5501 static const RegisterTypeBuiltin ieee_single_type(
5502 "ieee_single", eEncodingIEEE754, eFormatFloat, 4);
5503 static const RegisterTypeBuiltin ieee_double_type(
5504 "ieee_double", eEncodingIEEE754, eFormatFloat, 8);
5505 static const RegisterTypeBuiltin i387_ext_type("i387_ext", eEncodingIEEE754,
5506 eFormatFloat, 10);
5507 static const RegisterTypeBuiltin bfloat16_type("bfloat16", eEncodingIEEE754,
5508 eFormatFloat, 2);
5509
5510 return llvm::StringSwitch<const RegisterTypeBuiltin *>(type_name)
5511 .Case("bool", &bool_type)
5512 .Case("int8", &int8_type)
5513 .Case("int16", &int16_type)
5514 .Case("int32", &int32_type)
5515 .Case("int64", &int64_type)
5516 .Case("int128", &int128_type)
5517 .Case("uint8", &uint8_type)
5518 .Case("uint16", &uint16_type)
5519 .Case("uint32", &uint32_type)
5520 .Case("uint64", &uint64_type)
5521 .Case("uint128", &uint128_type)
5522 .Case("code_ptr", &code_ptr_type)
5523 .Case("data_ptr", &data_ptr_type)
5524 .Case("ieee_half", &ieee_half_type)
5525 .Case("ieee_single", &ieee_single_type)
5526 .Case("ieee_double", &ieee_double_type)
5527 .Case("i387_ext", &i387_ext_type)
5528 .Case("bfloat16", &bfloat16_type)
5529 .Default(nullptr);
5530}
5531
5532static const RegisterType *
5533ResolveGDBType(llvm::StringRef type_name,
5534 const RegisterTypeMap &feature_register_types) {
5535 auto type_it = feature_register_types.find(type_name);
5536 if (type_it != feature_register_types.end())
5537 return type_it->second;
5538 return ResolveGDBBuiltinType(type_name);
5539}
5540
5541static void
5542ParseVector(const XMLNode &vector_node, RegisterTypeMap &feature_register_types,
5543 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5544 Log *log(GetLog(GDBRLog::Process));
5545 std::optional<llvm::StringRef> id;
5546 std::optional<llvm::StringRef> element_type_name;
5547 std::optional<uint32_t> count;
5548
5549 vector_node.ForEachAttribute(
5550 [&id, &element_type_name, &count, log](llvm::StringRef name,
5551 llvm::StringRef value) {
5552 if (name == "id") {
5553 id = value;
5554 } else if (name == "type") {
5555 element_type_name = value;
5556 } else if (name == "count") {
5557 uint32_t parsed_count = 0;
5558 if (llvm::to_integer(value, parsed_count))
5559 count = parsed_count;
5560 else
5561 LLDB_LOG(log, "ProcessGDBRemote::ParseVector Invalid count \"{0}\"",
5562 value);
5563 } else {
5564 LLDB_LOG(log,
5565 "ProcessGDBRemote::ParseVector Ignoring unknown attribute "
5566 "\"{0}\"",
5567 name);
5568 }
5569 return true;
5570 });
5571
5572 // GDB limits vectors to 65536 elements. This is also LLDB's maximum
5573 // register size in bytes, so use the existing named limit.
5574 constexpr uint32_t max_vector_count = RegisterValue::kMaxRegisterByteSize;
5575 if (!id || id->empty() || !element_type_name || element_type_name->empty() ||
5576 !count || *count == 0 || *count > max_vector_count) {
5577 LLDB_LOG(log, "ProcessGDBRemote::ParseVector Ignoring vector with invalid "
5578 "id, type, or count");
5579 return;
5580 }
5581
5582 if (feature_register_types.contains(*id)) {
5583 LLDB_LOG(log,
5584 "ProcessGDBRemote::ParseVector Ignoring duplicate type \"{0}\"",
5585 *id);
5586 return;
5587 }
5588
5589 const RegisterType *element_type =
5590 ResolveGDBType(*element_type_name, feature_register_types);
5591 if (!element_type) {
5592 LLDB_LOG(log,
5593 "ProcessGDBRemote::ParseVector Could not resolve element type "
5594 "\"{0}\" for vector \"{1}\"",
5595 *element_type_name, *id);
5596 return;
5597 }
5598
5599 if (!llvm::isa<RegisterTypeBuiltin, RegisterTypeVector, RegisterTypeUnion>(
5600 element_type)) {
5601 LLDB_LOG(log,
5602 "ProcessGDBRemote::ParseVector Found element type \"{0}\" for "
5603 "vector \"{1}\", but it is not a builtin, vector, or union "
5604 "type",
5605 *element_type_name, *id);
5606 return;
5607 }
5608
5609 std::optional<uint64_t> element_size = element_type->GetByteSize();
5610 if (element_size &&
5611 *element_size > RegisterValue::kMaxRegisterByteSize / *count) {
5612 LLDB_LOG(log,
5613 "ProcessGDBRemote::ParseVector Size of vector \"{0}\" is too "
5614 "large",
5615 *id);
5616 return;
5617 }
5618
5619 auto vector_type =
5620 std::make_unique<RegisterTypeVector>(id->str(), element_type, *count);
5621 feature_register_types.try_emplace(*id, vector_type.get());
5622 owned_register_types.push_back(std::move(vector_type));
5623}
5624
5625static std::vector<RegisterTypeUnion::Field>
5626ParseUnionFields(const XMLNode &union_node, llvm::StringRef union_id,
5627 const RegisterTypeMap &feature_register_types) {
5628 Log *log(GetLog(GDBRLog::Process));
5629 std::vector<RegisterTypeUnion::Field> fields;
5630 bool invalid_field = false;
5631
5632 union_node.ForEachChildElementWithName(
5633 "field", [&fields, &invalid_field, log, &feature_register_types,
5634 union_id](const XMLNode &field_node) {
5635 std::optional<llvm::StringRef> name;
5636 std::optional<llvm::StringRef> type_name;
5637
5638 field_node.ForEachAttribute(
5639 [&name, &type_name, log, union_id](llvm::StringRef attribute,
5640 llvm::StringRef value) {
5641 if (attribute == "name")
5642 name = value;
5643 else if (attribute == "type")
5644 type_name = value;
5645 else
5646 LLDB_LOG(log,
5647 "ProcessGDBRemote::ParseUnionFields Ignoring unknown "
5648 "attribute \"{0}\" in a field of union \"{1}\"",
5649 attribute, union_id);
5650 return true;
5651 });
5652
5653 if (!name || name->empty() || !type_name || type_name->empty()) {
5654 LLDB_LOG(log,
5655 "ProcessGDBRemote::ParseUnionFields Union \"{0}\" has a "
5656 "field missing a non-empty name or type",
5657 union_id);
5658 invalid_field = true;
5659 return true;
5660 }
5661
5662 const RegisterType *field_type =
5663 ResolveGDBType(*type_name, feature_register_types);
5664 if (!field_type) {
5665 LLDB_LOG(log,
5666 "ProcessGDBRemote::ParseUnionFields Could not resolve type "
5667 "\"{0}\" for field \"{1}\" of union \"{2}\"",
5668 *type_name, *name, union_id);
5669 invalid_field = true;
5670 return true;
5671 }
5672
5673 if (!llvm::isa<RegisterTypeBuiltin, RegisterTypeVector,
5674 RegisterTypeUnion>(field_type)) {
5675 LLDB_LOG(log,
5676 "ProcessGDBRemote::ParseUnionFields Found type \"{0}\" "
5677 "for field \"{1}\", but it is not a builtin, vector, or "
5678 "union type. Union \"{2}\" will be ignored.",
5679 *type_name, *name, union_id);
5680 invalid_field = true;
5681 return true;
5682 }
5683
5684 fields.emplace_back(name->str(), field_type);
5685 return true;
5686 });
5687
5688 // Reject the whole union if any field is invalid. Retaining only valid fields
5689 // would misrepresent the target's type definition.
5690 if (invalid_field) {
5691 LLDB_LOG(log,
5692 "ProcessGDBRemote::ParseUnionFields Ignoring union \"{0}\" "
5693 "because it contains an invalid field",
5694 union_id);
5695 fields.clear();
5696 } else if (fields.empty()) {
5697 LLDB_LOG(log,
5698 "ProcessGDBRemote::ParseUnionFields Ignoring union \"{0}\" "
5699 "because it has no fields",
5700 union_id);
5701 }
5702 return fields;
5703}
5704
5705static void
5706ParseUnion(const XMLNode &union_node, RegisterTypeMap &feature_register_types,
5707 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5708 Log *log(GetLog(GDBRLog::Process));
5709 std::optional<llvm::StringRef> id;
5710
5711 union_node.ForEachAttribute(
5712 [&id, log](llvm::StringRef name, llvm::StringRef value) {
5713 if (name == "id")
5714 id = value;
5715 else
5716 LLDB_LOG(log,
5717 "ProcessGDBRemote::ParseUnion Ignoring unknown attribute "
5718 "\"{0}\"",
5719 name);
5720 return true;
5721 });
5722
5723 if (!id || id->empty()) {
5724 LLDB_LOG(log, "ProcessGDBRemote::ParseUnion Ignoring union without an id");
5725 return;
5726 }
5727
5728 if (feature_register_types.contains(*id)) {
5729 LLDB_LOG(log,
5730 "ProcessGDBRemote::ParseUnion Ignoring duplicate type \"{0}\"",
5731 *id);
5732 return;
5733 }
5734
5735 std::vector<RegisterTypeUnion::Field> fields =
5736 ParseUnionFields(union_node, *id, feature_register_types);
5737 if (fields.empty())
5738 return;
5739
5740 auto union_type =
5741 std::make_unique<RegisterTypeUnion>(id->str(), std::move(fields));
5742 feature_register_types.try_emplace(*id, union_type.get());
5743 owned_register_types.push_back(std::move(union_type));
5744}
5745
5746static void ParseCompositeTypes(
5747 XMLNode feature_node, RegisterTypeMap &feature_register_types,
5748 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5749 feature_node.ForEachChildElement(
5750 [&feature_register_types,
5751 &owned_register_types](const XMLNode &type_node) {
5752 if (type_node.NameIs("vector"))
5753 ParseVector(type_node, feature_register_types, owned_register_types);
5754 else if (type_node.NameIs("union"))
5755 ParseUnion(type_node, feature_register_types, owned_register_types);
5756 return true;
5757 });
5758}
5759
5760bool ParseRegisters(
5761 XMLNode feature_node, GdbServerTargetInfo &target_info,
5762 std::vector<DynamicRegisterInfo::Register> &registers,
5763 std::vector<std::unique_ptr<RegisterType>> &owned_register_types) {
5764 if (!feature_node)
5765 return false;
5766
5767 Log *log(GetLog(GDBRLog::Process));
5768 RegisterTypeMap feature_register_types;
5769
5770 // Enums first because they are referenced by fields in the flags.
5771 ParseEnums(feature_node, feature_register_types, owned_register_types);
5772 for (const auto &register_type : feature_register_types)
5773 if (const auto *enum_type =
5774 llvm::dyn_cast<RegisterTypeEnum>(register_type.second))
5775 enum_type->DumpToLog(log);
5776
5777 ParseFlags(feature_node, feature_register_types, owned_register_types);
5778 for (const auto &register_type : feature_register_types)
5779 if (const auto *flags_type =
5780 llvm::dyn_cast<RegisterTypeFlags>(register_type.second))
5781 flags_type->DumpToLog(log);
5782
5783 // Enums and flags retain their dedicated passes above. Vectors and unions
5784 // can reference one another, so parse them together in document order. A
5785 // referenced composite type must precede its user.
5786 ParseCompositeTypes(feature_node, feature_register_types,
5787 owned_register_types);
5788 for (const auto &register_type : feature_register_types)
5789 if (const auto *vector_type =
5790 llvm::dyn_cast<RegisterTypeVector>(register_type.second))
5791 vector_type->DumpToLog(log);
5792 for (const auto &register_type : feature_register_types)
5793 if (const auto *union_type =
5794 llvm::dyn_cast<RegisterTypeUnion>(register_type.second))
5795 union_type->DumpToLog(log);
5796
5797 feature_node.ForEachChildElementWithName(
5798 "reg",
5799 [&target_info, &registers, &feature_register_types,
5800 log](const XMLNode &reg_node) -> bool {
5801 std::string gdb_group;
5802 std::string gdb_type;
5803 DynamicRegisterInfo::Register reg_info;
5804 bool encoding_set = false;
5805 bool format_set = false;
5806
5807 // FIXME: we're silently ignoring invalid data here
5808 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
5809 &encoding_set, &format_set, &reg_info,
5810 log](const llvm::StringRef &name,
5811 const llvm::StringRef &value) -> bool {
5812 if (name == "name") {
5813 reg_info.name.SetString(value);
5814 } else if (name == "bitsize") {
5815 if (llvm::to_integer(value, reg_info.byte_size))
5816 reg_info.byte_size =
5817 llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
5818 } else if (name == "type") {
5819 gdb_type = value.str();
5820 } else if (name == "group") {
5821 gdb_group = value.str();
5822 } else if (name == "regnum") {
5823 llvm::to_integer(value, reg_info.regnum_remote);
5824 } else if (name == "offset") {
5825 llvm::to_integer(value, reg_info.byte_offset);
5826 } else if (name == "altname") {
5827 reg_info.alt_name.SetString(value);
5828 } else if (name == "encoding") {
5829 encoding_set = true;
5831 } else if (name == "format") {
5832 format_set = true;
5833 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
5834 nullptr)
5835 .Success())
5836 reg_info.format =
5837 llvm::StringSwitch<lldb::Format>(value)
5838 .Case("vector-sint8", eFormatVectorOfSInt8)
5839 .Case("vector-uint8", eFormatVectorOfUInt8)
5840 .Case("vector-sint16", eFormatVectorOfSInt16)
5841 .Case("vector-uint16", eFormatVectorOfUInt16)
5842 .Case("vector-sint32", eFormatVectorOfSInt32)
5843 .Case("vector-uint32", eFormatVectorOfUInt32)
5844 .Case("vector-float32", eFormatVectorOfFloat32)
5845 .Case("vector-uint64", eFormatVectorOfUInt64)
5846 .Case("vector-uint128", eFormatVectorOfUInt128)
5847 .Default(eFormatInvalid);
5848 } else if (name == "group_id") {
5849 uint32_t set_id = UINT32_MAX;
5850 llvm::to_integer(value, set_id);
5851 RegisterSetMap::const_iterator pos =
5852 target_info.reg_set_map.find(set_id);
5853 if (pos != target_info.reg_set_map.end())
5854 reg_info.set_name = pos->second.name;
5855 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
5856 llvm::to_integer(value, reg_info.regnum_ehframe);
5857 } else if (name == "dwarf_regnum") {
5858 llvm::to_integer(value, reg_info.regnum_dwarf);
5859 } else if (name == "generic") {
5861 } else if (name == "value_regnums") {
5863 0);
5864 } else if (name == "invalidate_regnums") {
5866 value, reg_info.invalidate_regs, 0);
5867 } else {
5868 LLDB_LOGF(log,
5869 "ProcessGDBRemote::ParseRegisters unhandled reg "
5870 "attribute %s = %s",
5871 name.data(), value.data());
5872 }
5873 return true; // Keep iterating through all attributes
5874 });
5875
5876 if (!gdb_type.empty()) {
5877 // gdb_type could reference a type defined in this feature.
5878 auto it = feature_register_types.find(gdb_type);
5879 if (it != feature_register_types.end()) {
5880 if (const auto *vector_type =
5881 llvm::dyn_cast<RegisterTypeVector>(it->second)) {
5882 std::optional<uint64_t> type_size = vector_type->GetByteSize();
5884 LLDB_LOG(log,
5885 "ProcessGDBRemote::ParseRegisters Register {0} is "
5886 "too large for vector type {1}",
5887 reg_info.name, vector_type->GetID());
5888 } else if (!vector_type->IsByteSizeCompatible(
5889 reg_info.byte_size)) {
5890 if (!type_size) {
5891 LLDB_LOG(log,
5892 "ProcessGDBRemote::ParseRegisters Size of register "
5893 "{0} is incompatible with vector type {1}",
5894 reg_info.name, vector_type->GetID());
5895 } else {
5896 LLDB_LOG(
5897 log,
5898 "ProcessGDBRemote::ParseRegisters Size of register type "
5899 "{0} ({1} bytes) for register {2} does not match the "
5900 "register size ({3} bytes). Ignoring this type.",
5901 vector_type->GetID(), *type_size, reg_info.name,
5902 reg_info.byte_size);
5903 }
5904 } else {
5905 reg_info.register_type = vector_type;
5906 if (!encoding_set) {
5907 reg_info.encoding = eEncodingVector;
5908 encoding_set = true;
5909 }
5910 if (!format_set) {
5911 reg_info.format = eFormatVectorOfUInt8;
5912 format_set = true;
5913 }
5914 }
5915 } else if (const auto *union_type =
5916 llvm::dyn_cast<RegisterTypeUnion>(it->second)) {
5918 LLDB_LOG(log,
5919 "ProcessGDBRemote::ParseRegisters Register {0} is "
5920 "too large for union type {1}",
5921 reg_info.name, union_type->GetID());
5922 } else if (!union_type->IsByteSizeCompatible(
5923 reg_info.byte_size)) {
5924 LLDB_LOG(log,
5925 "ProcessGDBRemote::ParseRegisters Size of register "
5926 "{0} is incompatible with union type {1}",
5927 reg_info.name, union_type->GetID());
5928 } else {
5929 reg_info.register_type = union_type;
5930 if (!encoding_set) {
5931 reg_info.encoding = eEncodingUint;
5932 encoding_set = true;
5933 }
5934 if (!format_set) {
5935 reg_info.format = eFormatHex;
5936 format_set = true;
5937 }
5938 }
5939 } else if (const auto *flags_type =
5940 llvm::dyn_cast<RegisterTypeFlags>(it->second)) {
5941 if (reg_info.byte_size == flags_type->GetSize())
5942 reg_info.register_type = flags_type;
5943 else
5944 LLDB_LOG(
5945 log,
5946 "ProcessGDBRemote::ParseRegisters Size of register flags "
5947 "{0} ({1} bytes) for register {2} does not match the "
5948 "register size ({3} bytes). Ignoring this set of flags.",
5949 flags_type->GetID().c_str(), flags_type->GetSize(),
5950 reg_info.name, reg_info.byte_size);
5951 }
5952 }
5953
5954 // There's a slim chance that the gdb_type name is both a flags type
5955 // and a simple type. Just in case, look for that too (setting both
5956 // does no harm).
5957 if (!gdb_type.empty() && !(encoding_set || format_set)) {
5958 if (llvm::StringRef(gdb_type).starts_with("int")) {
5959 reg_info.format = eFormatHex;
5960 reg_info.encoding = eEncodingUint;
5961 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
5962 reg_info.format = eFormatAddressInfo;
5963 reg_info.encoding = eEncodingUint;
5964 } else if (gdb_type == "float" || gdb_type == "ieee_single" ||
5965 gdb_type == "ieee_double") {
5966 reg_info.format = eFormatFloat;
5967 reg_info.encoding = eEncodingIEEE754;
5968 } else if (gdb_type == "aarch64v" ||
5969 llvm::StringRef(gdb_type).starts_with("vec") ||
5970 gdb_type == "i387_ext" || gdb_type == "uint128" ||
5971 reg_info.byte_size > 16) {
5972 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
5973 // treat them as vector (similarly to xmm/ymm).
5974 // We can fall back to handling anything else <= 128 bit as an
5975 // unsigned integer, more than that, call it a vector of bytes.
5976 // This can happen if we don't recognise the type for AArc64 SVE
5977 // registers.
5978 reg_info.format = eFormatVectorOfUInt8;
5979 reg_info.encoding = eEncodingVector;
5980 } else {
5981 LLDB_LOGF(
5982 log,
5983 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
5984 "format and encoding for gdb type %s",
5985 gdb_type.c_str());
5986 }
5987 }
5988 }
5989
5990 // Only update the register set name if we didn't get a "reg_set"
5991 // attribute. "set_name" will be empty if we didn't have a "reg_set"
5992 // attribute.
5993 if (!reg_info.set_name) {
5994 if (!gdb_group.empty()) {
5995 reg_info.set_name.SetCString(gdb_group.c_str());
5996 } else {
5997 // If no register group name provided anywhere,
5998 // we'll create a 'general' register set
5999 reg_info.set_name.SetCString("general");
6000 }
6001 }
6002
6003 if (reg_info.byte_size == 0) {
6004 LLDB_LOG(log,
6005 "ProcessGDBRemote::{0} Skipping zero bitsize register {1}",
6006 __FUNCTION__, reg_info.name);
6007 } else
6008 registers.push_back(reg_info);
6009
6010 return true; // Keep iterating through all "reg" elements
6011 });
6012 return true;
6013}
6014
6015} // namespace
6016
6017// This method fetches a register description feature xml file from
6018// the remote stub and adds registers/register groupsets/architecture
6019// information to the current process. It will call itself recursively
6020// for nested register definition files. It returns true if it was able
6021// to fetch and parse an xml file.
6023 ArchSpec &arch_to_use, std::string xml_filename,
6024 std::vector<DynamicRegisterInfo::Register> &registers) {
6025 // request the target xml file
6026 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
6027 if (errorToBool(raw.takeError()))
6028 return false;
6029
6030 XMLDocument xml_document;
6031
6032 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
6033 xml_filename.c_str())) {
6034 GdbServerTargetInfo target_info;
6035 std::vector<XMLNode> feature_nodes;
6036
6037 // The top level feature XML file will start with a <target> tag.
6038 XMLNode target_node = xml_document.GetRootElement("target");
6039 if (target_node) {
6040 target_node.ForEachChildElement([&target_info, &feature_nodes](
6041 const XMLNode &node) -> bool {
6042 llvm::StringRef name = node.GetName();
6043 if (name == "architecture") {
6044 node.GetElementText(target_info.arch);
6045 } else if (name == "osabi") {
6046 node.GetElementText(target_info.osabi);
6047 } else if (name == "xi:include" || name == "include") {
6048 std::string href = node.GetAttributeValue("href");
6049 if (!href.empty())
6050 target_info.includes.push_back(href);
6051 } else if (name == "feature") {
6052 feature_nodes.push_back(node);
6053 } else if (name == "groups") {
6055 "group", [&target_info](const XMLNode &node) -> bool {
6056 uint32_t set_id = UINT32_MAX;
6057 RegisterSetInfo set_info;
6058
6059 node.ForEachAttribute(
6060 [&set_id, &set_info](const llvm::StringRef &name,
6061 const llvm::StringRef &value) -> bool {
6062 // FIXME: we're silently ignoring invalid data here
6063 if (name == "id")
6064 llvm::to_integer(value, set_id);
6065 if (name == "name")
6066 set_info.name = ConstString(value);
6067 return true; // Keep iterating through all attributes
6068 });
6069
6070 if (set_id != UINT32_MAX)
6071 target_info.reg_set_map[set_id] = set_info;
6072 return true; // Keep iterating through all "group" elements
6073 });
6074 }
6075 return true; // Keep iterating through all children of the target_node
6076 });
6077 } else {
6078 // In an included XML feature file, we're already "inside" the <target>
6079 // tag of the initial XML file; this included file will likely only have
6080 // a <feature> tag. Need to check for any more included files in this
6081 // <feature> element.
6082 XMLNode feature_node = xml_document.GetRootElement("feature");
6083 if (feature_node) {
6084 feature_nodes.push_back(feature_node);
6085 feature_node.ForEachChildElement([&target_info](
6086 const XMLNode &node) -> bool {
6087 llvm::StringRef name = node.GetName();
6088 if (name == "xi:include" || name == "include") {
6089 std::string href = node.GetAttributeValue("href");
6090 if (!href.empty())
6091 target_info.includes.push_back(href);
6092 }
6093 return true;
6094 });
6095 }
6096 }
6097
6098 // gdbserver does not implement the LLDB packets used to determine host
6099 // or process architecture. If that is the case, attempt to use
6100 // the <architecture/> field from target.xml, e.g.:
6101 //
6102 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
6103 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
6104 // arm board)
6105 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
6106 // We don't have any information about vendor or OS.
6107 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
6108 .Case("i386:x86-64", "x86_64")
6109 .Case("riscv:rv64", "riscv64")
6110 .Case("riscv:rv32", "riscv32")
6111 .Default(target_info.arch) +
6112 "--");
6113
6114 if (arch_to_use.IsValid())
6115 GetTarget().MergeArchitecture(arch_to_use);
6116 }
6117
6118 if (arch_to_use.IsValid()) {
6119 for (auto &feature_node : feature_nodes) {
6120 ParseRegisters(feature_node, target_info, registers, m_register_types);
6121 }
6122
6123 for (const auto &include : target_info.includes) {
6124 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
6125 registers);
6126 }
6127 }
6128 } else {
6129 return false;
6130 }
6131 return true;
6132}
6133
6135 std::vector<DynamicRegisterInfo::Register> &registers,
6136 const ArchSpec &arch_to_use) {
6137 std::map<uint32_t, uint32_t> remote_to_local_map;
6138 uint32_t remote_regnum = 0;
6139 for (auto it : llvm::enumerate(registers)) {
6140 DynamicRegisterInfo::Register &remote_reg_info = it.value();
6141
6142 // Assign successive remote regnums if missing.
6143 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
6144 remote_reg_info.regnum_remote = remote_regnum;
6145
6146 // Create a mapping from remote to local regnos.
6147 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
6148
6149 remote_regnum = remote_reg_info.regnum_remote + 1;
6150 }
6151
6152 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
6153 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
6154 auto lldb_regit = remote_to_local_map.find(process_regnum);
6155 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
6157 };
6158
6159 llvm::transform(remote_reg_info.value_regs,
6160 remote_reg_info.value_regs.begin(), proc_to_lldb);
6161 llvm::transform(remote_reg_info.invalidate_regs,
6162 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
6163 }
6164
6165 // Don't use Process::GetABI, this code gets called from DidAttach, and
6166 // in that context we haven't set the Target's architecture yet, so the
6167 // ABI is also potentially incorrect.
6168 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
6169 abi_sp->AugmentRegisterInfo(registers);
6170
6171 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
6172}
6173
6174// query the target of gdb-remote for extended target information returns
6175// true on success (got register definitions), false on failure (did not).
6177 // If the remote does not offer XML, does not matter if we would have been
6178 // able to parse it.
6179 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
6180 return llvm::createStringError(
6181 llvm::inconvertibleErrorCode(),
6182 "the debug server does not support \"qXfer:features:read\"");
6183
6185 return llvm::createStringError(
6186 llvm::inconvertibleErrorCode(),
6187 "the debug server supports \"qXfer:features:read\", but LLDB does not "
6188 "have XML parsing enabled (check LLLDB_ENABLE_LIBXML2)");
6189
6190 std::vector<DynamicRegisterInfo::Register> registers;
6191 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
6192 registers) &&
6193 // Target XML is not required to include register information.
6194 !registers.empty())
6195 AddRemoteRegisters(registers, arch_to_use);
6196
6197 return m_register_info_sp->GetNumRegisters() > 0
6198 ? llvm::ErrorSuccess()
6199 : llvm::createStringError(
6200 llvm::inconvertibleErrorCode(),
6201 "the debug server did not describe any registers");
6202}
6203
6204llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
6205 // Make sure LLDB has an XML parser it can use first
6207 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6208 "XML parsing not available");
6209
6210 Log *log = GetLog(LLDBLog::Process);
6211 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
6212
6215 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
6216
6217 // check that we have extended feature read support
6218 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
6219 // request the loaded library list
6220 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
6221 if (!raw)
6222 return raw.takeError();
6223
6224 // parse the xml file in memory
6225 LLDB_LOGF(log, "parsing: %s", raw->c_str());
6226 XMLDocument doc;
6227
6228 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
6229 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6230 "Error reading noname.xml");
6231
6232 XMLNode root_element = doc.GetRootElement("library-list-svr4");
6233 if (!root_element)
6234 return llvm::createStringError(
6235 llvm::inconvertibleErrorCode(),
6236 "Error finding library-list-svr4 xml element");
6237
6238 // main link map structure
6239 std::string main_lm = root_element.GetAttributeValue("main-lm");
6240 // FIXME: we're silently ignoring invalid data here
6241 if (!main_lm.empty())
6242 llvm::to_integer(main_lm, list.m_link_map);
6243
6244 root_element.ForEachChildElementWithName(
6245 "library", [log, &list](const XMLNode &library) -> bool {
6247
6248 // FIXME: we're silently ignoring invalid data here
6249 library.ForEachAttribute(
6250 [&module](const llvm::StringRef &name,
6251 const llvm::StringRef &value) -> bool {
6252 uint64_t uint_value = LLDB_INVALID_ADDRESS;
6253 if (name == "name")
6254 module.set_name(value.str());
6255 else if (name == "lm") {
6256 // the address of the link_map struct.
6257 llvm::to_integer(value, uint_value);
6258 module.set_link_map(uint_value);
6259 } else if (name == "l_addr") {
6260 // the displacement as read from the field 'l_addr' of the
6261 // link_map struct.
6262 llvm::to_integer(value, uint_value);
6263 module.set_base(uint_value);
6264 // base address is always a displacement, not an absolute
6265 // value.
6266 module.set_base_is_offset(true);
6267 } else if (name == "l_ld") {
6268 // the memory address of the libraries PT_DYNAMIC section.
6269 llvm::to_integer(value, uint_value);
6270 module.set_dynamic(uint_value);
6271 }
6272
6273 return true; // Keep iterating over all properties of "library"
6274 });
6275
6276 if (log) {
6277 std::string name;
6278 lldb::addr_t lm = 0, base = 0, ld = 0;
6279 bool base_is_offset;
6280
6281 module.get_name(name);
6282 module.get_link_map(lm);
6283 module.get_base(base);
6284 module.get_base_is_offset(base_is_offset);
6285 module.get_dynamic(ld);
6286
6287 LLDB_LOGF(log,
6288 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
6289 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
6290 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
6291 name.c_str());
6292 }
6293
6294 list.add(module);
6295 return true; // Keep iterating over all "library" elements in the root
6296 // node
6297 });
6298
6299 LLDB_LOGF(log, "found %" PRId32 " modules in total",
6300 (int)list.m_list.size());
6301 return list;
6302 } else if (comm.GetQXferLibrariesReadSupported()) {
6303 // request the loaded library list
6304 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
6305
6306 if (!raw)
6307 return raw.takeError();
6308
6309 LLDB_LOGF(log, "parsing: %s", raw->c_str());
6310 XMLDocument doc;
6311
6312 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
6313 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6314 "Error reading noname.xml");
6315
6316 XMLNode root_element = doc.GetRootElement("library-list");
6317 if (!root_element)
6318 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6319 "Error finding library-list xml element");
6320
6321 // FIXME: we're silently ignoring invalid data here
6322 root_element.ForEachChildElementWithName(
6323 "library", [log, &list](const XMLNode &library) -> bool {
6325
6326 std::string name = library.GetAttributeValue("name");
6327 module.set_name(name);
6328
6329 // The base address of a given library will be the address of its
6330 // first section. Most remotes send only one section for Windows
6331 // targets for example.
6332 const XMLNode &section =
6333 library.FindFirstChildElementWithName("section");
6334 std::string address = section.GetAttributeValue("address");
6335 uint64_t address_value = LLDB_INVALID_ADDRESS;
6336 llvm::to_integer(address, address_value);
6337 module.set_base(address_value);
6338 // These addresses are absolute values.
6339 module.set_base_is_offset(false);
6340
6341 if (log) {
6342 std::string name;
6343 lldb::addr_t base = 0;
6344 bool base_is_offset;
6345 module.get_name(name);
6346 module.get_base(base);
6347 module.get_base_is_offset(base_is_offset);
6348
6349 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
6350 (base_is_offset ? "offset" : "absolute"), name.c_str());
6351 }
6352
6353 list.add(module);
6354 return true; // Keep iterating over all "library" elements in the root
6355 // node
6356 });
6357
6358 LLDB_LOGF(log, "found %" PRId32 " modules in total",
6359 (int)list.m_list.size());
6360 return list;
6361 } else {
6362 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6363 "Remote libraries not supported");
6364 }
6365}
6366
6368 lldb::addr_t link_map,
6369 lldb::addr_t base_addr,
6370 bool value_is_offset) {
6371 DynamicLoader *loader = GetDynamicLoader();
6372 if (!loader)
6373 return nullptr;
6374
6375 return loader->LoadModuleAtAddress(file, link_map, base_addr,
6376 value_is_offset);
6377}
6378
6381
6382 // request a list of loaded libraries from GDBServer
6383 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
6384 if (!module_list)
6385 return module_list.takeError();
6386
6387 // get a list of all the modules
6388 ModuleList new_modules;
6389
6390 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
6391 std::string mod_name;
6392 lldb::addr_t mod_base;
6393 lldb::addr_t link_map;
6394 bool mod_base_is_offset;
6395
6396 bool valid = true;
6397 valid &= modInfo.get_name(mod_name);
6398 valid &= modInfo.get_base(mod_base);
6399 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
6400 if (!valid)
6401 continue;
6402
6403 if (!modInfo.get_link_map(link_map))
6404 link_map = LLDB_INVALID_ADDRESS;
6405
6406 FileSpec file(mod_name);
6408 lldb::ModuleSP module_sp =
6409 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
6410
6411 if (module_sp.get())
6412 new_modules.Append(module_sp);
6413 }
6414
6415 if (new_modules.GetSize() > 0) {
6416 ModuleList removed_modules;
6417 Target &target = GetTarget();
6418 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
6419
6420 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
6421 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
6422
6423 bool found = false;
6424 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
6425 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
6426 found = true;
6427 }
6428
6429 // The main executable will never be included in libraries-svr4, don't
6430 // remove it
6431 if (!found &&
6432 loaded_module.get() != target.GetExecutableModulePointer()) {
6433 removed_modules.Append(loaded_module);
6434 }
6435 }
6436
6437 loaded_modules.Remove(removed_modules);
6438 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
6439
6440 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) {
6441 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
6442 if (!obj)
6444
6447
6448 if (target.GetExecutableModulePointer() == module_sp.get())
6449 return IterationAction::Stop;
6450
6451 lldb::ModuleSP module_copy_sp = module_sp;
6452 target.RebuildModuleListWithExecutable(module_copy_sp, eLoadDependentsNo);
6453 return IterationAction::Stop;
6454 });
6455
6456 loaded_modules.AppendIfNeeded(new_modules);
6457 m_process->GetTarget().ModulesDidLoad(new_modules);
6458 }
6459
6460 return llvm::ErrorSuccess();
6461}
6462
6464 bool &is_loaded,
6465 lldb::addr_t &load_addr) {
6466 is_loaded = false;
6467 load_addr = LLDB_INVALID_ADDRESS;
6468
6469 std::string file_path = file.GetPath(false);
6470 if (file_path.empty())
6471 return Status::FromErrorString("Empty file name specified");
6472
6473 StreamString packet;
6474 packet.PutCString("qFileLoadAddress:");
6475 packet.PutStringAsRawHex8(file_path);
6476
6477 StringExtractorGDBRemote response;
6478 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
6480 return Status::FromErrorString("Sending qFileLoadAddress packet failed");
6481
6482 if (response.IsErrorResponse()) {
6483 if (response.GetError() == 1) {
6484 // The file is not loaded into the inferior
6485 is_loaded = false;
6486 load_addr = LLDB_INVALID_ADDRESS;
6487 return Status();
6488 }
6489
6491 "Fetching file load address from remote server returned an error");
6492 }
6493
6494 if (response.IsNormalResponse()) {
6495 is_loaded = true;
6496 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
6497 return Status();
6498 }
6499
6501 "Unknown error happened during sending the load address packet");
6502}
6503
6505 // We must call the lldb_private::Process::ModulesDidLoad () first before we
6506 // do anything
6507 Process::ModulesDidLoad(module_list);
6508
6509 // After loading shared libraries, we can ask our remote GDB server if it
6510 // needs any symbols.
6511 m_gdb_comm.ServeSymbolLookups(this);
6512}
6513
6514void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
6515 AppendSTDOUT(out.data(), out.size());
6516}
6517
6518static const char *end_delimiter = "--end--;";
6519static const int end_delimiter_len = 8;
6520
6521void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
6522 std::string input = data.str(); // '1' to move beyond 'A'
6523 if (m_partial_profile_data.length() > 0) {
6524 m_partial_profile_data.append(input);
6525 input = m_partial_profile_data;
6526 m_partial_profile_data.clear();
6527 }
6528
6529 size_t found, pos = 0, len = input.length();
6530 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
6531 StringExtractorGDBRemote profileDataExtractor(
6532 input.substr(pos, found).c_str());
6533 std::string profile_data =
6534 HarmonizeThreadIdsForProfileData(profileDataExtractor);
6535 BroadcastAsyncProfileData(profile_data);
6536
6537 pos = found + end_delimiter_len;
6538 }
6539
6540 if (pos < len) {
6541 // Last incomplete chunk.
6542 m_partial_profile_data = input.substr(pos);
6543 }
6544}
6545
6547 StringExtractorGDBRemote &profileDataExtractor) {
6548 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
6549 std::string output;
6550 llvm::raw_string_ostream output_stream(output);
6551 llvm::StringRef name, value;
6552
6553 // Going to assuming thread_used_usec comes first, else bail out.
6554 while (profileDataExtractor.GetNameColonValue(name, value)) {
6555 if (name.compare("thread_used_id") == 0) {
6556 StringExtractor threadIDHexExtractor(value);
6557 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
6558
6559 bool has_used_usec = false;
6560 uint32_t curr_used_usec = 0;
6561 llvm::StringRef usec_name, usec_value;
6562 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
6563 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
6564 if (usec_name == "thread_used_usec") {
6565 has_used_usec = true;
6566 usec_value.getAsInteger(BASE_10, curr_used_usec);
6567 } else {
6568 // We didn't find what we want, it is probably an older version. Bail
6569 // out.
6570 profileDataExtractor.SetFilePos(input_file_pos);
6571 }
6572 }
6573
6574 if (has_used_usec) {
6575 uint32_t prev_used_usec = 0;
6576 std::map<uint64_t, uint32_t>::iterator iterator =
6577 m_thread_id_to_used_usec_map.find(thread_id);
6578 if (iterator != m_thread_id_to_used_usec_map.end())
6579 prev_used_usec = iterator->second;
6580
6581 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
6582 // A good first time record is one that runs for at least 0.25 sec
6583 bool good_first_time =
6584 (prev_used_usec == 0) && (real_used_usec > 250000);
6585 bool good_subsequent_time =
6586 (prev_used_usec > 0) &&
6587 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
6588
6589 if (good_first_time || good_subsequent_time) {
6590 // We try to avoid doing too many index id reservation, resulting in
6591 // fast increase of index ids.
6592
6593 output_stream << name << ":";
6594 int32_t index_id = AssignIndexIDToThread(thread_id);
6595 output_stream << index_id << ";";
6596
6597 output_stream << usec_name << ":" << usec_value << ";";
6598 } else {
6599 // Skip past 'thread_used_name'.
6600 llvm::StringRef local_name, local_value;
6601 profileDataExtractor.GetNameColonValue(local_name, local_value);
6602 }
6603
6604 // Store current time as previous time so that they can be compared
6605 // later.
6606 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
6607 } else {
6608 // Bail out and use old string.
6609 output_stream << name << ":" << value << ";";
6610 }
6611 } else {
6612 output_stream << name << ":" << value << ";";
6613 }
6614 }
6615 output_stream << end_delimiter;
6616 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
6617
6618 return output;
6619}
6620
6622 if (GetStopID() != 0)
6623 return;
6624
6625 if (GetID() == LLDB_INVALID_PROCESS_ID) {
6626 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
6627 if (pid != LLDB_INVALID_PROCESS_ID)
6628 SetID(pid);
6629 }
6631}
6632
6633llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
6634 if (!m_gdb_comm.GetSaveCoreSupported())
6635 return false;
6636
6637 StreamString packet;
6638 packet.PutCString("qSaveCore;path-hint:");
6639 packet.PutStringAsRawHex8(outfile);
6640
6641 StringExtractorGDBRemote response;
6642 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
6644 // TODO: grab error message from the packet? StringExtractor seems to
6645 // be missing a method for that
6646 if (response.IsErrorResponse())
6647 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6648 "qSaveCore returned an error");
6649
6650 std::string path;
6651
6652 // process the response
6653 for (auto x : llvm::split(response.GetStringRef(), ';')) {
6654 if (x.consume_front("core-path:"))
6656 }
6657
6658 // verify that we've gotten what we need
6659 if (path.empty())
6660 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6661 "qSaveCore returned no core path");
6662
6663 // now transfer the core file
6664 FileSpec remote_core{llvm::StringRef(path)};
6665 Platform &platform = *GetTarget().GetPlatform();
6666 Status error = platform.GetFile(remote_core, FileSpec(outfile));
6667
6668 if (platform.IsRemote()) {
6669 // NB: we unlink the file on error too
6670 platform.Unlink(remote_core);
6671 if (error.Fail())
6672 return error.ToError();
6673 }
6674
6675 return true;
6676 }
6677
6678 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6679 "Unable to send qSaveCore");
6680}
6681
6682static const char *const s_async_json_packet_prefix = "JSON-async:";
6683
6685ParseStructuredDataPacket(llvm::StringRef packet) {
6686 Log *log = GetLog(GDBRLog::Process);
6687
6688 if (!packet.consume_front(s_async_json_packet_prefix)) {
6689 LLDB_LOGF(
6690 log,
6691 "GDBRemoteCommunicationClientBase::%s() received $J packet "
6692 "but was not a StructuredData packet: packet starts with "
6693 "%s",
6694 __FUNCTION__,
6695 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
6696 return StructuredData::ObjectSP();
6697 }
6698
6699 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
6701 if (log) {
6702 if (json_sp) {
6703 StreamString json_str;
6704 json_sp->Dump(json_str, true);
6705 json_str.Flush();
6706 LLDB_LOGF(log,
6707 "ProcessGDBRemote::%s() "
6708 "received Async StructuredData packet: %s",
6709 __FUNCTION__, json_str.GetData());
6710 } else {
6711 LLDB_LOGF(log,
6712 "ProcessGDBRemote::%s"
6713 "() received StructuredData packet:"
6714 " parse failure",
6715 __FUNCTION__);
6716 }
6717 }
6718 return json_sp;
6719}
6720
6722 auto structured_data_sp = ParseStructuredDataPacket(data);
6723 if (structured_data_sp)
6724 RouteAsyncStructuredData(structured_data_sp);
6725}
6726
6728public:
6730 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
6731 "Tests packet speeds of various sizes to determine "
6732 "the performance characteristics of the GDB remote "
6733 "connection. ",
6734 nullptr),
6736 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
6737 "The number of packets to send of each varying size "
6738 "(default is 1000).",
6739 1000),
6740 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
6741 "The maximum number of bytes to send in a packet. Sizes "
6742 "increase in powers of 2 while the size is less than or "
6743 "equal to this option value. (default 1024).",
6744 1024),
6745 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
6746 "The maximum number of bytes to receive in a packet. Sizes "
6747 "increase in powers of 2 while the size is less than or "
6748 "equal to this option value. (default 1024).",
6749 1024),
6750 m_json(LLDB_OPT_SET_1, false, "json", 'j',
6751 "Print the output as JSON data for easy parsing.", false, true) {
6756 m_option_group.Finalize();
6757 }
6758
6760
6761 Options *GetOptions() override { return &m_option_group; }
6762
6763 void DoExecute(Args &command, CommandReturnObject &result) override {
6764 const size_t argc = command.GetArgumentCount();
6765 if (argc == 0) {
6766 ProcessGDBRemote *process =
6767 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
6768 .GetProcessPtr();
6769 if (process) {
6770 StreamSP output_stream_sp = result.GetImmediateOutputStream();
6771 if (!output_stream_sp)
6772 output_stream_sp = m_interpreter.GetDebugger().GetAsyncOutputStream();
6773 result.SetImmediateOutputStream(output_stream_sp);
6774
6775 const uint32_t num_packets =
6776 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
6777 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
6778 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
6779 const bool json = m_json.GetOptionValue().GetCurrentValue();
6780 const uint64_t k_recv_amount =
6781 4 * 1024 * 1024; // Receive amount in bytes
6782 process->GetGDBRemote().TestPacketSpeed(
6783 num_packets, max_send, max_recv, k_recv_amount, json,
6784 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
6786 return;
6787 }
6788 } else {
6789 result.AppendErrorWithFormat("'%s' takes no arguments",
6790 m_cmd_name.c_str());
6791 }
6793 }
6794
6795protected:
6801};
6802
6804private:
6805public:
6807 : CommandObjectParsed(interpreter, "process plugin packet history",
6808 "Dumps the packet history buffer. ", nullptr) {}
6809
6811
6812 void DoExecute(Args &command, CommandReturnObject &result) override {
6813 ProcessGDBRemote *process =
6814 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6815 if (process) {
6816 process->DumpPluginHistory(result.GetOutputStream());
6818 return;
6819 }
6821 }
6822};
6823
6825private:
6826public:
6829 interpreter, "process plugin packet xfer-size",
6830 "Maximum size that lldb will try to read/write one one chunk.",
6831 nullptr) {
6833 }
6834
6836
6837 void DoExecute(Args &command, CommandReturnObject &result) override {
6838 const size_t argc = command.GetArgumentCount();
6839 if (argc == 0) {
6840 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
6841 "amount to be transferred when "
6842 "reading/writing",
6843 m_cmd_name.c_str());
6844 return;
6845 }
6846
6847 ProcessGDBRemote *process =
6848 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6849 if (process) {
6850 const char *packet_size = command.GetArgumentAtIndex(0);
6851 errno = 0;
6852 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
6853 if (errno == 0 && user_specified_max != 0) {
6854 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
6856 return;
6857 }
6858 }
6860 }
6861};
6862
6864private:
6865public:
6867 : CommandObjectParsed(interpreter, "process plugin packet send",
6868 "Send a custom packet through the GDB remote "
6869 "protocol and print the answer. "
6870 "The packet header and footer will automatically "
6871 "be added to the packet prior to sending and "
6872 "stripped from the result.",
6873 nullptr) {
6875 }
6876
6878
6879 void DoExecute(Args &command, CommandReturnObject &result) override {
6880 const size_t argc = command.GetArgumentCount();
6881 if (argc == 0) {
6882 result.AppendErrorWithFormat(
6883 "'%s' takes a one or more packet content arguments",
6884 m_cmd_name.c_str());
6885 return;
6886 }
6887
6888 ProcessGDBRemote *process =
6889 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6890 if (process) {
6891 for (size_t i = 0; i < argc; ++i) {
6892 const char *packet_cstr = command.GetArgumentAtIndex(0);
6893 StringExtractorGDBRemote response;
6895 packet_cstr, response, process->GetInterruptTimeout());
6897 Stream &output_strm = result.GetOutputStream();
6898 output_strm.Printf(" packet: %s\n", packet_cstr);
6899 std::string response_str = std::string(response.GetStringRef());
6900
6901 if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
6902 response_str = process->HarmonizeThreadIdsForProfileData(response);
6903 }
6904
6905 if (response_str.empty())
6906 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6907 else
6908 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6909 }
6910 }
6911 }
6912};
6913
6915private:
6916public:
6918 : CommandObjectRaw(interpreter, "process plugin packet monitor",
6919 "Send a qRcmd packet through the GDB remote protocol "
6920 "and print the response. "
6921 "The argument passed to this command will be hex "
6922 "encoded into a valid 'qRcmd' packet, sent and the "
6923 "response will be printed.") {}
6924
6926
6927 void DoExecute(llvm::StringRef command,
6928 CommandReturnObject &result) override {
6929 if (command.empty()) {
6930 result.AppendErrorWithFormat("'%s' takes a command string argument",
6931 m_cmd_name.c_str());
6932 return;
6933 }
6934
6935 ProcessGDBRemote *process =
6936 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6937 if (process) {
6938 StreamString packet;
6939 packet.PutCString("qRcmd,");
6940 packet.PutBytesAsRawHex8(command.data(), command.size());
6941
6942 StringExtractorGDBRemote response;
6943 Stream &output_strm = result.GetOutputStream();
6945 packet.GetString(), response, process->GetInterruptTimeout(),
6946 [&output_strm](llvm::StringRef output) { output_strm << output; });
6948 output_strm.Printf(" packet: %s\n", packet.GetData());
6949 const std::string &response_str = std::string(response.GetStringRef());
6950
6951 if (response_str.empty())
6952 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6953 else
6954 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6955 }
6956 }
6957};
6958
6960private:
6961public:
6963 : CommandObjectMultiword(interpreter, "process plugin packet",
6964 "Commands that deal with GDB remote packets.",
6965 nullptr) {
6967 "history",
6971 "send", CommandObjectSP(
6972 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
6974 "monitor",
6978 "xfer-size",
6981 LoadSubCommand("speed-test",
6983 interpreter)));
6984 }
6985
6987};
6988
6990public:
6993 interpreter, "process plugin",
6994 "Commands for operating on a ProcessGDBRemote process.",
6995 "process plugin <subcommand> [<subcommand-options>]") {
6997 "packet",
6999 }
7000
7002};
7003
7005 if (!m_command_sp)
7006 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
7007 GetTarget().GetDebugger().GetCommandInterpreter());
7008 return m_command_sp.get();
7009}
7010
7012 bool enable, bool is_expression_fork) {
7013 Log *log = GetLog(GDBRLog::Process);
7014
7015 // Resolve the expression-return sentinel address (_start) once. This is
7016 // the same address ThreadPlanCallFunction uses as the return trap.
7018 if (!enable && is_expression_fork) {
7019 if (auto entry = GetTarget().GetEntryPointAddress())
7020 entry_addr = entry->GetOpcodeLoadAddress(&GetTarget());
7021 }
7022
7023 GetBreakpointSiteList().ForEach([this, enable, entry_addr,
7024 log](BreakpointSite *bp_site) {
7025 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
7026 (bp_site->GetType() == BreakpointSite::eSoftware ||
7027 bp_site->GetType() == BreakpointSite::eExternal)) {
7028 // During expression evaluation, retain the expression-return trap
7029 // at _start in the forked child so it dies deterministically on
7030 // SIGTRAP rather than executing _start with a corrupted stack.
7031 if (entry_addr != LLDB_INVALID_ADDRESS &&
7032 bp_site->GetLoadAddress() == entry_addr) {
7033 LLDB_LOG(log,
7034 "DidForkSwitchSoftwareBreakpoints: retaining expression-"
7035 "return trap at {0:x} in forked child",
7036 bp_site->GetLoadAddress());
7037 return;
7038 }
7039 m_gdb_comm.SendGDBStoppointTypePacket(
7040 eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
7042 }
7043 });
7044}
7045
7047 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
7048 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
7049 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
7050 bp_site->GetType() == BreakpointSite::eHardware) {
7051 m_gdb_comm.SendGDBStoppointTypePacket(
7052 eBreakpointHardware, enable, bp_site->GetLoadAddress(),
7054 }
7055 });
7056 }
7057
7058 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
7059 addr_t addr = wp_res_sp->GetLoadAddress();
7060 size_t size = wp_res_sp->GetByteSize();
7061 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
7062 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, addr, size,
7064 }
7065}
7066
7068 bool is_expression_fork) {
7069 Log *log = GetLog(GDBRLog::Process);
7070
7071 // During expression evaluation, force follow-parent regardless of which
7072 // thread forked. The expression is running on the parent and following the
7073 // child would cause the expression thread to vanish (the child has different
7074 // thread IDs). Even if a *different* thread forks, switching to the child
7075 // would destroy the expression thread's process context.
7076 FollowForkMode follow_fork_mode = GetFollowForkMode();
7077 bool overrode_follow_mode = false;
7078 if (follow_fork_mode == eFollowChild &&
7079 GetModIDRef().IsRunningExpression()) {
7080 if (is_expression_fork) {
7081 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
7082 "to parent during expression evaluation");
7083 } else {
7084 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
7085 "to parent during expression evaluation. Child process "
7086 "{0} is available for manual attachment.",
7087 child_pid);
7088 }
7089 follow_fork_mode = eFollowParent;
7090 overrode_follow_mode = true;
7091 }
7092
7093 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
7094 // Any valid TID will suffice, thread-relevant actions will set a proper TID
7095 // anyway.
7096 lldb::tid_t parent_tid = m_thread_ids.front();
7097
7098 lldb::pid_t follow_pid, detach_pid;
7099 lldb::tid_t follow_tid, detach_tid;
7100
7101 switch (follow_fork_mode) {
7102 case eFollowParent:
7103 follow_pid = parent_pid;
7104 follow_tid = parent_tid;
7105 detach_pid = child_pid;
7106 detach_tid = child_tid;
7107 break;
7108 case eFollowChild:
7109 follow_pid = child_pid;
7110 follow_tid = child_tid;
7111 detach_pid = parent_pid;
7112 detach_tid = parent_tid;
7113 break;
7114 }
7115
7116 // Switch to the process that is going to be detached.
7117 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
7118 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
7119 return;
7120 }
7121
7122 // Disable all software breakpoints in the forked process.
7123 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7124 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
7125
7126 // Remove hardware breakpoints / watchpoints from parent process if we're
7127 // following child.
7128 if (follow_fork_mode == eFollowChild)
7130
7131 // Switch to the process that is going to be followed
7132 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
7133 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
7134 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
7135 return;
7136 }
7137
7138 LLDB_LOG(log, "Detaching process {0}", detach_pid);
7139 // When we overrode follow-child because of a concurrent expression, try to
7140 // keep the child stopped so the user can attach to it manually.
7141 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
7142 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
7143 if (error.Fail() && keep_stopped) {
7144 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach-and-stay-stopped not "
7145 "supported, falling back to normal detach");
7146 keep_stopped = false;
7147 error = m_gdb_comm.Detach(false, detach_pid);
7148 }
7149 if (error.Fail()) {
7150 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
7151 error.AsCString() ? error.AsCString() : "<unknown error>");
7152 return;
7153 }
7154
7155 // Notify the user via the async output channel when we overrode
7156 // follow-fork-mode for a non-expression fork during expression evaluation.
7157 if (overrode_follow_mode && !is_expression_fork) {
7158 StreamUP output_up =
7160 if (output_up) {
7161 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
7162 "'parent' because an expression is being evaluated.\n"
7163 "Child process %" PRIu64
7164 " has been detached%s.\n"
7165 "You can attach to it with: process attach -p %" PRIu64
7166 "\n",
7167 child_pid,
7168 keep_stopped ? " and stopped" : " (running)",
7169 child_pid);
7170 output_up->Flush();
7171 }
7172 }
7173
7174 // Hardware breakpoints/watchpoints are not inherited implicitly,
7175 // so we need to readd them if we're following child.
7176 if (follow_fork_mode == eFollowChild) {
7178 // Update our PID
7179 SetID(child_pid);
7180 }
7181}
7182
7184 bool is_expression_fork) {
7185 Log *log = GetLog(GDBRLog::Process);
7186
7187 LLDB_LOG(
7188 log,
7189 "ProcessGDBRemote::DidVFork() called for child_pid: {0}, child_tid {1}",
7190 child_pid, child_tid);
7192
7193 // See comment in DidFork(): force follow-parent during expression evaluation
7194 // regardless of which thread triggered the vfork.
7195 FollowForkMode follow_fork_mode = GetFollowForkMode();
7196 bool overrode_follow_mode = false;
7197 if (follow_fork_mode == eFollowChild &&
7198 GetModIDRef().IsRunningExpression()) {
7199 if (is_expression_fork) {
7200 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
7201 "to parent during expression evaluation");
7202 } else {
7203 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
7204 "to parent during expression evaluation. Child process "
7205 "{0} is available for manual attachment.",
7206 child_pid);
7207 }
7208 follow_fork_mode = eFollowParent;
7209 overrode_follow_mode = true;
7210 }
7211
7212 // Disable all software breakpoints for the duration of vfork.
7213 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7214 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
7215
7216 lldb::pid_t detach_pid;
7217 lldb::tid_t detach_tid;
7218
7219 switch (follow_fork_mode) {
7220 case eFollowParent:
7221 detach_pid = child_pid;
7222 detach_tid = child_tid;
7223 break;
7224 case eFollowChild:
7225 detach_pid = m_gdb_comm.GetCurrentProcessID();
7226 // Any valid TID will suffice, thread-relevant actions will set a proper TID
7227 // anyway.
7228 detach_tid = m_thread_ids.front();
7229
7230 // Switch to the parent process before detaching it.
7231 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
7232 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to set pid/tid");
7233 return;
7234 }
7235
7236 // Remove hardware breakpoints / watchpoints from the parent process.
7238
7239 // Switch to the child process.
7240 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
7241 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
7242 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to reset pid/tid");
7243 return;
7244 }
7245 break;
7246 }
7247
7248 LLDB_LOG(log, "Detaching process {0}", detach_pid);
7249 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
7250 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
7251 if (error.Fail() && keep_stopped) {
7252 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() detach-and-stay-stopped not "
7253 "supported, falling back to normal detach");
7254 keep_stopped = false;
7255 error = m_gdb_comm.Detach(false, detach_pid);
7256 }
7257 if (error.Fail()) {
7258 LLDB_LOG(log,
7259 "ProcessGDBRemote::DidVFork() detach packet send failed: {0}",
7260 error.AsCString() ? error.AsCString() : "<unknown error>");
7261 return;
7262 }
7263
7264 if (overrode_follow_mode && !is_expression_fork) {
7265 StreamUP output_up =
7267 if (output_up) {
7268 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
7269 "'parent' because an expression is being evaluated.\n"
7270 "Child process %" PRIu64
7271 " has been detached%s.\n"
7272 "You can attach to it with: process attach -p %" PRIu64
7273 "\n",
7274 child_pid,
7275 keep_stopped ? " and stopped" : " (running)",
7276 child_pid);
7277 output_up->Flush();
7278 }
7279 }
7280
7281 if (follow_fork_mode == eFollowChild) {
7282 // Update our PID
7283 SetID(child_pid);
7284 }
7285}
7286
7288 assert(m_vfork_in_progress_count > 0);
7290
7291 // Reenable all software breakpoints that were enabled before vfork.
7292 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
7294}
7295
7297 // If we are following children, vfork is finished by exec (rather than
7298 // vforkdone that is submitted for parent).
7302 }
7304}
7305
7307 const BreakpointSiteToActionMap &site_to_action) {
7308 llvm::Error joined = llvm::Error::success();
7309 for (auto &[site, action] : site_to_action) {
7310 llvm::Error error = action == Process::BreakpointAction::Enable
7311 ? DoEnableBreakpointSite(*site)
7312 : DoDisableBreakpointSite(*site);
7313 joined = llvm::joinErrors(std::move(joined), std::move(error));
7314 }
7315 return joined;
7316}
7317
7318/// Parse a MultiBreakpoint response into per-request results.
7319/// Returns a vector of results: std::nullopt means OK, a uint8_t value is the
7320/// error code from an Exx response.
7321static llvm::SmallVector<std::optional<uint8_t>>
7322ParseMultiBreakpointResponse(llvm::StringRef response_str) {
7323 llvm::SmallVector<std::optional<uint8_t>> results;
7324
7327 parsed ? parsed->GetAsDictionary() : nullptr;
7328 StructuredData::Array *array = nullptr;
7329 if (dict)
7330 dict->GetValueForKeyAsArray("results", array);
7331 if (!array)
7332 return results;
7333
7334 array->ForEach([&results](StructuredData::Object *object) -> bool {
7335 llvm::StringRef token;
7336 if (auto *string = object->GetAsString())
7337 token = string->GetValue();
7338 if (token == "OK") {
7339 results.push_back(std::nullopt);
7340 return true;
7341 }
7342 if (token.size() != 3 || !token.starts_with("E")) {
7343 results.push_back(uint8_t(0xff));
7344 return true;
7345 }
7346 uint8_t error_code = 0;
7347 if (token.drop_front(1).getAsInteger(BASE_16, error_code))
7348 results.push_back(0xff);
7349 else
7350 results.push_back(error_code);
7351 return true;
7352 });
7353 return results;
7354}
7355
7356/// Determine the GDB stoppoint type for a breakpoint site by checking which
7357/// packet types the remote supports (for insertions), or by checking the site
7358/// type (for deletions).
7359static std::optional<GDBStoppointType>
7361 GDBRemoteCommunicationClient &gdb_comm) {
7362 if (insert) {
7363 if (!site.HardwareRequired() &&
7365 return eBreakpointSoftware;
7367 return eBreakpointHardware;
7368 return std::nullopt;
7369 }
7370
7371 switch (site.GetType()) {
7373 return eBreakpointSoftware;
7375 return eBreakpointHardware;
7377 return std::nullopt;
7378 }
7379 llvm_unreachable("unhandled BreakpointSite type");
7380}
7381
7382namespace {
7383struct BreakpointPacketInfo {
7384 BreakpointSite &site;
7385 size_t trap_opcode_size;
7386 GDBStoppointType type;
7387 bool is_enable;
7388};
7389
7390std::string to_string(const BreakpointPacketInfo &info) {
7391 char packet = info.is_enable ? 'Z' : 'z';
7392 return llvm::formatv("{0}{1},{2:x-},{3:x-}", packet,
7393 static_cast<int>(info.type), info.site.GetLoadAddress(),
7394 info.trap_opcode_size)
7395 .str();
7396}
7397} // namespace
7398
7400 const BreakpointSiteToActionMap &site_to_action) {
7401 if (site_to_action.empty())
7402 return llvm::Error::success();
7403 if (!m_gdb_comm.GetMultiBreakpointSupported())
7404 return UpdateBreakpointSitesNotBatched(site_to_action);
7405
7407
7408 std::vector<BreakpointPacketInfo> breakpoint_infos;
7409 for (auto [site, action] : site_to_action) {
7410 size_t trap_opcode_size = GetSoftwareBreakpointTrapOpcode(site.get());
7411 std::optional<GDBStoppointType> type =
7413
7414 if (!type) {
7415 LLDB_LOG(log, "MultiBreakpoint: site {0} at {1:x} can't be batched",
7416 site->GetID(), site->GetLoadAddress());
7417 return UpdateBreakpointSitesNotBatched(site_to_action);
7418 }
7419
7420 breakpoint_infos.push_back(
7421 {*site, trap_opcode_size, *type, action == BreakpointAction::Enable});
7422 }
7423
7424 StreamString stream;
7425 stream << "jMultiBreakpoint:";
7426
7427 auto args_array = std::make_shared<StructuredData::Array>();
7428 for (auto &bp_info : breakpoint_infos)
7429 args_array->AddStringItem(to_string(bp_info));
7430
7431 StructuredData::Dictionary packet_dict;
7432 packet_dict.AddItem("breakpoint_requests", args_array);
7433 packet_dict.Dump(stream, false);
7434
7435 StreamGDBRemote escaped_stream;
7436 escaped_stream.PutEscapedBytes(stream.GetString());
7437 llvm::Expected<StringExtractorGDBRemote> response =
7438 m_gdb_comm.SendPacketAndExpectResponse(escaped_stream.GetString(),
7440
7441 if (!response) {
7442 LLDB_LOG_ERROR(log, response.takeError(), "jMultiBreakpoint failed: {0}");
7443 return UpdateBreakpointSitesNotBatched(site_to_action);
7444 }
7445
7446 llvm::SmallVector<std::optional<uint8_t>> results =
7447 ParseMultiBreakpointResponse(response->GetStringRef());
7448
7449 // This is a protocol violation, do nothing.
7450 if (results.size() != breakpoint_infos.size())
7451 return llvm::createStringErrorV(
7452 "MultiBreakpoint response count mismatch (expected {0}, got {1})",
7453 site_to_action.size(), results.size());
7454
7455 llvm::Error joined = llvm::Error::success();
7456 for (auto [error_code, bp_info] :
7457 llvm::zip_equal(results, breakpoint_infos)) {
7458 BreakpointSite &site = bp_info.site;
7459 if (error_code) {
7460 auto error = llvm::createStringErrorV(
7461 "MultiBreakpoint: site {0} at {1:x} failed with E{2}",
7462 bp_info.site.GetID(), bp_info.site.GetLoadAddress(), error_code);
7463 joined = llvm::joinErrors(std::move(joined), std::move(error));
7464 continue;
7465 }
7466 SetBreakpointSiteEnabled(site, bp_info.is_enable);
7467 if (bp_info.is_enable)
7468 site.SetType(bp_info.type == eBreakpointHardware
7471 }
7472
7473 return joined;
7474}
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:455
void Clear()
Clears the object state.
Definition ArchSpec.cpp:735
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:547
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:952
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition ArchSpec.h:599
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:886
Core GetCore() const
Definition ArchSpec.h:536
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:745
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:223
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:225
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:128
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:91
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1178
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:447
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:3543
std::mutex m_process_input_reader_mutex
Definition Process.h:3544
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:2370
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:7209
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:3950
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:5022
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6425
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:2172
void ResumePrivateStateThread()
Definition Process.cpp:4208
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:6668
std::map< lldb::BreakpointSiteSP, BreakpointAction, SiteIDCmp > BreakpointSiteToActionMap
Definition Process.h:2290
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:3149
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition Process.h:3493
lldb::StateType GetPrivateState() const
Definition Process.h:3450
void SetBreakpointSiteEnabled(BreakpointSite &site, bool is_enabled=true)
Definition Process.h:3744
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3531
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition Process.cpp:2726
StopPointSiteList< lldb_private::WatchpointResource > m_watchpoint_resource_list
Watchpoint resources currently in use.
Definition Process.h:3523
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:3514
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4916
bool HasAssignedIndexIDToThread(uint64_t sb_thread_id)
Definition Process.cpp:1305
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3960
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:6358
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:4930
lldb::UnixSignalsSP m_unix_signals_sp
Definition Process.h:3541
lldb::tid_t m_interrupt_tid
Definition Process.h:3573
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:6735
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:3499
lldb::StateType m_last_broadcast_state
Definition Process.h:3605
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:3964
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:7232
lldb::StateType GetPublicState() const
Definition Process.h:3444
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:5052
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3501
const lldb::UnixSignalsSP & GetUnixSignals()
Definition Process.cpp:3955
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition Process.h:3468
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
Locate the memory region that contains load_addr.
Definition Process.cpp:6599
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:3545
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 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:67
bool include_inlines
Include inlined functions.
Definition Module.h:71
bool include_symbols
Include the symbol table.
Definition Module.h:69
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