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