[Go to site: main page, start]

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