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 ModuleSP module_sp;
1171
1172 if (standalone_uuid.IsValid()) {
1173 const bool force_symbol_search = true;
1174 const bool notify = true;
1175 const bool set_address_in_target = true;
1176 const bool allow_memory_image_last_resort = false;
1178 this, "", standalone_uuid, standalone_value,
1179 standalone_value_is_offset, force_symbol_search, notify,
1180 set_address_in_target, allow_memory_image_last_resort);
1181 }
1182 }
1183
1184 // The remote stub may know about a list of binaries to
1185 // force load into the process -- a firmware type situation
1186 // where multiple binaries are present in virtual memory,
1187 // and we are only given the addresses of the binaries.
1188 // Not intended for use with userland debugging, when we use
1189 // a DynamicLoader plugin that knows how to find the loaded
1190 // binaries, and will track updates as binaries are added.
1191
1192 std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
1193 if (bin_addrs.size()) {
1194 UUID uuid;
1195 const bool value_is_slide = false;
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 const bool force_symbol_search = true;
1208 const bool set_address_in_target = true;
1209 const bool allow_memory_image_last_resort = false;
1210 // Second manually load this binary into the Target.
1212 this, llvm::StringRef(), uuid, addr, value_is_slide,
1213 force_symbol_search, notify, set_address_in_target,
1214 allow_memory_image_last_resort);
1215 }
1216 }
1217}
1218
1220 ModuleSP module_sp = GetTarget().GetExecutableModule();
1221 if (!module_sp)
1222 return;
1223
1224 std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1225 if (!offsets)
1226 return;
1227
1228 bool is_uniform =
1229 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1230 offsets->offsets.size();
1231 if (!is_uniform)
1232 return; // TODO: Handle non-uniform responses.
1233
1234 bool changed = false;
1235 module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1236 /*value_is_offset=*/true, changed);
1237 if (changed) {
1238 ModuleList list;
1239 list.Append(module_sp);
1240 m_process->GetTarget().ModulesDidLoad(list);
1241 }
1242}
1243
1245 ArchSpec process_arch;
1246 DidLaunchOrAttach(process_arch);
1247}
1248
1250 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1251 Log *log = GetLog(GDBRLog::Process);
1252 Status error;
1253
1254 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1255
1256 // Clear out and clean up from any current state
1257 Clear();
1258 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1259 error = EstablishConnectionIfNeeded(attach_info);
1260 if (error.Success()) {
1261 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1262
1263 char packet[64];
1264 const int packet_len =
1265 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1266 SetID(attach_pid);
1267 auto data_sp =
1268 std::make_shared<EventDataBytes>(llvm::StringRef(packet, packet_len));
1269 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1270 } else
1271 SetExitStatus(-1, error.AsCString());
1272 }
1273
1274 return error;
1275}
1276
1278 const char *process_name, const ProcessAttachInfo &attach_info) {
1279 Status error;
1280 // Clear out and clean up from any current state
1281 Clear();
1282
1283 if (process_name && process_name[0]) {
1284 error = EstablishConnectionIfNeeded(attach_info);
1285 if (error.Success()) {
1286 StreamString packet;
1287
1288 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1289
1290 if (attach_info.GetWaitForLaunch()) {
1291 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1292 packet.PutCString("vAttachWait");
1293 } else {
1294 if (attach_info.GetIgnoreExisting())
1295 packet.PutCString("vAttachWait");
1296 else
1297 packet.PutCString("vAttachOrWait");
1298 }
1299 } else
1300 packet.PutCString("vAttachName");
1301 packet.PutChar(';');
1302 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1305
1306 auto data_sp = std::make_shared<EventDataBytes>(packet.GetString());
1307 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1308
1309 } else
1310 SetExitStatus(-1, error.AsCString());
1311 }
1312 return error;
1313}
1314
1315llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1316 return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
1317}
1318
1320 return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1321}
1322
1323llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1324 return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1325}
1326
1327llvm::Expected<std::string>
1328ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1329 return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
1330}
1331
1332llvm::Expected<std::vector<uint8_t>>
1334 return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1335}
1336
1338 // When we exit, disconnect from the GDB server communications
1339 m_gdb_comm.Disconnect();
1340}
1341
1343 // If you can figure out what the architecture is, fill it in here.
1344 process_arch.Clear();
1345 DidLaunchOrAttach(process_arch);
1346}
1347
1349 m_continue_c_tids.clear();
1350 m_continue_C_tids.clear();
1351 m_continue_s_tids.clear();
1352 m_continue_S_tids.clear();
1353 m_jstopinfo_sp.reset();
1354 m_jthreadsinfo_sp.reset();
1355 m_shared_cache_info_sp.reset();
1356 return Status();
1357}
1358
1360 return m_gdb_comm.GetReverseStepSupported() ||
1361 m_gdb_comm.GetReverseContinueSupported();
1362}
1363
1365 Status error;
1366 Log *log = GetLog(GDBRLog::Process);
1367 LLDB_LOGF(log, "ProcessGDBRemote::Resume(%s)",
1368 direction == RunDirection::eRunForward ? "" : "reverse");
1369
1370 ListenerSP listener_sp(
1371 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1372 if (listener_sp->StartListeningForEvents(
1374 listener_sp->StartListeningForEvents(
1377
1378 const size_t num_threads = GetThreadList().GetSize();
1379
1380 StreamString continue_packet;
1381 bool continue_packet_error = false;
1382 // Number of threads continuing with "c", i.e. continuing without a signal
1383 // to deliver.
1384 const size_t num_continue_c_tids = m_continue_c_tids.size();
1385 // Number of threads continuing with "C", i.e. continuing with a signal to
1386 // deliver.
1387 const size_t num_continue_C_tids = m_continue_C_tids.size();
1388 // Number of threads continuing with "s", i.e. single-stepping.
1389 const size_t num_continue_s_tids = m_continue_s_tids.size();
1390 // Number of threads continuing with "S", i.e. single-stepping with a signal
1391 // to deliver.
1392 const size_t num_continue_S_tids = m_continue_S_tids.size();
1393 if (direction == RunDirection::eRunForward &&
1394 m_gdb_comm.HasAnyVContSupport()) {
1395 std::string pid_prefix;
1396 if (m_gdb_comm.GetMultiprocessSupported())
1397 pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1398
1399 if (num_continue_c_tids == num_threads ||
1400 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1401 m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1402 // All threads are continuing
1403 if (m_gdb_comm.GetMultiprocessSupported())
1404 continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1405 else
1406 continue_packet.PutCString("c");
1407 } else {
1408 continue_packet.PutCString("vCont");
1409
1410 if (!m_continue_c_tids.empty()) {
1411 if (m_gdb_comm.GetVContSupported("c")) {
1412 for (tid_collection::const_iterator
1413 t_pos = m_continue_c_tids.begin(),
1414 t_end = m_continue_c_tids.end();
1415 t_pos != t_end; ++t_pos)
1416 continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1417 } else
1418 continue_packet_error = true;
1419 }
1420
1421 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1422 if (m_gdb_comm.GetVContSupported("C")) {
1423 for (tid_sig_collection::const_iterator
1424 s_pos = m_continue_C_tids.begin(),
1425 s_end = m_continue_C_tids.end();
1426 s_pos != s_end; ++s_pos)
1427 continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1428 pid_prefix, s_pos->first);
1429 } else
1430 continue_packet_error = true;
1431 }
1432
1433 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1434 if (m_gdb_comm.GetVContSupported("s")) {
1435 for (tid_collection::const_iterator
1436 t_pos = m_continue_s_tids.begin(),
1437 t_end = m_continue_s_tids.end();
1438 t_pos != t_end; ++t_pos)
1439 continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1440 } else
1441 continue_packet_error = true;
1442 }
1443
1444 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1445 if (m_gdb_comm.GetVContSupported("S")) {
1446 for (tid_sig_collection::const_iterator
1447 s_pos = m_continue_S_tids.begin(),
1448 s_end = m_continue_S_tids.end();
1449 s_pos != s_end; ++s_pos)
1450 continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1451 pid_prefix, s_pos->first);
1452 } else
1453 continue_packet_error = true;
1454 }
1455
1456 if (continue_packet_error)
1457 continue_packet.Clear();
1458 }
1459 } else
1460 continue_packet_error = true;
1461
1462 if (direction == RunDirection::eRunForward && continue_packet_error) {
1463 // Either no vCont support, or we tried to use part of the vCont packet
1464 // that wasn't supported by the remote GDB server. We need to try and
1465 // make a simple packet that can do our continue.
1466 if (num_continue_c_tids > 0) {
1467 if (num_continue_c_tids == num_threads) {
1468 // All threads are resuming...
1469 m_gdb_comm.SetCurrentThreadForRun(-1);
1470 continue_packet.PutChar('c');
1471 continue_packet_error = false;
1472 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1473 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1474 // Only one thread is continuing
1475 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1476 continue_packet.PutChar('c');
1477 continue_packet_error = false;
1478 }
1479 }
1480
1481 if (continue_packet_error && num_continue_C_tids > 0) {
1482 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1483 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1484 num_continue_S_tids == 0) {
1485 const int continue_signo = m_continue_C_tids.front().second;
1486 // Only one thread is continuing
1487 if (num_continue_C_tids > 1) {
1488 // More that one thread with a signal, yet we don't have vCont
1489 // support and we are being asked to resume each thread with a
1490 // signal, we need to make sure they are all the same signal, or we
1491 // can't issue the continue accurately with the current support...
1492 if (num_continue_C_tids > 1) {
1493 continue_packet_error = false;
1494 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1495 if (m_continue_C_tids[i].second != continue_signo)
1496 continue_packet_error = true;
1497 }
1498 }
1499 if (!continue_packet_error)
1500 m_gdb_comm.SetCurrentThreadForRun(-1);
1501 } else {
1502 // Set the continue thread ID
1503 continue_packet_error = false;
1504 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1505 }
1506 if (!continue_packet_error) {
1507 // Add threads continuing with the same signo...
1508 continue_packet.Printf("C%2.2x", continue_signo);
1509 }
1510 }
1511 }
1512
1513 if (continue_packet_error && num_continue_s_tids > 0) {
1514 if (num_continue_s_tids == num_threads) {
1515 // All threads are resuming...
1516 m_gdb_comm.SetCurrentThreadForRun(-1);
1517
1518 continue_packet.PutChar('s');
1519
1520 continue_packet_error = false;
1521 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1522 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1523 // Only one thread is stepping
1524 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1525 continue_packet.PutChar('s');
1526 continue_packet_error = false;
1527 }
1528 }
1529
1530 if (!continue_packet_error && num_continue_S_tids > 0) {
1531 if (num_continue_S_tids == num_threads) {
1532 const int step_signo = m_continue_S_tids.front().second;
1533 // Are all threads trying to step with the same signal?
1534 continue_packet_error = false;
1535 if (num_continue_S_tids > 1) {
1536 for (size_t i = 1; i < num_threads; ++i) {
1537 if (m_continue_S_tids[i].second != step_signo)
1538 continue_packet_error = true;
1539 }
1540 }
1541 if (!continue_packet_error) {
1542 // Add threads stepping with the same signo...
1543 m_gdb_comm.SetCurrentThreadForRun(-1);
1544 continue_packet.Printf("S%2.2x", step_signo);
1545 }
1546 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1547 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1548 // Only one thread is stepping with signal
1549 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1550 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1551 continue_packet_error = false;
1552 }
1553 }
1554 }
1555
1556 if (direction == RunDirection::eRunReverse) {
1557 if (num_continue_s_tids > 0 || num_continue_S_tids > 0) {
1558 if (!m_gdb_comm.GetReverseStepSupported()) {
1559 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1560 "support reverse-stepping");
1562 "target does not support reverse-stepping");
1563 }
1564
1565 if (num_continue_S_tids > 0) {
1566 LLDB_LOGF(
1567 log,
1568 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1570 "can't deliver signals while running in reverse");
1571 }
1572
1573 if (num_continue_s_tids > 1) {
1574 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: can't step multiple "
1575 "threads in reverse");
1577 "can't step multiple threads while reverse-stepping");
1578 }
1579
1580 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1581 continue_packet.PutCString("bs");
1582 } else {
1583 if (!m_gdb_comm.GetReverseContinueSupported()) {
1584 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1585 "support reverse-continue");
1587 "target does not support reverse execution of processes");
1588 }
1589
1590 if (num_continue_C_tids > 0) {
1591 LLDB_LOGF(
1592 log,
1593 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1595 "can't deliver signals while running in reverse");
1596 }
1597
1598 // All threads continue whether requested or not ---
1599 // we can't change how threads ran in the past.
1600 continue_packet.PutCString("bc");
1601 }
1602
1603 continue_packet_error = false;
1604 }
1605
1606 if (continue_packet_error) {
1608 "can't make continue packet for this resume");
1609 } else {
1610 EventSP event_sp;
1611 if (!m_async_thread.IsJoinable()) {
1613 "Trying to resume but the async thread is dead.");
1614 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1615 "async thread is dead.");
1616 return error;
1617 }
1618
1619 auto data_sp =
1620 std::make_shared<EventDataBytes>(continue_packet.GetString());
1621 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1622
1623 if (!listener_sp->GetEvent(event_sp, ResumeTimeout())) {
1624 error = Status::FromErrorString("Resume timed out.");
1625 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1626 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1628 "Broadcast continue, but the async thread was "
1629 "killed before we got an ack back.");
1630 LLDB_LOGF(log,
1631 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1632 "async thread was killed before we got an ack back.");
1633 return error;
1634 }
1635 }
1636 }
1637
1638 return error;
1639}
1640
1642 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1643 m_thread_ids.clear();
1644 m_thread_pcs.clear();
1645}
1646
1648 llvm::StringRef value) {
1649 m_thread_ids.clear();
1650 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1651 StringExtractorGDBRemote thread_ids{value};
1652
1653 do {
1654 auto pid_tid = thread_ids.GetPidTid(pid);
1655 if (pid_tid && pid_tid->first == pid) {
1656 lldb::tid_t tid = pid_tid->second;
1657 if (tid != LLDB_INVALID_THREAD_ID &&
1659 m_thread_ids.push_back(tid);
1660 }
1661 } while (thread_ids.GetChar() == ',');
1662
1663 return m_thread_ids.size();
1664}
1665
1667 llvm::StringRef value) {
1668 m_thread_pcs.clear();
1669 for (llvm::StringRef x : llvm::split(value, ',')) {
1671 if (llvm::to_integer(x, pc, 16))
1672 m_thread_pcs.push_back(pc);
1673 }
1674 return m_thread_pcs.size();
1675}
1676
1678 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1679
1680 if (m_jthreadsinfo_sp) {
1681 // If we have the JSON threads info, we can get the thread list from that
1682 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1683 if (thread_infos && thread_infos->GetSize() > 0) {
1684 m_thread_ids.clear();
1685 m_thread_pcs.clear();
1686 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1687 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1688 if (thread_dict) {
1689 // Set the thread stop info from the JSON dictionary
1690 SetThreadStopInfo(thread_dict);
1692 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1693 m_thread_ids.push_back(tid);
1694 }
1695 return true; // Keep iterating through all thread_info objects
1696 });
1697 }
1698 if (!m_thread_ids.empty())
1699 return true;
1700 } else {
1701 // See if we can get the thread IDs from the current stop reply packets
1702 // that might contain a "threads" key/value pair
1703
1704 if (m_last_stop_packet) {
1705 // Get the thread stop info
1707 const llvm::StringRef stop_info_str = stop_info.GetStringRef();
1708
1709 m_thread_pcs.clear();
1710 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1711 if (thread_pcs_pos != llvm::StringRef::npos) {
1712 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1713 const size_t end = stop_info_str.find(';', start);
1714 if (end != llvm::StringRef::npos) {
1715 llvm::StringRef value = stop_info_str.substr(start, end - start);
1717 }
1718 }
1719
1720 const size_t threads_pos = stop_info_str.find(";threads:");
1721 if (threads_pos != llvm::StringRef::npos) {
1722 const size_t start = threads_pos + strlen(";threads:");
1723 const size_t end = stop_info_str.find(';', start);
1724 if (end != llvm::StringRef::npos) {
1725 llvm::StringRef value = stop_info_str.substr(start, end - start);
1727 return true;
1728 }
1729 }
1730 }
1731 }
1732
1733 bool sequence_mutex_unavailable = false;
1734 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1735 if (sequence_mutex_unavailable) {
1736 return false; // We just didn't get the list
1737 }
1738 return true;
1739}
1740
1742 ThreadList &new_thread_list) {
1743 // locker will keep a mutex locked until it goes out of scope
1744 Log *log = GetLog(GDBRLog::Thread);
1745 LLDB_LOG_VERBOSE(log, "pid = {0}", GetID());
1746
1747 size_t num_thread_ids = m_thread_ids.size();
1748 // The "m_thread_ids" thread ID list should always be updated after each stop
1749 // reply packet, but in case it isn't, update it here.
1750 if (num_thread_ids == 0) {
1751 if (!UpdateThreadIDList())
1752 return false;
1753 num_thread_ids = m_thread_ids.size();
1754 }
1755
1756 ThreadList old_thread_list_copy(old_thread_list);
1757 if (num_thread_ids > 0) {
1758 for (size_t i = 0; i < num_thread_ids; ++i) {
1759 lldb::tid_t tid = m_thread_ids[i];
1760 ThreadSP thread_sp(
1761 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1762 if (!thread_sp) {
1763 thread_sp = CreateThread(tid);
1764 LLDB_LOG_VERBOSE(log, "Making new thread: {0} for thread ID: {1:x}.",
1765 thread_sp.get(), thread_sp->GetID());
1766 } else {
1767 LLDB_LOG_VERBOSE(log, "Found old thread: {0} for thread ID: {1:x}.",
1768 thread_sp.get(), thread_sp->GetID());
1769 }
1770
1771 SetThreadPc(thread_sp, i);
1772 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1773 }
1774 }
1775
1776 // Whatever that is left in old_thread_list_copy are not present in
1777 // new_thread_list. Remove non-existent threads from internal id table.
1778 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1779 for (size_t i = 0; i < old_num_thread_ids; i++) {
1780 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1781 if (old_thread_sp) {
1782 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1783 m_thread_id_to_index_id_map.erase(old_thread_id);
1784 }
1785 }
1786
1787 return true;
1788}
1789
1790void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1791 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1793 ThreadGDBRemote *gdb_thread =
1794 static_cast<ThreadGDBRemote *>(thread_sp.get());
1795 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1796 if (reg_ctx_sp) {
1797 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1799 if (pc_regnum != LLDB_INVALID_REGNUM) {
1800 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1801 }
1802 }
1803 }
1804}
1805
1807 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1808 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1809 // packet
1810 if (thread_infos_sp) {
1811 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1812 if (thread_infos) {
1813 lldb::tid_t tid;
1814 const size_t n = thread_infos->GetSize();
1815 for (size_t i = 0; i < n; ++i) {
1816 StructuredData::Dictionary *thread_dict =
1817 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1818 if (thread_dict) {
1819 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1820 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1821 if (tid == thread->GetID())
1822 return (bool)SetThreadStopInfo(thread_dict);
1823 }
1824 }
1825 }
1826 }
1827 }
1828 return false;
1829}
1830
1832 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1833 // packet
1835 return true;
1836
1837 // See if we got thread stop info for any threads valid stop info reasons
1838 // threads via the "jstopinfo" packet stop reply packet key/value pair?
1839 if (m_jstopinfo_sp) {
1840 // If we have "jstopinfo" then we have stop descriptions for all threads
1841 // that have stop reasons, and if there is no entry for a thread, then it
1842 // has no stop reason.
1844 thread->SetStopInfo(StopInfoSP());
1845 return true;
1846 }
1847
1848 // Fall back to using the qThreadStopInfo packet
1849 StringExtractorGDBRemote stop_packet;
1850 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1851 return SetThreadStopInfo(stop_packet) == eStateStopped;
1852 return false;
1853}
1854
1856 ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) {
1857 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1858 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1859
1860 for (const auto &pair : expedited_register_map) {
1861 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1862 eRegisterKindProcessPlugin, pair.first);
1863 if (lldb_regnum != LLDB_INVALID_REGNUM) {
1864 StringExtractor reg_value_extractor(pair.second);
1865 if (reg_value_extractor.GetStringRef().empty()) {
1866 gdb_thread->PrivateSetRegisterUnavailable(lldb_regnum);
1867 continue;
1868 }
1869 WritableDataBufferSP buffer_sp(
1870 new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1871 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1872 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1873 }
1874 }
1875}
1876
1878 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1879 uint8_t signo, const std::string &thread_name, const std::string &reason,
1880 const std::string &description, uint32_t exc_type,
1881 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1882 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1883 // queue_serial are valid
1884 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1885 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial,
1886 std::vector<lldb::addr_t> &added_binaries,
1887 StructuredData::ObjectSP &detailed_binaries_info) {
1888
1889 if (tid == LLDB_INVALID_THREAD_ID)
1890 return nullptr;
1891
1892 ThreadSP thread_sp;
1893 // Scope for "locker" below
1894 {
1895 // m_thread_list_real does have its own mutex, but we need to hold onto the
1896 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1897 // m_thread_list_real.AddThread(...) so it doesn't change on us
1898 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1899 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1900
1901 if (!thread_sp) {
1902 // Create the thread if we need to
1903 thread_sp = CreateThread(tid);
1904 m_thread_list_real.AddThread(thread_sp);
1905 }
1906 }
1907
1908 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1909 RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext());
1910
1911 reg_ctx_sp->InvalidateIfNeeded(true);
1912
1913 auto iter = llvm::find(m_thread_ids, tid);
1914 if (iter != m_thread_ids.end())
1915 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1916
1917 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1918
1919 if (reg_ctx_sp->ReconfigureRegisterInfo()) {
1920 // Now we have changed the offsets of all the registers, so the values
1921 // will be corrupted.
1922 reg_ctx_sp->InvalidateAllRegisters();
1923 // Expedited registers values will never contain registers that would be
1924 // resized by a reconfigure. So we are safe to continue using these
1925 // values.
1926 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1927 }
1928
1929 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1930
1931 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1932 // Check if the GDB server was able to provide the queue name, kind and serial
1933 // number
1934 if (queue_vars_valid)
1935 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1936 dispatch_queue_t, associated_with_dispatch_queue);
1937 else
1938 gdb_thread->ClearQueueInfo();
1939
1940 gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);
1941
1942 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1943 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1944
1945 gdb_thread->SetNewlyAddedBinaries(added_binaries);
1946 gdb_thread->SetDetailedBinariesInfo(detailed_binaries_info);
1947
1948 // Make sure we update our thread stop reason just once, but don't overwrite
1949 // the stop info for threads that haven't moved:
1950 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1951 if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1952 current_stop_info_sp) {
1953 thread_sp->SetStopInfo(current_stop_info_sp);
1954 return thread_sp;
1955 }
1956
1957 if (!thread_sp->StopInfoIsUpToDate()) {
1958 thread_sp->SetStopInfo(StopInfoSP());
1959
1960 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1961 BreakpointSiteSP bp_site_sp =
1962 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1963 if (bp_site_sp && IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
1964 thread_sp->SetThreadStoppedAtUnexecutedBP(pc);
1965
1966 if (exc_type != 0) {
1967 // For thread plan async interrupt, creating stop info on the
1968 // original async interrupt request thread instead. If interrupt thread
1969 // does not exist anymore we fallback to current signal receiving thread
1970 // instead.
1971 ThreadSP interrupt_thread;
1973 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
1974 if (interrupt_thread)
1975 thread_sp = interrupt_thread;
1976 else {
1977 const size_t exc_data_size = exc_data.size();
1978 thread_sp->SetStopInfo(
1980 *thread_sp, exc_type, exc_data_size,
1981 exc_data_size >= 1 ? exc_data[0] : 0,
1982 exc_data_size >= 2 ? exc_data[1] : 0,
1983 exc_data_size >= 3 ? exc_data[2] : 0));
1984 }
1985 } else {
1986 bool handled = false;
1987 bool did_exec = false;
1988 // debugserver can send reason = "none" which is equivalent
1989 // to no reason.
1990 if (!reason.empty() && reason != "none") {
1991 if (reason == "trace") {
1992 thread_sp->SetStopInfo(StopInfo::CreateStopReasonToTrace(*thread_sp));
1993 handled = true;
1994 } else if (reason == "breakpoint") {
1995 thread_sp->SetThreadHitBreakpointSite();
1996 if (bp_site_sp) {
1997 // If the breakpoint is for this thread, then we'll report the hit,
1998 // but if it is for another thread, we can just report no reason.
1999 // We don't need to worry about stepping over the breakpoint here,
2000 // that will be taken care of when the thread resumes and notices
2001 // that there's a breakpoint under the pc.
2002 handled = true;
2003 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2004 thread_sp->SetStopInfo(
2006 *thread_sp, bp_site_sp->GetID()));
2007 } else {
2008 StopInfoSP invalid_stop_info_sp;
2009 thread_sp->SetStopInfo(invalid_stop_info_sp);
2010 }
2011 }
2012 } else if (reason == "trap") {
2013 // Let the trap just use the standard signal stop reason below...
2014 } else if (reason == "watchpoint") {
2015 // We will have between 1 and 3 fields in the description.
2016 //
2017 // \a wp_addr which is the original start address that
2018 // lldb requested be watched, or an address that the
2019 // hardware reported. This address should be within the
2020 // range of a currently active watchpoint region - lldb
2021 // should be able to find a watchpoint with this address.
2022 //
2023 // \a wp_index is the hardware watchpoint register number.
2024 //
2025 // \a wp_hit_addr is the actual address reported by the hardware,
2026 // which may be outside the range of a region we are watching.
2027 //
2028 // On MIPS, we may get a false watchpoint exception where an
2029 // access to the same 8 byte granule as a watchpoint will trigger,
2030 // even if the access was not within the range of the watched
2031 // region. When we get a \a wp_hit_addr outside the range of any
2032 // set watchpoint, continue execution without making it visible to
2033 // the user.
2034 //
2035 // On ARM, a related issue where a large access that starts
2036 // before the watched region (and extends into the watched
2037 // region) may report a hit address before the watched region.
2038 // lldb will not find the "nearest" watchpoint to
2039 // disable/step/re-enable it, so one of the valid watchpoint
2040 // addresses should be provided as \a wp_addr.
2041 StringExtractor desc_extractor(description.c_str());
2042 // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this
2043 // up as
2044 // <address within wp range> <wp hw index> <actual accessed addr>
2045 // but this is not reading the <wp hw index>. Seems like it
2046 // wouldn't work on MIPS, where that third field is important.
2047 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2048 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
2050 bool silently_continue = false;
2051 WatchpointResourceSP wp_resource_sp;
2052 if (wp_hit_addr != LLDB_INVALID_ADDRESS) {
2053 wp_resource_sp =
2054 m_watchpoint_resource_list.FindByAddress(wp_hit_addr);
2055 // On MIPS, \a wp_hit_addr outside the range of a watched
2056 // region means we should silently continue, it is a false hit.
2058 if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first &&
2060 silently_continue = true;
2061 }
2062 if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS)
2063 wp_resource_sp = m_watchpoint_resource_list.FindByAddress(wp_addr);
2064 if (!wp_resource_sp) {
2066 LLDB_LOGF(log, "failed to find watchpoint");
2067 watch_id = LLDB_INVALID_SITE_ID;
2068 } else {
2069 // LWP_TODO: This is hardcoding a single Watchpoint in a
2070 // Resource, need to add
2071 // StopInfo::CreateStopReasonWithWatchpointResource which
2072 // represents all watchpoints that were tripped at this stop.
2073 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();
2074 }
2075 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
2076 *thread_sp, watch_id, silently_continue));
2077 handled = true;
2078 } else if (reason == "exception") {
2079 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2080 *thread_sp, description.c_str()));
2081 handled = true;
2082 } else if (reason == "history boundary") {
2083 thread_sp->SetStopInfo(StopInfo::CreateStopReasonHistoryBoundary(
2084 *thread_sp, description.c_str()));
2085 handled = true;
2086 } else if (reason == "exec") {
2087 did_exec = true;
2088 thread_sp->SetStopInfo(
2090 handled = true;
2091 } else if (reason == "processor trace") {
2092 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
2093 *thread_sp, description.c_str()));
2094 } else if (reason == "fork") {
2095 StringExtractor desc_extractor(description.c_str());
2096 lldb::pid_t child_pid =
2097 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
2098 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
2099 thread_sp->SetStopInfo(
2100 StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));
2101 handled = true;
2102 } else if (reason == "vfork") {
2103 StringExtractor desc_extractor(description.c_str());
2104 lldb::pid_t child_pid =
2105 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
2106 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
2107 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
2108 *thread_sp, child_pid, child_tid));
2109 handled = true;
2110 } else if (reason == "vforkdone") {
2111 thread_sp->SetStopInfo(
2113 handled = true;
2114 }
2115 }
2116
2117 if (!handled && signo && !did_exec) {
2118 if (signo == SIGTRAP) {
2119 // Currently we are going to assume SIGTRAP means we are either
2120 // hitting a breakpoint or hardware single stepping.
2121
2122 // We can't disambiguate between stepping-to-a-breakpointsite and
2123 // hitting-a-breakpointsite.
2124 //
2125 // A user can instruction-step, and be stopped at a BreakpointSite.
2126 // Or a user can be sitting at a BreakpointSite,
2127 // instruction-step which hits the breakpoint and the pc does not
2128 // advance.
2129 //
2130 // In both cases, we're at a BreakpointSite when stopped, and
2131 // the resume state was eStateStepping.
2132
2133 // Assume if we're at a BreakpointSite, we hit it.
2134 handled = true;
2135 addr_t pc =
2136 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2137 BreakpointSiteSP bp_site_sp =
2138 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
2139 pc);
2140
2141 // We can't know if we hit it or not. So if we are stopped at
2142 // a BreakpointSite, assume we hit it, and should step past the
2143 // breakpoint when we resume. This is contrary to how we handle
2144 // BreakpointSites in any other location, but we can't know for
2145 // sure what happened so it's a reasonable default.
2146 if (bp_site_sp) {
2147 if (IsBreakpointSitePhysicallyEnabled(*bp_site_sp))
2148 thread_sp->SetThreadHitBreakpointSite();
2149
2150 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2151 if (m_breakpoint_pc_offset != 0)
2152 thread_sp->GetRegisterContext()->SetPC(pc);
2153 thread_sp->SetStopInfo(
2155 *thread_sp, bp_site_sp->GetID()));
2156 } else {
2157 StopInfoSP invalid_stop_info_sp;
2158 thread_sp->SetStopInfo(invalid_stop_info_sp);
2159 }
2160 } else {
2161 // If we were stepping then assume the stop was the result of the
2162 // trace. If we were not stepping then report the SIGTRAP.
2163 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2164 thread_sp->SetStopInfo(
2166 else
2167 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2168 *thread_sp, signo, description.c_str()));
2169 }
2170 }
2171 if (!handled) {
2172 // For thread plan async interrupt, creating stop info on the
2173 // original async interrupt request thread instead. If interrupt
2174 // thread does not exist anymore we fallback to current signal
2175 // receiving thread instead.
2176 ThreadSP interrupt_thread;
2178 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
2179 if (interrupt_thread)
2180 thread_sp = interrupt_thread;
2181 else
2182 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2183 *thread_sp, signo, description.c_str()));
2184 }
2185 }
2186
2187 if (!description.empty()) {
2188 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2189 if (stop_info_sp) {
2190 const char *stop_info_desc = stop_info_sp->GetDescription();
2191 if (!stop_info_desc || !stop_info_desc[0])
2192 stop_info_sp->SetDescription(description.c_str());
2193 } else {
2194 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2195 *thread_sp, description.c_str()));
2196 }
2197 }
2198 }
2199 }
2200 return thread_sp;
2201}
2202
2205 const std::string &description) {
2206 ThreadSP thread_sp;
2207 {
2208 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2209 thread_sp = m_thread_list_real.FindThreadByProtocolID(m_interrupt_tid,
2210 /*can_update=*/false);
2211 }
2212 if (thread_sp)
2213 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(
2214 *thread_sp, signo, description.c_str()));
2215 // Clear m_interrupt_tid regardless we can find original interrupt thread or
2216 // not.
2218 return thread_sp;
2219}
2220
2223 static constexpr llvm::StringLiteral g_key_tid("tid");
2224 static constexpr llvm::StringLiteral g_key_name("name");
2225 static constexpr llvm::StringLiteral g_key_reason("reason");
2226 static constexpr llvm::StringLiteral g_key_metype("metype");
2227 static constexpr llvm::StringLiteral g_key_medata("medata");
2228 static constexpr llvm::StringLiteral g_key_qaddr("qaddr");
2229 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2230 "dispatch_queue_t");
2231 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2232 "associated_with_dispatch_queue");
2233 static constexpr llvm::StringLiteral g_key_queue_name("qname");
2234 static constexpr llvm::StringLiteral g_key_queue_kind("qkind");
2235 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");
2236 static constexpr llvm::StringLiteral g_key_registers("registers");
2237 static constexpr llvm::StringLiteral g_key_memory("memory");
2238 static constexpr llvm::StringLiteral g_key_description("description");
2239 static constexpr llvm::StringLiteral g_key_signal("signal");
2240 static constexpr llvm::StringLiteral g_key_added_binaries("added-binaries");
2241 static constexpr llvm::StringLiteral g_key_detailed_binaries_info(
2242 "detailed-binaries-info");
2243
2244 // Stop with signal and thread info
2246 uint8_t signo = 0;
2247 std::string thread_name;
2248 std::string reason;
2249 std::string description;
2250 uint32_t exc_type = 0;
2251 std::vector<addr_t> exc_data;
2252 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2253 ExpeditedRegisterMap expedited_register_map;
2254 bool queue_vars_valid = false;
2255 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2256 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2257 std::string queue_name;
2258 QueueKind queue_kind = eQueueKindUnknown;
2259 uint64_t queue_serial_number = 0;
2260 std::vector<addr_t> added_binaries;
2261 StructuredData::ObjectSP detailed_binaries_info;
2262 // Iterate through all of the thread dictionary key/value pairs from the
2263 // structured data dictionary
2264
2265 // FIXME: we're silently ignoring invalid data here
2266 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2267 &signo, &reason, &description, &exc_type, &exc_data,
2268 &thread_dispatch_qaddr, &queue_vars_valid,
2269 &associated_with_dispatch_queue, &dispatch_queue_t,
2270 &queue_name, &queue_kind, &queue_serial_number,
2271 &added_binaries, &detailed_binaries_info](
2272 llvm::StringRef key,
2273 StructuredData::Object *object) -> bool {
2274 if (key == g_key_tid) {
2275 // thread in big endian hex
2276 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
2277 } else if (key == g_key_metype) {
2278 // exception type in big endian hex
2279 exc_type = object->GetUnsignedIntegerValue(0);
2280 } else if (key == g_key_medata) {
2281 // exception data in big endian hex
2282 StructuredData::Array *array = object->GetAsArray();
2283 if (array) {
2284 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2285 exc_data.push_back(object->GetUnsignedIntegerValue());
2286 return true; // Keep iterating through all array items
2287 });
2288 }
2289 } else if (key == g_key_name) {
2290 thread_name = std::string(object->GetStringValue());
2291 } else if (key == g_key_qaddr) {
2292 thread_dispatch_qaddr =
2293 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
2294 } else if (key == g_key_queue_name) {
2295 queue_vars_valid = true;
2296 queue_name = std::string(object->GetStringValue());
2297 } else if (key == g_key_queue_kind) {
2298 std::string queue_kind_str = std::string(object->GetStringValue());
2299 if (queue_kind_str == "serial") {
2300 queue_vars_valid = true;
2301 queue_kind = eQueueKindSerial;
2302 } else if (queue_kind_str == "concurrent") {
2303 queue_vars_valid = true;
2304 queue_kind = eQueueKindConcurrent;
2305 }
2306 } else if (key == g_key_queue_serial_number) {
2307 queue_serial_number = object->GetUnsignedIntegerValue(0);
2308 if (queue_serial_number != 0)
2309 queue_vars_valid = true;
2310 } else if (key == g_key_dispatch_queue_t) {
2311 dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2312 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2313 queue_vars_valid = true;
2314 } else if (key == g_key_associated_with_dispatch_queue) {
2315 queue_vars_valid = true;
2316 bool associated = object->GetBooleanValue();
2317 if (associated)
2318 associated_with_dispatch_queue = eLazyBoolYes;
2319 else
2320 associated_with_dispatch_queue = eLazyBoolNo;
2321 } else if (key == g_key_reason) {
2322 reason = std::string(object->GetStringValue());
2323 } else if (key == g_key_description) {
2324 description = std::string(object->GetStringValue());
2325 } else if (key == g_key_registers) {
2326 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2327
2328 if (registers_dict) {
2329 registers_dict->ForEach(
2330 [&expedited_register_map](llvm::StringRef key,
2331 StructuredData::Object *object) -> bool {
2332 uint32_t reg;
2333 if (llvm::to_integer(key, reg))
2334 expedited_register_map[reg] =
2335 std::string(object->GetStringValue());
2336 return true; // Keep iterating through all array items
2337 });
2338 }
2339 } else if (key == g_key_memory) {
2340 StructuredData::Array *array = object->GetAsArray();
2341 if (array) {
2342 array->ForEach([this](StructuredData::Object *object) -> bool {
2343 StructuredData::Dictionary *mem_cache_dict =
2344 object->GetAsDictionary();
2345 if (mem_cache_dict) {
2346 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2347 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2348 "address", mem_cache_addr)) {
2349 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2350 llvm::StringRef str;
2351 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2352 StringExtractor bytes(str);
2353 bytes.SetFilePos(0);
2354
2355 const size_t byte_size = bytes.GetStringRef().size() / 2;
2356 WritableDataBufferSP data_buffer_sp(
2357 new DataBufferHeap(byte_size, 0));
2358 const size_t bytes_copied =
2359 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2360 if (bytes_copied == byte_size)
2361 m_memory_cache.AddL1CacheData(mem_cache_addr,
2362 data_buffer_sp);
2363 }
2364 }
2365 }
2366 }
2367 return true; // Keep iterating through all array items
2368 });
2369 }
2370 } else if (key == g_key_signal)
2371 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2372 else if (key == g_key_added_binaries) {
2373 StructuredData::Array *array = object->GetAsArray();
2374 if (array) {
2375 array->ForEach([&added_binaries](
2376 StructuredData::Object *object) -> bool {
2378 object->GetAsUnsignedInteger();
2379 if (addr) {
2381 if (value != LLDB_INVALID_ADDRESS)
2382 added_binaries.push_back(value);
2383 }
2384 return true; // Keep iterating through all array items
2385 });
2386 }
2387 } else if (key == g_key_detailed_binaries_info) {
2388 // Get a string representation and then parse it into
2389 // StructuredData to get a separate copy of this part of
2390 // the response. We only have an Object* here, not the
2391 // original shared pointer, to increase the ref count.
2392 if (object->GetAsDictionary()) {
2393 StreamString json_str;
2394 object->Dump(json_str);
2395 detailed_binaries_info =
2397 }
2398 }
2399 return true; // Keep iterating through all dictionary key/value pairs
2400 });
2401
2402 return SetThreadStopInfo(
2403 tid, expedited_register_map, signo, thread_name, reason, description,
2404 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2405 associated_with_dispatch_queue, dispatch_queue_t, queue_name, queue_kind,
2406 queue_serial_number, added_binaries, detailed_binaries_info);
2407}
2408
2410 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2411 stop_packet.SetFilePos(0);
2412 const char stop_type = stop_packet.GetChar();
2413 switch (stop_type) {
2414 case 'T':
2415 case 'S': {
2416 // This is a bit of a hack, but it is required. If we did exec, we need to
2417 // clear our thread lists and also know to rebuild our dynamic register
2418 // info before we lookup and threads and populate the expedited register
2419 // values so we need to know this right away so we can cleanup and update
2420 // our registers.
2421 const uint32_t stop_id = GetStopID();
2422 if (stop_id == 0) {
2423 // Our first stop, make sure we have a process ID, and also make sure we
2424 // know about our registers
2426 SetID(pid);
2428 }
2429 // Stop with signal and thread info
2432 const uint8_t signo = stop_packet.GetHexU8();
2433 llvm::StringRef key;
2434 llvm::StringRef value;
2435 std::string thread_name;
2436 std::string reason;
2437 std::string description;
2438 std::vector<addr_t> added_binaries;
2439 StructuredData::ObjectSP detailed_binaries_info;
2440 uint32_t exc_type = 0;
2441 std::vector<addr_t> exc_data;
2442 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2443 bool queue_vars_valid =
2444 false; // says if locals below that start with "queue_" are valid
2445 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2446 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2447 std::string queue_name;
2448 QueueKind queue_kind = eQueueKindUnknown;
2449 uint64_t queue_serial_number = 0;
2450 ExpeditedRegisterMap expedited_register_map;
2451 AddressableBits addressable_bits;
2452 while (stop_packet.GetNameColonValue(key, value)) {
2453 if (key.compare("metype") == 0) {
2454 // exception type in big endian hex
2455 value.getAsInteger(BASE_16, exc_type);
2456 } else if (key.compare("medata") == 0) {
2457 // exception data in big endian hex
2458 uint64_t x;
2459 value.getAsInteger(BASE_16, x);
2460 exc_data.push_back(x);
2461 } else if (key.compare("thread") == 0) {
2462 // thread-id
2463 StringExtractorGDBRemote thread_id{value};
2464 auto pid_tid = thread_id.GetPidTid(pid);
2465 if (pid_tid) {
2466 stop_pid = pid_tid->first;
2467 tid = pid_tid->second;
2468 } else
2470 } else if (key.compare("threads") == 0) {
2471 std::lock_guard<std::recursive_mutex> guard(
2472 m_thread_list_real.GetMutex());
2474 } else if (key.compare("thread-pcs") == 0) {
2475 m_thread_pcs.clear();
2476 // A comma separated list of all threads in the current
2477 // process that includes the thread for this stop reply packet
2479 while (!value.empty()) {
2480 llvm::StringRef pc_str;
2481 std::tie(pc_str, value) = value.split(',');
2482 if (pc_str.getAsInteger(BASE_16, pc))
2484 m_thread_pcs.push_back(pc);
2485 }
2486 } else if (key.compare("jstopinfo") == 0) {
2487 StringExtractor json_extractor(value);
2488 std::string json;
2489 // Now convert the HEX bytes into a string value
2490 json_extractor.GetHexByteString(json);
2491
2492 // This JSON contains thread IDs and thread stop info for all threads.
2493 // It doesn't contain expedited registers, memory or queue info.
2495 } else if (key.compare("hexname") == 0) {
2496 StringExtractor name_extractor(value);
2497 // Now convert the HEX bytes into a string value
2498 name_extractor.GetHexByteString(thread_name);
2499 } else if (key.compare("name") == 0) {
2500 thread_name = std::string(value);
2501 } else if (key.compare("qaddr") == 0) {
2502 value.getAsInteger(BASE_16, thread_dispatch_qaddr);
2503 } else if (key.compare("dispatch_queue_t") == 0) {
2504 queue_vars_valid = true;
2505 value.getAsInteger(BASE_16, dispatch_queue_t);
2506 } else if (key.compare("qname") == 0) {
2507 queue_vars_valid = true;
2508 StringExtractor name_extractor(value);
2509 // Now convert the HEX bytes into a string value
2510 name_extractor.GetHexByteString(queue_name);
2511 } else if (key.compare("qkind") == 0) {
2512 queue_kind = llvm::StringSwitch<QueueKind>(value)
2513 .Case("serial", eQueueKindSerial)
2514 .Case("concurrent", eQueueKindConcurrent)
2515 .Default(eQueueKindUnknown);
2516 queue_vars_valid = queue_kind != eQueueKindUnknown;
2517 } else if (key.compare("qserialnum") == 0) {
2518 if (!value.getAsInteger(BASE_10, queue_serial_number))
2519 queue_vars_valid = true;
2520 } else if (key.compare("reason") == 0) {
2521 reason = std::string(value);
2522 } else if (key.compare("description") == 0) {
2523 StringExtractor desc_extractor(value);
2524 // Now convert the HEX bytes into a string value
2525 desc_extractor.GetHexByteString(description);
2526 } else if (key.compare("memory") == 0) {
2527 // Expedited memory. GDB servers can choose to send back expedited
2528 // memory that can populate the L1 memory cache in the process so that
2529 // things like the frame pointer backchain can be expedited. This will
2530 // help stack backtracing be more efficient by not having to send as
2531 // many memory read requests down the remote GDB server.
2532
2533 // Key/value pair format: memory:<addr>=<bytes>;
2534 // <addr> is a number whose base will be interpreted by the prefix:
2535 // "0x[0-9a-fA-F]+" for hex
2536 // "0[0-7]+" for octal
2537 // "[1-9]+" for decimal
2538 // <bytes> is native endian ASCII hex bytes just like the register
2539 // values
2540 llvm::StringRef addr_str, bytes_str;
2541 std::tie(addr_str, bytes_str) = value.split('=');
2542 if (!addr_str.empty() && !bytes_str.empty()) {
2543 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2544 if (!addr_str.getAsInteger(BASE_AUTOSENSE, mem_cache_addr)) {
2545 StringExtractor bytes(bytes_str);
2546 const size_t byte_size = bytes.GetBytesLeft() / 2;
2547 WritableDataBufferSP data_buffer_sp(
2548 new DataBufferHeap(byte_size, 0));
2549 const size_t bytes_copied =
2550 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2551 if (bytes_copied == byte_size)
2552 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2553 }
2554 }
2555 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2556 key.compare("awatch") == 0) {
2557 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2559 value.getAsInteger(BASE_16, wp_addr);
2560
2561 WatchpointResourceSP wp_resource_sp =
2562 m_watchpoint_resource_list.FindByAddress(wp_addr);
2563
2564 // Rewrite gdb standard watch/rwatch/awatch to
2565 // "reason:watchpoint" + "description:ADDR",
2566 // which is parsed in SetThreadStopInfo.
2567 reason = "watchpoint";
2568 StreamString ostr;
2569 ostr.Printf("%" PRIu64, wp_addr);
2570 description = std::string(ostr.GetString());
2571 } else if (key.compare("swbreak") == 0 || key.compare("hwbreak") == 0) {
2572 reason = "breakpoint";
2573 } else if (key.compare("replaylog") == 0) {
2574 reason = "history boundary";
2575 } else if (key.compare("library") == 0) {
2576 auto error = LoadModules();
2577 if (error) {
2579 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2580 }
2581 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2582 // fork includes child pid/tid in thread-id format
2583 StringExtractorGDBRemote thread_id{value};
2584 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2585 if (!pid_tid) {
2587 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2589 }
2590
2591 reason = key.str();
2592 StreamString ostr;
2593 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2594 description = std::string(ostr.GetString());
2595 } else if (key.compare("addressing_bits") == 0) {
2596 uint64_t addressing_bits;
2597 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2598 addressable_bits.SetAddressableBits(addressing_bits);
2599 }
2600 } else if (key.compare("low_mem_addressing_bits") == 0) {
2601 uint64_t addressing_bits;
2602 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2603 addressable_bits.SetLowmemAddressableBits(addressing_bits);
2604 }
2605 } else if (key.compare("high_mem_addressing_bits") == 0) {
2606 uint64_t addressing_bits;
2607 if (!value.getAsInteger(BASE_10, addressing_bits)) {
2608 addressable_bits.SetHighmemAddressableBits(addressing_bits);
2609 }
2610 } else if (key == "added-binaries") {
2611 // A comma separated list of all threads in the current
2612 // process that includes the thread for this stop reply packet
2614 while (!value.empty()) {
2615 llvm::StringRef pc_str;
2616 std::tie(pc_str, value) = value.split(',');
2617 if (pc_str.getAsInteger(BASE_16, pc))
2619 added_binaries.push_back(pc);
2620 }
2621 } else if (key == "detailed-binaries-info") {
2622 StringExtractor json_extractor(value);
2623 std::string json;
2624 // Now convert the HEX bytes into a string value.
2625 json_extractor.GetHexByteString(json);
2626
2627 // This JSON contains detailed information about binares.
2628 detailed_binaries_info = StructuredData::ParseJSON(json);
2629 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2630 uint32_t reg = UINT32_MAX;
2631 if (!key.getAsInteger(BASE_16, reg))
2632 expedited_register_map[reg] = std::string(std::move(value));
2633 }
2634 // swbreak and hwbreak are also expected keys, but we don't need to
2635 // change our behaviour for them because lldb always expects the remote
2636 // to adjust the program counter (if relevant, e.g., for x86 targets)
2637 }
2638
2639 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2640 Log *log = GetLog(GDBRLog::Process);
2641 LLDB_LOG(log,
2642 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2643 stop_pid, pid);
2644 return eStateInvalid;
2645 }
2646
2647 if (tid == LLDB_INVALID_THREAD_ID) {
2648 // A thread id may be invalid if the response is old style 'S' packet
2649 // which does not provide the
2650 // thread information. So update the thread list and choose the first
2651 // one.
2653
2654 if (!m_thread_ids.empty()) {
2655 tid = m_thread_ids.front();
2656 }
2657 }
2658
2659 SetAddressableBitMasks(addressable_bits);
2660
2662
2663 ThreadSP thread_sp = SetThreadStopInfo(
2664 tid, expedited_register_map, signo, thread_name, reason, description,
2665 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2666 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2667 queue_kind, queue_serial_number, added_binaries,
2668 detailed_binaries_info);
2669
2670 return eStateStopped;
2671 } break;
2672
2673 case 'W':
2674 case 'X':
2675 // process exited
2676 return eStateExited;
2677
2678 default:
2679 break;
2680 }
2681 return eStateInvalid;
2682}
2683
2685 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2686
2687 m_thread_ids.clear();
2688 m_thread_pcs.clear();
2689
2690 // Set the thread stop info. It might have a "threads" key whose value is a
2691 // list of all thread IDs in the current process, so m_thread_ids might get
2692 // set.
2693 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2694 if (m_thread_ids.empty()) {
2695 // No, we need to fetch the thread list manually
2697 }
2698
2699 // We might set some stop info's so make sure the thread list is up to
2700 // date before we do that or we might overwrite what was computed here.
2702
2705 m_last_stop_packet.reset();
2706
2707 // If we have queried for a default thread id
2709 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2713 if (ThreadSP primary_thread_sp = m_thread_list.FindThreadByProtocolID(
2714 m_last_stop_primary_tid, /*can_update=*/false)) {
2715 ThreadSP selected_thread_sp = m_thread_list.GetSelectedThread();
2716 if (!selected_thread_sp ||
2717 selected_thread_sp->GetID() != primary_thread_sp->GetID())
2718 m_thread_list.SetSelectedThreadByID(primary_thread_sp->GetID());
2719 }
2720 }
2722
2723 // Let all threads recover from stopping and do any clean up based on the
2724 // previous thread state (if any).
2725 m_thread_list_real.RefreshStateAfterStop();
2726}
2727
2729 Status error;
2730
2732 // We are being asked to halt during an attach. We used to just close our
2733 // file handle and debugserver will go away, but with remote proxies, it
2734 // is better to send a positive signal, so let's send the interrupt first...
2735 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2736 m_gdb_comm.Disconnect();
2737 } else
2738 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2739 return error;
2740}
2741
2743 Status error;
2744 Log *log = GetLog(GDBRLog::Process);
2745 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2746
2747 error = m_gdb_comm.Detach(keep_stopped);
2748 if (log) {
2749 if (error.Success())
2750 log->PutCString(
2751 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2752 else
2753 LLDB_LOGF(log,
2754 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2755 error.AsCString() ? error.AsCString() : "<unknown error>");
2756 }
2757
2758 if (!error.Success())
2759 return error;
2760
2761 // Sleep for one second to let the process get all detached...
2763
2766
2767 // KillDebugserverProcess ();
2768 return error;
2769}
2770
2772 Log *log = GetLog(GDBRLog::Process);
2773 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2774
2775 // Interrupt if our inferior is running...
2776 int exit_status = SIGABRT;
2777 std::string exit_string;
2778
2779 if (m_gdb_comm.IsConnected()) {
2781 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2782
2783 if (kill_res) {
2784 exit_status = kill_res.get();
2785#if defined(__APPLE__)
2786 // For Native processes on Mac OS X, we launch through the Host
2787 // Platform, then hand the process off to debugserver, which becomes
2788 // the parent process through "PT_ATTACH". Then when we go to kill
2789 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2790 // we call waitpid which returns with no error and the correct
2791 // status. But amusingly enough that doesn't seem to actually reap
2792 // the process, but instead it is left around as a Zombie. Probably
2793 // the kernel is in the process of switching ownership back to lldb
2794 // which was the original parent, and gets confused in the handoff.
2795 // Anyway, so call waitpid here to finally reap it.
2796 PlatformSP platform_sp(GetTarget().GetPlatform());
2797 if (platform_sp && platform_sp->IsHost()) {
2798 int status;
2799 ::pid_t reap_pid;
2800 reap_pid = waitpid(GetID(), &status, WNOHANG);
2801 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2802 }
2803#endif
2805 exit_string.assign("killed");
2806 } else {
2807 exit_string.assign(llvm::toString(kill_res.takeError()));
2808 }
2809 } else {
2810 exit_string.assign("killed or interrupted while attaching.");
2811 }
2812 } else {
2813 // If we missed setting the exit status on the way out, do it here.
2814 // NB set exit status can be called multiple times, the first one sets the
2815 // status.
2816 exit_string.assign("destroying when not connected to debugserver");
2817 }
2818
2819 SetExitStatus(exit_status, exit_string.c_str());
2820
2824 return Status();
2825}
2826
2829 if (TargetSP target_sp = m_target_wp.lock())
2830 target_sp->RemoveBreakpointByID(m_thread_create_bp_sp->GetID());
2831 m_thread_create_bp_sp.reset();
2832 }
2833}
2834
2836 const StringExtractorGDBRemote &response) {
2837 const bool did_exec =
2838 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2839 if (did_exec) {
2840 Log *log = GetLog(GDBRLog::Process);
2841 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2842
2843 m_thread_list_real.Clear();
2844 m_thread_list.Clear();
2846 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2847 }
2848
2849 m_last_stop_packet = response;
2850}
2851
2853 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2854}
2855
2856// Process Queries
2857
2859 return m_gdb_comm.IsConnected() && Process::IsAlive();
2860}
2861
2863 // request the link map address via the $qShlibInfoAddr packet
2864 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2865
2866 // the loaded module list can also provides a link map address
2867 if (addr == LLDB_INVALID_ADDRESS) {
2868 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2869 if (!list) {
2870 Log *log = GetLog(GDBRLog::Process);
2871 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2872 } else {
2873 addr = list->m_link_map;
2874 }
2875 }
2876
2877 return addr;
2878}
2879
2881 // See if the GDB remote client supports the JSON threads info. If so, we
2882 // gather stop info for all threads, expedited registers, expedited memory,
2883 // runtime queue information (iOS and MacOSX only), and more. Expediting
2884 // memory will help stack backtracing be much faster. Expediting registers
2885 // will make sure we don't have to read the thread registers for GPRs.
2886 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2887
2888 if (m_jthreadsinfo_sp) {
2889 // Now set the stop info for each thread and also expedite any registers
2890 // and memory that was in the jThreadsInfo response.
2891 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2892 if (thread_infos) {
2893 const size_t n = thread_infos->GetSize();
2894 for (size_t i = 0; i < n; ++i) {
2895 StructuredData::Dictionary *thread_dict =
2896 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2897 if (thread_dict)
2898 SetThreadStopInfo(thread_dict);
2899 }
2900 }
2901 }
2902}
2903
2904// Process Memory
2905size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2906 Status &error) {
2907 using xPacketState = GDBRemoteCommunicationClient::xPacketState;
2908
2910 xPacketState x_state = m_gdb_comm.GetxPacketState();
2911
2912 // M and m packets take 2 bytes for 1 byte of memory
2913 size_t max_memory_size = x_state != xPacketState::Unimplemented
2915 : m_max_memory_size / 2;
2916 if (size > max_memory_size) {
2917 // Keep memory read sizes down to a sane limit. This function will be
2918 // called multiple times in order to complete the task by
2919 // lldb_private::Process so it is ok to do this.
2920 size = max_memory_size;
2921 }
2922
2923 char packet[64];
2924 int packet_len;
2925 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2926 x_state != xPacketState::Unimplemented ? 'x' : 'm',
2927 (uint64_t)addr, (uint64_t)size);
2928 assert(packet_len + 1 < (int)sizeof(packet));
2929 UNUSED_IF_ASSERT_DISABLED(packet_len);
2930 StringExtractorGDBRemote response;
2931 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2934 if (response.IsNormalResponse()) {
2935 error.Clear();
2936 if (x_state != xPacketState::Unimplemented) {
2937 // The lower level GDBRemoteCommunication packet receive layer has
2938 // already de-quoted any 0x7d character escaping that was present in
2939 // the packet
2940
2941 llvm::StringRef data_received = response.GetStringRef();
2942 if (x_state == xPacketState::Prefixed &&
2943 !data_received.consume_front("b")) {
2945 "unexpected response to GDB server memory read packet '{0}': "
2946 "'{1}'",
2947 packet, data_received);
2948 return 0;
2949 }
2950 // Don't write past the end of BUF if the remote debug server gave us
2951 // too much data for some reason.
2952 size_t memcpy_size = std::min(size, data_received.size());
2953 memcpy(buf, data_received.data(), memcpy_size);
2954 return memcpy_size;
2955 } else {
2956 return response.GetHexBytes(
2957 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2958 }
2959 } else if (response.IsErrorResponse())
2961 "memory read failed for 0x%" PRIx64, addr);
2962 else if (response.IsUnsupportedResponse())
2964 "GDB server does not support reading memory");
2965 else
2967 "unexpected response to GDB server memory read packet '%s': '%s'",
2968 packet, response.GetStringRef().data());
2969 } else {
2970 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
2971 packet);
2972 }
2973 return 0;
2974}
2975
2976/// Returns the number of ranges that is safe to request using MultiMemRead
2977/// while respecting max_packet_size.
2979 uint64_t max_packet_size,
2980 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
2981 // Each range is specified by two numbers (up to 16 ASCII characters) and one
2982 // comma.
2983 constexpr uint64_t range_overhead = 33;
2984 uint64_t current_size = 0;
2985 for (auto [idx, range] : llvm::enumerate(ranges)) {
2986 uint64_t potential_size = current_size + range.size + range_overhead;
2987 if (potential_size > max_packet_size) {
2988 if (idx == 0)
2990 "MultiMemRead input has a range (base = {0:x}, size = {1}) "
2991 "bigger than the maximum allowed by remote",
2992 range.base, range.size);
2993 return idx;
2994 }
2995 }
2996 return ranges.size();
2997}
2998
2999llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
3001 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
3002 llvm::MutableArrayRef<uint8_t> buffer) {
3003 if (!m_gdb_comm.GetMultiMemReadSupported())
3004 return Process::DoReadMemoryRanges(ranges, buffer);
3005
3006 const llvm::ArrayRef<Range<lldb::addr_t, size_t>> original_ranges = ranges;
3007 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory_regions;
3008
3009 while (!ranges.empty()) {
3010 uint64_t num_ranges =
3012 if (num_ranges == 0)
3013 return Process::DoReadMemoryRanges(original_ranges, buffer);
3014
3015 auto ranges_for_request = ranges.take_front(num_ranges);
3016 ranges = ranges.drop_front(num_ranges);
3017
3018 llvm::Expected<StringExtractorGDBRemote> response =
3019 SendMultiMemReadPacket(ranges_for_request);
3020 if (!response) {
3021 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(),
3022 "MultiMemRead error response: {0}");
3023 return Process::DoReadMemoryRanges(original_ranges, buffer);
3024 }
3025
3026 llvm::StringRef response_str = response->GetStringRef();
3027 const unsigned expected_num_ranges = ranges_for_request.size();
3028 if (llvm::Error error = ParseMultiMemReadPacket(
3029 response_str, buffer, expected_num_ranges, memory_regions)) {
3031 "MultiMemRead error parsing response: {0}");
3032 return Process::DoReadMemoryRanges(original_ranges, buffer);
3033 }
3034 }
3035 return memory_regions;
3036}
3037
3038llvm::Expected<StringExtractorGDBRemote>
3040 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
3041 std::string packet_str;
3042 llvm::raw_string_ostream stream(packet_str);
3043 stream << "MultiMemRead:ranges:";
3044
3045 auto range_to_stream = [&](auto range) {
3046 // the "-" marker omits the '0x' prefix.
3047 stream << llvm::formatv("{0:x-},{1:x-}", range.base, range.size);
3048 };
3049 llvm::interleave(ranges, stream, range_to_stream, ",");
3050 stream << ";";
3051
3052 StringExtractorGDBRemote response;
3054 m_gdb_comm.SendPacketAndWaitForResponse(packet_str.data(), response,
3057 return llvm::createStringErrorV("MultiMemRead failed to send packet: '{0}'",
3058 packet_str);
3059
3060 if (response.IsErrorResponse())
3061 return llvm::createStringErrorV("MultiMemRead failed: '{0}'",
3062 response.GetStringRef());
3063
3064 if (!response.IsNormalResponse())
3065 return llvm::createStringErrorV("MultiMemRead unexpected response: '{0}'",
3066 response.GetStringRef());
3067
3068 return response;
3069}
3070
3072 llvm::StringRef response_str, llvm::MutableArrayRef<uint8_t> buffer,
3073 unsigned expected_num_ranges,
3074 llvm::SmallVectorImpl<llvm::MutableArrayRef<uint8_t>> &memory_regions) {
3075 // The sizes and the data are separated by a `;`.
3076 auto [sizes_str, memory_data] = response_str.split(';');
3077 if (sizes_str.size() == response_str.size())
3078 return llvm::createStringErrorV(
3079 "MultiMemRead response missing field separator ';' in: '{0}'",
3080 response_str);
3081
3082 // Sizes are separated by a `,`.
3083 for (llvm::StringRef size_str : llvm::split(sizes_str, ',')) {
3084 uint64_t read_size;
3085 if (size_str.getAsInteger(BASE_16, read_size))
3086 return llvm::createStringErrorV(
3087 "MultiMemRead response has invalid size string: {0}", size_str);
3088
3089 if (memory_data.size() < read_size)
3090 return llvm::createStringErrorV("MultiMemRead response did not have "
3091 "enough data, requested sizes: {0}",
3092 sizes_str);
3093
3094 llvm::StringRef region_to_read = memory_data.take_front(read_size);
3095 memory_data = memory_data.drop_front(read_size);
3096
3097 assert(buffer.size() >= read_size);
3098 llvm::MutableArrayRef<uint8_t> region_to_write =
3099 buffer.take_front(read_size);
3100 buffer = buffer.drop_front(read_size);
3101
3102 memcpy(region_to_write.data(), region_to_read.data(), read_size);
3103 memory_regions.push_back(region_to_write);
3104 }
3105
3106 return llvm::Error::success();
3107}
3108
3110 return m_gdb_comm.GetMemoryTaggingSupported();
3111}
3112
3113llvm::Expected<std::vector<uint8_t>>
3115 int32_t type) {
3116 // By this point ReadMemoryTags has validated that tagging is enabled
3117 // for this target/process/address.
3118 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
3119 if (!buffer_sp) {
3120 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3121 "Error reading memory tags from remote");
3122 }
3123
3124 // Return the raw tag data
3125 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
3126 std::vector<uint8_t> got;
3127 got.reserve(tag_data.size());
3128 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
3129 return got;
3130}
3131
3133 int32_t type,
3134 const std::vector<uint8_t> &tags) {
3135 // By now WriteMemoryTags should have validated that tagging is enabled
3136 // for this target/process.
3137 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
3138}
3139
3141 std::vector<ObjectFile::LoadableData> entries) {
3142 Status error;
3143 // Sort the entries by address because some writes, like those to flash
3144 // memory, must happen in order of increasing address.
3145 llvm::stable_sort(entries, [](const ObjectFile::LoadableData a,
3146 const ObjectFile::LoadableData b) {
3147 return a.Dest < b.Dest;
3148 });
3149 m_allow_flash_writes = true;
3151 if (error.Success())
3152 error = FlashDone();
3153 else
3154 // Even though some of the writing failed, try to send a flash done if some
3155 // of the writing succeeded so the flash state is reset to normal, but
3156 // don't stomp on the error status that was set in the write failure since
3157 // that's the one we want to report back.
3158 FlashDone();
3159 m_allow_flash_writes = false;
3160 return error;
3161}
3162
3164 auto size = m_erased_flash_ranges.GetSize();
3165 for (size_t i = 0; i < size; ++i)
3166 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
3167 return true;
3168 return false;
3169}
3170
3172 Status status;
3173
3174 MemoryRegionInfo region;
3175 status = GetMemoryRegionInfo(addr, region);
3176 if (!status.Success())
3177 return status;
3178
3179 // The gdb spec doesn't say if erasures are allowed across multiple regions,
3180 // but we'll disallow it to be safe and to keep the logic simple by worring
3181 // about only one region's block size. DoMemoryWrite is this function's
3182 // primary user, and it can easily keep writes within a single memory region
3183 if (addr + size > region.GetRange().GetRangeEnd()) {
3184 status =
3185 Status::FromErrorString("Unable to erase flash in multiple regions");
3186 return status;
3187 }
3188
3189 uint64_t blocksize = region.GetBlocksize();
3190 if (blocksize == 0) {
3191 status =
3192 Status::FromErrorString("Unable to erase flash because blocksize is 0");
3193 return status;
3194 }
3195
3196 // Erasures can only be done on block boundary adresses, so round down addr
3197 // and round up size
3198 lldb::addr_t block_start_addr = addr - (addr % blocksize);
3199 size += (addr - block_start_addr);
3200 if ((size % blocksize) != 0)
3201 size += (blocksize - size % blocksize);
3202
3203 FlashRange range(block_start_addr, size);
3204
3205 if (HasErased(range))
3206 return status;
3207
3208 // We haven't erased the entire range, but we may have erased part of it.
3209 // (e.g., block A is already erased and range starts in A and ends in B). So,
3210 // adjust range if necessary to exclude already erased blocks.
3211 if (!m_erased_flash_ranges.IsEmpty()) {
3212 // Assuming that writes and erasures are done in increasing addr order,
3213 // because that is a requirement of the vFlashWrite command. Therefore, we
3214 // only need to look at the last range in the list for overlap.
3215 const auto &last_range = *m_erased_flash_ranges.Back();
3216 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
3217 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
3218 // overlap will be less than range.GetByteSize() or else HasErased()
3219 // would have been true
3220 range.SetByteSize(range.GetByteSize() - overlap);
3221 range.SetRangeBase(range.GetRangeBase() + overlap);
3222 }
3223 }
3224
3225 StreamString packet;
3226 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
3227 (uint64_t)range.GetByteSize());
3228
3229 StringExtractorGDBRemote response;
3230 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3233 if (response.IsOKResponse()) {
3234 m_erased_flash_ranges.Insert(range, true);
3235 } else {
3236 if (response.IsErrorResponse())
3238 "flash erase failed for 0x%" PRIx64, addr);
3239 else if (response.IsUnsupportedResponse())
3241 "GDB server does not support flashing");
3242 else
3244 "unexpected response to GDB server flash erase packet '%s': '%s'",
3245 packet.GetData(), response.GetStringRef().data());
3246 }
3247 } else {
3248 status = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3249 packet.GetData());
3250 }
3251 return status;
3252}
3253
3255 Status status;
3256 // If we haven't erased any blocks, then we must not have written anything
3257 // either, so there is no need to actually send a vFlashDone command
3258 if (m_erased_flash_ranges.IsEmpty())
3259 return status;
3260 StringExtractorGDBRemote response;
3261 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
3264 if (response.IsOKResponse()) {
3265 m_erased_flash_ranges.Clear();
3266 } else {
3267 if (response.IsErrorResponse())
3268 status = Status::FromErrorStringWithFormat("flash done failed");
3269 else if (response.IsUnsupportedResponse())
3271 "GDB server does not support flashing");
3272 else
3274 "unexpected response to GDB server flash done packet: '%s'",
3275 response.GetStringRef().data());
3276 }
3277 } else {
3278 status =
3279 Status::FromErrorStringWithFormat("failed to send flash done packet");
3280 }
3281 return status;
3282}
3283
3284size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
3285 size_t size, Status &error) {
3287 // M and m packets take 2 bytes for 1 byte of memory
3288 size_t max_memory_size = m_max_memory_size / 2;
3289 if (size > max_memory_size) {
3290 // Keep memory read sizes down to a sane limit. This function will be
3291 // called multiple times in order to complete the task by
3292 // lldb_private::Process so it is ok to do this.
3293 size = max_memory_size;
3294 }
3295
3296 StreamGDBRemote packet;
3297
3298 MemoryRegionInfo region;
3299 Status region_status = GetMemoryRegionInfo(addr, region);
3300
3301 bool is_flash = region_status.Success() && region.GetFlash() == eLazyBoolYes;
3302
3303 if (is_flash) {
3304 if (!m_allow_flash_writes) {
3305 error = Status::FromErrorString("Writing to flash memory is not allowed");
3306 return 0;
3307 }
3308 // Keep the write within a flash memory region
3309 if (addr + size > region.GetRange().GetRangeEnd())
3310 size = region.GetRange().GetRangeEnd() - addr;
3311 // Flash memory must be erased before it can be written
3312 error = FlashErase(addr, size);
3313 if (!error.Success())
3314 return 0;
3315 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
3316 packet.PutEscapedBytes(buf, size);
3317 } else {
3318 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
3319 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
3321 }
3322 StringExtractorGDBRemote response;
3323 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3326 if (response.IsOKResponse()) {
3327 error.Clear();
3328 return size;
3329 } else if (response.IsErrorResponse())
3331 "memory write failed for 0x%" PRIx64, addr);
3332 else if (response.IsUnsupportedResponse())
3334 "GDB server does not support writing memory");
3335 else
3337 "unexpected response to GDB server memory write packet '%s': '%s'",
3338 packet.GetData(), response.GetStringRef().data());
3339 } else {
3340 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3341 packet.GetData());
3342 }
3343 return 0;
3344}
3345
3347 uint32_t permissions,
3348 Status &error) {
3350 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3351
3352 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3353 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3354 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3355 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3356 return allocated_addr;
3357 }
3358
3359 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3360 // Call mmap() to create memory in the inferior..
3361 unsigned prot = 0;
3362 if (permissions & lldb::ePermissionsReadable)
3363 prot |= eMmapProtRead;
3364 if (permissions & lldb::ePermissionsWritable)
3365 prot |= eMmapProtWrite;
3366 if (permissions & lldb::ePermissionsExecutable)
3367 prot |= eMmapProtExec;
3368
3369 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3371 m_addr_to_mmap_size[allocated_addr] = size;
3372 else {
3373 allocated_addr = LLDB_INVALID_ADDRESS;
3374 LLDB_LOGF(log,
3375 "ProcessGDBRemote::%s no direct stub support for memory "
3376 "allocation, and InferiorCallMmap also failed - is stub "
3377 "missing register context save/restore capability?",
3378 __FUNCTION__);
3379 }
3380 }
3381
3382 if (allocated_addr == LLDB_INVALID_ADDRESS)
3384 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3385 (uint64_t)size, GetPermissionsAsCString(permissions));
3386 else
3387 error.Clear();
3388 return allocated_addr;
3389}
3390
3392 MemoryRegionInfo &region_info) {
3393
3394 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
3395 return error;
3396}
3397
3399 return m_gdb_comm.GetWatchpointSlotCount();
3400}
3401
3403 return m_gdb_comm.GetWatchpointReportedAfter();
3404}
3405
3407 Status error;
3408 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3409
3410 switch (supported) {
3411 case eLazyBoolCalculate:
3412 // We should never be deallocating memory without allocating memory first
3413 // so we should never get eLazyBoolCalculate
3415 "tried to deallocate memory without ever allocating memory");
3416 break;
3417
3418 case eLazyBoolYes:
3419 if (!m_gdb_comm.DeallocateMemory(addr))
3421 "unable to deallocate memory at 0x%" PRIx64, addr);
3422 break;
3423
3424 case eLazyBoolNo:
3425 // Call munmap() to deallocate memory in the inferior..
3426 {
3427 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3428 if (pos != m_addr_to_mmap_size.end() &&
3429 InferiorCallMunmap(this, addr, pos->second))
3430 m_addr_to_mmap_size.erase(pos);
3431 else
3433 "unable to deallocate memory at 0x%" PRIx64, addr);
3434 }
3435 break;
3436 }
3437
3438 return error;
3439}
3440
3441// Process STDIO
3442size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3443 Status &error) {
3444 if (m_stdio_communication.IsConnected()) {
3445 ConnectionStatus status;
3446 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
3447 } else if (m_stdin_forward) {
3448 m_gdb_comm.SendStdinNotification(src, src_len, GetInterruptTimeout());
3449 }
3450 return 0;
3451}
3452
3453/// Enable a single breakpoint site by trying Z0 (software), then Z1
3454/// (hardware), then manual memory write as a last resort.
3457 const addr_t addr = bp_site.GetLoadAddress();
3458 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3459 auto &gdb_comm = GetGDBRemote();
3460
3461 // SupportsGDBStoppointPacket always returns true unless a previously sent
3462 // packet failed. As such, query the function before AND after sending the
3463 // packet.
3464 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3465 !bp_site.HardwareRequired()) {
3466 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3467 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
3468 if (error_no == 0) {
3469 SetBreakpointSiteEnabled(bp_site);
3471 return llvm::Error::success();
3472 }
3473 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3474 if (error_no != UINT8_MAX)
3475 return llvm::createStringErrorV(
3476 "error sending the breakpoint request: {0}", error_no);
3477 return llvm::createStringError("error sending the breakpoint request");
3478 }
3479 LLDB_LOG(log, "Software breakpoints are unsupported");
3480 }
3481
3482 // Like above, this is also queried twice.
3483 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3484 uint8_t error_no = gdb_comm.SendGDBStoppointTypePacket(
3485 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3486 if (error_no == 0) {
3487 SetBreakpointSiteEnabled(bp_site);
3489 return llvm::Error::success();
3490 }
3491 if (gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3492 if (error_no != UINT8_MAX)
3493 return llvm::createStringErrorV(
3494 "error sending the hardware breakpoint request: {0} "
3495 "(hardware breakpoint resources might be exhausted or unavailable)",
3496 error_no);
3497 return llvm::createStringError(
3498 "error sending the hardware breakpoint request "
3499 "(hardware breakpoint resources might be exhausted or unavailable)");
3500 }
3501 LLDB_LOG(log, "Hardware breakpoints are unsupported");
3502 }
3503
3504 if (bp_site.HardwareRequired())
3505 return llvm::createStringError("hardware breakpoints are not supported");
3506
3507 return EnableSoftwareBreakpoint(&bp_site).takeError();
3508}
3509
3510/// Disable a single breakpoint site directly by sending the appropriate
3511/// z packet or restoring the original instruction.
3513 const addr_t addr = bp_site.GetLoadAddress();
3514 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(&bp_site);
3515 auto &gdb_comm = GetGDBRemote();
3516
3517 switch (bp_site.GetType()) {
3520 if (error.Fail())
3521 return error.takeError();
3522 break;
3523 }
3525 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr,
3526 bp_op_size, GetInterruptTimeout()))
3527 return llvm::createStringError("unknown error");
3528 break;
3530 if (gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false, addr,
3531 bp_op_size, GetInterruptTimeout()))
3532 return llvm::createStringError("unknown error");
3533 break;
3534 }
3535 SetBreakpointSiteEnabled(bp_site, false);
3536 return llvm::Error::success();
3537}
3538
3540 assert(bp_site != nullptr);
3541
3542 // Get logging info
3544 user_id_t site_id = bp_site->GetID();
3545
3546 // Get the breakpoint address
3547 const addr_t addr = bp_site->GetLoadAddress();
3548
3549 // Log that a breakpoint was requested
3550 LLDB_LOGF(log,
3551 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3552 ") address = 0x%" PRIx64,
3553 site_id, (uint64_t)addr);
3554
3555 // Breakpoint already exists and is enabled
3556 if (IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3557 LLDB_LOGF(log,
3558 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3559 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3560 site_id, (uint64_t)addr);
3561 return Status();
3562 }
3563
3564 return Status::FromError(DoEnableBreakpointSite(*bp_site));
3565}
3566
3568 assert(bp_site != nullptr);
3569 addr_t addr = bp_site->GetLoadAddress();
3570 user_id_t site_id = bp_site->GetID();
3572 LLDB_LOGF(log,
3573 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3574 ") addr = 0x%8.8" PRIx64,
3575 site_id, (uint64_t)addr);
3576
3577 if (!IsBreakpointSitePhysicallyEnabled(*bp_site)) {
3578 LLDB_LOGF(log,
3579 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3580 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3581 site_id, (uint64_t)addr);
3582 return Status();
3583 }
3584
3586}
3587
3588// Pre-requisite: wp != NULL.
3589static GDBStoppointType
3591 assert(wp_res_sp);
3592 bool read = wp_res_sp->WatchpointResourceRead();
3593 bool write = wp_res_sp->WatchpointResourceWrite();
3594
3595 assert((read || write) &&
3596 "WatchpointResource type is neither read nor write");
3597 if (read && write)
3598 return eWatchpointReadWrite;
3599 else if (read)
3600 return eWatchpointRead;
3601 else
3602 return eWatchpointWrite;
3603}
3604
3606 Status error;
3607 if (!wp_sp) {
3608 error = Status::FromErrorString("No watchpoint specified");
3609 return error;
3610 }
3611 user_id_t watchID = wp_sp->GetID();
3612 addr_t addr = wp_sp->GetLoadAddress();
3614 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3615 watchID);
3616 if (wp_sp->IsEnabled()) {
3617 LLDB_LOGF(log,
3618 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3619 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3620 watchID, (uint64_t)addr);
3621 return error;
3622 }
3623
3624 bool read = wp_sp->WatchpointRead();
3625 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3626 size_t size = wp_sp->GetByteSize();
3627
3628 ArchSpec target_arch = GetTarget().GetArchitecture();
3629 WatchpointHardwareFeature supported_features =
3630 m_gdb_comm.GetSupportedWatchpointTypes();
3631
3632 std::vector<WatchpointResourceSP> resources =
3634 addr, size, read, write, supported_features, target_arch);
3635
3636 // LWP_TODO: Now that we know the WP Resources needed to implement this
3637 // Watchpoint, we need to look at currently allocated Resources in the
3638 // Process and if they match, or are within the same memory granule, or
3639 // overlapping memory ranges, then we need to combine them. e.g. one
3640 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1
3641 // byte at 0x1003, they must use the same hardware watchpoint register
3642 // (Resource) to watch them.
3643
3644 // This may mean that an existing resource changes its type (read to
3645 // read+write) or address range it is watching, in which case the old
3646 // watchpoint needs to be disabled and the new Resource addr/size/type
3647 // watchpoint enabled.
3648
3649 // If we modify a shared Resource to accomodate this newly added Watchpoint,
3650 // and we are unable to set all of the Resources for it in the inferior, we
3651 // will return an error for this Watchpoint and the shared Resource should
3652 // be restored. e.g. this Watchpoint requires three Resources, one which
3653 // is shared with another Watchpoint. We extend the shared Resouce to
3654 // handle both Watchpoints and we try to set two new ones. But if we don't
3655 // have sufficient watchpoint register for all 3, we need to show an error
3656 // for creating this Watchpoint and we should reset the shared Resource to
3657 // its original configuration because it is no longer shared.
3658
3659 bool set_all_resources = true;
3660 std::vector<WatchpointResourceSP> succesfully_set_resources;
3661 for (const auto &wp_res_sp : resources) {
3662 addr_t addr = wp_res_sp->GetLoadAddress();
3663 size_t size = wp_res_sp->GetByteSize();
3664 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3665 if (!m_gdb_comm.SupportsGDBStoppointPacket(type) ||
3666 m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size,
3668 set_all_resources = false;
3669 break;
3670 } else {
3671 succesfully_set_resources.push_back(wp_res_sp);
3672 }
3673 }
3674 if (set_all_resources) {
3675 wp_sp->SetEnabled(true, notify);
3676 for (const auto &wp_res_sp : resources) {
3677 // LWP_TODO: If we expanded/reused an existing Resource,
3678 // it's already in the WatchpointResourceList.
3679 wp_res_sp->AddConstituent(wp_sp);
3680 m_watchpoint_resource_list.Add(wp_res_sp);
3681 }
3682 return error;
3683 } else {
3684 // We failed to allocate one of the resources. Unset all
3685 // of the new resources we did successfully set in the
3686 // process.
3687 for (const auto &wp_res_sp : succesfully_set_resources) {
3688 addr_t addr = wp_res_sp->GetLoadAddress();
3689 size_t size = wp_res_sp->GetByteSize();
3690 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3691 m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3693 }
3695 "Setting one of the watchpoint resources failed");
3696 }
3697 return error;
3698}
3699
3701 Status error;
3702 if (!wp_sp) {
3703 error = Status::FromErrorString("Watchpoint argument was NULL.");
3704 return error;
3705 }
3706
3707 user_id_t watchID = wp_sp->GetID();
3708
3710
3711 addr_t addr = wp_sp->GetLoadAddress();
3712
3713 LLDB_LOGF(log,
3714 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3715 ") addr = 0x%8.8" PRIx64,
3716 watchID, (uint64_t)addr);
3717
3718 if (!wp_sp->IsEnabled()) {
3719 LLDB_LOGF(log,
3720 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3721 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3722 watchID, (uint64_t)addr);
3723 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3724 // attempt might come from the user-supplied actions, we'll route it in
3725 // order for the watchpoint object to intelligently process this action.
3726 wp_sp->SetEnabled(false, notify);
3727 return error;
3728 }
3729
3730 if (wp_sp->IsHardware()) {
3731 bool disabled_all = true;
3732
3733 std::vector<WatchpointResourceSP> unused_resources;
3734 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
3735 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3736 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3737 addr_t addr = wp_res_sp->GetLoadAddress();
3738 size_t size = wp_res_sp->GetByteSize();
3739 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3741 disabled_all = false;
3742 } else {
3743 wp_res_sp->RemoveConstituent(wp_sp);
3744 if (wp_res_sp->GetNumberOfConstituents() == 0)
3745 unused_resources.push_back(wp_res_sp);
3746 }
3747 }
3748 }
3749 for (auto &wp_res_sp : unused_resources)
3750 m_watchpoint_resource_list.Remove(wp_res_sp->GetID());
3751
3752 wp_sp->SetEnabled(false, notify);
3753 if (!disabled_all)
3755 "Failure disabling one of the watchpoint locations");
3756 }
3757 return error;
3758}
3759
3761 m_thread_list_real.Clear();
3762 m_thread_list.Clear();
3763}
3764
3766 Status error;
3767 Log *log = GetLog(GDBRLog::Process);
3768 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3769
3770 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3771 error =
3772 Status::FromErrorStringWithFormat("failed to send signal %i", signo);
3773 return error;
3774}
3775
3776Status
3778 // Make sure we aren't already connected?
3779 if (m_gdb_comm.IsConnected())
3780 return Status();
3781
3782 PlatformSP platform_sp(GetTarget().GetPlatform());
3783 if (platform_sp && !platform_sp->IsHost())
3784 return Status::FromErrorString("Lost debug server connection");
3785
3786 auto error = LaunchAndConnectToDebugserver(process_info);
3787 if (error.Fail()) {
3788 const char *error_string = error.AsCString();
3789 if (error_string == nullptr)
3790 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3791 }
3792 return error;
3793}
3794
3796 Log *log = GetLog(GDBRLog::Process);
3797 // If we locate debugserver, keep that located version around
3798 static FileSpec g_debugserver_file_spec;
3799 FileSpec debugserver_file_spec;
3800
3801 Environment host_env = Host::GetEnvironment();
3802
3803 // Always check to see if we have an environment override for the path to the
3804 // debugserver to use and use it if we do.
3805 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
3806 if (!env_debugserver_path.empty()) {
3807 debugserver_file_spec.SetFile(env_debugserver_path,
3808 FileSpec::Style::native);
3809 LLDB_LOG(log, "gdb-remote stub exe path set from environment variable: {0}",
3810 env_debugserver_path);
3811 } else
3812 debugserver_file_spec = g_debugserver_file_spec;
3813 if (FileSystem::Instance().Exists(debugserver_file_spec))
3814 return debugserver_file_spec;
3815
3816 // The debugserver binary is in the LLDB.framework/Resources directory.
3817 debugserver_file_spec = HostInfo::GetSupportExeDir();
3818 if (debugserver_file_spec) {
3819 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
3820 if (FileSystem::Instance().Exists(debugserver_file_spec)) {
3821 LLDB_LOG(log, "found gdb-remote stub exe '{0}'", debugserver_file_spec);
3822
3823 g_debugserver_file_spec = debugserver_file_spec;
3824 } else {
3825 debugserver_file_spec = platform.LocateExecutable(DEBUGSERVER_BASENAME);
3826 if (!debugserver_file_spec) {
3827 // Platform::LocateExecutable() wouldn't return a path if it doesn't
3828 // exist
3829 LLDB_LOG(log, "could not find gdb-remote stub exe '{0}'",
3830 debugserver_file_spec);
3831 }
3832 // Don't cache the platform specific GDB server binary as it could
3833 // change from platform to platform
3834 g_debugserver_file_spec.Clear();
3835 }
3836 }
3837 return debugserver_file_spec;
3838}
3839
3841 const ProcessInfo &process_info) {
3842 using namespace std::placeholders; // For _1, _2, etc.
3843
3845 return Status();
3846
3847 ProcessLaunchInfo debugserver_launch_info;
3848 // Make debugserver run in its own session so signals generated by special
3849 // terminal key sequences (^C) don't affect debugserver.
3850 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3851
3852 const std::weak_ptr<ProcessGDBRemote> this_wp =
3853 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3854 debugserver_launch_info.SetMonitorProcessCallback(
3855 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3856 debugserver_launch_info.SetUserID(process_info.GetUserID());
3857
3858 FileSpec debugserver_path = GetDebugserverPath(*GetTarget().GetPlatform());
3859
3860#if defined(__APPLE__)
3861 // On macOS 11, we need to support x86_64 applications translated to
3862 // arm64. We check whether a binary is translated and spawn the correct
3863 // debugserver accordingly.
3864 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID,
3865 static_cast<int>(process_info.GetProcessID())};
3866 struct kinfo_proc processInfo;
3867 size_t bufsize = sizeof(processInfo);
3868 if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize,
3869 NULL, 0) == 0 &&
3870 bufsize > 0) {
3871 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3872 debugserver_path = FileSpec("/Library/Apple/usr/libexec/oah/debugserver");
3873 }
3874 }
3875#endif
3876
3877 if (!FileSystem::Instance().Exists(debugserver_path))
3878 return Status::FromErrorString("could not find '" DEBUGSERVER_BASENAME
3879 "'. Please ensure it is properly installed "
3880 "and available in your PATH");
3881
3882 debugserver_launch_info.SetExecutableFile(debugserver_path,
3883 /*add_exe_file_as_first_arg=*/true);
3884
3885 llvm::Expected<Socket::Pair> socket_pair = Socket::CreatePair();
3886 if (!socket_pair)
3887 return Status::FromError(socket_pair.takeError());
3888
3889 Status error;
3890 SharedSocket shared_socket(socket_pair->first.get(), error);
3891 if (error.Fail())
3892 return error;
3893
3894 error = m_gdb_comm.StartDebugserverProcess(shared_socket.GetSendableFD(),
3895 debugserver_launch_info, nullptr);
3896
3897 if (error.Fail()) {
3898 Log *log = GetLog(GDBRLog::Process);
3899
3900 LLDB_LOGF(log, "failed to start debugserver process: %s",
3901 error.AsCString());
3902 return error;
3903 }
3904
3905 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3906 shared_socket.CompleteSending(m_debugserver_pid);
3907
3908 // Our process spawned correctly, we can now set our connection to use
3909 // our end of the socket pair
3910 m_gdb_comm.SetConnection(std::make_unique<ConnectionFileDescriptor>(
3911 std::move(socket_pair->second)));
3913
3914 if (m_gdb_comm.IsConnected()) {
3915 // Finish the connection process by doing the handshake without
3916 // connecting (send NULL URL)
3918 } else {
3919 error = Status::FromErrorString("connection failed");
3920 }
3921 return error;
3922}
3923
3925 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3926 int signo, // Zero for no signal
3927 int exit_status // Exit value of process if signal is zero
3928) {
3929 // "debugserver_pid" argument passed in is the process ID for debugserver
3930 // that we are tracking...
3931 Log *log = GetLog(GDBRLog::Process);
3932
3933 LLDB_LOGF(log,
3934 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3935 ", signo=%i (0x%x), exit_status=%i)",
3936 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3937
3938 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3939 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3940 static_cast<void *>(process_sp.get()));
3941 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3942 return;
3943
3944 // Sleep for a half a second to make sure our inferior process has time to
3945 // set its exit status before we set it incorrectly when both the debugserver
3946 // and the inferior process shut down.
3947 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3948
3949 // If our process hasn't yet exited, debugserver might have died. If the
3950 // process did exit, then we are reaping it.
3951 const StateType state = process_sp->GetState();
3952
3953 if (state != eStateInvalid && state != eStateUnloaded &&
3954 state != eStateExited && state != eStateDetached) {
3955 StreamString stream;
3956 if (signo == 0)
3957 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",
3958 exit_status);
3959 else {
3960 llvm::StringRef signal_name =
3961 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
3962 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";
3963 if (!signal_name.empty())
3964 stream.Format(format_str, signal_name);
3965 else
3966 stream.Format(format_str, signo);
3967 }
3968 process_sp->SetExitStatus(-1, stream.GetString());
3969 }
3970 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3971 // longer has a debugserver instance
3972 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3973}
3974
3982
3988
3991 debugger, PluginProperties::GetSettingName())) {
3992 const bool is_global_setting = true;
3995 "Properties for the gdb-remote process plug-in.", is_global_setting);
3996 }
3997}
3998
4000 Log *log = GetLog(GDBRLog::Process);
4001
4002 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4003
4004 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4005 if (!m_async_thread.IsJoinable()) {
4006 // Create a thread that watches our internal state and controls which
4007 // events make it to clients (into the DCProcess event queue).
4008
4009 llvm::Expected<HostThread> async_thread =
4010 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
4012 });
4013 if (!async_thread) {
4014 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
4015 "failed to launch host thread: {0}");
4016 return false;
4017 }
4018 m_async_thread = *async_thread;
4019 } else
4020 LLDB_LOGF(log,
4021 "ProcessGDBRemote::%s () - Called when Async thread was "
4022 "already running.",
4023 __FUNCTION__);
4024
4025 return m_async_thread.IsJoinable();
4026}
4027
4029 Log *log = GetLog(GDBRLog::Process);
4030
4031 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
4032
4033 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
4034 if (m_async_thread.IsJoinable()) {
4036
4037 // This will shut down the async thread.
4038 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
4039
4040 // Stop the stdio thread
4041 m_async_thread.Join(nullptr);
4042 m_async_thread.Reset();
4043 } else
4044 LLDB_LOGF(
4045 log,
4046 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
4047 __FUNCTION__);
4048}
4049
4051 Log *log = GetLog(GDBRLog::Process);
4052 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
4053 __FUNCTION__, GetID());
4054
4055 EventSP event_sp;
4056
4057 // We need to ignore any packets that come in after we have
4058 // have decided the process has exited. There are some
4059 // situations, for instance when we try to interrupt a running
4060 // process and the interrupt fails, where another packet might
4061 // get delivered after we've decided to give up on the process.
4062 // But once we've decided we are done with the process we will
4063 // not be in a state to do anything useful with new packets.
4064 // So it is safer to simply ignore any remaining packets by
4065 // explicitly checking for eStateExited before reentering the
4066 // fetch loop.
4067
4068 bool done = false;
4069 while (!done && GetPrivateState() != eStateExited) {
4070 LLDB_LOGF(log,
4071 "ProcessGDBRemote::%s(pid = %" PRIu64
4072 ") listener.WaitForEvent (NULL, event_sp)...",
4073 __FUNCTION__, GetID());
4074
4075 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
4076 const uint32_t event_type = event_sp->GetType();
4077 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
4078 LLDB_LOGF(log,
4079 "ProcessGDBRemote::%s(pid = %" PRIu64
4080 ") Got an event of type: %d...",
4081 __FUNCTION__, GetID(), event_type);
4082
4083 switch (event_type) {
4085 const EventDataBytes *continue_packet =
4087
4088 if (continue_packet) {
4089 const char *continue_cstr =
4090 (const char *)continue_packet->GetBytes();
4091 const size_t continue_cstr_len = continue_packet->GetByteSize();
4092 LLDB_LOGF(log,
4093 "ProcessGDBRemote::%s(pid = %" PRIu64
4094 ") got eBroadcastBitAsyncContinue: %s",
4095 __FUNCTION__, GetID(), continue_cstr);
4096
4097 if (::strstr(continue_cstr, "vAttach") == nullptr)
4099 StringExtractorGDBRemote response;
4100
4101 StateType stop_state =
4103 *this, *GetUnixSignals(),
4104 llvm::StringRef(continue_cstr, continue_cstr_len),
4105 GetInterruptTimeout(), response);
4106
4107 // We need to immediately clear the thread ID list so we are sure
4108 // to get a valid list of threads. The thread ID list might be
4109 // contained within the "response", or the stop reply packet that
4110 // caused the stop. So clear it now before we give the stop reply
4111 // packet to the process using the
4112 // SetLastStopPacket()...
4114
4115 switch (stop_state) {
4116 case eStateStopped:
4117 case eStateCrashed:
4118 case eStateSuspended:
4119 SetLastStopPacket(response);
4120 SetPrivateState(stop_state);
4121 break;
4122
4123 case eStateExited: {
4124 SetLastStopPacket(response);
4126 response.SetFilePos(1);
4127
4128 int exit_status = response.GetHexU8();
4129 std::string desc_string;
4130 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
4131 llvm::StringRef desc_str;
4132 llvm::StringRef desc_token;
4133 while (response.GetNameColonValue(desc_token, desc_str)) {
4134 if (desc_token != "description")
4135 continue;
4136 StringExtractor extractor(desc_str);
4137 extractor.GetHexByteString(desc_string);
4138 }
4139 }
4140 SetExitStatus(exit_status, desc_string.c_str());
4141 done = true;
4142 break;
4143 }
4144 case eStateInvalid: {
4145 // Check to see if we were trying to attach and if we got back
4146 // the "E87" error code from debugserver -- this indicates that
4147 // the process is not debuggable. Return a slightly more
4148 // helpful error message about why the attach failed.
4149 if (::strstr(continue_cstr, "vAttach") != nullptr &&
4150 response.GetError() == 0x87) {
4151 SetExitStatus(-1, "cannot attach to process due to "
4152 "System Integrity Protection");
4153 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
4154 response.GetStatus().Fail()) {
4155 SetExitStatus(-1, response.GetStatus().AsCString());
4156 } else {
4157 SetExitStatus(-1, "lost connection");
4158 }
4159 done = true;
4160 break;
4161 }
4162
4163 default:
4164 SetPrivateState(stop_state);
4165 break;
4166 } // switch(stop_state)
4167 } // if (continue_packet)
4168 } // case eBroadcastBitAsyncContinue
4169 break;
4170
4172 LLDB_LOGF(log,
4173 "ProcessGDBRemote::%s(pid = %" PRIu64
4174 ") got eBroadcastBitAsyncThreadShouldExit...",
4175 __FUNCTION__, GetID());
4176 done = true;
4177 break;
4178
4179 default:
4180 LLDB_LOGF(log,
4181 "ProcessGDBRemote::%s(pid = %" PRIu64
4182 ") got unknown event 0x%8.8x",
4183 __FUNCTION__, GetID(), event_type);
4184 done = true;
4185 break;
4186 }
4187 }
4188 } else {
4189 LLDB_LOGF(log,
4190 "ProcessGDBRemote::%s(pid = %" PRIu64
4191 ") listener.WaitForEvent (NULL, event_sp) => false",
4192 __FUNCTION__, GetID());
4193 done = true;
4194 }
4195 }
4196
4197 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
4198 __FUNCTION__, GetID());
4199
4200 return {};
4201}
4202
4203// uint32_t
4204// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
4205// &matches, std::vector<lldb::pid_t> &pids)
4206//{
4207// // If we are planning to launch the debugserver remotely, then we need to
4208// fire up a debugserver
4209// // process and ask it for the list of processes. But if we are local, we
4210// can let the Host do it.
4211// if (m_local_debugserver)
4212// {
4213// return Host::ListProcessesMatchingName (name, matches, pids);
4214// }
4215// else
4216// {
4217// // FIXME: Implement talking to the remote debugserver.
4218// return 0;
4219// }
4220//
4221//}
4222//
4224 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4225 lldb::user_id_t break_loc_id) {
4226 // I don't think I have to do anything here, just make sure I notice the new
4227 // thread when it starts to
4228 // run so I can stop it if that's what I want to do.
4229 Log *log = GetLog(LLDBLog::Step);
4230 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
4231 return false;
4232}
4233
4234namespace {
4235/// Baton that carries the breakpoint hit arguments to the accelerator plugin
4236/// breakpoint callback.
4237class AcceleratorBreakpointCallbackBaton
4238 : public TypedBaton<AcceleratorBreakpointHitArgs> {
4239public:
4240 explicit AcceleratorBreakpointCallbackBaton(
4241 std::unique_ptr<AcceleratorBreakpointHitArgs> data)
4242 : TypedBaton(std::move(data)) {}
4243};
4244} // namespace
4245
4246llvm::Error
4248 Log *log = GetLog(GDBRLog::Process);
4249
4250 // The same set of actions can be delivered to the client more than once: a
4251 // plugin may keep reporting the same actions (with the same identifier) on
4252 // subsequent native stops until its state advances. The identifier uniquely
4253 // names a set of actions for a plugin, so skip any set we have already
4254 // processed to avoid re-running its side effects (e.g. setting the same
4255 // breakpoints again).
4256 auto it = m_processed_accelerator_actions.find(actions.plugin_name);
4257 if (it != m_processed_accelerator_actions.end() &&
4258 it->second == actions.identifier) {
4259 LLDB_LOG(log,
4260 "ProcessGDBRemote::HandleAcceleratorActions skipping already "
4261 "processed actions for plugin '{0}' with identifier {1}",
4262 actions.plugin_name, actions.identifier);
4263 return llvm::Error::success();
4264 }
4266
4267 // Handle each kind of action. More action kinds will be handled here in the
4268 // future, so only return early on error; otherwise fall through so the next
4269 // kind of action still gets a chance to run.
4270 if (!actions.breakpoints.empty()) {
4271 if (llvm::Error error = HandleAcceleratorBreakpoints(actions))
4272 return error;
4273 }
4274
4275 if (actions.connect_info) {
4276 if (llvm::Error error = HandleAcceleratorConnection(actions))
4277 return error;
4278 }
4279
4280 return llvm::Error::success();
4281}
4282
4284 const AcceleratorActions &actions) {
4285 const AcceleratorConnectionInfo &connect_info = *actions.connect_info;
4286 Debugger &debugger = GetTarget().GetDebugger();
4287
4288 OptionGroupPlatform platform_options(/*include_platform_option=*/false);
4289 platform_options.SetPlatformName(connect_info.platform_name.c_str());
4290 std::string exe_path = connect_info.exe_path.value_or("");
4291 TargetSP accelerator_target_sp;
4293 debugger, exe_path, connect_info.triple, eLoadDependentsNo,
4294 &platform_options, accelerator_target_sp);
4295 if (error.Fail())
4296 return error.takeError();
4297 if (!accelerator_target_sp)
4298 return llvm::createStringError("failed to create accelerator target");
4299
4300 PlatformSP platform_sp = accelerator_target_sp->GetPlatform();
4301 if (!platform_sp)
4302 return llvm::createStringErrorV(
4303 "no platform '{0}' compatible with triple '{1}' for the accelerator "
4304 "target",
4305 connect_info.platform_name, connect_info.triple);
4306 ProcessSP process_sp =
4307 connect_info.synchronous
4308 ? platform_sp->ConnectProcessSynchronous(
4309 connect_info.connect_url, GetPluginNameStatic(), debugger,
4310 *debugger.GetAsyncOutputStream(), accelerator_target_sp.get(),
4311 error)
4312 : platform_sp->ConnectProcess(connect_info.connect_url,
4313 GetPluginNameStatic(), debugger,
4314 accelerator_target_sp.get(), error);
4315 if (error.Fail())
4316 return error.takeError();
4317 if (!process_sp)
4318 return llvm::createStringError("failed to connect to the accelerator");
4319
4320 accelerator_target_sp->SetTargetSessionName(actions.session_name);
4321
4322 // Broadcast the new-target event so API clients can detect it.
4323 auto event_sp = std::make_shared<Event>(
4325 new Target::TargetEventData(GetTarget().shared_from_this(),
4326 accelerator_target_sp));
4327 GetTarget().BroadcastEvent(event_sp);
4328 return llvm::Error::success();
4329}
4330
4332 const AcceleratorActions &actions) {
4333 Target &target = GetTarget();
4334 llvm::Error error = llvm::Error::success();
4335 for (const AcceleratorBreakpointInfo &bp : actions.breakpoints) {
4336 // Carry data with the breakpoint so the callback can notify the plugin
4337 // when the breakpoint is hit.
4338 auto args_up = std::make_unique<AcceleratorBreakpointHitArgs>();
4339 args_up->plugin_name = actions.plugin_name;
4340 args_up->breakpoint = bp;
4341
4342 // Each breakpoint must specify exactly one of by_name or by_address. Bad
4343 // breakpoints are collected as errors but don't stop the remaining ones
4344 // from being set.
4345 BreakpointSP bp_sp;
4346 if (bp.by_name && bp.by_address) {
4347 error = llvm::joinErrors(
4348 std::move(error),
4349 llvm::createStringErrorV(
4350 "accelerator breakpoint {0} specifies both a by_name and a "
4351 "by_address specification",
4352 bp.identifier));
4353 continue;
4354 } else if (bp.by_name) {
4355 FileSpecList bp_modules;
4356 if (bp.by_name->shlib && !bp.by_name->shlib->empty())
4357 bp_modules.Append(FileSpec(*bp.by_name->shlib));
4358 bp_sp = target.CreateBreakpoint(
4359 bp_modules.GetSize() ? &bp_modules : nullptr, // Containing modules.
4360 nullptr, // Containing source.
4361 bp.by_name->function_name.c_str(), // Function name.
4362 eFunctionNameTypeFull, // Function name type.
4363 eLanguageTypeUnknown, // Language type.
4364 0, // Byte offset.
4365 false, // Offset is insn count.
4366 eLazyBoolNo, // Skip prologue.
4367 true, // Internal breakpoint.
4368 false); // Request hardware.
4369 } else if (bp.by_address) {
4370 bp_sp = target.CreateBreakpoint(bp.by_address->load_address,
4371 /*internal=*/true,
4372 /*request_hardware=*/false);
4373 } else {
4374 error = llvm::joinErrors(
4375 std::move(error),
4376 llvm::createStringErrorV(
4377 "accelerator breakpoint {0} has neither a by_name nor a "
4378 "by_address specification",
4379 bp.identifier));
4380 continue;
4381 }
4382
4383 if (!bp_sp) {
4384 error = llvm::joinErrors(
4385 std::move(error),
4386 llvm::createStringErrorV("failed to set accelerator breakpoint {0}",
4387 bp.identifier));
4388 continue;
4389 }
4390
4391 // Give the internal breakpoint a meaningful description for stop reasons,
4392 // including the plugin that requested it.
4393 std::string kind =
4394 llvm::formatv("accelerator-plugin ({0})", actions.plugin_name);
4395 bp_sp->SetBreakpointKind(kind.c_str());
4396 auto baton_sp = std::make_shared<AcceleratorBreakpointCallbackBaton>(
4397 std::move(args_up));
4398 bp_sp->SetCallback(AcceleratorBreakpointHitCallback, baton_sp,
4399 /*is_synchronous=*/true);
4400 }
4401 return error;
4402}
4403
4405 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4406 lldb::user_id_t break_loc_id) {
4407 ProcessSP process_sp = context->exe_ctx_ref.GetProcessSP();
4408 ProcessGDBRemote *process = static_cast<ProcessGDBRemote *>(process_sp.get());
4409 return process->AcceleratorBreakpointHit(baton, context, break_id,
4410 break_loc_id);
4411}
4412
4414 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4415 lldb::user_id_t break_loc_id) {
4416 AcceleratorBreakpointHitArgs *callback_data =
4417 static_cast<AcceleratorBreakpointHitArgs *>(baton);
4418 // Copy the args so we can fill in requested symbol values before notifying
4419 // lldb-server.
4420 AcceleratorBreakpointHitArgs args = *callback_data;
4421 Target &target = GetTarget();
4422
4423 const std::vector<std::string> &symbol_names = args.breakpoint.symbol_names;
4424 args.symbol_values.resize(symbol_names.size());
4425 for (size_t i = 0; i < symbol_names.size(); ++i) {
4426 args.symbol_values[i].name = symbol_names[i];
4427 SymbolContextList sc_list;
4428 target.GetImages().FindSymbolsWithNameAndType(ConstString(symbol_names[i]),
4429 eSymbolTypeAny, sc_list);
4430 for (const SymbolContext &sc : sc_list) {
4431 if (!sc.symbol)
4432 continue;
4433 addr_t load_addr = sc.symbol->GetAddress().GetLoadAddress(&target);
4434 if (load_addr != LLDB_INVALID_ADDRESS) {
4435 args.symbol_values[i].value = load_addr;
4436 break;
4437 }
4438 }
4439 }
4440
4441 Log *log = GetLog(GDBRLog::Process);
4442 llvm::Expected<AcceleratorBreakpointHitResponse> response =
4443 m_gdb_comm.AcceleratorBreakpointHit(args);
4444 if (!response) {
4445 LLDB_LOG_ERROR(log, response.takeError(),
4446 "accelerator breakpoint hit notification failed: {0}");
4447 // We could not reach the plugin, so auto-resume rather than stopping the
4448 // native process at an internal breakpoint the user can't see.
4449 return false;
4450 }
4451
4452 // Disable the breakpoint if requested, but keep it around so its hit count
4453 // and other stats remain visible.
4454 if (response->disable_bp) {
4455 if (BreakpointSP bp_sp = target.GetBreakpointByID(break_id))
4456 bp_sp->SetEnabled(false);
4457 }
4458
4459 // The plugin may request new actions (e.g. additional breakpoints) in
4460 // response to this breakpoint being hit.
4461 if (response->actions) {
4462 if (llvm::Error error = HandleAcceleratorActions(*response->actions)) {
4463 // Also print the failure to the user; during a stop, logging alone is
4464 // invisible.
4465 std::string message = llvm::toString(std::move(error));
4466 LLDB_LOG(log, "failed to handle accelerator actions: {0}", message);
4467 target.GetDebugger().GetAsyncErrorStream()->Printf(
4468 "error: accelerator plugin '%s': %s\n",
4469 response->actions->plugin_name.c_str(), message.c_str());
4470 }
4471 }
4472
4473 // Returning true stops the native process; false auto-resumes it.
4474 return !response->auto_resume_native;
4475}
4476
4478 Log *log = GetLog(GDBRLog::Process);
4479 LLDB_LOG(log, "Check if need to update ignored signals");
4480
4481 // QPassSignals package is not supported by the server, there is no way we
4482 // can ignore any signals on server side.
4483 if (!m_gdb_comm.GetQPassSignalsSupported())
4484 return Status();
4485
4486 // No signals, nothing to send.
4487 if (m_unix_signals_sp == nullptr)
4488 return Status();
4489
4490 // Signals' version hasn't changed, no need to send anything.
4491 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
4492 if (new_signals_version == m_last_signals_version) {
4493 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
4495 return Status();
4496 }
4497
4498 auto signals_to_ignore =
4499 m_unix_signals_sp->GetFilteredSignals(false, false, false);
4500 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
4501
4502 LLDB_LOG(log,
4503 "Signals' version changed. old version={0}, new version={1}, "
4504 "signals ignored={2}, update result={3}",
4505 m_last_signals_version, new_signals_version,
4506 signals_to_ignore.size(), error);
4507
4508 if (error.Success())
4509 m_last_signals_version = new_signals_version;
4510
4511 return error;
4512}
4513
4515 Log *log = GetLog(LLDBLog::Step);
4517 LLDB_LOGF_VERBOSE(log, "Enabled noticing new thread breakpoint.");
4518 m_thread_create_bp_sp->SetEnabled(true);
4519 } else {
4520 PlatformSP platform_sp(GetTarget().GetPlatform());
4521 if (platform_sp) {
4523 platform_sp->SetThreadCreationBreakpoint(GetTarget());
4526 log, "Successfully created new thread notification breakpoint %i",
4527 m_thread_create_bp_sp->GetID());
4528 m_thread_create_bp_sp->SetCallback(
4530 } else {
4531 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
4532 }
4533 }
4534 }
4535 return m_thread_create_bp_sp.get() != nullptr;
4536}
4537
4539 Log *log = GetLog(LLDBLog::Step);
4540 LLDB_LOGF_VERBOSE(log, "Disabling new thread notification breakpoint.");
4541
4543 m_thread_create_bp_sp->SetEnabled(false);
4544
4545 return true;
4546}
4547
4549 if (m_dyld_up.get() == nullptr)
4550 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
4551 return m_dyld_up.get();
4552}
4553
4555 int return_value;
4556 bool was_supported;
4557
4558 Status error;
4559
4560 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4561 if (return_value != 0) {
4562 if (!was_supported)
4564 "Sending events is not supported for this process.");
4565 else
4566 error = Status::FromErrorStringWithFormat("Error sending event data: %d.",
4567 return_value);
4568 }
4569 return error;
4570}
4571
4573 DataBufferSP buf;
4574 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4575 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
4576 if (response)
4577 buf = std::make_shared<DataBufferHeap>(response->c_str(),
4578 response->length());
4579 else
4580 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
4581 }
4583}
4584
4587 StructuredData::ObjectSP object_sp;
4588
4589 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
4591 SystemRuntime *runtime = GetSystemRuntime();
4592 if (runtime) {
4593 runtime->AddThreadExtendedInfoPacketHints(args_dict);
4594 }
4595 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
4596
4597 StreamString packet;
4598 packet << "jThreadExtendedInfo:";
4599 args_dict->Dump(packet, false);
4600
4601 // FIXME the final character of a JSON dictionary, '}', is the escape
4602 // character in gdb-remote binary mode. lldb currently doesn't escape
4603 // these characters in its packet output -- so we add the quoted version of
4604 // the } character here manually in case we talk to a debugserver which un-
4605 // escapes the characters at packet read time.
4606 packet << (char)(0x7d ^ 0x20);
4607
4608 StringExtractorGDBRemote response;
4609 response.SetResponseValidatorToJSON();
4610 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4613 response.GetResponseType();
4614 if (response_type == StringExtractorGDBRemote::eResponse) {
4615 if (!response.Empty()) {
4616 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4617 }
4618 }
4619 }
4620 }
4621 return object_sp;
4622}
4623
4625 lldb::addr_t image_list_address, lldb::addr_t image_count) {
4626
4628 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4629 image_list_address);
4630 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4631
4632 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4633}
4634
4635static std::string
4637 std::string info_level_str;
4638 if (info_level == eBinaryInformationLevelAddrOnly)
4639 info_level_str = "address-only";
4640 else if (info_level == eBinaryInformationLevelAddrName)
4641 info_level_str = "address-name";
4642 else if (info_level == eBinaryInformationLevelAddrNameUUID)
4643 info_level_str = "address-name-uuid";
4644 else if (info_level == eBinaryInformationLevelFull)
4645 info_level_str = "full";
4646
4647 return info_level_str;
4648}
4649
4651 BinaryInformationLevel info_level) {
4653
4654 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4655 if (info_level != eBinaryInformationLevelFull)
4656 args_dict->GetAsDictionary()->AddBooleanItem("report_load_commands", false);
4657 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4658 if (!info_level_str.empty())
4659 args_dict->GetAsDictionary()->AddStringItem("information-level",
4660 info_level_str.c_str());
4661
4662 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4663}
4664
4666 BinaryInformationLevel info_level,
4667 const std::vector<lldb::addr_t> &load_addresses) {
4670
4671 for (auto addr : load_addresses)
4672 addresses->AddIntegerItem(addr);
4673
4674 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4675
4676 std::string info_level_str = BinaryInformationLevelToJSONKey(info_level);
4677 if (!info_level_str.empty())
4678 args_dict->GetAsDictionary()->AddStringItem("information-level",
4679 info_level_str.c_str());
4680
4681 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4682}
4683
4686 StructuredData::ObjectSP args_dict) {
4687 StructuredData::ObjectSP object_sp;
4688
4689 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4690 // Scope for the scoped timeout object
4692 std::chrono::seconds(10));
4693
4694 StreamString packet;
4695 packet << "jGetLoadedDynamicLibrariesInfos:";
4696 args_dict->Dump(packet, false);
4697
4698 // FIXME the final character of a JSON dictionary, '}', is the escape
4699 // character in gdb-remote binary mode. lldb currently doesn't escape
4700 // these characters in its packet output -- so we add the quoted version of
4701 // the } character here manually in case we talk to a debugserver which un-
4702 // escapes the characters at packet read time.
4703 packet << (char)(0x7d ^ 0x20);
4704
4705 StringExtractorGDBRemote response;
4706 response.SetResponseValidatorToJSON();
4707 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4710 response.GetResponseType();
4711 if (response_type == StringExtractorGDBRemote::eResponse) {
4712 if (!response.Empty()) {
4713 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4714 }
4715 }
4716 }
4717 }
4718 return object_sp;
4719}
4720
4722 StructuredData::ObjectSP object_sp;
4724
4725 if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
4726 StringExtractorGDBRemote response;
4727 response.SetResponseValidatorToJSON();
4728 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
4729 response) ==
4732 response.GetResponseType();
4733 if (response_type == StringExtractorGDBRemote::eResponse) {
4734 if (!response.Empty()) {
4735 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4736 }
4737 }
4738 }
4739 }
4740 return object_sp;
4741}
4742
4744 std::lock_guard<std::mutex> guard(m_shared_cache_info_mutex);
4746
4747 if (m_shared_cache_info_sp || !m_gdb_comm.GetSharedCacheInfoSupported())
4749
4750 StreamString packet;
4751 packet << "jGetSharedCacheInfo:";
4752 args_dict->Dump(packet, false);
4753
4754 StringExtractorGDBRemote response;
4755 response.SetResponseValidatorToJSON();
4756 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4759 response.GetResponseType();
4760 if (response_type == StringExtractorGDBRemote::eResponse) {
4761 if (response.Empty())
4762 return {};
4763 StructuredData::ObjectSP response_sp =
4765 if (!response_sp)
4766 return {};
4767 StructuredData::Dictionary *dict = response_sp->GetAsDictionary();
4768 if (!dict)
4769 return {};
4770 if (!dict->HasKey("shared_cache_uuid"))
4771 return {};
4772 llvm::StringRef uuid_str;
4773 if (!dict->GetValueForKeyAsString("shared_cache_uuid", uuid_str, "") ||
4774 uuid_str == "00000000-0000-0000-0000-000000000000")
4775 return {};
4776 if (dict->HasKey("shared_cache_path")) {
4777 UUID uuid;
4778 uuid.SetFromStringRef(uuid_str);
4779 FileSpec sc_path(
4780 dict->GetValueForKey("shared_cache_path")->GetStringValue());
4781
4782 SymbolSharedCacheUse sc_mode =
4785
4788 // Attempt to open the shared cache at sc_path, and
4789 // if the uuid matches, index all the files.
4790 HostInfo::SharedCacheIndexFiles(sc_path, uuid, sc_mode);
4791 }
4792 }
4793 m_shared_cache_info_sp = response_sp;
4794 }
4795 }
4797}
4798
4800 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4801 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4802}
4803
4804// Establish the largest memory read/write payloads we should use. If the
4805// remote stub has a max packet size, stay under that size.
4806//
4807// If the remote stub's max packet size is crazy large, use a reasonable
4808// largeish default.
4809//
4810// If the remote stub doesn't advertise a max packet size, use a conservative
4811// default.
4812
4814 const uint64_t reasonable_largeish_default = 128 * 1024;
4815 const uint64_t conservative_default = 512;
4816
4817 if (m_max_memory_size == 0) {
4818 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4819 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4820 // Save the stub's claimed maximum packet size
4821 m_remote_stub_max_memory_size = stub_max_size;
4822
4823 // Even if the stub says it can support ginormous packets, don't exceed
4824 // our reasonable largeish default packet size.
4825 if (stub_max_size > reasonable_largeish_default) {
4826 stub_max_size = reasonable_largeish_default;
4827 }
4828
4829 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4830 // calculating the bytes taken by size and addr every time, we take a
4831 // maximum guess here.
4832 if (stub_max_size > 70)
4833 stub_max_size -= 32 + 32 + 6;
4834 else {
4835 // In unlikely scenario that max packet size is less then 70, we will
4836 // hope that data being written is small enough to fit.
4838 LLDB_LOG(log, "warning: Packet size is too small. "
4839 "LLDB may face problems while writing memory");
4840 }
4841
4842 m_max_memory_size = stub_max_size;
4843 } else {
4844 m_max_memory_size = conservative_default;
4845 }
4846 }
4847}
4848
4850 uint64_t user_specified_max) {
4851 if (user_specified_max != 0) {
4853
4855 if (m_remote_stub_max_memory_size < user_specified_max) {
4857 // packet size too
4858 // big, go as big
4859 // as the remote stub says we can go.
4860 } else {
4861 m_max_memory_size = user_specified_max; // user's packet size is good
4862 }
4863 } else {
4865 user_specified_max; // user's packet size is probably fine
4866 }
4867 }
4868}
4869
4870bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4871 const ArchSpec &arch,
4872 ModuleSpec &module_spec) {
4874
4875 const ModuleCacheKey key(module_file_spec.GetPath(),
4876 arch.GetTriple().getTriple());
4877 auto cached = m_cached_module_specs.find(key);
4878 if (cached != m_cached_module_specs.end()) {
4879 module_spec = cached->second;
4880 return bool(module_spec);
4881 }
4882
4883 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4884 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4885 __FUNCTION__, module_file_spec.GetPath().c_str(),
4886 arch.GetTriple().getTriple().c_str());
4887 return false;
4888 }
4889
4890 if (log) {
4891 StreamString stream;
4892 module_spec.Dump(stream);
4893 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4894 __FUNCTION__, module_file_spec.GetPath().c_str(),
4895 arch.GetTriple().getTriple().c_str(), stream.GetData());
4896 }
4897
4898 m_cached_module_specs[key] = module_spec;
4899 return true;
4900}
4901
4903 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4904 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4905 if (module_specs) {
4906 for (const FileSpec &spec : module_file_specs)
4908 triple.getTriple())] = ModuleSpec();
4909 for (const ModuleSpec &spec : *module_specs)
4910 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4911 triple.getTriple())] = spec;
4912 }
4913}
4914
4916 return m_gdb_comm.GetOSVersion();
4917}
4918
4920 return m_gdb_comm.GetMacCatalystVersion();
4921}
4922
4923namespace {
4924
4925typedef std::vector<std::string> stringVec;
4926
4927typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4928struct RegisterSetInfo {
4929 ConstString name;
4930};
4931
4932typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4933
4934struct GdbServerTargetInfo {
4935 std::string arch;
4936 std::string osabi;
4937 stringVec includes;
4938 RegisterSetMap reg_set_map;
4939};
4940
4941static FieldEnum::Enumerators ParseEnumEvalues(const XMLNode &enum_node) {
4943 // We will use the last instance of each value. Also we preserve the order
4944 // of declaration in the XML, as it may not be numerical.
4945 // For example, hardware may initially release with two states that software
4946 // can read from a register field:
4947 // 0 = startup, 1 = running
4948 // If in a future hardware release, the designers added a pre-startup state:
4949 // 0 = startup, 1 = running, 2 = pre-startup
4950 // Now it makes more sense to list them in this logical order as opposed to
4951 // numerical order:
4952 // 2 = pre-startup, 1 = startup, 0 = startup
4953 // This only matters for "register info" but let's trust what the server
4954 // chose regardless.
4955 std::map<uint64_t, FieldEnum::Enumerator> enumerators;
4956
4958 "evalue", [&enumerators, &log](const XMLNode &enumerator_node) {
4959 std::optional<llvm::StringRef> name;
4960 std::optional<uint64_t> value;
4961
4962 enumerator_node.ForEachAttribute(
4963 [&name, &value, &log](const llvm::StringRef &attr_name,
4964 const llvm::StringRef &attr_value) {
4965 if (attr_name == "name") {
4966 if (attr_value.size())
4967 name = attr_value;
4968 else
4969 LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues "
4970 "Ignoring empty name in evalue");
4971 } else if (attr_name == "value") {
4972 uint64_t parsed_value = 0;
4973 if (llvm::to_integer(attr_value, parsed_value))
4974 value = parsed_value;
4975 else
4976 LLDB_LOG(log,
4977 "ProcessGDBRemote::ParseEnumEvalues "
4978 "Invalid value \"{0}\" in "
4979 "evalue",
4980 attr_value.data());
4981 } else
4982 LLDB_LOG(log,
4983 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
4984 "unknown attribute "
4985 "\"{0}\" in evalue",
4986 attr_name.data());
4987
4988 // Keep walking attributes.
4989 return true;
4990 });
4991
4992 if (value && name)
4993 enumerators.insert_or_assign(
4994 *value, FieldEnum::Enumerator(*value, name->str()));
4995
4996 // Find all evalue elements.
4997 return true;
4998 });
4999
5000 FieldEnum::Enumerators final_enumerators;
5001 for (auto [_, enumerator] : enumerators)
5002 final_enumerators.push_back(enumerator);
5003
5004 return final_enumerators;
5005}
5006
5007static void
5008ParseEnums(XMLNode feature_node,
5009 llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
5010 Log *log(GetLog(GDBRLog::Process));
5011
5012 // The top level element is "<enum...".
5013 feature_node.ForEachChildElementWithName(
5014 "enum", [log, &registers_enum_types](const XMLNode &enum_node) {
5015 std::string id;
5016
5017 enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name,
5018 const llvm::StringRef &attr_value) {
5019 if (attr_name == "id")
5020 id = attr_value;
5021
5022 // There is also a "size" attribute that is supposed to be the size in
5023 // bytes of the register this applies to. However:
5024 // * LLDB doesn't need this information.
5025 // * It is difficult to verify because you have to wait until the
5026 // enum is applied to a field.
5027 //
5028 // So we will emit this attribute in XML for GDB's sake, but will not
5029 // bother ingesting it.
5030
5031 // Walk all attributes.
5032 return true;
5033 });
5034
5035 if (!id.empty()) {
5036 FieldEnum::Enumerators enumerators = ParseEnumEvalues(enum_node);
5037 if (!enumerators.empty()) {
5038 LLDB_LOG(log,
5039 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
5040 id);
5041 registers_enum_types.insert_or_assign(
5042 id, std::make_unique<FieldEnum>(id, enumerators));
5043 }
5044 }
5045
5046 // Find all <enum> elements.
5047 return true;
5048 });
5049}
5050
5051static std::vector<RegisterFlags::Field> ParseFlagsFields(
5052 XMLNode flags_node, unsigned size,
5053 const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
5054 Log *log(GetLog(GDBRLog::Process));
5055 const unsigned max_start_bit = size * 8 - 1;
5056
5057 // Process the fields of this set of flags.
5058 std::vector<RegisterFlags::Field> fields;
5059 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log,
5060 &registers_enum_types](
5061 const XMLNode
5062 &field_node) {
5063 std::optional<llvm::StringRef> name;
5064 std::optional<unsigned> start;
5065 std::optional<unsigned> end;
5066 std::optional<llvm::StringRef> type;
5067
5068 field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit,
5069 &log](const llvm::StringRef &attr_name,
5070 const llvm::StringRef &attr_value) {
5071 // Note that XML in general requires that each of these attributes only
5072 // appears once, so we don't have to handle that here.
5073 if (attr_name == "name") {
5074 LLDB_LOG(
5075 log,
5076 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
5077 attr_value.data());
5078 name = attr_value;
5079 } else if (attr_name == "start") {
5080 unsigned parsed_start = 0;
5081 if (llvm::to_integer(attr_value, parsed_start)) {
5082 if (parsed_start > max_start_bit) {
5083 LLDB_LOG(log,
5084 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
5085 "field node, "
5086 "cannot be > {1}",
5087 parsed_start, max_start_bit);
5088 } else
5089 start = parsed_start;
5090 } else {
5091 LLDB_LOG(
5092 log,
5093 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
5094 "field node",
5095 attr_value.data());
5096 }
5097 } else if (attr_name == "end") {
5098 unsigned parsed_end = 0;
5099 if (llvm::to_integer(attr_value, parsed_end))
5100 if (parsed_end > max_start_bit) {
5101 LLDB_LOG(log,
5102 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
5103 "field node, "
5104 "cannot be > {1}",
5105 parsed_end, max_start_bit);
5106 } else
5107 end = parsed_end;
5108 else {
5109 LLDB_LOG(log,
5110 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
5111 "field node",
5112 attr_value.data());
5113 }
5114 } else if (attr_name == "type") {
5115 type = attr_value;
5116 } else {
5117 LLDB_LOG(
5118 log,
5119 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
5120 "\"{0}\" in field node",
5121 attr_name.data());
5122 }
5123
5124 return true; // Walk all attributes of the field.
5125 });
5126
5127 if (name && start && end) {
5128 if (*start > *end)
5129 LLDB_LOG(
5130 log,
5131 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
5132 "\"{2}\", ignoring",
5133 *start, *end, name->data());
5134 else {
5135 if (RegisterFlags::Field::GetSizeInBits(*start, *end) > 64)
5136 LLDB_LOG(log,
5137 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{}\" "
5138 "that has size > 64 bits, this is not supported",
5139 name->data());
5140 else {
5141 // A field's type may be set to the name of an enum type.
5142 const FieldEnum *enum_type = nullptr;
5143 if (type && !type->empty()) {
5144 auto found = registers_enum_types.find(*type);
5145 if (found != registers_enum_types.end()) {
5146 enum_type = found->second.get();
5147
5148 // No enumerator can exceed the range of the field itself.
5149 uint64_t max_value =
5151 for (const auto &enumerator : enum_type->GetEnumerators()) {
5152 if (enumerator.m_value > max_value) {
5153 enum_type = nullptr;
5154 LLDB_LOG(
5155 log,
5156 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
5157 "evalue \"{1}\" with value {2} exceeds the maximum value "
5158 "of field \"{3}\" ({4}), ignoring enum",
5159 type->data(), enumerator.m_name, enumerator.m_value,
5160 name->data(), max_value);
5161 break;
5162 }
5163 }
5164 } else {
5165 LLDB_LOG(log,
5166 "ProcessGDBRemote::ParseFlagsFields Could not find type "
5167 "\"{0}\" "
5168 "for field \"{1}\", ignoring",
5169 type->data(), name->data());
5170 }
5171 }
5172
5173 fields.push_back(
5174 RegisterFlags::Field(name->str(), *start, *end, enum_type));
5175 }
5176 }
5177 }
5178
5179 return true; // Iterate all "field" nodes.
5180 });
5181 return fields;
5182}
5183
5184void ParseFlags(
5185 XMLNode feature_node,
5186 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,
5187 const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
5188 Log *log(GetLog(GDBRLog::Process));
5189
5190 feature_node.ForEachChildElementWithName(
5191 "flags",
5192 [&log, &registers_flags_types,
5193 &registers_enum_types](const XMLNode &flags_node) -> bool {
5194 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
5195 flags_node.GetAttributeValue("id").c_str());
5196
5197 std::optional<llvm::StringRef> id;
5198 std::optional<unsigned> size;
5199 flags_node.ForEachAttribute(
5200 [&id, &size, &log](const llvm::StringRef &name,
5201 const llvm::StringRef &value) {
5202 if (name == "id") {
5203 id = value;
5204 } else if (name == "size") {
5205 unsigned parsed_size = 0;
5206 if (llvm::to_integer(value, parsed_size))
5207 size = parsed_size;
5208 else {
5209 LLDB_LOG(log,
5210 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
5211 "in flags node",
5212 value.data());
5213 }
5214 } else {
5215 LLDB_LOG(log,
5216 "ProcessGDBRemote::ParseFlags Ignoring unknown "
5217 "attribute \"{0}\" in flags node",
5218 name.data());
5219 }
5220 return true; // Walk all attributes.
5221 });
5222
5223 if (id && size) {
5224 // Process the fields of this set of flags.
5225 std::vector<RegisterFlags::Field> fields =
5226 ParseFlagsFields(flags_node, *size, registers_enum_types);
5227 if (fields.size()) {
5228 // Sort so that the fields with the MSBs are first.
5229 std::sort(fields.rbegin(), fields.rend());
5230 std::vector<RegisterFlags::Field>::const_iterator overlap =
5231 std::adjacent_find(fields.begin(), fields.end(),
5232 [](const RegisterFlags::Field &lhs,
5233 const RegisterFlags::Field &rhs) {
5234 return lhs.Overlaps(rhs);
5235 });
5236
5237 // If no fields overlap, use them.
5238 if (overlap == fields.end()) {
5239 if (registers_flags_types.contains(*id)) {
5240 // In theory you could define some flag set, use it with a
5241 // register then redefine it. We do not know if anyone does
5242 // that, or what they would expect to happen in that case.
5243 //
5244 // LLDB chooses to take the first definition and ignore the rest
5245 // as waiting until everything has been processed is more
5246 // expensive and difficult. This means that pointers to flag
5247 // sets in the register info remain valid if later the flag set
5248 // is redefined. If we allowed redefinitions, LLDB would crash
5249 // when you tried to print a register that used the original
5250 // definition.
5251 LLDB_LOG(
5252 log,
5253 "ProcessGDBRemote::ParseFlags Definition of flags "
5254 "\"{0}\" shadows "
5255 "previous definition, using original definition instead.",
5256 id->data());
5257 } else {
5258 registers_flags_types.insert_or_assign(
5259 *id, std::make_unique<RegisterFlags>(id->str(), *size,
5260 std::move(fields)));
5261 }
5262 } else {
5263 // If any fields overlap, ignore the whole set of flags.
5264 std::vector<RegisterFlags::Field>::const_iterator next =
5265 std::next(overlap);
5266 LLDB_LOG(
5267 log,
5268 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
5269 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
5270 "overlap.",
5271 overlap->GetName().c_str(), overlap->GetStart(),
5272 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
5273 next->GetEnd());
5274 }
5275 } else {
5276 LLDB_LOG(
5277 log,
5278 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
5279 "\"{0}\" because it contains no fields.",
5280 id->data());
5281 }
5282 }
5283
5284 return true; // Keep iterating through all "flags" elements.
5285 });
5286}
5287
5288bool ParseRegisters(
5289 XMLNode feature_node, GdbServerTargetInfo &target_info,
5290 std::vector<DynamicRegisterInfo::Register> &registers,
5291 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,
5292 llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
5293 if (!feature_node)
5294 return false;
5295
5296 Log *log(GetLog(GDBRLog::Process));
5297
5298 // Enums first because they are referenced by fields in the flags.
5299 ParseEnums(feature_node, registers_enum_types);
5300 for (const auto &enum_type : registers_enum_types)
5301 enum_type.second->DumpToLog(log);
5302
5303 ParseFlags(feature_node, registers_flags_types, registers_enum_types);
5304 for (const auto &flags : registers_flags_types)
5305 flags.second->DumpToLog(log);
5306
5307 feature_node.ForEachChildElementWithName(
5308 "reg",
5309 [&target_info, &registers, &registers_flags_types,
5310 log](const XMLNode &reg_node) -> bool {
5311 std::string gdb_group;
5312 std::string gdb_type;
5313 DynamicRegisterInfo::Register reg_info;
5314 bool encoding_set = false;
5315 bool format_set = false;
5316
5317 // FIXME: we're silently ignoring invalid data here
5318 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
5319 &encoding_set, &format_set, &reg_info,
5320 log](const llvm::StringRef &name,
5321 const llvm::StringRef &value) -> bool {
5322 if (name == "name") {
5323 reg_info.name.SetString(value);
5324 } else if (name == "bitsize") {
5325 if (llvm::to_integer(value, reg_info.byte_size))
5326 reg_info.byte_size =
5327 llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
5328 } else if (name == "type") {
5329 gdb_type = value.str();
5330 } else if (name == "group") {
5331 gdb_group = value.str();
5332 } else if (name == "regnum") {
5333 llvm::to_integer(value, reg_info.regnum_remote);
5334 } else if (name == "offset") {
5335 llvm::to_integer(value, reg_info.byte_offset);
5336 } else if (name == "altname") {
5337 reg_info.alt_name.SetString(value);
5338 } else if (name == "encoding") {
5339 encoding_set = true;
5341 } else if (name == "format") {
5342 format_set = true;
5343 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
5344 nullptr)
5345 .Success())
5346 reg_info.format =
5347 llvm::StringSwitch<lldb::Format>(value)
5348 .Case("vector-sint8", eFormatVectorOfSInt8)
5349 .Case("vector-uint8", eFormatVectorOfUInt8)
5350 .Case("vector-sint16", eFormatVectorOfSInt16)
5351 .Case("vector-uint16", eFormatVectorOfUInt16)
5352 .Case("vector-sint32", eFormatVectorOfSInt32)
5353 .Case("vector-uint32", eFormatVectorOfUInt32)
5354 .Case("vector-float32", eFormatVectorOfFloat32)
5355 .Case("vector-uint64", eFormatVectorOfUInt64)
5356 .Case("vector-uint128", eFormatVectorOfUInt128)
5357 .Default(eFormatInvalid);
5358 } else if (name == "group_id") {
5359 uint32_t set_id = UINT32_MAX;
5360 llvm::to_integer(value, set_id);
5361 RegisterSetMap::const_iterator pos =
5362 target_info.reg_set_map.find(set_id);
5363 if (pos != target_info.reg_set_map.end())
5364 reg_info.set_name = pos->second.name;
5365 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
5366 llvm::to_integer(value, reg_info.regnum_ehframe);
5367 } else if (name == "dwarf_regnum") {
5368 llvm::to_integer(value, reg_info.regnum_dwarf);
5369 } else if (name == "generic") {
5371 } else if (name == "value_regnums") {
5373 0);
5374 } else if (name == "invalidate_regnums") {
5376 value, reg_info.invalidate_regs, 0);
5377 } else {
5378 LLDB_LOGF(log,
5379 "ProcessGDBRemote::ParseRegisters unhandled reg "
5380 "attribute %s = %s",
5381 name.data(), value.data());
5382 }
5383 return true; // Keep iterating through all attributes
5384 });
5385
5386 if (!gdb_type.empty()) {
5387 // gdb_type could reference some flags type defined in XML.
5388 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
5389 registers_flags_types.find(gdb_type);
5390 if (it != registers_flags_types.end()) {
5391 auto flags_type = it->second.get();
5392 if (reg_info.byte_size == flags_type->GetSize())
5393 reg_info.flags_type = flags_type;
5394 else
5395 LLDB_LOG(
5396 log,
5397 "ProcessGDBRemote::ParseRegisters Size of register flags {0} "
5398 "({1} bytes) for register {2} does not match the register "
5399 "size ({3} bytes). Ignoring this set of flags.",
5400 flags_type->GetID().c_str(), flags_type->GetSize(),
5401 reg_info.name, reg_info.byte_size);
5402 }
5403
5404 // There's a slim chance that the gdb_type name is both a flags type
5405 // and a simple type. Just in case, look for that too (setting both
5406 // does no harm).
5407 if (!gdb_type.empty() && !(encoding_set || format_set)) {
5408 if (llvm::StringRef(gdb_type).starts_with("int")) {
5409 reg_info.format = eFormatHex;
5410 reg_info.encoding = eEncodingUint;
5411 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
5412 reg_info.format = eFormatAddressInfo;
5413 reg_info.encoding = eEncodingUint;
5414 } else if (gdb_type == "float" || gdb_type == "ieee_single" ||
5415 gdb_type == "ieee_double") {
5416 reg_info.format = eFormatFloat;
5417 reg_info.encoding = eEncodingIEEE754;
5418 } else if (gdb_type == "aarch64v" ||
5419 llvm::StringRef(gdb_type).starts_with("vec") ||
5420 gdb_type == "i387_ext" || gdb_type == "uint128" ||
5421 reg_info.byte_size > 16) {
5422 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
5423 // treat them as vector (similarly to xmm/ymm).
5424 // We can fall back to handling anything else <= 128 bit as an
5425 // unsigned integer, more than that, call it a vector of bytes.
5426 // This can happen if we don't recognise the type for AArc64 SVE
5427 // registers.
5428 reg_info.format = eFormatVectorOfUInt8;
5429 reg_info.encoding = eEncodingVector;
5430 } else {
5431 LLDB_LOGF(
5432 log,
5433 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
5434 "format and encoding for gdb type %s",
5435 gdb_type.c_str());
5436 }
5437 }
5438 }
5439
5440 // Only update the register set name if we didn't get a "reg_set"
5441 // attribute. "set_name" will be empty if we didn't have a "reg_set"
5442 // attribute.
5443 if (!reg_info.set_name) {
5444 if (!gdb_group.empty()) {
5445 reg_info.set_name.SetCString(gdb_group.c_str());
5446 } else {
5447 // If no register group name provided anywhere,
5448 // we'll create a 'general' register set
5449 reg_info.set_name.SetCString("general");
5450 }
5451 }
5452
5453 if (reg_info.byte_size == 0) {
5454 LLDB_LOG(log,
5455 "ProcessGDBRemote::{0} Skipping zero bitsize register {1}",
5456 __FUNCTION__, reg_info.name);
5457 } else
5458 registers.push_back(reg_info);
5459
5460 return true; // Keep iterating through all "reg" elements
5461 });
5462 return true;
5463}
5464
5465} // namespace
5466
5467// This method fetches a register description feature xml file from
5468// the remote stub and adds registers/register groupsets/architecture
5469// information to the current process. It will call itself recursively
5470// for nested register definition files. It returns true if it was able
5471// to fetch and parse an xml file.
5473 ArchSpec &arch_to_use, std::string xml_filename,
5474 std::vector<DynamicRegisterInfo::Register> &registers) {
5475 // request the target xml file
5476 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
5477 if (errorToBool(raw.takeError()))
5478 return false;
5479
5480 XMLDocument xml_document;
5481
5482 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
5483 xml_filename.c_str())) {
5484 GdbServerTargetInfo target_info;
5485 std::vector<XMLNode> feature_nodes;
5486
5487 // The top level feature XML file will start with a <target> tag.
5488 XMLNode target_node = xml_document.GetRootElement("target");
5489 if (target_node) {
5490 target_node.ForEachChildElement([&target_info, &feature_nodes](
5491 const XMLNode &node) -> bool {
5492 llvm::StringRef name = node.GetName();
5493 if (name == "architecture") {
5494 node.GetElementText(target_info.arch);
5495 } else if (name == "osabi") {
5496 node.GetElementText(target_info.osabi);
5497 } else if (name == "xi:include" || name == "include") {
5498 std::string href = node.GetAttributeValue("href");
5499 if (!href.empty())
5500 target_info.includes.push_back(href);
5501 } else if (name == "feature") {
5502 feature_nodes.push_back(node);
5503 } else if (name == "groups") {
5505 "group", [&target_info](const XMLNode &node) -> bool {
5506 uint32_t set_id = UINT32_MAX;
5507 RegisterSetInfo set_info;
5508
5509 node.ForEachAttribute(
5510 [&set_id, &set_info](const llvm::StringRef &name,
5511 const llvm::StringRef &value) -> bool {
5512 // FIXME: we're silently ignoring invalid data here
5513 if (name == "id")
5514 llvm::to_integer(value, set_id);
5515 if (name == "name")
5516 set_info.name = ConstString(value);
5517 return true; // Keep iterating through all attributes
5518 });
5519
5520 if (set_id != UINT32_MAX)
5521 target_info.reg_set_map[set_id] = set_info;
5522 return true; // Keep iterating through all "group" elements
5523 });
5524 }
5525 return true; // Keep iterating through all children of the target_node
5526 });
5527 } else {
5528 // In an included XML feature file, we're already "inside" the <target>
5529 // tag of the initial XML file; this included file will likely only have
5530 // a <feature> tag. Need to check for any more included files in this
5531 // <feature> element.
5532 XMLNode feature_node = xml_document.GetRootElement("feature");
5533 if (feature_node) {
5534 feature_nodes.push_back(feature_node);
5535 feature_node.ForEachChildElement([&target_info](
5536 const XMLNode &node) -> bool {
5537 llvm::StringRef name = node.GetName();
5538 if (name == "xi:include" || name == "include") {
5539 std::string href = node.GetAttributeValue("href");
5540 if (!href.empty())
5541 target_info.includes.push_back(href);
5542 }
5543 return true;
5544 });
5545 }
5546 }
5547
5548 // gdbserver does not implement the LLDB packets used to determine host
5549 // or process architecture. If that is the case, attempt to use
5550 // the <architecture/> field from target.xml, e.g.:
5551 //
5552 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
5553 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
5554 // arm board)
5555 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
5556 // We don't have any information about vendor or OS.
5557 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
5558 .Case("i386:x86-64", "x86_64")
5559 .Case("riscv:rv64", "riscv64")
5560 .Case("riscv:rv32", "riscv32")
5561 .Default(target_info.arch) +
5562 "--");
5563
5564 if (arch_to_use.IsValid())
5565 GetTarget().MergeArchitecture(arch_to_use);
5566 }
5567
5568 if (arch_to_use.IsValid()) {
5569 for (auto &feature_node : feature_nodes) {
5570 ParseRegisters(feature_node, target_info, registers,
5572 }
5573
5574 for (const auto &include : target_info.includes) {
5575 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
5576 registers);
5577 }
5578 }
5579 } else {
5580 return false;
5581 }
5582 return true;
5583}
5584
5586 std::vector<DynamicRegisterInfo::Register> &registers,
5587 const ArchSpec &arch_to_use) {
5588 std::map<uint32_t, uint32_t> remote_to_local_map;
5589 uint32_t remote_regnum = 0;
5590 for (auto it : llvm::enumerate(registers)) {
5591 DynamicRegisterInfo::Register &remote_reg_info = it.value();
5592
5593 // Assign successive remote regnums if missing.
5594 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
5595 remote_reg_info.regnum_remote = remote_regnum;
5596
5597 // Create a mapping from remote to local regnos.
5598 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
5599
5600 remote_regnum = remote_reg_info.regnum_remote + 1;
5601 }
5602
5603 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
5604 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
5605 auto lldb_regit = remote_to_local_map.find(process_regnum);
5606 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
5608 };
5609
5610 llvm::transform(remote_reg_info.value_regs,
5611 remote_reg_info.value_regs.begin(), proc_to_lldb);
5612 llvm::transform(remote_reg_info.invalidate_regs,
5613 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
5614 }
5615
5616 // Don't use Process::GetABI, this code gets called from DidAttach, and
5617 // in that context we haven't set the Target's architecture yet, so the
5618 // ABI is also potentially incorrect.
5619 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
5620 abi_sp->AugmentRegisterInfo(registers);
5621
5622 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
5623}
5624
5625// query the target of gdb-remote for extended target information returns
5626// true on success (got register definitions), false on failure (did not).
5628 // If the remote does not offer XML, does not matter if we would have been
5629 // able to parse it.
5630 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
5631 return llvm::createStringError(
5632 llvm::inconvertibleErrorCode(),
5633 "the debug server does not support \"qXfer:features:read\"");
5634
5636 return llvm::createStringError(
5637 llvm::inconvertibleErrorCode(),
5638 "the debug server supports \"qXfer:features:read\", but LLDB does not "
5639 "have XML parsing enabled (check LLLDB_ENABLE_LIBXML2)");
5640
5641 // These hold register type information for the whole of target.xml.
5642 // target.xml may include further documents that
5643 // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.
5644 // That's why we clear the cache here, and not in
5645 // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every
5646 // include read.
5648 m_registers_enum_types.clear();
5649 std::vector<DynamicRegisterInfo::Register> registers;
5650 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
5651 registers) &&
5652 // Target XML is not required to include register information.
5653 !registers.empty())
5654 AddRemoteRegisters(registers, arch_to_use);
5655
5656 return m_register_info_sp->GetNumRegisters() > 0
5657 ? llvm::ErrorSuccess()
5658 : llvm::createStringError(
5659 llvm::inconvertibleErrorCode(),
5660 "the debug server did not describe any registers");
5661}
5662
5663llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
5664 // Make sure LLDB has an XML parser it can use first
5666 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5667 "XML parsing not available");
5668
5669 Log *log = GetLog(LLDBLog::Process);
5670 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
5671
5674 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
5675
5676 // check that we have extended feature read support
5677 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
5678 // request the loaded library list
5679 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
5680 if (!raw)
5681 return raw.takeError();
5682
5683 // parse the xml file in memory
5684 LLDB_LOGF(log, "parsing: %s", raw->c_str());
5685 XMLDocument doc;
5686
5687 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
5688 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5689 "Error reading noname.xml");
5690
5691 XMLNode root_element = doc.GetRootElement("library-list-svr4");
5692 if (!root_element)
5693 return llvm::createStringError(
5694 llvm::inconvertibleErrorCode(),
5695 "Error finding library-list-svr4 xml element");
5696
5697 // main link map structure
5698 std::string main_lm = root_element.GetAttributeValue("main-lm");
5699 // FIXME: we're silently ignoring invalid data here
5700 if (!main_lm.empty())
5701 llvm::to_integer(main_lm, list.m_link_map);
5702
5703 root_element.ForEachChildElementWithName(
5704 "library", [log, &list](const XMLNode &library) -> bool {
5706
5707 // FIXME: we're silently ignoring invalid data here
5708 library.ForEachAttribute(
5709 [&module](const llvm::StringRef &name,
5710 const llvm::StringRef &value) -> bool {
5711 uint64_t uint_value = LLDB_INVALID_ADDRESS;
5712 if (name == "name")
5713 module.set_name(value.str());
5714 else if (name == "lm") {
5715 // the address of the link_map struct.
5716 llvm::to_integer(value, uint_value);
5717 module.set_link_map(uint_value);
5718 } else if (name == "l_addr") {
5719 // the displacement as read from the field 'l_addr' of the
5720 // link_map struct.
5721 llvm::to_integer(value, uint_value);
5722 module.set_base(uint_value);
5723 // base address is always a displacement, not an absolute
5724 // value.
5725 module.set_base_is_offset(true);
5726 } else if (name == "l_ld") {
5727 // the memory address of the libraries PT_DYNAMIC section.
5728 llvm::to_integer(value, uint_value);
5729 module.set_dynamic(uint_value);
5730 }
5731
5732 return true; // Keep iterating over all properties of "library"
5733 });
5734
5735 if (log) {
5736 std::string name;
5737 lldb::addr_t lm = 0, base = 0, ld = 0;
5738 bool base_is_offset;
5739
5740 module.get_name(name);
5741 module.get_link_map(lm);
5742 module.get_base(base);
5743 module.get_base_is_offset(base_is_offset);
5744 module.get_dynamic(ld);
5745
5746 LLDB_LOGF(log,
5747 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
5748 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
5749 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
5750 name.c_str());
5751 }
5752
5753 list.add(module);
5754 return true; // Keep iterating over all "library" elements in the root
5755 // node
5756 });
5757
5758 LLDB_LOGF(log, "found %" PRId32 " modules in total",
5759 (int)list.m_list.size());
5760 return list;
5761 } else if (comm.GetQXferLibrariesReadSupported()) {
5762 // request the loaded library list
5763 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
5764
5765 if (!raw)
5766 return raw.takeError();
5767
5768 LLDB_LOGF(log, "parsing: %s", raw->c_str());
5769 XMLDocument doc;
5770
5771 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
5772 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5773 "Error reading noname.xml");
5774
5775 XMLNode root_element = doc.GetRootElement("library-list");
5776 if (!root_element)
5777 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5778 "Error finding library-list xml element");
5779
5780 // FIXME: we're silently ignoring invalid data here
5781 root_element.ForEachChildElementWithName(
5782 "library", [log, &list](const XMLNode &library) -> bool {
5784
5785 std::string name = library.GetAttributeValue("name");
5786 module.set_name(name);
5787
5788 // The base address of a given library will be the address of its
5789 // first section. Most remotes send only one section for Windows
5790 // targets for example.
5791 const XMLNode &section =
5792 library.FindFirstChildElementWithName("section");
5793 std::string address = section.GetAttributeValue("address");
5794 uint64_t address_value = LLDB_INVALID_ADDRESS;
5795 llvm::to_integer(address, address_value);
5796 module.set_base(address_value);
5797 // These addresses are absolute values.
5798 module.set_base_is_offset(false);
5799
5800 if (log) {
5801 std::string name;
5802 lldb::addr_t base = 0;
5803 bool base_is_offset;
5804 module.get_name(name);
5805 module.get_base(base);
5806 module.get_base_is_offset(base_is_offset);
5807
5808 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
5809 (base_is_offset ? "offset" : "absolute"), name.c_str());
5810 }
5811
5812 list.add(module);
5813 return true; // Keep iterating over all "library" elements in the root
5814 // node
5815 });
5816
5817 LLDB_LOGF(log, "found %" PRId32 " modules in total",
5818 (int)list.m_list.size());
5819 return list;
5820 } else {
5821 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5822 "Remote libraries not supported");
5823 }
5824}
5825
5827 lldb::addr_t link_map,
5828 lldb::addr_t base_addr,
5829 bool value_is_offset) {
5830 DynamicLoader *loader = GetDynamicLoader();
5831 if (!loader)
5832 return nullptr;
5833
5834 return loader->LoadModuleAtAddress(file, link_map, base_addr,
5835 value_is_offset);
5836}
5837
5840
5841 // request a list of loaded libraries from GDBServer
5842 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
5843 if (!module_list)
5844 return module_list.takeError();
5845
5846 // get a list of all the modules
5847 ModuleList new_modules;
5848
5849 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
5850 std::string mod_name;
5851 lldb::addr_t mod_base;
5852 lldb::addr_t link_map;
5853 bool mod_base_is_offset;
5854
5855 bool valid = true;
5856 valid &= modInfo.get_name(mod_name);
5857 valid &= modInfo.get_base(mod_base);
5858 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
5859 if (!valid)
5860 continue;
5861
5862 if (!modInfo.get_link_map(link_map))
5863 link_map = LLDB_INVALID_ADDRESS;
5864
5865 FileSpec file(mod_name);
5867 lldb::ModuleSP module_sp =
5868 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
5869
5870 if (module_sp.get())
5871 new_modules.Append(module_sp);
5872 }
5873
5874 if (new_modules.GetSize() > 0) {
5875 ModuleList removed_modules;
5876 Target &target = GetTarget();
5877 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
5878
5879 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
5880 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
5881
5882 bool found = false;
5883 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
5884 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
5885 found = true;
5886 }
5887
5888 // The main executable will never be included in libraries-svr4, don't
5889 // remove it
5890 if (!found &&
5891 loaded_module.get() != target.GetExecutableModulePointer()) {
5892 removed_modules.Append(loaded_module);
5893 }
5894 }
5895
5896 loaded_modules.Remove(removed_modules);
5897 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
5898
5899 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) {
5900 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
5901 if (!obj)
5903
5906
5907 if (target.GetExecutableModulePointer() == module_sp.get())
5908 return IterationAction::Stop;
5909
5910 lldb::ModuleSP module_copy_sp = module_sp;
5911 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
5912 return IterationAction::Stop;
5913 });
5914
5915 loaded_modules.AppendIfNeeded(new_modules);
5916 m_process->GetTarget().ModulesDidLoad(new_modules);
5917 }
5918
5919 return llvm::ErrorSuccess();
5920}
5921
5923 bool &is_loaded,
5924 lldb::addr_t &load_addr) {
5925 is_loaded = false;
5926 load_addr = LLDB_INVALID_ADDRESS;
5927
5928 std::string file_path = file.GetPath(false);
5929 if (file_path.empty())
5930 return Status::FromErrorString("Empty file name specified");
5931
5932 StreamString packet;
5933 packet.PutCString("qFileLoadAddress:");
5934 packet.PutStringAsRawHex8(file_path);
5935
5936 StringExtractorGDBRemote response;
5937 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
5939 return Status::FromErrorString("Sending qFileLoadAddress packet failed");
5940
5941 if (response.IsErrorResponse()) {
5942 if (response.GetError() == 1) {
5943 // The file is not loaded into the inferior
5944 is_loaded = false;
5945 load_addr = LLDB_INVALID_ADDRESS;
5946 return Status();
5947 }
5948
5950 "Fetching file load address from remote server returned an error");
5951 }
5952
5953 if (response.IsNormalResponse()) {
5954 is_loaded = true;
5955 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
5956 return Status();
5957 }
5958
5960 "Unknown error happened during sending the load address packet");
5961}
5962
5964 // We must call the lldb_private::Process::ModulesDidLoad () first before we
5965 // do anything
5966 Process::ModulesDidLoad(module_list);
5967
5968 // After loading shared libraries, we can ask our remote GDB server if it
5969 // needs any symbols.
5970 m_gdb_comm.ServeSymbolLookups(this);
5971}
5972
5973void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
5974 AppendSTDOUT(out.data(), out.size());
5975}
5976
5977static const char *end_delimiter = "--end--;";
5978static const int end_delimiter_len = 8;
5979
5980void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
5981 std::string input = data.str(); // '1' to move beyond 'A'
5982 if (m_partial_profile_data.length() > 0) {
5983 m_partial_profile_data.append(input);
5984 input = m_partial_profile_data;
5985 m_partial_profile_data.clear();
5986 }
5987
5988 size_t found, pos = 0, len = input.length();
5989 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
5990 StringExtractorGDBRemote profileDataExtractor(
5991 input.substr(pos, found).c_str());
5992 std::string profile_data =
5993 HarmonizeThreadIdsForProfileData(profileDataExtractor);
5994 BroadcastAsyncProfileData(profile_data);
5995
5996 pos = found + end_delimiter_len;
5997 }
5998
5999 if (pos < len) {
6000 // Last incomplete chunk.
6001 m_partial_profile_data = input.substr(pos);
6002 }
6003}
6004
6006 StringExtractorGDBRemote &profileDataExtractor) {
6007 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
6008 std::string output;
6009 llvm::raw_string_ostream output_stream(output);
6010 llvm::StringRef name, value;
6011
6012 // Going to assuming thread_used_usec comes first, else bail out.
6013 while (profileDataExtractor.GetNameColonValue(name, value)) {
6014 if (name.compare("thread_used_id") == 0) {
6015 StringExtractor threadIDHexExtractor(value);
6016 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
6017
6018 bool has_used_usec = false;
6019 uint32_t curr_used_usec = 0;
6020 llvm::StringRef usec_name, usec_value;
6021 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
6022 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
6023 if (usec_name == "thread_used_usec") {
6024 has_used_usec = true;
6025 usec_value.getAsInteger(BASE_10, curr_used_usec);
6026 } else {
6027 // We didn't find what we want, it is probably an older version. Bail
6028 // out.
6029 profileDataExtractor.SetFilePos(input_file_pos);
6030 }
6031 }
6032
6033 if (has_used_usec) {
6034 uint32_t prev_used_usec = 0;
6035 std::map<uint64_t, uint32_t>::iterator iterator =
6036 m_thread_id_to_used_usec_map.find(thread_id);
6037 if (iterator != m_thread_id_to_used_usec_map.end())
6038 prev_used_usec = iterator->second;
6039
6040 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
6041 // A good first time record is one that runs for at least 0.25 sec
6042 bool good_first_time =
6043 (prev_used_usec == 0) && (real_used_usec > 250000);
6044 bool good_subsequent_time =
6045 (prev_used_usec > 0) &&
6046 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
6047
6048 if (good_first_time || good_subsequent_time) {
6049 // We try to avoid doing too many index id reservation, resulting in
6050 // fast increase of index ids.
6051
6052 output_stream << name << ":";
6053 int32_t index_id = AssignIndexIDToThread(thread_id);
6054 output_stream << index_id << ";";
6055
6056 output_stream << usec_name << ":" << usec_value << ";";
6057 } else {
6058 // Skip past 'thread_used_name'.
6059 llvm::StringRef local_name, local_value;
6060 profileDataExtractor.GetNameColonValue(local_name, local_value);
6061 }
6062
6063 // Store current time as previous time so that they can be compared
6064 // later.
6065 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
6066 } else {
6067 // Bail out and use old string.
6068 output_stream << name << ":" << value << ";";
6069 }
6070 } else {
6071 output_stream << name << ":" << value << ";";
6072 }
6073 }
6074 output_stream << end_delimiter;
6075 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
6076
6077 return output;
6078}
6079
6081 if (GetStopID() != 0)
6082 return;
6083
6084 if (GetID() == LLDB_INVALID_PROCESS_ID) {
6085 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
6086 if (pid != LLDB_INVALID_PROCESS_ID)
6087 SetID(pid);
6088 }
6090}
6091
6092llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
6093 if (!m_gdb_comm.GetSaveCoreSupported())
6094 return false;
6095
6096 StreamString packet;
6097 packet.PutCString("qSaveCore;path-hint:");
6098 packet.PutStringAsRawHex8(outfile);
6099
6100 StringExtractorGDBRemote response;
6101 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
6103 // TODO: grab error message from the packet? StringExtractor seems to
6104 // be missing a method for that
6105 if (response.IsErrorResponse())
6106 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6107 "qSaveCore returned an error");
6108
6109 std::string path;
6110
6111 // process the response
6112 for (auto x : llvm::split(response.GetStringRef(), ';')) {
6113 if (x.consume_front("core-path:"))
6115 }
6116
6117 // verify that we've gotten what we need
6118 if (path.empty())
6119 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6120 "qSaveCore returned no core path");
6121
6122 // now transfer the core file
6123 FileSpec remote_core{llvm::StringRef(path)};
6124 Platform &platform = *GetTarget().GetPlatform();
6125 Status error = platform.GetFile(remote_core, FileSpec(outfile));
6126
6127 if (platform.IsRemote()) {
6128 // NB: we unlink the file on error too
6129 platform.Unlink(remote_core);
6130 if (error.Fail())
6131 return error.ToError();
6132 }
6133
6134 return true;
6135 }
6136
6137 return llvm::createStringError(llvm::inconvertibleErrorCode(),
6138 "Unable to send qSaveCore");
6139}
6140
6141static const char *const s_async_json_packet_prefix = "JSON-async:";
6142
6144ParseStructuredDataPacket(llvm::StringRef packet) {
6145 Log *log = GetLog(GDBRLog::Process);
6146
6147 if (!packet.consume_front(s_async_json_packet_prefix)) {
6148 LLDB_LOGF(
6149 log,
6150 "GDBRemoteCommunicationClientBase::%s() received $J packet "
6151 "but was not a StructuredData packet: packet starts with "
6152 "%s",
6153 __FUNCTION__,
6154 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
6155 return StructuredData::ObjectSP();
6156 }
6157
6158 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
6160 if (log) {
6161 if (json_sp) {
6162 StreamString json_str;
6163 json_sp->Dump(json_str, true);
6164 json_str.Flush();
6165 LLDB_LOGF(log,
6166 "ProcessGDBRemote::%s() "
6167 "received Async StructuredData packet: %s",
6168 __FUNCTION__, json_str.GetData());
6169 } else {
6170 LLDB_LOGF(log,
6171 "ProcessGDBRemote::%s"
6172 "() received StructuredData packet:"
6173 " parse failure",
6174 __FUNCTION__);
6175 }
6176 }
6177 return json_sp;
6178}
6179
6181 auto structured_data_sp = ParseStructuredDataPacket(data);
6182 if (structured_data_sp)
6183 RouteAsyncStructuredData(structured_data_sp);
6184}
6185
6187public:
6189 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
6190 "Tests packet speeds of various sizes to determine "
6191 "the performance characteristics of the GDB remote "
6192 "connection. ",
6193 nullptr),
6195 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
6196 "The number of packets to send of each varying size "
6197 "(default is 1000).",
6198 1000),
6199 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
6200 "The maximum number of bytes to send in a packet. Sizes "
6201 "increase in powers of 2 while the size is less than or "
6202 "equal to this option value. (default 1024).",
6203 1024),
6204 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
6205 "The maximum number of bytes to receive in a packet. Sizes "
6206 "increase in powers of 2 while the size is less than or "
6207 "equal to this option value. (default 1024).",
6208 1024),
6209 m_json(LLDB_OPT_SET_1, false, "json", 'j',
6210 "Print the output as JSON data for easy parsing.", false, true) {
6215 m_option_group.Finalize();
6216 }
6217
6219
6220 Options *GetOptions() override { return &m_option_group; }
6221
6222 void DoExecute(Args &command, CommandReturnObject &result) override {
6223 const size_t argc = command.GetArgumentCount();
6224 if (argc == 0) {
6225 ProcessGDBRemote *process =
6226 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
6227 .GetProcessPtr();
6228 if (process) {
6229 StreamSP output_stream_sp = result.GetImmediateOutputStream();
6230 if (!output_stream_sp)
6231 output_stream_sp = m_interpreter.GetDebugger().GetAsyncOutputStream();
6232 result.SetImmediateOutputStream(output_stream_sp);
6233
6234 const uint32_t num_packets =
6235 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
6236 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
6237 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
6238 const bool json = m_json.GetOptionValue().GetCurrentValue();
6239 const uint64_t k_recv_amount =
6240 4 * 1024 * 1024; // Receive amount in bytes
6241 process->GetGDBRemote().TestPacketSpeed(
6242 num_packets, max_send, max_recv, k_recv_amount, json,
6243 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
6245 return;
6246 }
6247 } else {
6248 result.AppendErrorWithFormat("'%s' takes no arguments",
6249 m_cmd_name.c_str());
6250 }
6252 }
6253
6254protected:
6260};
6261
6263private:
6264public:
6266 : CommandObjectParsed(interpreter, "process plugin packet history",
6267 "Dumps the packet history buffer. ", nullptr) {}
6268
6270
6271 void DoExecute(Args &command, CommandReturnObject &result) override {
6272 ProcessGDBRemote *process =
6273 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6274 if (process) {
6275 process->DumpPluginHistory(result.GetOutputStream());
6277 return;
6278 }
6280 }
6281};
6282
6284private:
6285public:
6288 interpreter, "process plugin packet xfer-size",
6289 "Maximum size that lldb will try to read/write one one chunk.",
6290 nullptr) {
6292 }
6293
6295
6296 void DoExecute(Args &command, CommandReturnObject &result) override {
6297 const size_t argc = command.GetArgumentCount();
6298 if (argc == 0) {
6299 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
6300 "amount to be transferred when "
6301 "reading/writing",
6302 m_cmd_name.c_str());
6303 return;
6304 }
6305
6306 ProcessGDBRemote *process =
6307 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6308 if (process) {
6309 const char *packet_size = command.GetArgumentAtIndex(0);
6310 errno = 0;
6311 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
6312 if (errno == 0 && user_specified_max != 0) {
6313 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
6315 return;
6316 }
6317 }
6319 }
6320};
6321
6323private:
6324public:
6326 : CommandObjectParsed(interpreter, "process plugin packet send",
6327 "Send a custom packet through the GDB remote "
6328 "protocol and print the answer. "
6329 "The packet header and footer will automatically "
6330 "be added to the packet prior to sending and "
6331 "stripped from the result.",
6332 nullptr) {
6334 }
6335
6337
6338 void DoExecute(Args &command, CommandReturnObject &result) override {
6339 const size_t argc = command.GetArgumentCount();
6340 if (argc == 0) {
6341 result.AppendErrorWithFormat(
6342 "'%s' takes a one or more packet content arguments",
6343 m_cmd_name.c_str());
6344 return;
6345 }
6346
6347 ProcessGDBRemote *process =
6348 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6349 if (process) {
6350 for (size_t i = 0; i < argc; ++i) {
6351 const char *packet_cstr = command.GetArgumentAtIndex(0);
6352 StringExtractorGDBRemote response;
6354 packet_cstr, response, process->GetInterruptTimeout());
6356 Stream &output_strm = result.GetOutputStream();
6357 output_strm.Printf(" packet: %s\n", packet_cstr);
6358 std::string response_str = std::string(response.GetStringRef());
6359
6360 if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
6361 response_str = process->HarmonizeThreadIdsForProfileData(response);
6362 }
6363
6364 if (response_str.empty())
6365 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6366 else
6367 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6368 }
6369 }
6370 }
6371};
6372
6374private:
6375public:
6377 : CommandObjectRaw(interpreter, "process plugin packet monitor",
6378 "Send a qRcmd packet through the GDB remote protocol "
6379 "and print the response. "
6380 "The argument passed to this command will be hex "
6381 "encoded into a valid 'qRcmd' packet, sent and the "
6382 "response will be printed.") {}
6383
6385
6386 void DoExecute(llvm::StringRef command,
6387 CommandReturnObject &result) override {
6388 if (command.empty()) {
6389 result.AppendErrorWithFormat("'%s' takes a command string argument",
6390 m_cmd_name.c_str());
6391 return;
6392 }
6393
6394 ProcessGDBRemote *process =
6395 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
6396 if (process) {
6397 StreamString packet;
6398 packet.PutCString("qRcmd,");
6399 packet.PutBytesAsRawHex8(command.data(), command.size());
6400
6401 StringExtractorGDBRemote response;
6402 Stream &output_strm = result.GetOutputStream();
6404 packet.GetString(), response, process->GetInterruptTimeout(),
6405 [&output_strm](llvm::StringRef output) { output_strm << output; });
6407 output_strm.Printf(" packet: %s\n", packet.GetData());
6408 const std::string &response_str = std::string(response.GetStringRef());
6409
6410 if (response_str.empty())
6411 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6412 else
6413 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6414 }
6415 }
6416};
6417
6419private:
6420public:
6422 : CommandObjectMultiword(interpreter, "process plugin packet",
6423 "Commands that deal with GDB remote packets.",
6424 nullptr) {
6426 "history",
6430 "send", CommandObjectSP(
6431 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
6433 "monitor",
6437 "xfer-size",
6440 LoadSubCommand("speed-test",
6442 interpreter)));
6443 }
6444
6446};
6447
6449public:
6452 interpreter, "process plugin",
6453 "Commands for operating on a ProcessGDBRemote process.",
6454 "process plugin <subcommand> [<subcommand-options>]") {
6456 "packet",
6458 }
6459
6461};
6462
6464 if (!m_command_sp)
6465 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
6466 GetTarget().GetDebugger().GetCommandInterpreter());
6467 return m_command_sp.get();
6468}
6469
6471 bool enable, bool is_expression_fork) {
6472 Log *log = GetLog(GDBRLog::Process);
6473
6474 // Resolve the expression-return sentinel address (_start) once. This is
6475 // the same address ThreadPlanCallFunction uses as the return trap.
6477 if (!enable && is_expression_fork) {
6478 if (auto entry = GetTarget().GetEntryPointAddress())
6479 entry_addr = entry->GetOpcodeLoadAddress(&GetTarget());
6480 }
6481
6482 GetBreakpointSiteList().ForEach([this, enable, entry_addr,
6483 log](BreakpointSite *bp_site) {
6484 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
6485 (bp_site->GetType() == BreakpointSite::eSoftware ||
6486 bp_site->GetType() == BreakpointSite::eExternal)) {
6487 // During expression evaluation, retain the expression-return trap
6488 // at _start in the forked child so it dies deterministically on
6489 // SIGTRAP rather than executing _start with a corrupted stack.
6490 if (entry_addr != LLDB_INVALID_ADDRESS &&
6491 bp_site->GetLoadAddress() == entry_addr) {
6492 LLDB_LOG(log,
6493 "DidForkSwitchSoftwareBreakpoints: retaining expression-"
6494 "return trap at {0:x} in forked child",
6495 bp_site->GetLoadAddress());
6496 return;
6497 }
6498 m_gdb_comm.SendGDBStoppointTypePacket(
6499 eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
6501 }
6502 });
6503}
6504
6506 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
6507 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
6508 if (IsBreakpointSitePhysicallyEnabled(*bp_site) &&
6509 bp_site->GetType() == BreakpointSite::eHardware) {
6510 m_gdb_comm.SendGDBStoppointTypePacket(
6511 eBreakpointHardware, enable, bp_site->GetLoadAddress(),
6513 }
6514 });
6515 }
6516
6517 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
6518 addr_t addr = wp_res_sp->GetLoadAddress();
6519 size_t size = wp_res_sp->GetByteSize();
6520 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
6521 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, addr, size,
6523 }
6524}
6525
6527 bool is_expression_fork) {
6528 Log *log = GetLog(GDBRLog::Process);
6529
6530 // During expression evaluation, force follow-parent regardless of which
6531 // thread forked. The expression is running on the parent and following the
6532 // child would cause the expression thread to vanish (the child has different
6533 // thread IDs). Even if a *different* thread forks, switching to the child
6534 // would destroy the expression thread's process context.
6535 FollowForkMode follow_fork_mode = GetFollowForkMode();
6536 bool overrode_follow_mode = false;
6537 if (follow_fork_mode == eFollowChild &&
6538 GetModIDRef().IsRunningExpression()) {
6539 if (is_expression_fork) {
6540 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
6541 "to parent during expression evaluation");
6542 } else {
6543 LLDB_LOG(log, "ProcessGDBRemote::DidFork() overriding follow-fork-mode "
6544 "to parent during expression evaluation. Child process "
6545 "{0} is available for manual attachment.",
6546 child_pid);
6547 }
6548 follow_fork_mode = eFollowParent;
6549 overrode_follow_mode = true;
6550 }
6551
6552 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
6553 // Any valid TID will suffice, thread-relevant actions will set a proper TID
6554 // anyway.
6555 lldb::tid_t parent_tid = m_thread_ids.front();
6556
6557 lldb::pid_t follow_pid, detach_pid;
6558 lldb::tid_t follow_tid, detach_tid;
6559
6560 switch (follow_fork_mode) {
6561 case eFollowParent:
6562 follow_pid = parent_pid;
6563 follow_tid = parent_tid;
6564 detach_pid = child_pid;
6565 detach_tid = child_tid;
6566 break;
6567 case eFollowChild:
6568 follow_pid = child_pid;
6569 follow_tid = child_tid;
6570 detach_pid = parent_pid;
6571 detach_tid = parent_tid;
6572 break;
6573 }
6574
6575 // Switch to the process that is going to be detached.
6576 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
6577 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
6578 return;
6579 }
6580
6581 // Disable all software breakpoints in the forked process.
6582 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
6583 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
6584
6585 // Remove hardware breakpoints / watchpoints from parent process if we're
6586 // following child.
6587 if (follow_fork_mode == eFollowChild)
6589
6590 // Switch to the process that is going to be followed
6591 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
6592 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
6593 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
6594 return;
6595 }
6596
6597 LLDB_LOG(log, "Detaching process {0}", detach_pid);
6598 // When we overrode follow-child because of a concurrent expression, try to
6599 // keep the child stopped so the user can attach to it manually.
6600 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
6601 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
6602 if (error.Fail() && keep_stopped) {
6603 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach-and-stay-stopped not "
6604 "supported, falling back to normal detach");
6605 keep_stopped = false;
6606 error = m_gdb_comm.Detach(false, detach_pid);
6607 }
6608 if (error.Fail()) {
6609 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
6610 error.AsCString() ? error.AsCString() : "<unknown error>");
6611 return;
6612 }
6613
6614 // Notify the user via the async output channel when we overrode
6615 // follow-fork-mode for a non-expression fork during expression evaluation.
6616 if (overrode_follow_mode && !is_expression_fork) {
6617 StreamUP output_up =
6619 if (output_up) {
6620 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
6621 "'parent' because an expression is being evaluated.\n"
6622 "Child process %" PRIu64
6623 " has been detached%s.\n"
6624 "You can attach to it with: process attach -p %" PRIu64
6625 "\n",
6626 child_pid,
6627 keep_stopped ? " and stopped" : " (running)",
6628 child_pid);
6629 output_up->Flush();
6630 }
6631 }
6632
6633 // Hardware breakpoints/watchpoints are not inherited implicitly,
6634 // so we need to readd them if we're following child.
6635 if (follow_fork_mode == eFollowChild) {
6637 // Update our PID
6638 SetID(child_pid);
6639 }
6640}
6641
6643 bool is_expression_fork) {
6644 Log *log = GetLog(GDBRLog::Process);
6645
6646 LLDB_LOG(
6647 log,
6648 "ProcessGDBRemote::DidVFork() called for child_pid: {0}, child_tid {1}",
6649 child_pid, child_tid);
6651
6652 // See comment in DidFork(): force follow-parent during expression evaluation
6653 // regardless of which thread triggered the vfork.
6654 FollowForkMode follow_fork_mode = GetFollowForkMode();
6655 bool overrode_follow_mode = false;
6656 if (follow_fork_mode == eFollowChild &&
6657 GetModIDRef().IsRunningExpression()) {
6658 if (is_expression_fork) {
6659 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
6660 "to parent during expression evaluation");
6661 } else {
6662 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() overriding follow-fork-mode "
6663 "to parent during expression evaluation. Child process "
6664 "{0} is available for manual attachment.",
6665 child_pid);
6666 }
6667 follow_fork_mode = eFollowParent;
6668 overrode_follow_mode = true;
6669 }
6670
6671 // Disable all software breakpoints for the duration of vfork.
6672 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
6673 DidForkSwitchSoftwareBreakpoints(false, is_expression_fork);
6674
6675 lldb::pid_t detach_pid;
6676 lldb::tid_t detach_tid;
6677
6678 switch (follow_fork_mode) {
6679 case eFollowParent:
6680 detach_pid = child_pid;
6681 detach_tid = child_tid;
6682 break;
6683 case eFollowChild:
6684 detach_pid = m_gdb_comm.GetCurrentProcessID();
6685 // Any valid TID will suffice, thread-relevant actions will set a proper TID
6686 // anyway.
6687 detach_tid = m_thread_ids.front();
6688
6689 // Switch to the parent process before detaching it.
6690 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
6691 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to set pid/tid");
6692 return;
6693 }
6694
6695 // Remove hardware breakpoints / watchpoints from the parent process.
6697
6698 // Switch to the child process.
6699 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
6700 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
6701 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() unable to reset pid/tid");
6702 return;
6703 }
6704 break;
6705 }
6706
6707 LLDB_LOG(log, "Detaching process {0}", detach_pid);
6708 bool keep_stopped = overrode_follow_mode && !is_expression_fork;
6709 Status error = m_gdb_comm.Detach(keep_stopped, detach_pid);
6710 if (error.Fail() && keep_stopped) {
6711 LLDB_LOG(log, "ProcessGDBRemote::DidVFork() detach-and-stay-stopped not "
6712 "supported, falling back to normal detach");
6713 keep_stopped = false;
6714 error = m_gdb_comm.Detach(false, detach_pid);
6715 }
6716 if (error.Fail()) {
6717 LLDB_LOG(log,
6718 "ProcessGDBRemote::DidVFork() detach packet send failed: {0}",
6719 error.AsCString() ? error.AsCString() : "<unknown error>");
6720 return;
6721 }
6722
6723 if (overrode_follow_mode && !is_expression_fork) {
6724 StreamUP output_up =
6726 if (output_up) {
6727 output_up->Printf("warning: follow-fork-mode 'child' was overridden to "
6728 "'parent' because an expression is being evaluated.\n"
6729 "Child process %" PRIu64
6730 " has been detached%s.\n"
6731 "You can attach to it with: process attach -p %" PRIu64
6732 "\n",
6733 child_pid,
6734 keep_stopped ? " and stopped" : " (running)",
6735 child_pid);
6736 output_up->Flush();
6737 }
6738 }
6739
6740 if (follow_fork_mode == eFollowChild) {
6741 // Update our PID
6742 SetID(child_pid);
6743 }
6744}
6745
6747 assert(m_vfork_in_progress_count > 0);
6749
6750 // Reenable all software breakpoints that were enabled before vfork.
6751 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
6753}
6754
6756 // If we are following children, vfork is finished by exec (rather than
6757 // vforkdone that is submitted for parent).
6761 }
6763}
6764
6766 const BreakpointSiteToActionMap &site_to_action) {
6767 llvm::Error joined = llvm::Error::success();
6768 for (auto &[site, action] : site_to_action) {
6769 llvm::Error error = action == Process::BreakpointAction::Enable
6770 ? DoEnableBreakpointSite(*site)
6771 : DoDisableBreakpointSite(*site);
6772 joined = llvm::joinErrors(std::move(joined), std::move(error));
6773 }
6774 return joined;
6775}
6776
6777/// Parse a MultiBreakpoint response into per-request results.
6778/// Returns a vector of results: std::nullopt means OK, a uint8_t value is the
6779/// error code from an Exx response.
6780static llvm::SmallVector<std::optional<uint8_t>>
6781ParseMultiBreakpointResponse(llvm::StringRef response_str) {
6782 llvm::SmallVector<std::optional<uint8_t>> results;
6783
6786 parsed ? parsed->GetAsDictionary() : nullptr;
6787 StructuredData::Array *array = nullptr;
6788 if (dict)
6789 dict->GetValueForKeyAsArray("results", array);
6790 if (!array)
6791 return results;
6792
6793 array->ForEach([&results](StructuredData::Object *object) -> bool {
6794 llvm::StringRef token;
6795 if (auto *string = object->GetAsString())
6796 token = string->GetValue();
6797 if (token == "OK") {
6798 results.push_back(std::nullopt);
6799 return true;
6800 }
6801 if (token.size() != 3 || !token.starts_with("E")) {
6802 results.push_back(uint8_t(0xff));
6803 return true;
6804 }
6805 uint8_t error_code = 0;
6806 if (token.drop_front(1).getAsInteger(BASE_16, error_code))
6807 results.push_back(0xff);
6808 else
6809 results.push_back(error_code);
6810 return true;
6811 });
6812 return results;
6813}
6814
6815/// Determine the GDB stoppoint type for a breakpoint site by checking which
6816/// packet types the remote supports (for insertions), or by checking the site
6817/// type (for deletions).
6818static std::optional<GDBStoppointType>
6820 GDBRemoteCommunicationClient &gdb_comm) {
6821 if (insert) {
6822 if (!site.HardwareRequired() &&
6824 return eBreakpointSoftware;
6826 return eBreakpointHardware;
6827 return std::nullopt;
6828 }
6829
6830 switch (site.GetType()) {
6832 return eBreakpointSoftware;
6834 return eBreakpointHardware;
6836 return std::nullopt;
6837 }
6838 llvm_unreachable("unhandled BreakpointSite type");
6839}
6840
6841namespace {
6842struct BreakpointPacketInfo {
6843 BreakpointSite &site;
6844 size_t trap_opcode_size;
6845 GDBStoppointType type;
6846 bool is_enable;
6847};
6848
6849std::string to_string(const BreakpointPacketInfo &info) {
6850 char packet = info.is_enable ? 'Z' : 'z';
6851 return llvm::formatv("{0}{1},{2:x-},{3:x-}", packet,
6852 static_cast<int>(info.type), info.site.GetLoadAddress(),
6853 info.trap_opcode_size)
6854 .str();
6855}
6856} // namespace
6857
6859 const BreakpointSiteToActionMap &site_to_action) {
6860 if (site_to_action.empty())
6861 return llvm::Error::success();
6862 if (!m_gdb_comm.GetMultiBreakpointSupported())
6863 return UpdateBreakpointSitesNotBatched(site_to_action);
6864
6866
6867 std::vector<BreakpointPacketInfo> breakpoint_infos;
6868 for (auto [site, action] : site_to_action) {
6869 size_t trap_opcode_size = GetSoftwareBreakpointTrapOpcode(site.get());
6870 std::optional<GDBStoppointType> type =
6872
6873 if (!type) {
6874 LLDB_LOG(log, "MultiBreakpoint: site {0} at {1:x} can't be batched",
6875 site->GetID(), site->GetLoadAddress());
6876 return UpdateBreakpointSitesNotBatched(site_to_action);
6877 }
6878
6879 breakpoint_infos.push_back(
6880 {*site, trap_opcode_size, *type, action == BreakpointAction::Enable});
6881 }
6882
6883 StreamString stream;
6884 stream << "jMultiBreakpoint:";
6885
6886 auto args_array = std::make_shared<StructuredData::Array>();
6887 for (auto &bp_info : breakpoint_infos)
6888 args_array->AddStringItem(to_string(bp_info));
6889
6890 StructuredData::Dictionary packet_dict;
6891 packet_dict.AddItem("breakpoint_requests", args_array);
6892 packet_dict.Dump(stream, false);
6893
6894 StreamGDBRemote escaped_stream;
6895 escaped_stream.PutEscapedBytes(stream.GetString());
6896 llvm::Expected<StringExtractorGDBRemote> response =
6897 m_gdb_comm.SendPacketAndExpectResponse(escaped_stream.GetString(),
6899
6900 if (!response) {
6901 LLDB_LOG_ERROR(log, response.takeError(), "jMultiBreakpoint failed: {0}");
6902 return UpdateBreakpointSitesNotBatched(site_to_action);
6903 }
6904
6905 llvm::SmallVector<std::optional<uint8_t>> results =
6906 ParseMultiBreakpointResponse(response->GetStringRef());
6907
6908 // This is a protocol violation, do nothing.
6909 if (results.size() != breakpoint_infos.size())
6910 return llvm::createStringErrorV(
6911 "MultiBreakpoint response count mismatch (expected {0}, got {1})",
6912 site_to_action.size(), results.size());
6913
6914 llvm::Error joined = llvm::Error::success();
6915 for (auto [error_code, bp_info] :
6916 llvm::zip_equal(results, breakpoint_infos)) {
6917 BreakpointSite &site = bp_info.site;
6918 if (error_code) {
6919 auto error = llvm::createStringErrorV(
6920 "MultiBreakpoint: site {0} at {1:x} failed with E{2}",
6921 bp_info.site.GetID(), bp_info.site.GetLoadAddress(), error_code);
6922 joined = llvm::joinErrors(std::move(joined), std::move(error));
6923 continue;
6924 }
6925 SetBreakpointSiteEnabled(site, bp_info.is_enable);
6926 if (bp_info.is_enable)
6927 site.SetType(bp_info.type == eBreakpointHardware
6930 }
6931
6932 return joined;
6933}
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 *once=nullptr)
Report warning events.
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
lldb::StreamUP GetAsyncOutputStream()
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
ArtifactProviderID AddArtifactProvider(std::string name, ArtifactProvider provider)
Register provider to contribute file name.
void RemoveArtifactProvider(ArtifactProviderID id)
Unregister a provider. Thread-safe.
static Diagnostics & Instance()
static lldb::ModuleSP LoadBinaryWithUUIDAndAddress(Process *process, llvm::StringRef name, UUID uuid, lldb::addr_t value, bool value_is_offset, bool force_symbol_search, bool notify, bool set_address_in_target, bool allow_memory_image_last_resort)
Find/load a binary into lldb given a UUID and the address where it is loaded in memory,...
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...
std::vector< Enumerator > Enumerators
const Enumerators & GetEnumerators() const
void DumpToLog(Log *log) const
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:57
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:452
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
void Clear()
Clears the object state.
Definition FileSpec.cpp:261
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(const char *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:1181
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:869
virtual Status Unlink(const FileSpec &file_spec)
bool IsRemote() const
Definition Platform.h:561
virtual Status GetFile(const FileSpec &source, const FileSpec &destination)
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool CreateSettingForProcessPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static lldb::OptionValuePropertiesSP GetSettingForProcessPlugin(Debugger &debugger, llvm::StringRef setting_name)
static bool UnregisterPlugin(ABICreateInstance create_callback)
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.
uint64_t GetMaxValue() const
The maximum unsigned value that could be contained in this field.
unsigned GetSizeInBits() const
Get size of the field in bits. Will always be at least 1.
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:1975
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.
llvm::StringMap< std::unique_ptr< FieldEnum > > m_registers_enum_types
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.
size_t DoWriteMemory(lldb::addr_t addr, const void *buf, size_t size, Status &error) override
Actually do the writing of memory to a process.
Status DoLaunch(Module *exe_module, ProcessLaunchInfo &launch_info) override
Launch a new process.
void DidVForkDone() override
Called after reported vfork completion.
std::string HarmonizeThreadIdsForProfileData(StringExtractorGDBRemote &inputStringExtractor)
bool GetGDBServerRegisterInfoXMLAndProcess(ArchSpec &arch_to_use, std::string xml_filename, std::vector< DynamicRegisterInfo::Register > &registers)
Status DoWillAttachToProcessWithName(const char *process_name, bool wait_for_launch) override
Called before attaching to a process.
std::pair< std::string, std::string > ModuleCacheKey
bool SupportsMemoryTagging() override
Check whether the process supports memory tagging.
size_t UpdateThreadPCsFromStopReplyThreadsValue(llvm::StringRef value)
llvm::VersionTuple GetHostOSVersion() override
Sometimes the connection to a process can detect the host OS version that the process is running on.
llvm::Expected< StringExtractorGDBRemote > SendMultiMemReadPacket(llvm::ArrayRef< Range< lldb::addr_t, size_t > > ranges)
std::map< uint64_t, uint32_t > m_thread_id_to_used_usec_map
Status DoWriteMemoryTags(lldb::addr_t addr, size_t len, int32_t type, const std::vector< uint8_t > &tags) override
Does the final operation to write memory tags.
llvm::Error ParseMultiMemReadPacket(llvm::StringRef response_str, llvm::MutableArrayRef< uint8_t > buffer, unsigned expected_num_ranges, llvm::SmallVectorImpl< llvm::MutableArrayRef< uint8_t > > &memory_regions)
llvm::Expected< std::vector< uint8_t > > TraceGetBinaryData(const TraceGetBinaryDataRequest &request) override
Get binary data given a trace technology and a data identifier.
llvm::Error HandleAcceleratorBreakpoints(const AcceleratorActions &actions)
Set the breakpoints requested by an accelerator plugin as internal breakpoints with a callback that n...
Status EnableBreakpointSite(BreakpointSite *bp_site) override
void ModulesDidLoad(ModuleList &module_list) override
ProcessGDBRemote(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Status WillResume() override
Called before resuming to a process.
lldb::ModuleSP LoadModuleAtAddress(const FileSpec &file, lldb::addr_t link_map, lldb::addr_t base_addr, bool value_is_offset)
void SetLastStopPacket(const StringExtractorGDBRemote &response)
Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries) override
static std::chrono::milliseconds GetPacketTestDelay()
llvm::Error LoadModules() override
Sometimes processes know how to retrieve and load shared libraries.
void HandleAsyncMisc(llvm::StringRef data) override
lldb::addr_t GetImageInfoAddress() override
Get the image information address for the current process.
bool DoUpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) override
Update the thread list following process plug-in's specific logic.
static lldb::ProcessSP CreateInstance(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
void PrefetchModuleSpecs(llvm::ArrayRef< FileSpec > module_file_specs, const llvm::Triple &triple) override
StructuredData::ObjectSP GetDynamicLoaderProcessState() override
bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec) override
Try to fetch the module specification for a module with the given file name and architecture.
llvm::StringMap< std::unique_ptr< RegisterFlags > > m_registers_flags_types
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:83
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:88
std::shared_ptr< lldb_private::WatchpointResource > WatchpointResourceSP
uint64_t user_id_t
Definition lldb-types.h:82
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:84
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.
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