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