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