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