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