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