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 (log) {
718 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
719 LLDB_LOGF(log,
720 "ProcessGDBRemote::%s provided with STDIO paths via "
721 "launch_info: stdin=%s, stdout=%s, stderr=%s",
722 __FUNCTION__,
723 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
724 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
725 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
726 else
727 LLDB_LOGF(log,
728 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
729 __FUNCTION__);
730 }
731
732 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
733 if (stdin_file_spec || disable_stdio) {
734 // the inferior will be reading stdin from the specified file or stdio is
735 // completely disabled
736 m_stdin_forward = false;
737 } else {
738 m_stdin_forward = true;
739 }
740
741 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
742 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
743 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
744 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
745 // ::LogSetLogFile ("/dev/stdout");
746
747 error = EstablishConnectionIfNeeded(launch_info);
748 if (error.Success()) {
749 PseudoTerminal pty;
750 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
751
752 PlatformSP platform_sp(GetTarget().GetPlatform());
753 if (disable_stdio) {
754 // set to /dev/null unless redirected to a file above
755 if (!stdin_file_spec)
756 stdin_file_spec.SetFile(FileSystem::DEV_NULL,
757 FileSpec::Style::native);
758 if (!stdout_file_spec)
759 stdout_file_spec.SetFile(FileSystem::DEV_NULL,
760 FileSpec::Style::native);
761 if (!stderr_file_spec)
762 stderr_file_spec.SetFile(FileSystem::DEV_NULL,
763 FileSpec::Style::native);
764 } else if (platform_sp && platform_sp->IsHost()) {
765 // If the debugserver is local and we aren't disabling STDIO, lets use
766 // a pseudo terminal to instead of relying on the 'O' packets for stdio
767 // since 'O' packets can really slow down debugging if the inferior
768 // does a lot of output.
769 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
770 !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
771 FileSpec secondary_name(pty.GetSecondaryName());
772
773 if (!stdin_file_spec)
774 stdin_file_spec = secondary_name;
775
776 if (!stdout_file_spec)
777 stdout_file_spec = secondary_name;
778
779 if (!stderr_file_spec)
780 stderr_file_spec = secondary_name;
781 }
782 LLDB_LOGF(
783 log,
784 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
785 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
786 "stderr=%s",
787 __FUNCTION__,
788 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
789 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
790 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
791 }
792
793 LLDB_LOGF(log,
794 "ProcessGDBRemote::%s final STDIO paths after all "
795 "adjustments: stdin=%s, stdout=%s, stderr=%s",
796 __FUNCTION__,
797 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
798 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
799 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
800
801 if (stdin_file_spec)
802 m_gdb_comm.SetSTDIN(stdin_file_spec);
803 if (stdout_file_spec)
804 m_gdb_comm.SetSTDOUT(stdout_file_spec);
805 if (stderr_file_spec)
806 m_gdb_comm.SetSTDERR(stderr_file_spec);
807
808 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
809 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
810
811 m_gdb_comm.SendLaunchArchPacket(
812 GetTarget().GetArchitecture().GetArchitectureName());
813
814 const char *launch_event_data = launch_info.GetLaunchEventData();
815 if (launch_event_data != nullptr && *launch_event_data != '\0')
816 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
817
818 if (working_dir) {
819 m_gdb_comm.SetWorkingDir(working_dir);
820 }
821
822 // Send the environment and the program + arguments after we connect
823 m_gdb_comm.SendEnvironment(launch_info.GetEnvironment());
824
825 {
826 // Scope for the scoped timeout object
828 std::chrono::seconds(10));
829
830 // Since we can't send argv0 separate from the executable path, we need to
831 // make sure to use the actual executable path found in the launch_info...
832 Args args = launch_info.GetArguments();
833 if (FileSpec exe_file = launch_info.GetExecutableFile())
834 args.ReplaceArgumentAtIndex(0, exe_file.GetPath(false));
835 if (llvm::Error err = m_gdb_comm.LaunchProcess(args)) {
837 "Cannot launch '{0}': {1}", args.GetArgumentAtIndex(0),
838 llvm::fmt_consume(std::move(err)));
839 } else {
840 SetID(m_gdb_comm.GetCurrentProcessID());
841 }
842 }
843
845 LLDB_LOGF(log, "failed to connect to debugserver: %s",
846 error.AsCString());
848 return error;
849 }
850
852 if (m_gdb_comm.GetStopReply(response)) {
853 SetLastStopPacket(response);
854
855 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
856
857 if (process_arch.IsValid()) {
858 GetTarget().MergeArchitecture(process_arch);
859 } else {
860 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
861 if (host_arch.IsValid())
862 GetTarget().MergeArchitecture(host_arch);
863 }
864
866
867 if (!disable_stdio) {
870 }
871 }
872 } else {
873 LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
874 }
875 return error;
876}
877
878Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
880 // Only connect if we have a valid connect URL
882
883 if (!connect_url.empty()) {
884 LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
885 connect_url.str().c_str());
886 std::unique_ptr<ConnectionFileDescriptor> conn_up(
888 if (conn_up) {
889 const uint32_t max_retry_count = 50;
890 uint32_t retry_count = 0;
891 while (!m_gdb_comm.IsConnected()) {
892 if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
893 m_gdb_comm.SetConnection(std::move(conn_up));
894 break;
895 }
896
897 retry_count++;
898
899 if (retry_count >= max_retry_count)
900 break;
901
902 std::this_thread::sleep_for(std::chrono::milliseconds(100));
903 }
904 }
905 }
906
907 if (!m_gdb_comm.IsConnected()) {
908 if (error.Success())
909 error = Status::FromErrorString("not connected to remote gdb server");
910 return error;
911 }
912
913 // We always seem to be able to open a connection to a local port so we need
914 // to make sure we can then send data to it. If we can't then we aren't
915 // actually connected to anything, so try and do the handshake with the
916 // remote GDB server and make sure that goes alright.
917 if (!m_gdb_comm.HandshakeWithServer(&error)) {
918 m_gdb_comm.Disconnect();
919 if (error.Success())
920 error = Status::FromErrorString("not connected to remote gdb server");
921 return error;
922 }
923
924 m_gdb_comm.GetEchoSupported();
925 m_gdb_comm.GetThreadSuffixSupported();
926 m_gdb_comm.GetListThreadsInStopReplySupported();
927 m_gdb_comm.GetHostInfo();
928 m_gdb_comm.GetVContSupported("c");
929 m_gdb_comm.GetVAttachOrWaitSupported();
930 m_gdb_comm.EnableErrorStringInPacket();
931
932 // First dispatch any commands from the platform:
933 auto handle_cmds = [&] (const Args &args) -> void {
934 for (const Args::ArgEntry &entry : args) {
936 m_gdb_comm.SendPacketAndWaitForResponse(
937 entry.c_str(), response);
938 }
939 };
940
941 PlatformSP platform_sp = GetTarget().GetPlatform();
942 if (platform_sp) {
943 handle_cmds(platform_sp->GetExtraStartupCommands());
944 }
945
946 // Then dispatch any process commands:
947 handle_cmds(GetExtraStartupCommands());
948
949 return error;
950}
951
955
956 // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
957 // qProcessInfo as it will be more specific to our process.
958
959 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
960 if (remote_process_arch.IsValid()) {
961 process_arch = remote_process_arch;
962 LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
963 process_arch.GetArchitectureName(),
964 process_arch.GetTriple().getTriple());
965 } else {
966 process_arch = m_gdb_comm.GetHostArchitecture();
967 LLDB_LOG(log,
968 "gdb-remote did not have process architecture, using gdb-remote "
969 "host architecture {0} {1}",
970 process_arch.GetArchitectureName(),
971 process_arch.GetTriple().getTriple());
972 }
973
974 AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits();
975 SetAddressableBitMasks(addressable_bits);
976
977 if (process_arch.IsValid()) {
978 const ArchSpec &target_arch = GetTarget().GetArchitecture();
979 if (target_arch.IsValid()) {
980 LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
981 target_arch.GetArchitectureName(),
982 target_arch.GetTriple().getTriple());
983
984 // If the remote host is ARM and we have apple as the vendor, then
985 // ARM executables and shared libraries can have mixed ARM
986 // architectures.
987 // You can have an armv6 executable, and if the host is armv7, then the
988 // system will load the best possible architecture for all shared
989 // libraries it has, so we really need to take the remote host
990 // architecture as our defacto architecture in this case.
991
992 if ((process_arch.GetMachine() == llvm::Triple::arm ||
993 process_arch.GetMachine() == llvm::Triple::thumb) &&
994 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
995 GetTarget().SetArchitecture(process_arch);
996 LLDB_LOG(log,
997 "remote process is ARM/Apple, "
998 "setting target arch to {0} {1}",
999 process_arch.GetArchitectureName(),
1000 process_arch.GetTriple().getTriple());
1001 } else {
1002 // Fill in what is missing in the triple
1003 const llvm::Triple &remote_triple = process_arch.GetTriple();
1004 llvm::Triple new_target_triple = target_arch.GetTriple();
1005 if (new_target_triple.getVendorName().size() == 0) {
1006 new_target_triple.setVendor(remote_triple.getVendor());
1007
1008 if (new_target_triple.getOSName().size() == 0) {
1009 new_target_triple.setOS(remote_triple.getOS());
1010
1011 if (new_target_triple.getEnvironmentName().size() == 0)
1012 new_target_triple.setEnvironment(remote_triple.getEnvironment());
1013 }
1014
1015 ArchSpec new_target_arch = target_arch;
1016 new_target_arch.SetTriple(new_target_triple);
1017 GetTarget().SetArchitecture(new_target_arch);
1018 }
1019 }
1020
1021 LLDB_LOG(log,
1022 "final target arch after adjustments for remote architecture: "
1023 "{0} {1}",
1024 target_arch.GetArchitectureName(),
1025 target_arch.GetTriple().getTriple());
1026 } else {
1027 // The target doesn't have a valid architecture yet, set it from the
1028 // architecture we got from the remote GDB server
1029 GetTarget().SetArchitecture(process_arch);
1030 }
1031 }
1032
1033 // Target and Process are reasonably initailized;
1034 // load any binaries we have metadata for / set load address.
1037
1038 // Find out which StructuredDataPlugins are supported by the debug monitor.
1039 // These plugins transmit data over async $J packets.
1040 if (StructuredData::Array *supported_packets =
1041 m_gdb_comm.GetSupportedStructuredDataPlugins())
1042 MapSupportedStructuredDataPlugins(*supported_packets);
1043
1044 // If connected to LLDB ("native-signals+"), use signal defs for
1045 // the remote platform. If connected to GDB, just use the standard set.
1046 if (!m_gdb_comm.UsesNativeSignals()) {
1047 SetUnixSignals(std::make_shared<GDBRemoteSignals>());
1048 } else {
1049 PlatformSP platform_sp = GetTarget().GetPlatform();
1050 if (platform_sp && platform_sp->IsConnected())
1051 SetUnixSignals(platform_sp->GetUnixSignals());
1052 else
1053 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
1054 }
1055}
1056
1058 // The remote stub may know about the "main binary" in
1059 // the context of a firmware debug session, and can
1060 // give us a UUID and an address/slide of where the
1061 // binary is loaded in memory.
1062 UUID standalone_uuid;
1063 addr_t standalone_value;
1064 bool standalone_value_is_offset;
1065 if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value,
1066 standalone_value_is_offset)) {
1067 ModuleSP module_sp;
1068
1069 if (standalone_uuid.IsValid()) {
1070 const bool force_symbol_search = true;
1071 const bool notify = true;
1072 const bool set_address_in_target = true;
1073 const bool allow_memory_image_last_resort = false;
1075 this, "", standalone_uuid, standalone_value,
1076 standalone_value_is_offset, force_symbol_search, notify,
1077 set_address_in_target, allow_memory_image_last_resort);
1078 }
1079 }
1080
1081 // The remote stub may know about a list of binaries to
1082 // force load into the process -- a firmware type situation
1083 // where multiple binaries are present in virtual memory,
1084 // and we are only given the addresses of the binaries.
1085 // Not intended for use with userland debugging, when we use
1086 // a DynamicLoader plugin that knows how to find the loaded
1087 // binaries, and will track updates as binaries are added.
1088
1089 std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
1090 if (bin_addrs.size()) {
1091 UUID uuid;
1092 const bool value_is_slide = false;
1093 for (addr_t addr : bin_addrs) {
1094 const bool notify = true;
1095 // First see if this is a special platform
1096 // binary that may determine the DynamicLoader and
1097 // Platform to be used in this Process and Target.
1098 if (GetTarget()
1099 .GetDebugger()
1100 .GetPlatformList()
1101 .LoadPlatformBinaryAndSetup(this, addr, notify))
1102 continue;
1103
1104 const bool force_symbol_search = true;
1105 const bool set_address_in_target = true;
1106 const bool allow_memory_image_last_resort = false;
1107 // Second manually load this binary into the Target.
1109 this, llvm::StringRef(), uuid, addr, value_is_slide,
1110 force_symbol_search, notify, set_address_in_target,
1111 allow_memory_image_last_resort);
1112 }
1113 }
1114}
1115
1117 ModuleSP module_sp = GetTarget().GetExecutableModule();
1118 if (!module_sp)
1119 return;
1120
1121 std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1122 if (!offsets)
1123 return;
1124
1125 bool is_uniform =
1126 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1127 offsets->offsets.size();
1128 if (!is_uniform)
1129 return; // TODO: Handle non-uniform responses.
1130
1131 bool changed = false;
1132 module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1133 /*value_is_offset=*/true, changed);
1134 if (changed) {
1135 ModuleList list;
1136 list.Append(module_sp);
1137 m_process->GetTarget().ModulesDidLoad(list);
1138 }
1139}
1140
1142 ArchSpec process_arch;
1143 DidLaunchOrAttach(process_arch);
1144}
1145
1147 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1148 Log *log = GetLog(GDBRLog::Process);
1149 Status error;
1150
1151 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1152
1153 // Clear out and clean up from any current state
1154 Clear();
1155 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1156 error = EstablishConnectionIfNeeded(attach_info);
1157 if (error.Success()) {
1158 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1159
1160 char packet[64];
1161 const int packet_len =
1162 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1163 SetID(attach_pid);
1164 auto data_sp =
1165 std::make_shared<EventDataBytes>(llvm::StringRef(packet, packet_len));
1166 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1167 } else
1168 SetExitStatus(-1, error.AsCString());
1169 }
1170
1171 return error;
1172}
1173
1175 const char *process_name, const ProcessAttachInfo &attach_info) {
1176 Status error;
1177 // Clear out and clean up from any current state
1178 Clear();
1179
1180 if (process_name && process_name[0]) {
1181 error = EstablishConnectionIfNeeded(attach_info);
1182 if (error.Success()) {
1183 StreamString packet;
1184
1185 m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError());
1186
1187 if (attach_info.GetWaitForLaunch()) {
1188 if (!m_gdb_comm.GetVAttachOrWaitSupported()) {
1189 packet.PutCString("vAttachWait");
1190 } else {
1191 if (attach_info.GetIgnoreExisting())
1192 packet.PutCString("vAttachWait");
1193 else
1194 packet.PutCString("vAttachOrWait");
1195 }
1196 } else
1197 packet.PutCString("vAttachName");
1198 packet.PutChar(';');
1199 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1202
1203 auto data_sp = std::make_shared<EventDataBytes>(packet.GetString());
1204 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1205
1206 } else
1207 SetExitStatus(-1, error.AsCString());
1208 }
1209 return error;
1210}
1211
1212llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1213 return m_gdb_comm.SendTraceSupported(GetInterruptTimeout());
1214}
1215
1217 return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1218}
1219
1220llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1221 return m_gdb_comm.SendTraceStart(request, GetInterruptTimeout());
1222}
1223
1224llvm::Expected<std::string>
1225ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1226 return m_gdb_comm.SendTraceGetState(type, GetInterruptTimeout());
1227}
1228
1229llvm::Expected<std::vector<uint8_t>>
1231 return m_gdb_comm.SendTraceGetBinaryData(request, GetInterruptTimeout());
1232}
1233
1235 // When we exit, disconnect from the GDB server communications
1236 m_gdb_comm.Disconnect();
1237}
1238
1240 // If you can figure out what the architecture is, fill it in here.
1241 process_arch.Clear();
1242 DidLaunchOrAttach(process_arch);
1243}
1244
1246 m_continue_c_tids.clear();
1247 m_continue_C_tids.clear();
1248 m_continue_s_tids.clear();
1249 m_continue_S_tids.clear();
1250 m_jstopinfo_sp.reset();
1251 m_jthreadsinfo_sp.reset();
1252 m_shared_cache_info_sp.reset();
1253 return Status();
1254}
1255
1257 return m_gdb_comm.GetReverseStepSupported() ||
1258 m_gdb_comm.GetReverseContinueSupported();
1259}
1260
1262 Status error;
1263 Log *log = GetLog(GDBRLog::Process);
1264 LLDB_LOGF(log, "ProcessGDBRemote::Resume(%s)",
1265 direction == RunDirection::eRunForward ? "" : "reverse");
1266
1267 ListenerSP listener_sp(
1268 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1269 if (listener_sp->StartListeningForEvents(
1271 listener_sp->StartListeningForEvents(
1274
1275 const size_t num_threads = GetThreadList().GetSize();
1276
1277 StreamString continue_packet;
1278 bool continue_packet_error = false;
1279 // Number of threads continuing with "c", i.e. continuing without a signal
1280 // to deliver.
1281 const size_t num_continue_c_tids = m_continue_c_tids.size();
1282 // Number of threads continuing with "C", i.e. continuing with a signal to
1283 // deliver.
1284 const size_t num_continue_C_tids = m_continue_C_tids.size();
1285 // Number of threads continuing with "s", i.e. single-stepping.
1286 const size_t num_continue_s_tids = m_continue_s_tids.size();
1287 // Number of threads continuing with "S", i.e. single-stepping with a signal
1288 // to deliver.
1289 const size_t num_continue_S_tids = m_continue_S_tids.size();
1290 if (direction == RunDirection::eRunForward &&
1291 m_gdb_comm.HasAnyVContSupport()) {
1292 std::string pid_prefix;
1293 if (m_gdb_comm.GetMultiprocessSupported())
1294 pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1295
1296 if (num_continue_c_tids == num_threads ||
1297 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1298 m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1299 // All threads are continuing
1300 if (m_gdb_comm.GetMultiprocessSupported())
1301 continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1302 else
1303 continue_packet.PutCString("c");
1304 } else {
1305 continue_packet.PutCString("vCont");
1306
1307 if (!m_continue_c_tids.empty()) {
1308 if (m_gdb_comm.GetVContSupported("c")) {
1309 for (tid_collection::const_iterator
1310 t_pos = m_continue_c_tids.begin(),
1311 t_end = m_continue_c_tids.end();
1312 t_pos != t_end; ++t_pos)
1313 continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1314 } else
1315 continue_packet_error = true;
1316 }
1317
1318 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1319 if (m_gdb_comm.GetVContSupported("C")) {
1320 for (tid_sig_collection::const_iterator
1321 s_pos = m_continue_C_tids.begin(),
1322 s_end = m_continue_C_tids.end();
1323 s_pos != s_end; ++s_pos)
1324 continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1325 pid_prefix, s_pos->first);
1326 } else
1327 continue_packet_error = true;
1328 }
1329
1330 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1331 if (m_gdb_comm.GetVContSupported("s")) {
1332 for (tid_collection::const_iterator
1333 t_pos = m_continue_s_tids.begin(),
1334 t_end = m_continue_s_tids.end();
1335 t_pos != t_end; ++t_pos)
1336 continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1337 } else
1338 continue_packet_error = true;
1339 }
1340
1341 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1342 if (m_gdb_comm.GetVContSupported("S")) {
1343 for (tid_sig_collection::const_iterator
1344 s_pos = m_continue_S_tids.begin(),
1345 s_end = m_continue_S_tids.end();
1346 s_pos != s_end; ++s_pos)
1347 continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1348 pid_prefix, s_pos->first);
1349 } else
1350 continue_packet_error = true;
1351 }
1352
1353 if (continue_packet_error)
1354 continue_packet.Clear();
1355 }
1356 } else
1357 continue_packet_error = true;
1358
1359 if (direction == RunDirection::eRunForward && continue_packet_error) {
1360 // Either no vCont support, or we tried to use part of the vCont packet
1361 // that wasn't supported by the remote GDB server. We need to try and
1362 // make a simple packet that can do our continue.
1363 if (num_continue_c_tids > 0) {
1364 if (num_continue_c_tids == num_threads) {
1365 // All threads are resuming...
1366 m_gdb_comm.SetCurrentThreadForRun(-1);
1367 continue_packet.PutChar('c');
1368 continue_packet_error = false;
1369 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1370 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1371 // Only one thread is continuing
1372 m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front());
1373 continue_packet.PutChar('c');
1374 continue_packet_error = false;
1375 }
1376 }
1377
1378 if (continue_packet_error && num_continue_C_tids > 0) {
1379 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1380 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1381 num_continue_S_tids == 0) {
1382 const int continue_signo = m_continue_C_tids.front().second;
1383 // Only one thread is continuing
1384 if (num_continue_C_tids > 1) {
1385 // More that one thread with a signal, yet we don't have vCont
1386 // support and we are being asked to resume each thread with a
1387 // signal, we need to make sure they are all the same signal, or we
1388 // can't issue the continue accurately with the current support...
1389 if (num_continue_C_tids > 1) {
1390 continue_packet_error = false;
1391 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1392 if (m_continue_C_tids[i].second != continue_signo)
1393 continue_packet_error = true;
1394 }
1395 }
1396 if (!continue_packet_error)
1397 m_gdb_comm.SetCurrentThreadForRun(-1);
1398 } else {
1399 // Set the continue thread ID
1400 continue_packet_error = false;
1401 m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first);
1402 }
1403 if (!continue_packet_error) {
1404 // Add threads continuing with the same signo...
1405 continue_packet.Printf("C%2.2x", continue_signo);
1406 }
1407 }
1408 }
1409
1410 if (continue_packet_error && num_continue_s_tids > 0) {
1411 if (num_continue_s_tids == num_threads) {
1412 // All threads are resuming...
1413 m_gdb_comm.SetCurrentThreadForRun(-1);
1414
1415 continue_packet.PutChar('s');
1416
1417 continue_packet_error = false;
1418 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1419 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1420 // Only one thread is stepping
1421 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1422 continue_packet.PutChar('s');
1423 continue_packet_error = false;
1424 }
1425 }
1426
1427 if (!continue_packet_error && num_continue_S_tids > 0) {
1428 if (num_continue_S_tids == num_threads) {
1429 const int step_signo = m_continue_S_tids.front().second;
1430 // Are all threads trying to step with the same signal?
1431 continue_packet_error = false;
1432 if (num_continue_S_tids > 1) {
1433 for (size_t i = 1; i < num_threads; ++i) {
1434 if (m_continue_S_tids[i].second != step_signo)
1435 continue_packet_error = true;
1436 }
1437 }
1438 if (!continue_packet_error) {
1439 // Add threads stepping with the same signo...
1440 m_gdb_comm.SetCurrentThreadForRun(-1);
1441 continue_packet.Printf("S%2.2x", step_signo);
1442 }
1443 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1444 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1445 // Only one thread is stepping with signal
1446 m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first);
1447 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1448 continue_packet_error = false;
1449 }
1450 }
1451 }
1452
1453 if (direction == RunDirection::eRunReverse) {
1454 if (num_continue_s_tids > 0 || num_continue_S_tids > 0) {
1455 if (!m_gdb_comm.GetReverseStepSupported()) {
1456 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1457 "support reverse-stepping");
1459 "target does not support reverse-stepping");
1460 }
1461
1462 if (num_continue_S_tids > 0) {
1463 LLDB_LOGF(
1464 log,
1465 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1467 "can't deliver signals while running in reverse");
1468 }
1469
1470 if (num_continue_s_tids > 1) {
1471 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: can't step multiple "
1472 "threads in reverse");
1474 "can't step multiple threads while reverse-stepping");
1475 }
1476
1477 m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front());
1478 continue_packet.PutCString("bs");
1479 } else {
1480 if (!m_gdb_comm.GetReverseContinueSupported()) {
1481 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: target does not "
1482 "support reverse-continue");
1484 "target does not support reverse execution of processes");
1485 }
1486
1487 if (num_continue_C_tids > 0) {
1488 LLDB_LOGF(
1489 log,
1490 "ProcessGDBRemote::DoResume: Signals not supported in reverse");
1492 "can't deliver signals while running in reverse");
1493 }
1494
1495 // All threads continue whether requested or not ---
1496 // we can't change how threads ran in the past.
1497 continue_packet.PutCString("bc");
1498 }
1499
1500 continue_packet_error = false;
1501 }
1502
1503 if (continue_packet_error) {
1505 "can't make continue packet for this resume");
1506 } else {
1507 EventSP event_sp;
1508 if (!m_async_thread.IsJoinable()) {
1510 "Trying to resume but the async thread is dead.");
1511 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1512 "async thread is dead.");
1513 return error;
1514 }
1515
1516 auto data_sp =
1517 std::make_shared<EventDataBytes>(continue_packet.GetString());
1518 m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncContinue, data_sp);
1519
1520 if (!listener_sp->GetEvent(event_sp, ResumeTimeout())) {
1521 error = Status::FromErrorString("Resume timed out.");
1522 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1523 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1525 "Broadcast continue, but the async thread was "
1526 "killed before we got an ack back.");
1527 LLDB_LOGF(log,
1528 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1529 "async thread was killed before we got an ack back.");
1530 return error;
1531 }
1532 }
1533 }
1534
1535 return error;
1536}
1537
1539 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1540 m_thread_ids.clear();
1541 m_thread_pcs.clear();
1542}
1543
1545 llvm::StringRef value) {
1546 m_thread_ids.clear();
1547 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
1548 StringExtractorGDBRemote thread_ids{value};
1549
1550 do {
1551 auto pid_tid = thread_ids.GetPidTid(pid);
1552 if (pid_tid && pid_tid->first == pid) {
1553 lldb::tid_t tid = pid_tid->second;
1554 if (tid != LLDB_INVALID_THREAD_ID &&
1556 m_thread_ids.push_back(tid);
1557 }
1558 } while (thread_ids.GetChar() == ',');
1559
1560 return m_thread_ids.size();
1561}
1562
1564 llvm::StringRef value) {
1565 m_thread_pcs.clear();
1566 for (llvm::StringRef x : llvm::split(value, ',')) {
1568 if (llvm::to_integer(x, pc, 16))
1569 m_thread_pcs.push_back(pc);
1570 }
1571 return m_thread_pcs.size();
1572}
1573
1575 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1576
1577 if (m_jthreadsinfo_sp) {
1578 // If we have the JSON threads info, we can get the thread list from that
1579 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1580 if (thread_infos && thread_infos->GetSize() > 0) {
1581 m_thread_ids.clear();
1582 m_thread_pcs.clear();
1583 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1584 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1585 if (thread_dict) {
1586 // Set the thread stop info from the JSON dictionary
1587 SetThreadStopInfo(thread_dict);
1589 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1590 m_thread_ids.push_back(tid);
1591 }
1592 return true; // Keep iterating through all thread_info objects
1593 });
1594 }
1595 if (!m_thread_ids.empty())
1596 return true;
1597 } else {
1598 // See if we can get the thread IDs from the current stop reply packets
1599 // that might contain a "threads" key/value pair
1600
1601 if (m_last_stop_packet) {
1602 // Get the thread stop info
1604 const llvm::StringRef stop_info_str = stop_info.GetStringRef();
1605
1606 m_thread_pcs.clear();
1607 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1608 if (thread_pcs_pos != llvm::StringRef::npos) {
1609 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1610 const size_t end = stop_info_str.find(';', start);
1611 if (end != llvm::StringRef::npos) {
1612 llvm::StringRef value = stop_info_str.substr(start, end - start);
1614 }
1615 }
1616
1617 const size_t threads_pos = stop_info_str.find(";threads:");
1618 if (threads_pos != llvm::StringRef::npos) {
1619 const size_t start = threads_pos + strlen(";threads:");
1620 const size_t end = stop_info_str.find(';', start);
1621 if (end != llvm::StringRef::npos) {
1622 llvm::StringRef value = stop_info_str.substr(start, end - start);
1624 return true;
1625 }
1626 }
1627 }
1628 }
1629
1630 bool sequence_mutex_unavailable = false;
1631 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1632 if (sequence_mutex_unavailable) {
1633 return false; // We just didn't get the list
1634 }
1635 return true;
1636}
1637
1639 ThreadList &new_thread_list) {
1640 // locker will keep a mutex locked until it goes out of scope
1641 Log *log = GetLog(GDBRLog::Thread);
1642 LLDB_LOGV(log, "pid = {0}", GetID());
1643
1644 size_t num_thread_ids = m_thread_ids.size();
1645 // The "m_thread_ids" thread ID list should always be updated after each stop
1646 // reply packet, but in case it isn't, update it here.
1647 if (num_thread_ids == 0) {
1648 if (!UpdateThreadIDList())
1649 return false;
1650 num_thread_ids = m_thread_ids.size();
1651 }
1652
1653 ThreadList old_thread_list_copy(old_thread_list);
1654 if (num_thread_ids > 0) {
1655 for (size_t i = 0; i < num_thread_ids; ++i) {
1656 lldb::tid_t tid = m_thread_ids[i];
1657 ThreadSP thread_sp(
1658 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1659 if (!thread_sp) {
1660 thread_sp = CreateThread(tid);
1661 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1662 thread_sp.get(), thread_sp->GetID());
1663 } else {
1664 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1665 thread_sp.get(), thread_sp->GetID());
1666 }
1667
1668 SetThreadPc(thread_sp, i);
1669 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1670 }
1671 }
1672
1673 // Whatever that is left in old_thread_list_copy are not present in
1674 // new_thread_list. Remove non-existent threads from internal id table.
1675 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1676 for (size_t i = 0; i < old_num_thread_ids; i++) {
1677 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1678 if (old_thread_sp) {
1679 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1680 m_thread_id_to_index_id_map.erase(old_thread_id);
1681 }
1682 }
1683
1684 return true;
1685}
1686
1687void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1688 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1690 ThreadGDBRemote *gdb_thread =
1691 static_cast<ThreadGDBRemote *>(thread_sp.get());
1692 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1693 if (reg_ctx_sp) {
1694 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1696 if (pc_regnum != LLDB_INVALID_REGNUM) {
1697 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1698 }
1699 }
1700 }
1701}
1702
1704 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1705 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1706 // packet
1707 if (thread_infos_sp) {
1708 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1709 if (thread_infos) {
1710 lldb::tid_t tid;
1711 const size_t n = thread_infos->GetSize();
1712 for (size_t i = 0; i < n; ++i) {
1713 StructuredData::Dictionary *thread_dict =
1714 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1715 if (thread_dict) {
1716 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1717 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1718 if (tid == thread->GetID())
1719 return (bool)SetThreadStopInfo(thread_dict);
1720 }
1721 }
1722 }
1723 }
1724 }
1725 return false;
1726}
1727
1729 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1730 // packet
1732 return true;
1733
1734 // See if we got thread stop info for any threads valid stop info reasons
1735 // threads via the "jstopinfo" packet stop reply packet key/value pair?
1736 if (m_jstopinfo_sp) {
1737 // If we have "jstopinfo" then we have stop descriptions for all threads
1738 // that have stop reasons, and if there is no entry for a thread, then it
1739 // has no stop reason.
1741 thread->SetStopInfo(StopInfoSP());
1742 return true;
1743 }
1744
1745 // Fall back to using the qThreadStopInfo packet
1746 StringExtractorGDBRemote stop_packet;
1747 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1748 return SetThreadStopInfo(stop_packet) == eStateStopped;
1749 return false;
1750}
1751
1753 ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) {
1754 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1755 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1756
1757 for (const auto &pair : expedited_register_map) {
1758 StringExtractor reg_value_extractor(pair.second);
1759 WritableDataBufferSP buffer_sp(
1760 new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1761 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1762 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1763 eRegisterKindProcessPlugin, pair.first);
1764 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1765 }
1766}
1767
1769 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1770 uint8_t signo, const std::string &thread_name, const std::string &reason,
1771 const std::string &description, uint32_t exc_type,
1772 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1773 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1774 // queue_serial are valid
1775 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1776 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1777
1778 if (tid == LLDB_INVALID_THREAD_ID)
1779 return nullptr;
1780
1781 ThreadSP thread_sp;
1782 // Scope for "locker" below
1783 {
1784 // m_thread_list_real does have its own mutex, but we need to hold onto the
1785 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1786 // m_thread_list_real.AddThread(...) so it doesn't change on us
1787 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1788 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1789
1790 if (!thread_sp) {
1791 // Create the thread if we need to
1792 thread_sp = CreateThread(tid);
1793 m_thread_list_real.AddThread(thread_sp);
1794 }
1795 }
1796
1797 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1798 RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext());
1799
1800 reg_ctx_sp->InvalidateIfNeeded(true);
1801
1802 auto iter = llvm::find(m_thread_ids, tid);
1803 if (iter != m_thread_ids.end())
1804 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1805
1806 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1807
1808 if (reg_ctx_sp->ReconfigureRegisterInfo()) {
1809 // Now we have changed the offsets of all the registers, so the values
1810 // will be corrupted.
1811 reg_ctx_sp->InvalidateAllRegisters();
1812 // Expedited registers values will never contain registers that would be
1813 // resized by a reconfigure. So we are safe to continue using these
1814 // values.
1815 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1816 }
1817
1818 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1819
1820 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1821 // Check if the GDB server was able to provide the queue name, kind and serial
1822 // number
1823 if (queue_vars_valid)
1824 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1825 dispatch_queue_t, associated_with_dispatch_queue);
1826 else
1827 gdb_thread->ClearQueueInfo();
1828
1829 gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);
1830
1831 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1832 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1833
1834 // Make sure we update our thread stop reason just once, but don't overwrite
1835 // the stop info for threads that haven't moved:
1836 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1837 if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1838 current_stop_info_sp) {
1839 thread_sp->SetStopInfo(current_stop_info_sp);
1840 return thread_sp;
1841 }
1842
1843 if (!thread_sp->StopInfoIsUpToDate()) {
1844 thread_sp->SetStopInfo(StopInfoSP());
1845
1846 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1847 BreakpointSiteSP bp_site_sp =
1848 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1849 if (bp_site_sp && bp_site_sp->IsEnabled())
1850 thread_sp->SetThreadStoppedAtUnexecutedBP(pc);
1851
1852 if (exc_type != 0) {
1853 // For thread plan async interrupt, creating stop info on the
1854 // original async interrupt request thread instead. If interrupt thread
1855 // does not exist anymore we fallback to current signal receiving thread
1856 // instead.
1857 ThreadSP interrupt_thread;
1859 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
1860 if (interrupt_thread)
1861 thread_sp = interrupt_thread;
1862 else {
1863 const size_t exc_data_size = exc_data.size();
1864 thread_sp->SetStopInfo(
1866 *thread_sp, exc_type, exc_data_size,
1867 exc_data_size >= 1 ? exc_data[0] : 0,
1868 exc_data_size >= 2 ? exc_data[1] : 0,
1869 exc_data_size >= 3 ? exc_data[2] : 0));
1870 }
1871 } else {
1872 bool handled = false;
1873 bool did_exec = false;
1874 // debugserver can send reason = "none" which is equivalent
1875 // to no reason.
1876 if (!reason.empty() && reason != "none") {
1877 if (reason == "trace") {
1878 thread_sp->SetStopInfo(StopInfo::CreateStopReasonToTrace(*thread_sp));
1879 handled = true;
1880 } else if (reason == "breakpoint") {
1881 thread_sp->SetThreadHitBreakpointSite();
1882 if (bp_site_sp) {
1883 // If the breakpoint is for this thread, then we'll report the hit,
1884 // but if it is for another thread, we can just report no reason.
1885 // We don't need to worry about stepping over the breakpoint here,
1886 // that will be taken care of when the thread resumes and notices
1887 // that there's a breakpoint under the pc.
1888 handled = true;
1889 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1890 thread_sp->SetStopInfo(
1892 *thread_sp, bp_site_sp->GetID()));
1893 } else {
1894 StopInfoSP invalid_stop_info_sp;
1895 thread_sp->SetStopInfo(invalid_stop_info_sp);
1896 }
1897 }
1898 } else if (reason == "trap") {
1899 // Let the trap just use the standard signal stop reason below...
1900 } else if (reason == "watchpoint") {
1901 // We will have between 1 and 3 fields in the description.
1902 //
1903 // \a wp_addr which is the original start address that
1904 // lldb requested be watched, or an address that the
1905 // hardware reported. This address should be within the
1906 // range of a currently active watchpoint region - lldb
1907 // should be able to find a watchpoint with this address.
1908 //
1909 // \a wp_index is the hardware watchpoint register number.
1910 //
1911 // \a wp_hit_addr is the actual address reported by the hardware,
1912 // which may be outside the range of a region we are watching.
1913 //
1914 // On MIPS, we may get a false watchpoint exception where an
1915 // access to the same 8 byte granule as a watchpoint will trigger,
1916 // even if the access was not within the range of the watched
1917 // region. When we get a \a wp_hit_addr outside the range of any
1918 // set watchpoint, continue execution without making it visible to
1919 // the user.
1920 //
1921 // On ARM, a related issue where a large access that starts
1922 // before the watched region (and extends into the watched
1923 // region) may report a hit address before the watched region.
1924 // lldb will not find the "nearest" watchpoint to
1925 // disable/step/re-enable it, so one of the valid watchpoint
1926 // addresses should be provided as \a wp_addr.
1927 StringExtractor desc_extractor(description.c_str());
1928 // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this
1929 // up as
1930 // <address within wp range> <wp hw index> <actual accessed addr>
1931 // but this is not reading the <wp hw index>. Seems like it
1932 // wouldn't work on MIPS, where that third field is important.
1933 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1934 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1936 bool silently_continue = false;
1937 WatchpointResourceSP wp_resource_sp;
1938 if (wp_hit_addr != LLDB_INVALID_ADDRESS) {
1939 wp_resource_sp =
1940 m_watchpoint_resource_list.FindByAddress(wp_hit_addr);
1941 // On MIPS, \a wp_hit_addr outside the range of a watched
1942 // region means we should silently continue, it is a false hit.
1944 if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first &&
1946 silently_continue = true;
1947 }
1948 if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS)
1949 wp_resource_sp = m_watchpoint_resource_list.FindByAddress(wp_addr);
1950 if (!wp_resource_sp) {
1952 LLDB_LOGF(log, "failed to find watchpoint");
1953 watch_id = LLDB_INVALID_SITE_ID;
1954 } else {
1955 // LWP_TODO: This is hardcoding a single Watchpoint in a
1956 // Resource, need to add
1957 // StopInfo::CreateStopReasonWithWatchpointResource which
1958 // represents all watchpoints that were tripped at this stop.
1959 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();
1960 }
1961 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1962 *thread_sp, watch_id, silently_continue));
1963 handled = true;
1964 } else if (reason == "exception") {
1965 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1966 *thread_sp, description.c_str()));
1967 handled = true;
1968 } else if (reason == "history boundary") {
1969 thread_sp->SetStopInfo(StopInfo::CreateStopReasonHistoryBoundary(
1970 *thread_sp, description.c_str()));
1971 handled = true;
1972 } else if (reason == "exec") {
1973 did_exec = true;
1974 thread_sp->SetStopInfo(
1976 handled = true;
1977 } else if (reason == "processor trace") {
1978 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1979 *thread_sp, description.c_str()));
1980 } else if (reason == "fork") {
1981 StringExtractor desc_extractor(description.c_str());
1982 lldb::pid_t child_pid =
1983 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1984 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1985 thread_sp->SetStopInfo(
1986 StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));
1987 handled = true;
1988 } else if (reason == "vfork") {
1989 StringExtractor desc_extractor(description.c_str());
1990 lldb::pid_t child_pid =
1991 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1992 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1993 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1994 *thread_sp, child_pid, child_tid));
1995 handled = true;
1996 } else if (reason == "vforkdone") {
1997 thread_sp->SetStopInfo(
1999 handled = true;
2000 }
2001 }
2002
2003 if (!handled && signo && !did_exec) {
2004 if (signo == SIGTRAP) {
2005 // Currently we are going to assume SIGTRAP means we are either
2006 // hitting a breakpoint or hardware single stepping.
2007
2008 // We can't disambiguate between stepping-to-a-breakpointsite and
2009 // hitting-a-breakpointsite.
2010 //
2011 // A user can instruction-step, and be stopped at a BreakpointSite.
2012 // Or a user can be sitting at a BreakpointSite,
2013 // instruction-step which hits the breakpoint and the pc does not
2014 // advance.
2015 //
2016 // In both cases, we're at a BreakpointSite when stopped, and
2017 // the resume state was eStateStepping.
2018
2019 // Assume if we're at a BreakpointSite, we hit it.
2020 handled = true;
2021 addr_t pc =
2022 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
2023 BreakpointSiteSP bp_site_sp =
2024 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
2025 pc);
2026
2027 // We can't know if we hit it or not. So if we are stopped at
2028 // a BreakpointSite, assume we hit it, and should step past the
2029 // breakpoint when we resume. This is contrary to how we handle
2030 // BreakpointSites in any other location, but we can't know for
2031 // sure what happened so it's a reasonable default.
2032 if (bp_site_sp) {
2033 if (bp_site_sp->IsEnabled())
2034 thread_sp->SetThreadHitBreakpointSite();
2035
2036 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
2037 if (m_breakpoint_pc_offset != 0)
2038 thread_sp->GetRegisterContext()->SetPC(pc);
2039 thread_sp->SetStopInfo(
2041 *thread_sp, bp_site_sp->GetID()));
2042 } else {
2043 StopInfoSP invalid_stop_info_sp;
2044 thread_sp->SetStopInfo(invalid_stop_info_sp);
2045 }
2046 } else {
2047 // If we were stepping then assume the stop was the result of the
2048 // trace. If we were not stepping then report the SIGTRAP.
2049 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
2050 thread_sp->SetStopInfo(
2052 else
2053 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2054 *thread_sp, signo, description.c_str()));
2055 }
2056 }
2057 if (!handled) {
2058 // For thread plan async interrupt, creating stop info on the
2059 // original async interrupt request thread instead. If interrupt
2060 // thread does not exist anymore we fallback to current signal
2061 // receiving thread instead.
2062 ThreadSP interrupt_thread;
2064 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
2065 if (interrupt_thread)
2066 thread_sp = interrupt_thread;
2067 else
2068 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
2069 *thread_sp, signo, description.c_str()));
2070 }
2071 }
2072
2073 if (!description.empty()) {
2074 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
2075 if (stop_info_sp) {
2076 const char *stop_info_desc = stop_info_sp->GetDescription();
2077 if (!stop_info_desc || !stop_info_desc[0])
2078 stop_info_sp->SetDescription(description.c_str());
2079 } else {
2080 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
2081 *thread_sp, description.c_str()));
2082 }
2083 }
2084 }
2085 }
2086 return thread_sp;
2087}
2088
2091 const std::string &description) {
2092 ThreadSP thread_sp;
2093 {
2094 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2095 thread_sp = m_thread_list_real.FindThreadByProtocolID(m_interrupt_tid,
2096 /*can_update=*/false);
2097 }
2098 if (thread_sp)
2099 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(
2100 *thread_sp, signo, description.c_str()));
2101 // Clear m_interrupt_tid regardless we can find original interrupt thread or
2102 // not.
2104 return thread_sp;
2105}
2106
2109 static constexpr llvm::StringLiteral g_key_tid("tid");
2110 static constexpr llvm::StringLiteral g_key_name("name");
2111 static constexpr llvm::StringLiteral g_key_reason("reason");
2112 static constexpr llvm::StringLiteral g_key_metype("metype");
2113 static constexpr llvm::StringLiteral g_key_medata("medata");
2114 static constexpr llvm::StringLiteral g_key_qaddr("qaddr");
2115 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2116 "dispatch_queue_t");
2117 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2118 "associated_with_dispatch_queue");
2119 static constexpr llvm::StringLiteral g_key_queue_name("qname");
2120 static constexpr llvm::StringLiteral g_key_queue_kind("qkind");
2121 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");
2122 static constexpr llvm::StringLiteral g_key_registers("registers");
2123 static constexpr llvm::StringLiteral g_key_memory("memory");
2124 static constexpr llvm::StringLiteral g_key_description("description");
2125 static constexpr llvm::StringLiteral g_key_signal("signal");
2126
2127 // Stop with signal and thread info
2129 uint8_t signo = 0;
2130 std::string thread_name;
2131 std::string reason;
2132 std::string description;
2133 uint32_t exc_type = 0;
2134 std::vector<addr_t> exc_data;
2135 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2136 ExpeditedRegisterMap expedited_register_map;
2137 bool queue_vars_valid = false;
2138 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2139 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2140 std::string queue_name;
2141 QueueKind queue_kind = eQueueKindUnknown;
2142 uint64_t queue_serial_number = 0;
2143 // Iterate through all of the thread dictionary key/value pairs from the
2144 // structured data dictionary
2145
2146 // FIXME: we're silently ignoring invalid data here
2147 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2148 &signo, &reason, &description, &exc_type, &exc_data,
2149 &thread_dispatch_qaddr, &queue_vars_valid,
2150 &associated_with_dispatch_queue, &dispatch_queue_t,
2151 &queue_name, &queue_kind, &queue_serial_number](
2152 llvm::StringRef key,
2153 StructuredData::Object *object) -> bool {
2154 if (key == g_key_tid) {
2155 // thread in big endian hex
2156 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
2157 } else if (key == g_key_metype) {
2158 // exception type in big endian hex
2159 exc_type = object->GetUnsignedIntegerValue(0);
2160 } else if (key == g_key_medata) {
2161 // exception data in big endian hex
2162 StructuredData::Array *array = object->GetAsArray();
2163 if (array) {
2164 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2165 exc_data.push_back(object->GetUnsignedIntegerValue());
2166 return true; // Keep iterating through all array items
2167 });
2168 }
2169 } else if (key == g_key_name) {
2170 thread_name = std::string(object->GetStringValue());
2171 } else if (key == g_key_qaddr) {
2172 thread_dispatch_qaddr =
2173 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
2174 } else if (key == g_key_queue_name) {
2175 queue_vars_valid = true;
2176 queue_name = std::string(object->GetStringValue());
2177 } else if (key == g_key_queue_kind) {
2178 std::string queue_kind_str = std::string(object->GetStringValue());
2179 if (queue_kind_str == "serial") {
2180 queue_vars_valid = true;
2181 queue_kind = eQueueKindSerial;
2182 } else if (queue_kind_str == "concurrent") {
2183 queue_vars_valid = true;
2184 queue_kind = eQueueKindConcurrent;
2185 }
2186 } else if (key == g_key_queue_serial_number) {
2187 queue_serial_number = object->GetUnsignedIntegerValue(0);
2188 if (queue_serial_number != 0)
2189 queue_vars_valid = true;
2190 } else if (key == g_key_dispatch_queue_t) {
2191 dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2192 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2193 queue_vars_valid = true;
2194 } else if (key == g_key_associated_with_dispatch_queue) {
2195 queue_vars_valid = true;
2196 bool associated = object->GetBooleanValue();
2197 if (associated)
2198 associated_with_dispatch_queue = eLazyBoolYes;
2199 else
2200 associated_with_dispatch_queue = eLazyBoolNo;
2201 } else if (key == g_key_reason) {
2202 reason = std::string(object->GetStringValue());
2203 } else if (key == g_key_description) {
2204 description = std::string(object->GetStringValue());
2205 } else if (key == g_key_registers) {
2206 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2207
2208 if (registers_dict) {
2209 registers_dict->ForEach(
2210 [&expedited_register_map](llvm::StringRef key,
2211 StructuredData::Object *object) -> bool {
2212 uint32_t reg;
2213 if (llvm::to_integer(key, reg))
2214 expedited_register_map[reg] =
2215 std::string(object->GetStringValue());
2216 return true; // Keep iterating through all array items
2217 });
2218 }
2219 } else if (key == g_key_memory) {
2220 StructuredData::Array *array = object->GetAsArray();
2221 if (array) {
2222 array->ForEach([this](StructuredData::Object *object) -> bool {
2223 StructuredData::Dictionary *mem_cache_dict =
2224 object->GetAsDictionary();
2225 if (mem_cache_dict) {
2226 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2227 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2228 "address", mem_cache_addr)) {
2229 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2230 llvm::StringRef str;
2231 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2232 StringExtractor bytes(str);
2233 bytes.SetFilePos(0);
2234
2235 const size_t byte_size = bytes.GetStringRef().size() / 2;
2236 WritableDataBufferSP data_buffer_sp(
2237 new DataBufferHeap(byte_size, 0));
2238 const size_t bytes_copied =
2239 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2240 if (bytes_copied == byte_size)
2241 m_memory_cache.AddL1CacheData(mem_cache_addr,
2242 data_buffer_sp);
2243 }
2244 }
2245 }
2246 }
2247 return true; // Keep iterating through all array items
2248 });
2249 }
2250
2251 } else if (key == g_key_signal)
2252 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2253 return true; // Keep iterating through all dictionary key/value pairs
2254 });
2255
2256 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2257 reason, description, exc_type, exc_data,
2258 thread_dispatch_qaddr, queue_vars_valid,
2259 associated_with_dispatch_queue, dispatch_queue_t,
2260 queue_name, queue_kind, queue_serial_number);
2261}
2262
2264 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
2265 stop_packet.SetFilePos(0);
2266 const char stop_type = stop_packet.GetChar();
2267 switch (stop_type) {
2268 case 'T':
2269 case 'S': {
2270 // This is a bit of a hack, but it is required. If we did exec, we need to
2271 // clear our thread lists and also know to rebuild our dynamic register
2272 // info before we lookup and threads and populate the expedited register
2273 // values so we need to know this right away so we can cleanup and update
2274 // our registers.
2275 const uint32_t stop_id = GetStopID();
2276 if (stop_id == 0) {
2277 // Our first stop, make sure we have a process ID, and also make sure we
2278 // know about our registers
2280 SetID(pid);
2282 }
2283 // Stop with signal and thread info
2286 const uint8_t signo = stop_packet.GetHexU8();
2287 llvm::StringRef key;
2288 llvm::StringRef value;
2289 std::string thread_name;
2290 std::string reason;
2291 std::string description;
2292 uint32_t exc_type = 0;
2293 std::vector<addr_t> exc_data;
2294 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2295 bool queue_vars_valid =
2296 false; // says if locals below that start with "queue_" are valid
2297 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2298 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2299 std::string queue_name;
2300 QueueKind queue_kind = eQueueKindUnknown;
2301 uint64_t queue_serial_number = 0;
2302 ExpeditedRegisterMap expedited_register_map;
2303 AddressableBits addressable_bits;
2304 while (stop_packet.GetNameColonValue(key, value)) {
2305 if (key.compare("metype") == 0) {
2306 // exception type in big endian hex
2307 value.getAsInteger(16, exc_type);
2308 } else if (key.compare("medata") == 0) {
2309 // exception data in big endian hex
2310 uint64_t x;
2311 value.getAsInteger(16, x);
2312 exc_data.push_back(x);
2313 } else if (key.compare("thread") == 0) {
2314 // thread-id
2315 StringExtractorGDBRemote thread_id{value};
2316 auto pid_tid = thread_id.GetPidTid(pid);
2317 if (pid_tid) {
2318 stop_pid = pid_tid->first;
2319 tid = pid_tid->second;
2320 } else
2322 } else if (key.compare("threads") == 0) {
2323 std::lock_guard<std::recursive_mutex> guard(
2324 m_thread_list_real.GetMutex());
2326 } else if (key.compare("thread-pcs") == 0) {
2327 m_thread_pcs.clear();
2328 // A comma separated list of all threads in the current
2329 // process that includes the thread for this stop reply packet
2331 while (!value.empty()) {
2332 llvm::StringRef pc_str;
2333 std::tie(pc_str, value) = value.split(',');
2334 if (pc_str.getAsInteger(16, pc))
2336 m_thread_pcs.push_back(pc);
2337 }
2338 } else if (key.compare("jstopinfo") == 0) {
2339 StringExtractor json_extractor(value);
2340 std::string json;
2341 // Now convert the HEX bytes into a string value
2342 json_extractor.GetHexByteString(json);
2343
2344 // This JSON contains thread IDs and thread stop info for all threads.
2345 // It doesn't contain expedited registers, memory or queue info.
2347 } else if (key.compare("hexname") == 0) {
2348 StringExtractor name_extractor(value);
2349 // Now convert the HEX bytes into a string value
2350 name_extractor.GetHexByteString(thread_name);
2351 } else if (key.compare("name") == 0) {
2352 thread_name = std::string(value);
2353 } else if (key.compare("qaddr") == 0) {
2354 value.getAsInteger(16, thread_dispatch_qaddr);
2355 } else if (key.compare("dispatch_queue_t") == 0) {
2356 queue_vars_valid = true;
2357 value.getAsInteger(16, dispatch_queue_t);
2358 } else if (key.compare("qname") == 0) {
2359 queue_vars_valid = true;
2360 StringExtractor name_extractor(value);
2361 // Now convert the HEX bytes into a string value
2362 name_extractor.GetHexByteString(queue_name);
2363 } else if (key.compare("qkind") == 0) {
2364 queue_kind = llvm::StringSwitch<QueueKind>(value)
2365 .Case("serial", eQueueKindSerial)
2366 .Case("concurrent", eQueueKindConcurrent)
2367 .Default(eQueueKindUnknown);
2368 queue_vars_valid = queue_kind != eQueueKindUnknown;
2369 } else if (key.compare("qserialnum") == 0) {
2370 if (!value.getAsInteger(0, queue_serial_number))
2371 queue_vars_valid = true;
2372 } else if (key.compare("reason") == 0) {
2373 reason = std::string(value);
2374 } else if (key.compare("description") == 0) {
2375 StringExtractor desc_extractor(value);
2376 // Now convert the HEX bytes into a string value
2377 desc_extractor.GetHexByteString(description);
2378 } else if (key.compare("memory") == 0) {
2379 // Expedited memory. GDB servers can choose to send back expedited
2380 // memory that can populate the L1 memory cache in the process so that
2381 // things like the frame pointer backchain can be expedited. This will
2382 // help stack backtracing be more efficient by not having to send as
2383 // many memory read requests down the remote GDB server.
2384
2385 // Key/value pair format: memory:<addr>=<bytes>;
2386 // <addr> is a number whose base will be interpreted by the prefix:
2387 // "0x[0-9a-fA-F]+" for hex
2388 // "0[0-7]+" for octal
2389 // "[1-9]+" for decimal
2390 // <bytes> is native endian ASCII hex bytes just like the register
2391 // values
2392 llvm::StringRef addr_str, bytes_str;
2393 std::tie(addr_str, bytes_str) = value.split('=');
2394 if (!addr_str.empty() && !bytes_str.empty()) {
2395 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2396 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2397 StringExtractor bytes(bytes_str);
2398 const size_t byte_size = bytes.GetBytesLeft() / 2;
2399 WritableDataBufferSP data_buffer_sp(
2400 new DataBufferHeap(byte_size, 0));
2401 const size_t bytes_copied =
2402 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2403 if (bytes_copied == byte_size)
2404 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2405 }
2406 }
2407 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2408 key.compare("awatch") == 0) {
2409 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2411 value.getAsInteger(16, wp_addr);
2412
2413 WatchpointResourceSP wp_resource_sp =
2414 m_watchpoint_resource_list.FindByAddress(wp_addr);
2415
2416 // Rewrite gdb standard watch/rwatch/awatch to
2417 // "reason:watchpoint" + "description:ADDR",
2418 // which is parsed in SetThreadStopInfo.
2419 reason = "watchpoint";
2420 StreamString ostr;
2421 ostr.Printf("%" PRIu64, wp_addr);
2422 description = std::string(ostr.GetString());
2423 } else if (key.compare("swbreak") == 0 || key.compare("hwbreak") == 0) {
2424 reason = "breakpoint";
2425 } else if (key.compare("replaylog") == 0) {
2426 reason = "history boundary";
2427 } else if (key.compare("library") == 0) {
2428 auto error = LoadModules();
2429 if (error) {
2431 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2432 }
2433 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2434 // fork includes child pid/tid in thread-id format
2435 StringExtractorGDBRemote thread_id{value};
2436 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2437 if (!pid_tid) {
2439 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2441 }
2442
2443 reason = key.str();
2444 StreamString ostr;
2445 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2446 description = std::string(ostr.GetString());
2447 } else if (key.compare("addressing_bits") == 0) {
2448 uint64_t addressing_bits;
2449 if (!value.getAsInteger(0, addressing_bits)) {
2450 addressable_bits.SetAddressableBits(addressing_bits);
2451 }
2452 } else if (key.compare("low_mem_addressing_bits") == 0) {
2453 uint64_t addressing_bits;
2454 if (!value.getAsInteger(0, addressing_bits)) {
2455 addressable_bits.SetLowmemAddressableBits(addressing_bits);
2456 }
2457 } else if (key.compare("high_mem_addressing_bits") == 0) {
2458 uint64_t addressing_bits;
2459 if (!value.getAsInteger(0, addressing_bits)) {
2460 addressable_bits.SetHighmemAddressableBits(addressing_bits);
2461 }
2462 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2463 uint32_t reg = UINT32_MAX;
2464 if (!key.getAsInteger(16, reg))
2465 expedited_register_map[reg] = std::string(std::move(value));
2466 }
2467 // swbreak and hwbreak are also expected keys, but we don't need to
2468 // change our behaviour for them because lldb always expects the remote
2469 // to adjust the program counter (if relevant, e.g., for x86 targets)
2470 }
2471
2472 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2473 Log *log = GetLog(GDBRLog::Process);
2474 LLDB_LOG(log,
2475 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2476 stop_pid, pid);
2477 return eStateInvalid;
2478 }
2479
2480 if (tid == LLDB_INVALID_THREAD_ID) {
2481 // A thread id may be invalid if the response is old style 'S' packet
2482 // which does not provide the
2483 // thread information. So update the thread list and choose the first
2484 // one.
2486
2487 if (!m_thread_ids.empty()) {
2488 tid = m_thread_ids.front();
2489 }
2490 }
2491
2492 SetAddressableBitMasks(addressable_bits);
2493
2494 ThreadSP thread_sp = SetThreadStopInfo(
2495 tid, expedited_register_map, signo, thread_name, reason, description,
2496 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2497 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2498 queue_kind, queue_serial_number);
2499
2500 return eStateStopped;
2501 } break;
2502
2503 case 'W':
2504 case 'X':
2505 // process exited
2506 return eStateExited;
2507
2508 default:
2509 break;
2510 }
2511 return eStateInvalid;
2512}
2513
2515 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2516
2517 m_thread_ids.clear();
2518 m_thread_pcs.clear();
2519
2520 // Set the thread stop info. It might have a "threads" key whose value is a
2521 // list of all thread IDs in the current process, so m_thread_ids might get
2522 // set.
2523 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2524 if (m_thread_ids.empty()) {
2525 // No, we need to fetch the thread list manually
2527 }
2528
2529 // We might set some stop info's so make sure the thread list is up to
2530 // date before we do that or we might overwrite what was computed here.
2532
2535 m_last_stop_packet.reset();
2536
2537 // If we have queried for a default thread id
2539 m_thread_list.SetSelectedThreadByID(m_initial_tid);
2541 }
2542
2543 // Let all threads recover from stopping and do any clean up based on the
2544 // previous thread state (if any).
2545 m_thread_list_real.RefreshStateAfterStop();
2546}
2547
2549 Status error;
2550
2552 // We are being asked to halt during an attach. We used to just close our
2553 // file handle and debugserver will go away, but with remote proxies, it
2554 // is better to send a positive signal, so let's send the interrupt first...
2555 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2556 m_gdb_comm.Disconnect();
2557 } else
2558 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2559 return error;
2560}
2561
2563 Status error;
2564 Log *log = GetLog(GDBRLog::Process);
2565 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2566
2567 error = m_gdb_comm.Detach(keep_stopped);
2568 if (log) {
2569 if (error.Success())
2570 log->PutCString(
2571 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2572 else
2573 LLDB_LOGF(log,
2574 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2575 error.AsCString() ? error.AsCString() : "<unknown error>");
2576 }
2577
2578 if (!error.Success())
2579 return error;
2580
2581 // Sleep for one second to let the process get all detached...
2583
2586
2587 // KillDebugserverProcess ();
2588 return error;
2589}
2590
2592 Log *log = GetLog(GDBRLog::Process);
2593 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2594
2595 // Interrupt if our inferior is running...
2596 int exit_status = SIGABRT;
2597 std::string exit_string;
2598
2599 if (m_gdb_comm.IsConnected()) {
2601 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2602
2603 if (kill_res) {
2604 exit_status = kill_res.get();
2605#if defined(__APPLE__)
2606 // For Native processes on Mac OS X, we launch through the Host
2607 // Platform, then hand the process off to debugserver, which becomes
2608 // the parent process through "PT_ATTACH". Then when we go to kill
2609 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2610 // we call waitpid which returns with no error and the correct
2611 // status. But amusingly enough that doesn't seem to actually reap
2612 // the process, but instead it is left around as a Zombie. Probably
2613 // the kernel is in the process of switching ownership back to lldb
2614 // which was the original parent, and gets confused in the handoff.
2615 // Anyway, so call waitpid here to finally reap it.
2616 PlatformSP platform_sp(GetTarget().GetPlatform());
2617 if (platform_sp && platform_sp->IsHost()) {
2618 int status;
2619 ::pid_t reap_pid;
2620 reap_pid = waitpid(GetID(), &status, WNOHANG);
2621 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2622 }
2623#endif
2625 exit_string.assign("killed");
2626 } else {
2627 exit_string.assign(llvm::toString(kill_res.takeError()));
2628 }
2629 } else {
2630 exit_string.assign("killed or interrupted while attaching.");
2631 }
2632 } else {
2633 // If we missed setting the exit status on the way out, do it here.
2634 // NB set exit status can be called multiple times, the first one sets the
2635 // status.
2636 exit_string.assign("destroying when not connected to debugserver");
2637 }
2638
2639 SetExitStatus(exit_status, exit_string.c_str());
2640
2644 return Status();
2645}
2646
2649 if (TargetSP target_sp = m_target_wp.lock())
2650 target_sp->RemoveBreakpointByID(m_thread_create_bp_sp->GetID());
2651 m_thread_create_bp_sp.reset();
2652 }
2653}
2654
2656 const StringExtractorGDBRemote &response) {
2657 const bool did_exec =
2658 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2659 if (did_exec) {
2660 Log *log = GetLog(GDBRLog::Process);
2661 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2662
2663 m_thread_list_real.Clear();
2664 m_thread_list.Clear();
2666 m_gdb_comm.ResetDiscoverableSettings(did_exec);
2667 }
2668
2669 m_last_stop_packet = response;
2670}
2671
2673 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2674}
2675
2676// Process Queries
2677
2679 return m_gdb_comm.IsConnected() && Process::IsAlive();
2680}
2681
2683 // request the link map address via the $qShlibInfoAddr packet
2684 lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr();
2685
2686 // the loaded module list can also provides a link map address
2687 if (addr == LLDB_INVALID_ADDRESS) {
2688 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2689 if (!list) {
2690 Log *log = GetLog(GDBRLog::Process);
2691 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2692 } else {
2693 addr = list->m_link_map;
2694 }
2695 }
2696
2697 return addr;
2698}
2699
2701 // See if the GDB remote client supports the JSON threads info. If so, we
2702 // gather stop info for all threads, expedited registers, expedited memory,
2703 // runtime queue information (iOS and MacOSX only), and more. Expediting
2704 // memory will help stack backtracing be much faster. Expediting registers
2705 // will make sure we don't have to read the thread registers for GPRs.
2706 m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo();
2707
2708 if (m_jthreadsinfo_sp) {
2709 // Now set the stop info for each thread and also expedite any registers
2710 // and memory that was in the jThreadsInfo response.
2711 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2712 if (thread_infos) {
2713 const size_t n = thread_infos->GetSize();
2714 for (size_t i = 0; i < n; ++i) {
2715 StructuredData::Dictionary *thread_dict =
2716 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2717 if (thread_dict)
2718 SetThreadStopInfo(thread_dict);
2719 }
2720 }
2721 }
2722}
2723
2724// Process Memory
2725size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2726 Status &error) {
2727 using xPacketState = GDBRemoteCommunicationClient::xPacketState;
2728
2730 xPacketState x_state = m_gdb_comm.GetxPacketState();
2731
2732 // M and m packets take 2 bytes for 1 byte of memory
2733 size_t max_memory_size = x_state != xPacketState::Unimplemented
2735 : m_max_memory_size / 2;
2736 if (size > max_memory_size) {
2737 // Keep memory read sizes down to a sane limit. This function will be
2738 // called multiple times in order to complete the task by
2739 // lldb_private::Process so it is ok to do this.
2740 size = max_memory_size;
2741 }
2742
2743 char packet[64];
2744 int packet_len;
2745 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2746 x_state != xPacketState::Unimplemented ? 'x' : 'm',
2747 (uint64_t)addr, (uint64_t)size);
2748 assert(packet_len + 1 < (int)sizeof(packet));
2749 UNUSED_IF_ASSERT_DISABLED(packet_len);
2750 StringExtractorGDBRemote response;
2751 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2754 if (response.IsNormalResponse()) {
2755 error.Clear();
2756 if (x_state != xPacketState::Unimplemented) {
2757 // The lower level GDBRemoteCommunication packet receive layer has
2758 // already de-quoted any 0x7d character escaping that was present in
2759 // the packet
2760
2761 llvm::StringRef data_received = response.GetStringRef();
2762 if (x_state == xPacketState::Prefixed &&
2763 !data_received.consume_front("b")) {
2765 "unexpected response to GDB server memory read packet '{0}': "
2766 "'{1}'",
2767 packet, data_received);
2768 return 0;
2769 }
2770 // Don't write past the end of BUF if the remote debug server gave us
2771 // too much data for some reason.
2772 size_t memcpy_size = std::min(size, data_received.size());
2773 memcpy(buf, data_received.data(), memcpy_size);
2774 return memcpy_size;
2775 } else {
2776 return response.GetHexBytes(
2777 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2778 }
2779 } else if (response.IsErrorResponse())
2781 "memory read failed for 0x%" PRIx64, addr);
2782 else if (response.IsUnsupportedResponse())
2784 "GDB server does not support reading memory");
2785 else
2787 "unexpected response to GDB server memory read packet '%s': '%s'",
2788 packet, response.GetStringRef().data());
2789 } else {
2790 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
2791 packet);
2792 }
2793 return 0;
2794}
2795
2796/// Returns the number of ranges that is safe to request using MultiMemRead
2797/// while respecting max_packet_size.
2799 uint64_t max_packet_size,
2800 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
2801 // Each range is specified by two numbers (up to 16 ASCII characters) and one
2802 // comma.
2803 constexpr uint64_t range_overhead = 33;
2804 uint64_t current_size = 0;
2805 for (auto [idx, range] : llvm::enumerate(ranges)) {
2806 uint64_t potential_size = current_size + range.size + range_overhead;
2807 if (potential_size > max_packet_size) {
2808 if (idx == 0)
2810 "MultiMemRead input has a range (base = {0:x}, size = {1}) "
2811 "bigger than the maximum allowed by remote",
2812 range.base, range.size);
2813 return idx;
2814 }
2815 }
2816 return ranges.size();
2817}
2818
2819llvm::SmallVector<llvm::MutableArrayRef<uint8_t>>
2821 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges,
2822 llvm::MutableArrayRef<uint8_t> buffer) {
2823 if (!m_gdb_comm.GetMultiMemReadSupported())
2824 return Process::ReadMemoryRanges(ranges, buffer);
2825
2826 const llvm::ArrayRef<Range<lldb::addr_t, size_t>> original_ranges = ranges;
2827 llvm::SmallVector<llvm::MutableArrayRef<uint8_t>> memory_regions;
2828
2829 while (!ranges.empty()) {
2830 uint64_t num_ranges =
2832 if (num_ranges == 0)
2833 return Process::ReadMemoryRanges(original_ranges, buffer);
2834
2835 auto ranges_for_request = ranges.take_front(num_ranges);
2836 ranges = ranges.drop_front(num_ranges);
2837
2838 llvm::Expected<StringExtractorGDBRemote> response =
2839 SendMultiMemReadPacket(ranges_for_request);
2840 if (!response) {
2841 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(),
2842 "MultiMemRead error response: {0}");
2843 return Process::ReadMemoryRanges(original_ranges, buffer);
2844 }
2845
2846 llvm::StringRef response_str = response->GetStringRef();
2847 const unsigned expected_num_ranges = ranges_for_request.size();
2848 if (llvm::Error error = ParseMultiMemReadPacket(
2849 response_str, buffer, expected_num_ranges, memory_regions)) {
2851 "MultiMemRead error parsing response: {0}");
2852 return Process::ReadMemoryRanges(original_ranges, buffer);
2853 }
2854 }
2855 return memory_regions;
2856}
2857
2858llvm::Expected<StringExtractorGDBRemote>
2860 llvm::ArrayRef<Range<lldb::addr_t, size_t>> ranges) {
2861 std::string packet_str;
2862 llvm::raw_string_ostream stream(packet_str);
2863 stream << "MultiMemRead:ranges:";
2864
2865 auto range_to_stream = [&](auto range) {
2866 // the "-" marker omits the '0x' prefix.
2867 stream << llvm::formatv("{0:x-},{1:x-}", range.base, range.size);
2868 };
2869 llvm::interleave(ranges, stream, range_to_stream, ",");
2870 stream << ";";
2871
2872 StringExtractorGDBRemote response;
2874 m_gdb_comm.SendPacketAndWaitForResponse(packet_str.data(), response,
2877 return llvm::createStringErrorV("MultiMemRead failed to send packet: '{0}'",
2878 packet_str);
2879
2880 if (response.IsErrorResponse())
2881 return llvm::createStringErrorV("MultiMemRead failed: '{0}'",
2882 response.GetStringRef());
2883
2884 if (!response.IsNormalResponse())
2885 return llvm::createStringErrorV("MultiMemRead unexpected response: '{0}'",
2886 response.GetStringRef());
2887
2888 return response;
2889}
2890
2892 llvm::StringRef response_str, llvm::MutableArrayRef<uint8_t> buffer,
2893 unsigned expected_num_ranges,
2894 llvm::SmallVectorImpl<llvm::MutableArrayRef<uint8_t>> &memory_regions) {
2895 // The sizes and the data are separated by a `;`.
2896 auto [sizes_str, memory_data] = response_str.split(';');
2897 if (sizes_str.size() == response_str.size())
2898 return llvm::createStringErrorV(
2899 "MultiMemRead response missing field separator ';' in: '{0}'",
2900 response_str);
2901
2902 // Sizes are separated by a `,`.
2903 for (llvm::StringRef size_str : llvm::split(sizes_str, ',')) {
2904 uint64_t read_size;
2905 if (size_str.getAsInteger(16, read_size))
2906 return llvm::createStringErrorV(
2907 "MultiMemRead response has invalid size string: {0}", size_str);
2908
2909 if (memory_data.size() < read_size)
2910 return llvm::createStringErrorV("MultiMemRead response did not have "
2911 "enough data, requested sizes: {0}",
2912 sizes_str);
2913
2914 llvm::StringRef region_to_read = memory_data.take_front(read_size);
2915 memory_data = memory_data.drop_front(read_size);
2916
2917 assert(buffer.size() >= read_size);
2918 llvm::MutableArrayRef<uint8_t> region_to_write =
2919 buffer.take_front(read_size);
2920 buffer = buffer.drop_front(read_size);
2921
2922 memcpy(region_to_write.data(), region_to_read.data(), read_size);
2923 memory_regions.push_back(region_to_write);
2924 }
2925
2926 return llvm::Error::success();
2927}
2928
2930 return m_gdb_comm.GetMemoryTaggingSupported();
2931}
2932
2933llvm::Expected<std::vector<uint8_t>>
2935 int32_t type) {
2936 // By this point ReadMemoryTags has validated that tagging is enabled
2937 // for this target/process/address.
2938 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2939 if (!buffer_sp) {
2940 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2941 "Error reading memory tags from remote");
2942 }
2943
2944 // Return the raw tag data
2945 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2946 std::vector<uint8_t> got;
2947 got.reserve(tag_data.size());
2948 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2949 return got;
2950}
2951
2953 int32_t type,
2954 const std::vector<uint8_t> &tags) {
2955 // By now WriteMemoryTags should have validated that tagging is enabled
2956 // for this target/process.
2957 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2958}
2959
2961 std::vector<ObjectFile::LoadableData> entries) {
2962 Status error;
2963 // Sort the entries by address because some writes, like those to flash
2964 // memory, must happen in order of increasing address.
2965 llvm::stable_sort(entries, [](const ObjectFile::LoadableData a,
2966 const ObjectFile::LoadableData b) {
2967 return a.Dest < b.Dest;
2968 });
2969 m_allow_flash_writes = true;
2971 if (error.Success())
2972 error = FlashDone();
2973 else
2974 // Even though some of the writing failed, try to send a flash done if some
2975 // of the writing succeeded so the flash state is reset to normal, but
2976 // don't stomp on the error status that was set in the write failure since
2977 // that's the one we want to report back.
2978 FlashDone();
2979 m_allow_flash_writes = false;
2980 return error;
2981}
2982
2984 auto size = m_erased_flash_ranges.GetSize();
2985 for (size_t i = 0; i < size; ++i)
2986 if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range))
2987 return true;
2988 return false;
2989}
2990
2992 Status status;
2993
2994 MemoryRegionInfo region;
2995 status = GetMemoryRegionInfo(addr, region);
2996 if (!status.Success())
2997 return status;
2998
2999 // The gdb spec doesn't say if erasures are allowed across multiple regions,
3000 // but we'll disallow it to be safe and to keep the logic simple by worring
3001 // about only one region's block size. DoMemoryWrite is this function's
3002 // primary user, and it can easily keep writes within a single memory region
3003 if (addr + size > region.GetRange().GetRangeEnd()) {
3004 status =
3005 Status::FromErrorString("Unable to erase flash in multiple regions");
3006 return status;
3007 }
3008
3009 uint64_t blocksize = region.GetBlocksize();
3010 if (blocksize == 0) {
3011 status =
3012 Status::FromErrorString("Unable to erase flash because blocksize is 0");
3013 return status;
3014 }
3015
3016 // Erasures can only be done on block boundary adresses, so round down addr
3017 // and round up size
3018 lldb::addr_t block_start_addr = addr - (addr % blocksize);
3019 size += (addr - block_start_addr);
3020 if ((size % blocksize) != 0)
3021 size += (blocksize - size % blocksize);
3022
3023 FlashRange range(block_start_addr, size);
3024
3025 if (HasErased(range))
3026 return status;
3027
3028 // We haven't erased the entire range, but we may have erased part of it.
3029 // (e.g., block A is already erased and range starts in A and ends in B). So,
3030 // adjust range if necessary to exclude already erased blocks.
3031 if (!m_erased_flash_ranges.IsEmpty()) {
3032 // Assuming that writes and erasures are done in increasing addr order,
3033 // because that is a requirement of the vFlashWrite command. Therefore, we
3034 // only need to look at the last range in the list for overlap.
3035 const auto &last_range = *m_erased_flash_ranges.Back();
3036 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
3037 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
3038 // overlap will be less than range.GetByteSize() or else HasErased()
3039 // would have been true
3040 range.SetByteSize(range.GetByteSize() - overlap);
3041 range.SetRangeBase(range.GetRangeBase() + overlap);
3042 }
3043 }
3044
3045 StreamString packet;
3046 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
3047 (uint64_t)range.GetByteSize());
3048
3049 StringExtractorGDBRemote response;
3050 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3053 if (response.IsOKResponse()) {
3054 m_erased_flash_ranges.Insert(range, true);
3055 } else {
3056 if (response.IsErrorResponse())
3058 "flash erase failed for 0x%" PRIx64, addr);
3059 else if (response.IsUnsupportedResponse())
3061 "GDB server does not support flashing");
3062 else
3064 "unexpected response to GDB server flash erase packet '%s': '%s'",
3065 packet.GetData(), response.GetStringRef().data());
3066 }
3067 } else {
3068 status = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3069 packet.GetData());
3070 }
3071 return status;
3072}
3073
3075 Status status;
3076 // If we haven't erased any blocks, then we must not have written anything
3077 // either, so there is no need to actually send a vFlashDone command
3078 if (m_erased_flash_ranges.IsEmpty())
3079 return status;
3080 StringExtractorGDBRemote response;
3081 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
3084 if (response.IsOKResponse()) {
3085 m_erased_flash_ranges.Clear();
3086 } else {
3087 if (response.IsErrorResponse())
3088 status = Status::FromErrorStringWithFormat("flash done failed");
3089 else if (response.IsUnsupportedResponse())
3091 "GDB server does not support flashing");
3092 else
3094 "unexpected response to GDB server flash done packet: '%s'",
3095 response.GetStringRef().data());
3096 }
3097 } else {
3098 status =
3099 Status::FromErrorStringWithFormat("failed to send flash done packet");
3100 }
3101 return status;
3102}
3103
3104size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
3105 size_t size, Status &error) {
3107 // M and m packets take 2 bytes for 1 byte of memory
3108 size_t max_memory_size = m_max_memory_size / 2;
3109 if (size > max_memory_size) {
3110 // Keep memory read sizes down to a sane limit. This function will be
3111 // called multiple times in order to complete the task by
3112 // lldb_private::Process so it is ok to do this.
3113 size = max_memory_size;
3114 }
3115
3116 StreamGDBRemote packet;
3117
3118 MemoryRegionInfo region;
3119 Status region_status = GetMemoryRegionInfo(addr, region);
3120
3121 bool is_flash =
3122 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
3123
3124 if (is_flash) {
3125 if (!m_allow_flash_writes) {
3126 error = Status::FromErrorString("Writing to flash memory is not allowed");
3127 return 0;
3128 }
3129 // Keep the write within a flash memory region
3130 if (addr + size > region.GetRange().GetRangeEnd())
3131 size = region.GetRange().GetRangeEnd() - addr;
3132 // Flash memory must be erased before it can be written
3133 error = FlashErase(addr, size);
3134 if (!error.Success())
3135 return 0;
3136 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
3137 packet.PutEscapedBytes(buf, size);
3138 } else {
3139 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
3140 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
3142 }
3143 StringExtractorGDBRemote response;
3144 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
3147 if (response.IsOKResponse()) {
3148 error.Clear();
3149 return size;
3150 } else if (response.IsErrorResponse())
3152 "memory write failed for 0x%" PRIx64, addr);
3153 else if (response.IsUnsupportedResponse())
3155 "GDB server does not support writing memory");
3156 else
3158 "unexpected response to GDB server memory write packet '%s': '%s'",
3159 packet.GetData(), response.GetStringRef().data());
3160 } else {
3161 error = Status::FromErrorStringWithFormat("failed to send packet: '%s'",
3162 packet.GetData());
3163 }
3164 return 0;
3165}
3166
3168 uint32_t permissions,
3169 Status &error) {
3171 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
3172
3173 if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) {
3174 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
3175 if (allocated_addr != LLDB_INVALID_ADDRESS ||
3176 m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes)
3177 return allocated_addr;
3178 }
3179
3180 if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) {
3181 // Call mmap() to create memory in the inferior..
3182 unsigned prot = 0;
3183 if (permissions & lldb::ePermissionsReadable)
3184 prot |= eMmapProtRead;
3185 if (permissions & lldb::ePermissionsWritable)
3186 prot |= eMmapProtWrite;
3187 if (permissions & lldb::ePermissionsExecutable)
3188 prot |= eMmapProtExec;
3189
3190 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
3192 m_addr_to_mmap_size[allocated_addr] = size;
3193 else {
3194 allocated_addr = LLDB_INVALID_ADDRESS;
3195 LLDB_LOGF(log,
3196 "ProcessGDBRemote::%s no direct stub support for memory "
3197 "allocation, and InferiorCallMmap also failed - is stub "
3198 "missing register context save/restore capability?",
3199 __FUNCTION__);
3200 }
3201 }
3202
3203 if (allocated_addr == LLDB_INVALID_ADDRESS)
3205 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
3206 (uint64_t)size, GetPermissionsAsCString(permissions));
3207 else
3208 error.Clear();
3209 return allocated_addr;
3210}
3211
3213 MemoryRegionInfo &region_info) {
3214
3215 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
3216 return error;
3217}
3218
3220 return m_gdb_comm.GetWatchpointSlotCount();
3221}
3222
3224 return m_gdb_comm.GetWatchpointReportedAfter();
3225}
3226
3228 Status error;
3229 LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory();
3230
3231 switch (supported) {
3232 case eLazyBoolCalculate:
3233 // We should never be deallocating memory without allocating memory first
3234 // so we should never get eLazyBoolCalculate
3236 "tried to deallocate memory without ever allocating memory");
3237 break;
3238
3239 case eLazyBoolYes:
3240 if (!m_gdb_comm.DeallocateMemory(addr))
3242 "unable to deallocate memory at 0x%" PRIx64, addr);
3243 break;
3244
3245 case eLazyBoolNo:
3246 // Call munmap() to deallocate memory in the inferior..
3247 {
3248 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
3249 if (pos != m_addr_to_mmap_size.end() &&
3250 InferiorCallMunmap(this, addr, pos->second))
3251 m_addr_to_mmap_size.erase(pos);
3252 else
3254 "unable to deallocate memory at 0x%" PRIx64, addr);
3255 }
3256 break;
3257 }
3258
3259 return error;
3260}
3261
3262// Process STDIO
3263size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
3264 Status &error) {
3265 if (m_stdio_communication.IsConnected()) {
3266 ConnectionStatus status;
3267 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
3268 } else if (m_stdin_forward) {
3269 m_gdb_comm.SendStdinNotification(src, src_len);
3270 }
3271 return 0;
3272}
3273
3275 Status error;
3276 assert(bp_site != nullptr);
3277
3278 // Get logging info
3280 user_id_t site_id = bp_site->GetID();
3281
3282 // Get the breakpoint address
3283 const addr_t addr = bp_site->GetLoadAddress();
3284
3285 // Log that a breakpoint was requested
3286 LLDB_LOGF(log,
3287 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3288 ") address = 0x%" PRIx64,
3289 site_id, (uint64_t)addr);
3290
3291 // Breakpoint already exists and is enabled
3292 if (bp_site->IsEnabled()) {
3293 LLDB_LOGF(log,
3294 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3295 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3296 site_id, (uint64_t)addr);
3297 return error;
3298 }
3299
3300 // Get the software breakpoint trap opcode size
3301 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3302
3303 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3304 // breakpoint type is supported by the remote stub. These are set to true by
3305 // default, and later set to false only after we receive an unimplemented
3306 // response when sending a breakpoint packet. This means initially that
3307 // unless we were specifically instructed to use a hardware breakpoint, LLDB
3308 // will attempt to set a software breakpoint. HardwareRequired() also queries
3309 // a boolean variable which indicates if the user specifically asked for
3310 // hardware breakpoints. If true then we will skip over software
3311 // breakpoints.
3312 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) &&
3313 (!bp_site->HardwareRequired())) {
3314 // Try to send off a software breakpoint packet ($Z0)
3315 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3316 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
3317 if (error_no == 0) {
3318 // The breakpoint was placed successfully
3319 bp_site->SetEnabled(true);
3321 return error;
3322 }
3323
3324 // SendGDBStoppointTypePacket() will return an error if it was unable to
3325 // set this breakpoint. We need to differentiate between a error specific
3326 // to placing this breakpoint or if we have learned that this breakpoint
3327 // type is unsupported. To do this, we must test the support boolean for
3328 // this breakpoint type to see if it now indicates that this breakpoint
3329 // type is unsupported. If they are still supported then we should return
3330 // with the error code. If they are now unsupported, then we would like to
3331 // fall through and try another form of breakpoint.
3332 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) {
3333 if (error_no != UINT8_MAX)
3335 "error: %d sending the breakpoint request", error_no);
3336 else
3337 error = Status::FromErrorString("error sending the breakpoint request");
3338 return error;
3339 }
3340
3341 // We reach here when software breakpoints have been found to be
3342 // unsupported. For future calls to set a breakpoint, we will not attempt
3343 // to set a breakpoint with a type that is known not to be supported.
3344 LLDB_LOGF(log, "Software breakpoints are unsupported");
3345
3346 // So we will fall through and try a hardware breakpoint
3347 }
3348
3349 // The process of setting a hardware breakpoint is much the same as above.
3350 // We check the supported boolean for this breakpoint type, and if it is
3351 // thought to be supported then we will try to set this breakpoint with a
3352 // hardware breakpoint.
3353 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3354 // Try to send off a hardware breakpoint packet ($Z1)
3355 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3356 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3357 if (error_no == 0) {
3358 // The breakpoint was placed successfully
3359 bp_site->SetEnabled(true);
3361 return error;
3362 }
3363
3364 // Check if the error was something other then an unsupported breakpoint
3365 // type
3366 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
3367 // Unable to set this hardware breakpoint
3368 if (error_no != UINT8_MAX)
3370 "error: %d sending the hardware breakpoint request "
3371 "(hardware breakpoint resources might be exhausted or unavailable)",
3372 error_no);
3373 else
3375 "error sending the hardware breakpoint request "
3376 "(hardware breakpoint resources "
3377 "might be exhausted or unavailable)");
3378 return error;
3379 }
3380
3381 // We will reach here when the stub gives an unsupported response to a
3382 // hardware breakpoint
3383 LLDB_LOGF(log, "Hardware breakpoints are unsupported");
3384
3385 // Finally we will falling through to a #trap style breakpoint
3386 }
3387
3388 // Don't fall through when hardware breakpoints were specifically requested
3389 if (bp_site->HardwareRequired()) {
3390 error = Status::FromErrorString("hardware breakpoints are not supported");
3391 return error;
3392 }
3393
3394 // As a last resort we want to place a manual breakpoint. An instruction is
3395 // placed into the process memory using memory write packets.
3396 return EnableSoftwareBreakpoint(bp_site);
3397}
3398
3400 Status error;
3401 assert(bp_site != nullptr);
3402 addr_t addr = bp_site->GetLoadAddress();
3403 user_id_t site_id = bp_site->GetID();
3405 LLDB_LOGF(log,
3406 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3407 ") addr = 0x%8.8" PRIx64,
3408 site_id, (uint64_t)addr);
3409
3410 if (bp_site->IsEnabled()) {
3411 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3412
3413 BreakpointSite::Type bp_type = bp_site->GetType();
3414 switch (bp_type) {
3417 break;
3418
3420 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false,
3421 addr, bp_op_size,
3423 error = Status::FromErrorString("unknown error");
3424 break;
3425
3427 if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointSoftware, false,
3428 addr, bp_op_size,
3430 error = Status::FromErrorString("unknown error");
3431 } break;
3432 }
3433 if (error.Success())
3434 bp_site->SetEnabled(false);
3435 } else {
3436 LLDB_LOGF(log,
3437 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3438 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3439 site_id, (uint64_t)addr);
3440 return error;
3441 }
3442
3443 if (error.Success())
3444 error = Status::FromErrorString("unknown error");
3445 return error;
3446}
3447
3448// Pre-requisite: wp != NULL.
3449static GDBStoppointType
3451 assert(wp_res_sp);
3452 bool read = wp_res_sp->WatchpointResourceRead();
3453 bool write = wp_res_sp->WatchpointResourceWrite();
3454
3455 assert((read || write) &&
3456 "WatchpointResource type is neither read nor write");
3457 if (read && write)
3458 return eWatchpointReadWrite;
3459 else if (read)
3460 return eWatchpointRead;
3461 else
3462 return eWatchpointWrite;
3463}
3464
3466 Status error;
3467 if (!wp_sp) {
3468 error = Status::FromErrorString("No watchpoint specified");
3469 return error;
3470 }
3471 user_id_t watchID = wp_sp->GetID();
3472 addr_t addr = wp_sp->GetLoadAddress();
3474 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3475 watchID);
3476 if (wp_sp->IsEnabled()) {
3477 LLDB_LOGF(log,
3478 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3479 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3480 watchID, (uint64_t)addr);
3481 return error;
3482 }
3483
3484 bool read = wp_sp->WatchpointRead();
3485 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3486 size_t size = wp_sp->GetByteSize();
3487
3488 ArchSpec target_arch = GetTarget().GetArchitecture();
3489 WatchpointHardwareFeature supported_features =
3490 m_gdb_comm.GetSupportedWatchpointTypes();
3491
3492 std::vector<WatchpointResourceSP> resources =
3494 addr, size, read, write, supported_features, target_arch);
3495
3496 // LWP_TODO: Now that we know the WP Resources needed to implement this
3497 // Watchpoint, we need to look at currently allocated Resources in the
3498 // Process and if they match, or are within the same memory granule, or
3499 // overlapping memory ranges, then we need to combine them. e.g. one
3500 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1
3501 // byte at 0x1003, they must use the same hardware watchpoint register
3502 // (Resource) to watch them.
3503
3504 // This may mean that an existing resource changes its type (read to
3505 // read+write) or address range it is watching, in which case the old
3506 // watchpoint needs to be disabled and the new Resource addr/size/type
3507 // watchpoint enabled.
3508
3509 // If we modify a shared Resource to accomodate this newly added Watchpoint,
3510 // and we are unable to set all of the Resources for it in the inferior, we
3511 // will return an error for this Watchpoint and the shared Resource should
3512 // be restored. e.g. this Watchpoint requires three Resources, one which
3513 // is shared with another Watchpoint. We extend the shared Resouce to
3514 // handle both Watchpoints and we try to set two new ones. But if we don't
3515 // have sufficient watchpoint register for all 3, we need to show an error
3516 // for creating this Watchpoint and we should reset the shared Resource to
3517 // its original configuration because it is no longer shared.
3518
3519 bool set_all_resources = true;
3520 std::vector<WatchpointResourceSP> succesfully_set_resources;
3521 for (const auto &wp_res_sp : resources) {
3522 addr_t addr = wp_res_sp->GetLoadAddress();
3523 size_t size = wp_res_sp->GetByteSize();
3524 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3525 if (!m_gdb_comm.SupportsGDBStoppointPacket(type) ||
3526 m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size,
3528 set_all_resources = false;
3529 break;
3530 } else {
3531 succesfully_set_resources.push_back(wp_res_sp);
3532 }
3533 }
3534 if (set_all_resources) {
3535 wp_sp->SetEnabled(true, notify);
3536 for (const auto &wp_res_sp : resources) {
3537 // LWP_TODO: If we expanded/reused an existing Resource,
3538 // it's already in the WatchpointResourceList.
3539 wp_res_sp->AddConstituent(wp_sp);
3540 m_watchpoint_resource_list.Add(wp_res_sp);
3541 }
3542 return error;
3543 } else {
3544 // We failed to allocate one of the resources. Unset all
3545 // of the new resources we did successfully set in the
3546 // process.
3547 for (const auto &wp_res_sp : succesfully_set_resources) {
3548 addr_t addr = wp_res_sp->GetLoadAddress();
3549 size_t size = wp_res_sp->GetByteSize();
3550 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3551 m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3553 }
3555 "Setting one of the watchpoint resources failed");
3556 }
3557 return error;
3558}
3559
3561 Status error;
3562 if (!wp_sp) {
3563 error = Status::FromErrorString("Watchpoint argument was NULL.");
3564 return error;
3565 }
3566
3567 user_id_t watchID = wp_sp->GetID();
3568
3570
3571 addr_t addr = wp_sp->GetLoadAddress();
3572
3573 LLDB_LOGF(log,
3574 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3575 ") addr = 0x%8.8" PRIx64,
3576 watchID, (uint64_t)addr);
3577
3578 if (!wp_sp->IsEnabled()) {
3579 LLDB_LOGF(log,
3580 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3581 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3582 watchID, (uint64_t)addr);
3583 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3584 // attempt might come from the user-supplied actions, we'll route it in
3585 // order for the watchpoint object to intelligently process this action.
3586 wp_sp->SetEnabled(false, notify);
3587 return error;
3588 }
3589
3590 if (wp_sp->IsHardware()) {
3591 bool disabled_all = true;
3592
3593 std::vector<WatchpointResourceSP> unused_resources;
3594 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
3595 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3596 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3597 addr_t addr = wp_res_sp->GetLoadAddress();
3598 size_t size = wp_res_sp->GetByteSize();
3599 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3601 disabled_all = false;
3602 } else {
3603 wp_res_sp->RemoveConstituent(wp_sp);
3604 if (wp_res_sp->GetNumberOfConstituents() == 0)
3605 unused_resources.push_back(wp_res_sp);
3606 }
3607 }
3608 }
3609 for (auto &wp_res_sp : unused_resources)
3610 m_watchpoint_resource_list.Remove(wp_res_sp->GetID());
3611
3612 wp_sp->SetEnabled(false, notify);
3613 if (!disabled_all)
3615 "Failure disabling one of the watchpoint locations");
3616 }
3617 return error;
3618}
3619
3621 m_thread_list_real.Clear();
3622 m_thread_list.Clear();
3623}
3624
3626 Status error;
3627 Log *log = GetLog(GDBRLog::Process);
3628 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3629
3630 if (!m_gdb_comm.SendAsyncSignal(signo, GetInterruptTimeout()))
3631 error =
3632 Status::FromErrorStringWithFormat("failed to send signal %i", signo);
3633 return error;
3634}
3635
3636Status
3638 // Make sure we aren't already connected?
3639 if (m_gdb_comm.IsConnected())
3640 return Status();
3641
3642 PlatformSP platform_sp(GetTarget().GetPlatform());
3643 if (platform_sp && !platform_sp->IsHost())
3644 return Status::FromErrorString("Lost debug server connection");
3645
3646 auto error = LaunchAndConnectToDebugserver(process_info);
3647 if (error.Fail()) {
3648 const char *error_string = error.AsCString();
3649 if (error_string == nullptr)
3650 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3651 }
3652 return error;
3653}
3654
3656 Log *log = GetLog(GDBRLog::Process);
3657 // If we locate debugserver, keep that located version around
3658 static FileSpec g_debugserver_file_spec;
3659 FileSpec debugserver_file_spec;
3660
3661 Environment host_env = Host::GetEnvironment();
3662
3663 // Always check to see if we have an environment override for the path to the
3664 // debugserver to use and use it if we do.
3665 std::string env_debugserver_path = host_env.lookup("LLDB_DEBUGSERVER_PATH");
3666 if (!env_debugserver_path.empty()) {
3667 debugserver_file_spec.SetFile(env_debugserver_path,
3668 FileSpec::Style::native);
3669 LLDB_LOG(log, "gdb-remote stub exe path set from environment variable: {0}",
3670 env_debugserver_path);
3671 } else
3672 debugserver_file_spec = g_debugserver_file_spec;
3673 if (FileSystem::Instance().Exists(debugserver_file_spec))
3674 return debugserver_file_spec;
3675
3676 // The debugserver binary is in the LLDB.framework/Resources directory.
3677 debugserver_file_spec = HostInfo::GetSupportExeDir();
3678 if (debugserver_file_spec) {
3679 debugserver_file_spec.AppendPathComponent(DEBUGSERVER_BASENAME);
3680 if (FileSystem::Instance().Exists(debugserver_file_spec)) {
3681 LLDB_LOG(log, "found gdb-remote stub exe '{0}'", debugserver_file_spec);
3682
3683 g_debugserver_file_spec = debugserver_file_spec;
3684 } else {
3685 debugserver_file_spec = platform.LocateExecutable(DEBUGSERVER_BASENAME);
3686 if (!debugserver_file_spec) {
3687 // Platform::LocateExecutable() wouldn't return a path if it doesn't
3688 // exist
3689 LLDB_LOG(log, "could not find gdb-remote stub exe '{0}'",
3690 debugserver_file_spec);
3691 }
3692 // Don't cache the platform specific GDB server binary as it could
3693 // change from platform to platform
3694 g_debugserver_file_spec.Clear();
3695 }
3696 }
3697 return debugserver_file_spec;
3698}
3699
3701 const ProcessInfo &process_info) {
3702 using namespace std::placeholders; // For _1, _2, etc.
3703
3705 return Status();
3706
3707 ProcessLaunchInfo debugserver_launch_info;
3708 // Make debugserver run in its own session so signals generated by special
3709 // terminal key sequences (^C) don't affect debugserver.
3710 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3711
3712 const std::weak_ptr<ProcessGDBRemote> this_wp =
3713 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3714 debugserver_launch_info.SetMonitorProcessCallback(
3715 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3716 debugserver_launch_info.SetUserID(process_info.GetUserID());
3717
3718 FileSpec debugserver_path = GetDebugserverPath(*GetTarget().GetPlatform());
3719
3720#if defined(__APPLE__)
3721 // On macOS 11, we need to support x86_64 applications translated to
3722 // arm64. We check whether a binary is translated and spawn the correct
3723 // debugserver accordingly.
3724 int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID,
3725 static_cast<int>(process_info.GetProcessID())};
3726 struct kinfo_proc processInfo;
3727 size_t bufsize = sizeof(processInfo);
3728 if (sysctl(mib, (unsigned)(sizeof(mib) / sizeof(int)), &processInfo, &bufsize,
3729 NULL, 0) == 0 &&
3730 bufsize > 0) {
3731 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3732 debugserver_path = FileSpec("/Library/Apple/usr/libexec/oah/debugserver");
3733 }
3734 }
3735#endif
3736
3737 if (!FileSystem::Instance().Exists(debugserver_path))
3738 return Status::FromErrorString("could not find '" DEBUGSERVER_BASENAME
3739 "'. Please ensure it is properly installed "
3740 "and available in your PATH");
3741
3742 debugserver_launch_info.SetExecutableFile(debugserver_path,
3743 /*add_exe_file_as_first_arg=*/true);
3744
3745 llvm::Expected<Socket::Pair> socket_pair = Socket::CreatePair();
3746 if (!socket_pair)
3747 return Status::FromError(socket_pair.takeError());
3748
3749 Status error;
3750 SharedSocket shared_socket(socket_pair->first.get(), error);
3751 if (error.Fail())
3752 return error;
3753
3754 error = m_gdb_comm.StartDebugserverProcess(shared_socket.GetSendableFD(),
3755 debugserver_launch_info, nullptr);
3756
3757 if (error.Fail()) {
3758 Log *log = GetLog(GDBRLog::Process);
3759
3760 LLDB_LOGF(log, "failed to start debugserver process: %s",
3761 error.AsCString());
3762 return error;
3763 }
3764
3765 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3766 shared_socket.CompleteSending(m_debugserver_pid);
3767
3768 // Our process spawned correctly, we can now set our connection to use
3769 // our end of the socket pair
3770 m_gdb_comm.SetConnection(std::make_unique<ConnectionFileDescriptor>(
3771 std::move(socket_pair->second)));
3773
3774 if (m_gdb_comm.IsConnected()) {
3775 // Finish the connection process by doing the handshake without
3776 // connecting (send NULL URL)
3778 } else {
3779 error = Status::FromErrorString("connection failed");
3780 }
3781 return error;
3782}
3783
3785 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3786 int signo, // Zero for no signal
3787 int exit_status // Exit value of process if signal is zero
3788) {
3789 // "debugserver_pid" argument passed in is the process ID for debugserver
3790 // that we are tracking...
3791 Log *log = GetLog(GDBRLog::Process);
3792
3793 LLDB_LOGF(log,
3794 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3795 ", signo=%i (0x%x), exit_status=%i)",
3796 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3797
3798 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3799 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3800 static_cast<void *>(process_sp.get()));
3801 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3802 return;
3803
3804 // Sleep for a half a second to make sure our inferior process has time to
3805 // set its exit status before we set it incorrectly when both the debugserver
3806 // and the inferior process shut down.
3807 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3808
3809 // If our process hasn't yet exited, debugserver might have died. If the
3810 // process did exit, then we are reaping it.
3811 const StateType state = process_sp->GetState();
3812
3813 if (state != eStateInvalid && state != eStateUnloaded &&
3814 state != eStateExited && state != eStateDetached) {
3815 StreamString stream;
3816 if (signo == 0)
3817 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",
3818 exit_status);
3819 else {
3820 llvm::StringRef signal_name =
3821 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
3822 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";
3823 if (!signal_name.empty())
3824 stream.Format(format_str, signal_name);
3825 else
3826 stream.Format(format_str, signo);
3827 }
3828 process_sp->SetExitStatus(-1, stream.GetString());
3829 }
3830 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3831 // longer has a debugserver instance
3832 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3833}
3834
3842
3848
3851 debugger, PluginProperties::GetSettingName())) {
3852 const bool is_global_setting = true;
3855 "Properties for the gdb-remote process plug-in.", is_global_setting);
3856 }
3857}
3858
3860 Log *log = GetLog(GDBRLog::Process);
3861
3862 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3863
3864 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3865 if (!m_async_thread.IsJoinable()) {
3866 // Create a thread that watches our internal state and controls which
3867 // events make it to clients (into the DCProcess event queue).
3868
3869 llvm::Expected<HostThread> async_thread =
3870 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3872 });
3873 if (!async_thread) {
3874 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3875 "failed to launch host thread: {0}");
3876 return false;
3877 }
3878 m_async_thread = *async_thread;
3879 } else
3880 LLDB_LOGF(log,
3881 "ProcessGDBRemote::%s () - Called when Async thread was "
3882 "already running.",
3883 __FUNCTION__);
3884
3885 return m_async_thread.IsJoinable();
3886}
3887
3889 Log *log = GetLog(GDBRLog::Process);
3890
3891 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3892
3893 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3894 if (m_async_thread.IsJoinable()) {
3896
3897 // This will shut down the async thread.
3898 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3899
3900 // Stop the stdio thread
3901 m_async_thread.Join(nullptr);
3902 m_async_thread.Reset();
3903 } else
3904 LLDB_LOGF(
3905 log,
3906 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3907 __FUNCTION__);
3908}
3909
3911 Log *log = GetLog(GDBRLog::Process);
3912 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3913 __FUNCTION__, GetID());
3914
3915 EventSP event_sp;
3916
3917 // We need to ignore any packets that come in after we have
3918 // have decided the process has exited. There are some
3919 // situations, for instance when we try to interrupt a running
3920 // process and the interrupt fails, where another packet might
3921 // get delivered after we've decided to give up on the process.
3922 // But once we've decided we are done with the process we will
3923 // not be in a state to do anything useful with new packets.
3924 // So it is safer to simply ignore any remaining packets by
3925 // explicitly checking for eStateExited before reentering the
3926 // fetch loop.
3927
3928 bool done = false;
3929 while (!done && GetPrivateState() != eStateExited) {
3930 LLDB_LOGF(log,
3931 "ProcessGDBRemote::%s(pid = %" PRIu64
3932 ") listener.WaitForEvent (NULL, event_sp)...",
3933 __FUNCTION__, GetID());
3934
3935 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
3936 const uint32_t event_type = event_sp->GetType();
3937 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3938 LLDB_LOGF(log,
3939 "ProcessGDBRemote::%s(pid = %" PRIu64
3940 ") Got an event of type: %d...",
3941 __FUNCTION__, GetID(), event_type);
3942
3943 switch (event_type) {
3945 const EventDataBytes *continue_packet =
3947
3948 if (continue_packet) {
3949 const char *continue_cstr =
3950 (const char *)continue_packet->GetBytes();
3951 const size_t continue_cstr_len = continue_packet->GetByteSize();
3952 LLDB_LOGF(log,
3953 "ProcessGDBRemote::%s(pid = %" PRIu64
3954 ") got eBroadcastBitAsyncContinue: %s",
3955 __FUNCTION__, GetID(), continue_cstr);
3956
3957 if (::strstr(continue_cstr, "vAttach") == nullptr)
3959 StringExtractorGDBRemote response;
3960
3961 StateType stop_state =
3963 *this, *GetUnixSignals(),
3964 llvm::StringRef(continue_cstr, continue_cstr_len),
3965 GetInterruptTimeout(), response);
3966
3967 // We need to immediately clear the thread ID list so we are sure
3968 // to get a valid list of threads. The thread ID list might be
3969 // contained within the "response", or the stop reply packet that
3970 // caused the stop. So clear it now before we give the stop reply
3971 // packet to the process using the
3972 // SetLastStopPacket()...
3974
3975 switch (stop_state) {
3976 case eStateStopped:
3977 case eStateCrashed:
3978 case eStateSuspended:
3979 SetLastStopPacket(response);
3980 SetPrivateState(stop_state);
3981 break;
3982
3983 case eStateExited: {
3984 SetLastStopPacket(response);
3986 response.SetFilePos(1);
3987
3988 int exit_status = response.GetHexU8();
3989 std::string desc_string;
3990 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3991 llvm::StringRef desc_str;
3992 llvm::StringRef desc_token;
3993 while (response.GetNameColonValue(desc_token, desc_str)) {
3994 if (desc_token != "description")
3995 continue;
3996 StringExtractor extractor(desc_str);
3997 extractor.GetHexByteString(desc_string);
3998 }
3999 }
4000 SetExitStatus(exit_status, desc_string.c_str());
4001 done = true;
4002 break;
4003 }
4004 case eStateInvalid: {
4005 // Check to see if we were trying to attach and if we got back
4006 // the "E87" error code from debugserver -- this indicates that
4007 // the process is not debuggable. Return a slightly more
4008 // helpful error message about why the attach failed.
4009 if (::strstr(continue_cstr, "vAttach") != nullptr &&
4010 response.GetError() == 0x87) {
4011 SetExitStatus(-1, "cannot attach to process due to "
4012 "System Integrity Protection");
4013 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
4014 response.GetStatus().Fail()) {
4015 SetExitStatus(-1, response.GetStatus().AsCString());
4016 } else {
4017 SetExitStatus(-1, "lost connection");
4018 }
4019 done = true;
4020 break;
4021 }
4022
4023 default:
4024 SetPrivateState(stop_state);
4025 break;
4026 } // switch(stop_state)
4027 } // if (continue_packet)
4028 } // case eBroadcastBitAsyncContinue
4029 break;
4030
4032 LLDB_LOGF(log,
4033 "ProcessGDBRemote::%s(pid = %" PRIu64
4034 ") got eBroadcastBitAsyncThreadShouldExit...",
4035 __FUNCTION__, GetID());
4036 done = true;
4037 break;
4038
4039 default:
4040 LLDB_LOGF(log,
4041 "ProcessGDBRemote::%s(pid = %" PRIu64
4042 ") got unknown event 0x%8.8x",
4043 __FUNCTION__, GetID(), event_type);
4044 done = true;
4045 break;
4046 }
4047 }
4048 } else {
4049 LLDB_LOGF(log,
4050 "ProcessGDBRemote::%s(pid = %" PRIu64
4051 ") listener.WaitForEvent (NULL, event_sp) => false",
4052 __FUNCTION__, GetID());
4053 done = true;
4054 }
4055 }
4056
4057 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
4058 __FUNCTION__, GetID());
4059
4060 return {};
4061}
4062
4063// uint32_t
4064// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
4065// &matches, std::vector<lldb::pid_t> &pids)
4066//{
4067// // If we are planning to launch the debugserver remotely, then we need to
4068// fire up a debugserver
4069// // process and ask it for the list of processes. But if we are local, we
4070// can let the Host do it.
4071// if (m_local_debugserver)
4072// {
4073// return Host::ListProcessesMatchingName (name, matches, pids);
4074// }
4075// else
4076// {
4077// // FIXME: Implement talking to the remote debugserver.
4078// return 0;
4079// }
4080//
4081//}
4082//
4084 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
4085 lldb::user_id_t break_loc_id) {
4086 // I don't think I have to do anything here, just make sure I notice the new
4087 // thread when it starts to
4088 // run so I can stop it if that's what I want to do.
4089 Log *log = GetLog(LLDBLog::Step);
4090 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
4091 return false;
4092}
4093
4095 Log *log = GetLog(GDBRLog::Process);
4096 LLDB_LOG(log, "Check if need to update ignored signals");
4097
4098 // QPassSignals package is not supported by the server, there is no way we
4099 // can ignore any signals on server side.
4100 if (!m_gdb_comm.GetQPassSignalsSupported())
4101 return Status();
4102
4103 // No signals, nothing to send.
4104 if (m_unix_signals_sp == nullptr)
4105 return Status();
4106
4107 // Signals' version hasn't changed, no need to send anything.
4108 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
4109 if (new_signals_version == m_last_signals_version) {
4110 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
4112 return Status();
4113 }
4114
4115 auto signals_to_ignore =
4116 m_unix_signals_sp->GetFilteredSignals(false, false, false);
4117 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
4118
4119 LLDB_LOG(log,
4120 "Signals' version changed. old version={0}, new version={1}, "
4121 "signals ignored={2}, update result={3}",
4122 m_last_signals_version, new_signals_version,
4123 signals_to_ignore.size(), error);
4124
4125 if (error.Success())
4126 m_last_signals_version = new_signals_version;
4127
4128 return error;
4129}
4130
4132 Log *log = GetLog(LLDBLog::Step);
4134 if (log && log->GetVerbose())
4135 LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
4136 m_thread_create_bp_sp->SetEnabled(true);
4137 } else {
4138 PlatformSP platform_sp(GetTarget().GetPlatform());
4139 if (platform_sp) {
4141 platform_sp->SetThreadCreationBreakpoint(GetTarget());
4143 if (log && log->GetVerbose())
4144 LLDB_LOGF(
4145 log, "Successfully created new thread notification breakpoint %i",
4146 m_thread_create_bp_sp->GetID());
4147 m_thread_create_bp_sp->SetCallback(
4149 } else {
4150 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
4151 }
4152 }
4153 }
4154 return m_thread_create_bp_sp.get() != nullptr;
4155}
4156
4158 Log *log = GetLog(LLDBLog::Step);
4159 if (log && log->GetVerbose())
4160 LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
4161
4163 m_thread_create_bp_sp->SetEnabled(false);
4164
4165 return true;
4166}
4167
4169 if (m_dyld_up.get() == nullptr)
4170 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
4171 return m_dyld_up.get();
4172}
4173
4175 int return_value;
4176 bool was_supported;
4177
4178 Status error;
4179
4180 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
4181 if (return_value != 0) {
4182 if (!was_supported)
4184 "Sending events is not supported for this process.");
4185 else
4186 error = Status::FromErrorStringWithFormat("Error sending event data: %d.",
4187 return_value);
4188 }
4189 return error;
4190}
4191
4193 DataBufferSP buf;
4194 if (m_gdb_comm.GetQXferAuxvReadSupported()) {
4195 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
4196 if (response)
4197 buf = std::make_shared<DataBufferHeap>(response->c_str(),
4198 response->length());
4199 else
4200 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
4201 }
4203}
4204
4207 StructuredData::ObjectSP object_sp;
4208
4209 if (m_gdb_comm.GetThreadExtendedInfoSupported()) {
4211 SystemRuntime *runtime = GetSystemRuntime();
4212 if (runtime) {
4213 runtime->AddThreadExtendedInfoPacketHints(args_dict);
4214 }
4215 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
4216
4217 StreamString packet;
4218 packet << "jThreadExtendedInfo:";
4219 args_dict->Dump(packet, false);
4220
4221 // FIXME the final character of a JSON dictionary, '}', is the escape
4222 // character in gdb-remote binary mode. lldb currently doesn't escape
4223 // these characters in its packet output -- so we add the quoted version of
4224 // the } character here manually in case we talk to a debugserver which un-
4225 // escapes the characters at packet read time.
4226 packet << (char)(0x7d ^ 0x20);
4227
4228 StringExtractorGDBRemote response;
4229 response.SetResponseValidatorToJSON();
4230 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4233 response.GetResponseType();
4234 if (response_type == StringExtractorGDBRemote::eResponse) {
4235 if (!response.Empty()) {
4236 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4237 }
4238 }
4239 }
4240 }
4241 return object_sp;
4242}
4243
4245 lldb::addr_t image_list_address, lldb::addr_t image_count) {
4246
4248 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
4249 image_list_address);
4250 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
4251
4252 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4253}
4254
4257
4258 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
4259
4260 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4261}
4262
4264 const std::vector<lldb::addr_t> &load_addresses) {
4267
4268 for (auto addr : load_addresses)
4269 addresses->AddIntegerItem(addr);
4270
4271 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
4272
4273 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
4274}
4275
4278 StructuredData::ObjectSP args_dict) {
4279 StructuredData::ObjectSP object_sp;
4280
4281 if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) {
4282 // Scope for the scoped timeout object
4284 std::chrono::seconds(10));
4285
4286 StreamString packet;
4287 packet << "jGetLoadedDynamicLibrariesInfos:";
4288 args_dict->Dump(packet, false);
4289
4290 // FIXME the final character of a JSON dictionary, '}', is the escape
4291 // character in gdb-remote binary mode. lldb currently doesn't escape
4292 // these characters in its packet output -- so we add the quoted version of
4293 // the } character here manually in case we talk to a debugserver which un-
4294 // escapes the characters at packet read time.
4295 packet << (char)(0x7d ^ 0x20);
4296
4297 StringExtractorGDBRemote response;
4298 response.SetResponseValidatorToJSON();
4299 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4302 response.GetResponseType();
4303 if (response_type == StringExtractorGDBRemote::eResponse) {
4304 if (!response.Empty()) {
4305 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4306 }
4307 }
4308 }
4309 }
4310 return object_sp;
4311}
4312
4314 StructuredData::ObjectSP object_sp;
4316
4317 if (m_gdb_comm.GetDynamicLoaderProcessStateSupported()) {
4318 StringExtractorGDBRemote response;
4319 response.SetResponseValidatorToJSON();
4320 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
4321 response) ==
4324 response.GetResponseType();
4325 if (response_type == StringExtractorGDBRemote::eResponse) {
4326 if (!response.Empty()) {
4327 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4328 }
4329 }
4330 }
4331 }
4332 return object_sp;
4333}
4334
4336 std::lock_guard<std::mutex> guard(m_shared_cache_info_mutex);
4338
4339 if (m_shared_cache_info_sp || !m_gdb_comm.GetSharedCacheInfoSupported())
4341
4342 StreamString packet;
4343 packet << "jGetSharedCacheInfo:";
4344 args_dict->Dump(packet, false);
4345
4346 StringExtractorGDBRemote response;
4347 response.SetResponseValidatorToJSON();
4348 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4351 response.GetResponseType();
4352 if (response_type == StringExtractorGDBRemote::eResponse) {
4353 if (response.Empty())
4354 return {};
4355 StructuredData::ObjectSP response_sp =
4357 if (!response_sp)
4358 return {};
4359 StructuredData::Dictionary *dict = response_sp->GetAsDictionary();
4360 if (!dict)
4361 return {};
4362 if (!dict->HasKey("shared_cache_uuid"))
4363 return {};
4364 llvm::StringRef uuid_str;
4365 if (!dict->GetValueForKeyAsString("shared_cache_uuid", uuid_str, "") ||
4366 uuid_str == "00000000-0000-0000-0000-000000000000")
4367 return {};
4368 if (dict->HasKey("shared_cache_path")) {
4369 UUID uuid;
4370 uuid.SetFromStringRef(uuid_str);
4371 FileSpec sc_path(
4372 dict->GetValueForKey("shared_cache_path")->GetStringValue());
4373
4374 SymbolSharedCacheUse sc_mode =
4377
4380 // Attempt to open the shared cache at sc_path, and
4381 // if the uuid matches, index all the files.
4382 HostInfo::SharedCacheIndexFiles(sc_path, uuid, sc_mode);
4383 }
4384 }
4385 m_shared_cache_info_sp = response_sp;
4386 }
4387 }
4389}
4390
4392 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4393 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4394}
4395
4396// Establish the largest memory read/write payloads we should use. If the
4397// remote stub has a max packet size, stay under that size.
4398//
4399// If the remote stub's max packet size is crazy large, use a reasonable
4400// largeish default.
4401//
4402// If the remote stub doesn't advertise a max packet size, use a conservative
4403// default.
4404
4406 const uint64_t reasonable_largeish_default = 128 * 1024;
4407 const uint64_t conservative_default = 512;
4408
4409 if (m_max_memory_size == 0) {
4410 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4411 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4412 // Save the stub's claimed maximum packet size
4413 m_remote_stub_max_memory_size = stub_max_size;
4414
4415 // Even if the stub says it can support ginormous packets, don't exceed
4416 // our reasonable largeish default packet size.
4417 if (stub_max_size > reasonable_largeish_default) {
4418 stub_max_size = reasonable_largeish_default;
4419 }
4420
4421 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4422 // calculating the bytes taken by size and addr every time, we take a
4423 // maximum guess here.
4424 if (stub_max_size > 70)
4425 stub_max_size -= 32 + 32 + 6;
4426 else {
4427 // In unlikely scenario that max packet size is less then 70, we will
4428 // hope that data being written is small enough to fit.
4430 if (log)
4431 log->Warning("Packet size is too small. "
4432 "LLDB may face problems while writing memory");
4433 }
4434
4435 m_max_memory_size = stub_max_size;
4436 } else {
4437 m_max_memory_size = conservative_default;
4438 }
4439 }
4440}
4441
4443 uint64_t user_specified_max) {
4444 if (user_specified_max != 0) {
4446
4448 if (m_remote_stub_max_memory_size < user_specified_max) {
4450 // packet size too
4451 // big, go as big
4452 // as the remote stub says we can go.
4453 } else {
4454 m_max_memory_size = user_specified_max; // user's packet size is good
4455 }
4456 } else {
4458 user_specified_max; // user's packet size is probably fine
4459 }
4460 }
4461}
4462
4463bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4464 const ArchSpec &arch,
4465 ModuleSpec &module_spec) {
4467
4468 const ModuleCacheKey key(module_file_spec.GetPath(),
4469 arch.GetTriple().getTriple());
4470 auto cached = m_cached_module_specs.find(key);
4471 if (cached != m_cached_module_specs.end()) {
4472 module_spec = cached->second;
4473 return bool(module_spec);
4474 }
4475
4476 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4477 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4478 __FUNCTION__, module_file_spec.GetPath().c_str(),
4479 arch.GetTriple().getTriple().c_str());
4480 return false;
4481 }
4482
4483 if (log) {
4484 StreamString stream;
4485 module_spec.Dump(stream);
4486 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4487 __FUNCTION__, module_file_spec.GetPath().c_str(),
4488 arch.GetTriple().getTriple().c_str(), stream.GetData());
4489 }
4490
4491 m_cached_module_specs[key] = module_spec;
4492 return true;
4493}
4494
4496 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4497 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4498 if (module_specs) {
4499 for (const FileSpec &spec : module_file_specs)
4501 triple.getTriple())] = ModuleSpec();
4502 for (const ModuleSpec &spec : *module_specs)
4503 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4504 triple.getTriple())] = spec;
4505 }
4506}
4507
4509 return m_gdb_comm.GetOSVersion();
4510}
4511
4513 return m_gdb_comm.GetMacCatalystVersion();
4514}
4515
4516namespace {
4517
4518typedef std::vector<std::string> stringVec;
4519
4520typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4521struct RegisterSetInfo {
4522 ConstString name;
4523};
4524
4525typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4526
4527struct GdbServerTargetInfo {
4528 std::string arch;
4529 std::string osabi;
4530 stringVec includes;
4531 RegisterSetMap reg_set_map;
4532};
4533
4534static FieldEnum::Enumerators ParseEnumEvalues(const XMLNode &enum_node) {
4536 // We will use the last instance of each value. Also we preserve the order
4537 // of declaration in the XML, as it may not be numerical.
4538 // For example, hardware may initially release with two states that software
4539 // can read from a register field:
4540 // 0 = startup, 1 = running
4541 // If in a future hardware release, the designers added a pre-startup state:
4542 // 0 = startup, 1 = running, 2 = pre-startup
4543 // Now it makes more sense to list them in this logical order as opposed to
4544 // numerical order:
4545 // 2 = pre-startup, 1 = startup, 0 = startup
4546 // This only matters for "register info" but let's trust what the server
4547 // chose regardless.
4548 std::map<uint64_t, FieldEnum::Enumerator> enumerators;
4549
4551 "evalue", [&enumerators, &log](const XMLNode &enumerator_node) {
4552 std::optional<llvm::StringRef> name;
4553 std::optional<uint64_t> value;
4554
4555 enumerator_node.ForEachAttribute(
4556 [&name, &value, &log](const llvm::StringRef &attr_name,
4557 const llvm::StringRef &attr_value) {
4558 if (attr_name == "name") {
4559 if (attr_value.size())
4560 name = attr_value;
4561 else
4562 LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues "
4563 "Ignoring empty name in evalue");
4564 } else if (attr_name == "value") {
4565 uint64_t parsed_value = 0;
4566 if (llvm::to_integer(attr_value, parsed_value))
4567 value = parsed_value;
4568 else
4569 LLDB_LOG(log,
4570 "ProcessGDBRemote::ParseEnumEvalues "
4571 "Invalid value \"{0}\" in "
4572 "evalue",
4573 attr_value.data());
4574 } else
4575 LLDB_LOG(log,
4576 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
4577 "unknown attribute "
4578 "\"{0}\" in evalue",
4579 attr_name.data());
4580
4581 // Keep walking attributes.
4582 return true;
4583 });
4584
4585 if (value && name)
4586 enumerators.insert_or_assign(
4587 *value, FieldEnum::Enumerator(*value, name->str()));
4588
4589 // Find all evalue elements.
4590 return true;
4591 });
4592
4593 FieldEnum::Enumerators final_enumerators;
4594 for (auto [_, enumerator] : enumerators)
4595 final_enumerators.push_back(enumerator);
4596
4597 return final_enumerators;
4598}
4599
4600static void
4601ParseEnums(XMLNode feature_node,
4602 llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4603 Log *log(GetLog(GDBRLog::Process));
4604
4605 // The top level element is "<enum...".
4606 feature_node.ForEachChildElementWithName(
4607 "enum", [log, &registers_enum_types](const XMLNode &enum_node) {
4608 std::string id;
4609
4610 enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name,
4611 const llvm::StringRef &attr_value) {
4612 if (attr_name == "id")
4613 id = attr_value;
4614
4615 // There is also a "size" attribute that is supposed to be the size in
4616 // bytes of the register this applies to. However:
4617 // * LLDB doesn't need this information.
4618 // * It is difficult to verify because you have to wait until the
4619 // enum is applied to a field.
4620 //
4621 // So we will emit this attribute in XML for GDB's sake, but will not
4622 // bother ingesting it.
4623
4624 // Walk all attributes.
4625 return true;
4626 });
4627
4628 if (!id.empty()) {
4629 FieldEnum::Enumerators enumerators = ParseEnumEvalues(enum_node);
4630 if (!enumerators.empty()) {
4631 LLDB_LOG(log,
4632 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
4633 id);
4634 registers_enum_types.insert_or_assign(
4635 id, std::make_unique<FieldEnum>(id, enumerators));
4636 }
4637 }
4638
4639 // Find all <enum> elements.
4640 return true;
4641 });
4642}
4643
4644static std::vector<RegisterFlags::Field> ParseFlagsFields(
4645 XMLNode flags_node, unsigned size,
4646 const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4647 Log *log(GetLog(GDBRLog::Process));
4648 const unsigned max_start_bit = size * 8 - 1;
4649
4650 // Process the fields of this set of flags.
4651 std::vector<RegisterFlags::Field> fields;
4652 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log,
4653 &registers_enum_types](
4654 const XMLNode
4655 &field_node) {
4656 std::optional<llvm::StringRef> name;
4657 std::optional<unsigned> start;
4658 std::optional<unsigned> end;
4659 std::optional<llvm::StringRef> type;
4660
4661 field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit,
4662 &log](const llvm::StringRef &attr_name,
4663 const llvm::StringRef &attr_value) {
4664 // Note that XML in general requires that each of these attributes only
4665 // appears once, so we don't have to handle that here.
4666 if (attr_name == "name") {
4667 LLDB_LOG(
4668 log,
4669 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
4670 attr_value.data());
4671 name = attr_value;
4672 } else if (attr_name == "start") {
4673 unsigned parsed_start = 0;
4674 if (llvm::to_integer(attr_value, parsed_start)) {
4675 if (parsed_start > max_start_bit) {
4676 LLDB_LOG(log,
4677 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
4678 "field node, "
4679 "cannot be > {1}",
4680 parsed_start, max_start_bit);
4681 } else
4682 start = parsed_start;
4683 } else {
4684 LLDB_LOG(
4685 log,
4686 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
4687 "field node",
4688 attr_value.data());
4689 }
4690 } else if (attr_name == "end") {
4691 unsigned parsed_end = 0;
4692 if (llvm::to_integer(attr_value, parsed_end))
4693 if (parsed_end > max_start_bit) {
4694 LLDB_LOG(log,
4695 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
4696 "field node, "
4697 "cannot be > {1}",
4698 parsed_end, max_start_bit);
4699 } else
4700 end = parsed_end;
4701 else {
4702 LLDB_LOG(log,
4703 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
4704 "field node",
4705 attr_value.data());
4706 }
4707 } else if (attr_name == "type") {
4708 type = attr_value;
4709 } else {
4710 LLDB_LOG(
4711 log,
4712 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
4713 "\"{0}\" in field node",
4714 attr_name.data());
4715 }
4716
4717 return true; // Walk all attributes of the field.
4718 });
4719
4720 if (name && start && end) {
4721 if (*start > *end)
4722 LLDB_LOG(
4723 log,
4724 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
4725 "\"{2}\", ignoring",
4726 *start, *end, name->data());
4727 else {
4728 if (RegisterFlags::Field::GetSizeInBits(*start, *end) > 64)
4729 LLDB_LOG(log,
4730 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" "
4731 "that has "
4732 "size > 64 bits, this is not supported",
4733 name->data());
4734 else {
4735 // A field's type may be set to the name of an enum type.
4736 const FieldEnum *enum_type = nullptr;
4737 if (type && !type->empty()) {
4738 auto found = registers_enum_types.find(*type);
4739 if (found != registers_enum_types.end()) {
4740 enum_type = found->second.get();
4741
4742 // No enumerator can exceed the range of the field itself.
4743 uint64_t max_value =
4745 for (const auto &enumerator : enum_type->GetEnumerators()) {
4746 if (enumerator.m_value > max_value) {
4747 enum_type = nullptr;
4748 LLDB_LOG(
4749 log,
4750 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
4751 "evalue \"{1}\" with value {2} exceeds the maximum value "
4752 "of field \"{3}\" ({4}), ignoring enum",
4753 type->data(), enumerator.m_name, enumerator.m_value,
4754 name->data(), max_value);
4755 break;
4756 }
4757 }
4758 } else {
4759 LLDB_LOG(log,
4760 "ProcessGDBRemote::ParseFlagsFields Could not find type "
4761 "\"{0}\" "
4762 "for field \"{1}\", ignoring",
4763 type->data(), name->data());
4764 }
4765 }
4766
4767 fields.push_back(
4768 RegisterFlags::Field(name->str(), *start, *end, enum_type));
4769 }
4770 }
4771 }
4772
4773 return true; // Iterate all "field" nodes.
4774 });
4775 return fields;
4776}
4777
4778void ParseFlags(
4779 XMLNode feature_node,
4780 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,
4781 const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4782 Log *log(GetLog(GDBRLog::Process));
4783
4784 feature_node.ForEachChildElementWithName(
4785 "flags",
4786 [&log, &registers_flags_types,
4787 &registers_enum_types](const XMLNode &flags_node) -> bool {
4788 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4789 flags_node.GetAttributeValue("id").c_str());
4790
4791 std::optional<llvm::StringRef> id;
4792 std::optional<unsigned> size;
4793 flags_node.ForEachAttribute(
4794 [&id, &size, &log](const llvm::StringRef &name,
4795 const llvm::StringRef &value) {
4796 if (name == "id") {
4797 id = value;
4798 } else if (name == "size") {
4799 unsigned parsed_size = 0;
4800 if (llvm::to_integer(value, parsed_size))
4801 size = parsed_size;
4802 else {
4803 LLDB_LOG(log,
4804 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4805 "in flags node",
4806 value.data());
4807 }
4808 } else {
4809 LLDB_LOG(log,
4810 "ProcessGDBRemote::ParseFlags Ignoring unknown "
4811 "attribute \"{0}\" in flags node",
4812 name.data());
4813 }
4814 return true; // Walk all attributes.
4815 });
4816
4817 if (id && size) {
4818 // Process the fields of this set of flags.
4819 std::vector<RegisterFlags::Field> fields =
4820 ParseFlagsFields(flags_node, *size, registers_enum_types);
4821 if (fields.size()) {
4822 // Sort so that the fields with the MSBs are first.
4823 std::sort(fields.rbegin(), fields.rend());
4824 std::vector<RegisterFlags::Field>::const_iterator overlap =
4825 std::adjacent_find(fields.begin(), fields.end(),
4826 [](const RegisterFlags::Field &lhs,
4827 const RegisterFlags::Field &rhs) {
4828 return lhs.Overlaps(rhs);
4829 });
4830
4831 // If no fields overlap, use them.
4832 if (overlap == fields.end()) {
4833 if (registers_flags_types.contains(*id)) {
4834 // In theory you could define some flag set, use it with a
4835 // register then redefine it. We do not know if anyone does
4836 // that, or what they would expect to happen in that case.
4837 //
4838 // LLDB chooses to take the first definition and ignore the rest
4839 // as waiting until everything has been processed is more
4840 // expensive and difficult. This means that pointers to flag
4841 // sets in the register info remain valid if later the flag set
4842 // is redefined. If we allowed redefinitions, LLDB would crash
4843 // when you tried to print a register that used the original
4844 // definition.
4845 LLDB_LOG(
4846 log,
4847 "ProcessGDBRemote::ParseFlags Definition of flags "
4848 "\"{0}\" shadows "
4849 "previous definition, using original definition instead.",
4850 id->data());
4851 } else {
4852 registers_flags_types.insert_or_assign(
4853 *id, std::make_unique<RegisterFlags>(id->str(), *size,
4854 std::move(fields)));
4855 }
4856 } else {
4857 // If any fields overlap, ignore the whole set of flags.
4858 std::vector<RegisterFlags::Field>::const_iterator next =
4859 std::next(overlap);
4860 LLDB_LOG(
4861 log,
4862 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4863 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4864 "overlap.",
4865 overlap->GetName().c_str(), overlap->GetStart(),
4866 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4867 next->GetEnd());
4868 }
4869 } else {
4870 LLDB_LOG(
4871 log,
4872 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4873 "\"{0}\" because it contains no fields.",
4874 id->data());
4875 }
4876 }
4877
4878 return true; // Keep iterating through all "flags" elements.
4879 });
4880}
4881
4882bool ParseRegisters(
4883 XMLNode feature_node, GdbServerTargetInfo &target_info,
4884 std::vector<DynamicRegisterInfo::Register> &registers,
4885 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,
4886 llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4887 if (!feature_node)
4888 return false;
4889
4890 Log *log(GetLog(GDBRLog::Process));
4891
4892 // Enums first because they are referenced by fields in the flags.
4893 ParseEnums(feature_node, registers_enum_types);
4894 for (const auto &enum_type : registers_enum_types)
4895 enum_type.second->DumpToLog(log);
4896
4897 ParseFlags(feature_node, registers_flags_types, registers_enum_types);
4898 for (const auto &flags : registers_flags_types)
4899 flags.second->DumpToLog(log);
4900
4901 feature_node.ForEachChildElementWithName(
4902 "reg",
4903 [&target_info, &registers, &registers_flags_types,
4904 log](const XMLNode &reg_node) -> bool {
4905 std::string gdb_group;
4906 std::string gdb_type;
4907 DynamicRegisterInfo::Register reg_info;
4908 bool encoding_set = false;
4909 bool format_set = false;
4910
4911 // FIXME: we're silently ignoring invalid data here
4912 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4913 &encoding_set, &format_set, &reg_info,
4914 log](const llvm::StringRef &name,
4915 const llvm::StringRef &value) -> bool {
4916 if (name == "name") {
4917 reg_info.name.SetString(value);
4918 } else if (name == "bitsize") {
4919 if (llvm::to_integer(value, reg_info.byte_size))
4920 reg_info.byte_size =
4921 llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4922 } else if (name == "type") {
4923 gdb_type = value.str();
4924 } else if (name == "group") {
4925 gdb_group = value.str();
4926 } else if (name == "regnum") {
4927 llvm::to_integer(value, reg_info.regnum_remote);
4928 } else if (name == "offset") {
4929 llvm::to_integer(value, reg_info.byte_offset);
4930 } else if (name == "altname") {
4931 reg_info.alt_name.SetString(value);
4932 } else if (name == "encoding") {
4933 encoding_set = true;
4934 reg_info.encoding = Args::StringToEncoding(value, eEncodingUint);
4935 } else if (name == "format") {
4936 format_set = true;
4937 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4938 nullptr)
4939 .Success())
4940 reg_info.format =
4941 llvm::StringSwitch<lldb::Format>(value)
4942 .Case("vector-sint8", eFormatVectorOfSInt8)
4943 .Case("vector-uint8", eFormatVectorOfUInt8)
4944 .Case("vector-sint16", eFormatVectorOfSInt16)
4945 .Case("vector-uint16", eFormatVectorOfUInt16)
4946 .Case("vector-sint32", eFormatVectorOfSInt32)
4947 .Case("vector-uint32", eFormatVectorOfUInt32)
4948 .Case("vector-float32", eFormatVectorOfFloat32)
4949 .Case("vector-uint64", eFormatVectorOfUInt64)
4950 .Case("vector-uint128", eFormatVectorOfUInt128)
4951 .Default(eFormatInvalid);
4952 } else if (name == "group_id") {
4953 uint32_t set_id = UINT32_MAX;
4954 llvm::to_integer(value, set_id);
4955 RegisterSetMap::const_iterator pos =
4956 target_info.reg_set_map.find(set_id);
4957 if (pos != target_info.reg_set_map.end())
4958 reg_info.set_name = pos->second.name;
4959 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4960 llvm::to_integer(value, reg_info.regnum_ehframe);
4961 } else if (name == "dwarf_regnum") {
4962 llvm::to_integer(value, reg_info.regnum_dwarf);
4963 } else if (name == "generic") {
4964 reg_info.regnum_generic = Args::StringToGenericRegister(value);
4965 } else if (name == "value_regnums") {
4967 0);
4968 } else if (name == "invalidate_regnums") {
4970 value, reg_info.invalidate_regs, 0);
4971 } else {
4972 LLDB_LOGF(log,
4973 "ProcessGDBRemote::ParseRegisters unhandled reg "
4974 "attribute %s = %s",
4975 name.data(), value.data());
4976 }
4977 return true; // Keep iterating through all attributes
4978 });
4979
4980 if (!gdb_type.empty()) {
4981 // gdb_type could reference some flags type defined in XML.
4982 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4983 registers_flags_types.find(gdb_type);
4984 if (it != registers_flags_types.end()) {
4985 auto flags_type = it->second.get();
4986 if (reg_info.byte_size == flags_type->GetSize())
4987 reg_info.flags_type = flags_type;
4988 else
4989 LLDB_LOGF(log,
4990 "ProcessGDBRemote::ParseRegisters Size of register "
4991 "flags %s (%d bytes) for "
4992 "register %s does not match the register size (%d "
4993 "bytes). Ignoring this set of flags.",
4994 flags_type->GetID().c_str(), flags_type->GetSize(),
4995 reg_info.name.AsCString(), reg_info.byte_size);
4996 }
4997
4998 // There's a slim chance that the gdb_type name is both a flags type
4999 // and a simple type. Just in case, look for that too (setting both
5000 // does no harm).
5001 if (!gdb_type.empty() && !(encoding_set || format_set)) {
5002 if (llvm::StringRef(gdb_type).starts_with("int")) {
5003 reg_info.format = eFormatHex;
5004 reg_info.encoding = eEncodingUint;
5005 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
5006 reg_info.format = eFormatAddressInfo;
5007 reg_info.encoding = eEncodingUint;
5008 } else if (gdb_type == "float" || gdb_type == "ieee_single" ||
5009 gdb_type == "ieee_double") {
5010 reg_info.format = eFormatFloat;
5011 reg_info.encoding = eEncodingIEEE754;
5012 } else if (gdb_type == "aarch64v" ||
5013 llvm::StringRef(gdb_type).starts_with("vec") ||
5014 gdb_type == "i387_ext" || gdb_type == "uint128" ||
5015 reg_info.byte_size > 16) {
5016 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
5017 // treat them as vector (similarly to xmm/ymm).
5018 // We can fall back to handling anything else <= 128 bit as an
5019 // unsigned integer, more than that, call it a vector of bytes.
5020 // This can happen if we don't recognise the type for AArc64 SVE
5021 // registers.
5022 reg_info.format = eFormatVectorOfUInt8;
5023 reg_info.encoding = eEncodingVector;
5024 } else {
5025 LLDB_LOGF(
5026 log,
5027 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
5028 "format and encoding for gdb type %s",
5029 gdb_type.c_str());
5030 }
5031 }
5032 }
5033
5034 // Only update the register set name if we didn't get a "reg_set"
5035 // attribute. "set_name" will be empty if we didn't have a "reg_set"
5036 // attribute.
5037 if (!reg_info.set_name) {
5038 if (!gdb_group.empty()) {
5039 reg_info.set_name.SetCString(gdb_group.c_str());
5040 } else {
5041 // If no register group name provided anywhere,
5042 // we'll create a 'general' register set
5043 reg_info.set_name.SetCString("general");
5044 }
5045 }
5046
5047 if (reg_info.byte_size == 0) {
5048 LLDB_LOGF(log,
5049 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
5050 __FUNCTION__, reg_info.name.AsCString());
5051 } else
5052 registers.push_back(reg_info);
5053
5054 return true; // Keep iterating through all "reg" elements
5055 });
5056 return true;
5057}
5058
5059} // namespace
5060
5061// This method fetches a register description feature xml file from
5062// the remote stub and adds registers/register groupsets/architecture
5063// information to the current process. It will call itself recursively
5064// for nested register definition files. It returns true if it was able
5065// to fetch and parse an xml file.
5067 ArchSpec &arch_to_use, std::string xml_filename,
5068 std::vector<DynamicRegisterInfo::Register> &registers) {
5069 // request the target xml file
5070 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
5071 if (errorToBool(raw.takeError()))
5072 return false;
5073
5074 XMLDocument xml_document;
5075
5076 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
5077 xml_filename.c_str())) {
5078 GdbServerTargetInfo target_info;
5079 std::vector<XMLNode> feature_nodes;
5080
5081 // The top level feature XML file will start with a <target> tag.
5082 XMLNode target_node = xml_document.GetRootElement("target");
5083 if (target_node) {
5084 target_node.ForEachChildElement([&target_info, &feature_nodes](
5085 const XMLNode &node) -> bool {
5086 llvm::StringRef name = node.GetName();
5087 if (name == "architecture") {
5088 node.GetElementText(target_info.arch);
5089 } else if (name == "osabi") {
5090 node.GetElementText(target_info.osabi);
5091 } else if (name == "xi:include" || name == "include") {
5092 std::string href = node.GetAttributeValue("href");
5093 if (!href.empty())
5094 target_info.includes.push_back(href);
5095 } else if (name == "feature") {
5096 feature_nodes.push_back(node);
5097 } else if (name == "groups") {
5099 "group", [&target_info](const XMLNode &node) -> bool {
5100 uint32_t set_id = UINT32_MAX;
5101 RegisterSetInfo set_info;
5102
5103 node.ForEachAttribute(
5104 [&set_id, &set_info](const llvm::StringRef &name,
5105 const llvm::StringRef &value) -> bool {
5106 // FIXME: we're silently ignoring invalid data here
5107 if (name == "id")
5108 llvm::to_integer(value, set_id);
5109 if (name == "name")
5110 set_info.name = ConstString(value);
5111 return true; // Keep iterating through all attributes
5112 });
5113
5114 if (set_id != UINT32_MAX)
5115 target_info.reg_set_map[set_id] = set_info;
5116 return true; // Keep iterating through all "group" elements
5117 });
5118 }
5119 return true; // Keep iterating through all children of the target_node
5120 });
5121 } else {
5122 // In an included XML feature file, we're already "inside" the <target>
5123 // tag of the initial XML file; this included file will likely only have
5124 // a <feature> tag. Need to check for any more included files in this
5125 // <feature> element.
5126 XMLNode feature_node = xml_document.GetRootElement("feature");
5127 if (feature_node) {
5128 feature_nodes.push_back(feature_node);
5129 feature_node.ForEachChildElement([&target_info](
5130 const XMLNode &node) -> bool {
5131 llvm::StringRef name = node.GetName();
5132 if (name == "xi:include" || name == "include") {
5133 std::string href = node.GetAttributeValue("href");
5134 if (!href.empty())
5135 target_info.includes.push_back(href);
5136 }
5137 return true;
5138 });
5139 }
5140 }
5141
5142 // gdbserver does not implement the LLDB packets used to determine host
5143 // or process architecture. If that is the case, attempt to use
5144 // the <architecture/> field from target.xml, e.g.:
5145 //
5146 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
5147 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
5148 // arm board)
5149 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
5150 // We don't have any information about vendor or OS.
5151 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
5152 .Case("i386:x86-64", "x86_64")
5153 .Case("riscv:rv64", "riscv64")
5154 .Case("riscv:rv32", "riscv32")
5155 .Default(target_info.arch) +
5156 "--");
5157
5158 if (arch_to_use.IsValid())
5159 GetTarget().MergeArchitecture(arch_to_use);
5160 }
5161
5162 if (arch_to_use.IsValid()) {
5163 for (auto &feature_node : feature_nodes) {
5164 ParseRegisters(feature_node, target_info, registers,
5166 }
5167
5168 for (const auto &include : target_info.includes) {
5169 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
5170 registers);
5171 }
5172 }
5173 } else {
5174 return false;
5175 }
5176 return true;
5177}
5178
5180 std::vector<DynamicRegisterInfo::Register> &registers,
5181 const ArchSpec &arch_to_use) {
5182 std::map<uint32_t, uint32_t> remote_to_local_map;
5183 uint32_t remote_regnum = 0;
5184 for (auto it : llvm::enumerate(registers)) {
5185 DynamicRegisterInfo::Register &remote_reg_info = it.value();
5186
5187 // Assign successive remote regnums if missing.
5188 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
5189 remote_reg_info.regnum_remote = remote_regnum;
5190
5191 // Create a mapping from remote to local regnos.
5192 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
5193
5194 remote_regnum = remote_reg_info.regnum_remote + 1;
5195 }
5196
5197 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
5198 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
5199 auto lldb_regit = remote_to_local_map.find(process_regnum);
5200 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
5202 };
5203
5204 llvm::transform(remote_reg_info.value_regs,
5205 remote_reg_info.value_regs.begin(), proc_to_lldb);
5206 llvm::transform(remote_reg_info.invalidate_regs,
5207 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
5208 }
5209
5210 // Don't use Process::GetABI, this code gets called from DidAttach, and
5211 // in that context we haven't set the Target's architecture yet, so the
5212 // ABI is also potentially incorrect.
5213 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
5214 abi_sp->AugmentRegisterInfo(registers);
5215
5216 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
5217}
5218
5219// query the target of gdb-remote for extended target information returns
5220// true on success (got register definitions), false on failure (did not).
5222 // If the remote does not offer XML, does not matter if we would have been
5223 // able to parse it.
5224 if (!m_gdb_comm.GetQXferFeaturesReadSupported())
5225 return llvm::createStringError(
5226 llvm::inconvertibleErrorCode(),
5227 "the debug server does not support \"qXfer:features:read\"");
5228
5230 return llvm::createStringError(
5231 llvm::inconvertibleErrorCode(),
5232 "the debug server supports \"qXfer:features:read\", but LLDB does not "
5233 "have XML parsing enabled (check LLLDB_ENABLE_LIBXML2)");
5234
5235 // These hold register type information for the whole of target.xml.
5236 // target.xml may include further documents that
5237 // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.
5238 // That's why we clear the cache here, and not in
5239 // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every
5240 // include read.
5242 m_registers_enum_types.clear();
5243 std::vector<DynamicRegisterInfo::Register> registers;
5244 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
5245 registers) &&
5246 // Target XML is not required to include register information.
5247 !registers.empty())
5248 AddRemoteRegisters(registers, arch_to_use);
5249
5250 return m_register_info_sp->GetNumRegisters() > 0
5251 ? llvm::ErrorSuccess()
5252 : llvm::createStringError(
5253 llvm::inconvertibleErrorCode(),
5254 "the debug server did not describe any registers");
5255}
5256
5257llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
5258 // Make sure LLDB has an XML parser it can use first
5260 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5261 "XML parsing not available");
5262
5263 Log *log = GetLog(LLDBLog::Process);
5264 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
5265
5268 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
5269
5270 // check that we have extended feature read support
5271 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
5272 // request the loaded library list
5273 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
5274 if (!raw)
5275 return raw.takeError();
5276
5277 // parse the xml file in memory
5278 LLDB_LOGF(log, "parsing: %s", raw->c_str());
5279 XMLDocument doc;
5280
5281 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
5282 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5283 "Error reading noname.xml");
5284
5285 XMLNode root_element = doc.GetRootElement("library-list-svr4");
5286 if (!root_element)
5287 return llvm::createStringError(
5288 llvm::inconvertibleErrorCode(),
5289 "Error finding library-list-svr4 xml element");
5290
5291 // main link map structure
5292 std::string main_lm = root_element.GetAttributeValue("main-lm");
5293 // FIXME: we're silently ignoring invalid data here
5294 if (!main_lm.empty())
5295 llvm::to_integer(main_lm, list.m_link_map);
5296
5297 root_element.ForEachChildElementWithName(
5298 "library", [log, &list](const XMLNode &library) -> bool {
5300
5301 // FIXME: we're silently ignoring invalid data here
5302 library.ForEachAttribute(
5303 [&module](const llvm::StringRef &name,
5304 const llvm::StringRef &value) -> bool {
5305 uint64_t uint_value = LLDB_INVALID_ADDRESS;
5306 if (name == "name")
5307 module.set_name(value.str());
5308 else if (name == "lm") {
5309 // the address of the link_map struct.
5310 llvm::to_integer(value, uint_value);
5311 module.set_link_map(uint_value);
5312 } else if (name == "l_addr") {
5313 // the displacement as read from the field 'l_addr' of the
5314 // link_map struct.
5315 llvm::to_integer(value, uint_value);
5316 module.set_base(uint_value);
5317 // base address is always a displacement, not an absolute
5318 // value.
5319 module.set_base_is_offset(true);
5320 } else if (name == "l_ld") {
5321 // the memory address of the libraries PT_DYNAMIC section.
5322 llvm::to_integer(value, uint_value);
5323 module.set_dynamic(uint_value);
5324 }
5325
5326 return true; // Keep iterating over all properties of "library"
5327 });
5328
5329 if (log) {
5330 std::string name;
5331 lldb::addr_t lm = 0, base = 0, ld = 0;
5332 bool base_is_offset;
5333
5334 module.get_name(name);
5335 module.get_link_map(lm);
5336 module.get_base(base);
5337 module.get_base_is_offset(base_is_offset);
5338 module.get_dynamic(ld);
5339
5340 LLDB_LOGF(log,
5341 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
5342 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
5343 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
5344 name.c_str());
5345 }
5346
5347 list.add(module);
5348 return true; // Keep iterating over all "library" elements in the root
5349 // node
5350 });
5351
5352 if (log)
5353 LLDB_LOGF(log, "found %" PRId32 " modules in total",
5354 (int)list.m_list.size());
5355 return list;
5356 } else if (comm.GetQXferLibrariesReadSupported()) {
5357 // request the loaded library list
5358 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
5359
5360 if (!raw)
5361 return raw.takeError();
5362
5363 LLDB_LOGF(log, "parsing: %s", raw->c_str());
5364 XMLDocument doc;
5365
5366 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
5367 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5368 "Error reading noname.xml");
5369
5370 XMLNode root_element = doc.GetRootElement("library-list");
5371 if (!root_element)
5372 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5373 "Error finding library-list xml element");
5374
5375 // FIXME: we're silently ignoring invalid data here
5376 root_element.ForEachChildElementWithName(
5377 "library", [log, &list](const XMLNode &library) -> bool {
5379
5380 std::string name = library.GetAttributeValue("name");
5381 module.set_name(name);
5382
5383 // The base address of a given library will be the address of its
5384 // first section. Most remotes send only one section for Windows
5385 // targets for example.
5386 const XMLNode &section =
5387 library.FindFirstChildElementWithName("section");
5388 std::string address = section.GetAttributeValue("address");
5389 uint64_t address_value = LLDB_INVALID_ADDRESS;
5390 llvm::to_integer(address, address_value);
5391 module.set_base(address_value);
5392 // These addresses are absolute values.
5393 module.set_base_is_offset(false);
5394
5395 if (log) {
5396 std::string name;
5397 lldb::addr_t base = 0;
5398 bool base_is_offset;
5399 module.get_name(name);
5400 module.get_base(base);
5401 module.get_base_is_offset(base_is_offset);
5402
5403 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
5404 (base_is_offset ? "offset" : "absolute"), name.c_str());
5405 }
5406
5407 list.add(module);
5408 return true; // Keep iterating over all "library" elements in the root
5409 // node
5410 });
5411
5412 if (log)
5413 LLDB_LOGF(log, "found %" PRId32 " modules in total",
5414 (int)list.m_list.size());
5415 return list;
5416 } else {
5417 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5418 "Remote libraries not supported");
5419 }
5420}
5421
5423 lldb::addr_t link_map,
5424 lldb::addr_t base_addr,
5425 bool value_is_offset) {
5426 DynamicLoader *loader = GetDynamicLoader();
5427 if (!loader)
5428 return nullptr;
5429
5430 return loader->LoadModuleAtAddress(file, link_map, base_addr,
5431 value_is_offset);
5432}
5433
5436
5437 // request a list of loaded libraries from GDBServer
5438 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
5439 if (!module_list)
5440 return module_list.takeError();
5441
5442 // get a list of all the modules
5443 ModuleList new_modules;
5444
5445 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
5446 std::string mod_name;
5447 lldb::addr_t mod_base;
5448 lldb::addr_t link_map;
5449 bool mod_base_is_offset;
5450
5451 bool valid = true;
5452 valid &= modInfo.get_name(mod_name);
5453 valid &= modInfo.get_base(mod_base);
5454 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
5455 if (!valid)
5456 continue;
5457
5458 if (!modInfo.get_link_map(link_map))
5459 link_map = LLDB_INVALID_ADDRESS;
5460
5461 FileSpec file(mod_name);
5463 lldb::ModuleSP module_sp =
5464 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
5465
5466 if (module_sp.get())
5467 new_modules.Append(module_sp);
5468 }
5469
5470 if (new_modules.GetSize() > 0) {
5471 ModuleList removed_modules;
5472 Target &target = GetTarget();
5473 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
5474
5475 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
5476 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
5477
5478 bool found = false;
5479 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
5480 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
5481 found = true;
5482 }
5483
5484 // The main executable will never be included in libraries-svr4, don't
5485 // remove it
5486 if (!found &&
5487 loaded_module.get() != target.GetExecutableModulePointer()) {
5488 removed_modules.Append(loaded_module);
5489 }
5490 }
5491
5492 loaded_modules.Remove(removed_modules);
5493 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
5494
5495 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) {
5496 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
5497 if (!obj)
5499
5502
5503 lldb::ModuleSP module_copy_sp = module_sp;
5504 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
5505 return IterationAction::Stop;
5506 });
5507
5508 loaded_modules.AppendIfNeeded(new_modules);
5509 m_process->GetTarget().ModulesDidLoad(new_modules);
5510 }
5511
5512 return llvm::ErrorSuccess();
5513}
5514
5516 bool &is_loaded,
5517 lldb::addr_t &load_addr) {
5518 is_loaded = false;
5519 load_addr = LLDB_INVALID_ADDRESS;
5520
5521 std::string file_path = file.GetPath(false);
5522 if (file_path.empty())
5523 return Status::FromErrorString("Empty file name specified");
5524
5525 StreamString packet;
5526 packet.PutCString("qFileLoadAddress:");
5527 packet.PutStringAsRawHex8(file_path);
5528
5529 StringExtractorGDBRemote response;
5530 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) !=
5532 return Status::FromErrorString("Sending qFileLoadAddress packet failed");
5533
5534 if (response.IsErrorResponse()) {
5535 if (response.GetError() == 1) {
5536 // The file is not loaded into the inferior
5537 is_loaded = false;
5538 load_addr = LLDB_INVALID_ADDRESS;
5539 return Status();
5540 }
5541
5543 "Fetching file load address from remote server returned an error");
5544 }
5545
5546 if (response.IsNormalResponse()) {
5547 is_loaded = true;
5548 load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS);
5549 return Status();
5550 }
5551
5553 "Unknown error happened during sending the load address packet");
5554}
5555
5557 // We must call the lldb_private::Process::ModulesDidLoad () first before we
5558 // do anything
5559 Process::ModulesDidLoad(module_list);
5560
5561 // After loading shared libraries, we can ask our remote GDB server if it
5562 // needs any symbols.
5563 m_gdb_comm.ServeSymbolLookups(this);
5564}
5565
5566void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) {
5567 AppendSTDOUT(out.data(), out.size());
5568}
5569
5570static const char *end_delimiter = "--end--;";
5571static const int end_delimiter_len = 8;
5572
5573void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) {
5574 std::string input = data.str(); // '1' to move beyond 'A'
5575 if (m_partial_profile_data.length() > 0) {
5576 m_partial_profile_data.append(input);
5577 input = m_partial_profile_data;
5578 m_partial_profile_data.clear();
5579 }
5580
5581 size_t found, pos = 0, len = input.length();
5582 while ((found = input.find(end_delimiter, pos)) != std::string::npos) {
5583 StringExtractorGDBRemote profileDataExtractor(
5584 input.substr(pos, found).c_str());
5585 std::string profile_data =
5586 HarmonizeThreadIdsForProfileData(profileDataExtractor);
5587 BroadcastAsyncProfileData(profile_data);
5588
5589 pos = found + end_delimiter_len;
5590 }
5591
5592 if (pos < len) {
5593 // Last incomplete chunk.
5594 m_partial_profile_data = input.substr(pos);
5595 }
5596}
5597
5599 StringExtractorGDBRemote &profileDataExtractor) {
5600 std::map<uint64_t, uint32_t> new_thread_id_to_used_usec_map;
5601 std::string output;
5602 llvm::raw_string_ostream output_stream(output);
5603 llvm::StringRef name, value;
5604
5605 // Going to assuming thread_used_usec comes first, else bail out.
5606 while (profileDataExtractor.GetNameColonValue(name, value)) {
5607 if (name.compare("thread_used_id") == 0) {
5608 StringExtractor threadIDHexExtractor(value);
5609 uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0);
5610
5611 bool has_used_usec = false;
5612 uint32_t curr_used_usec = 0;
5613 llvm::StringRef usec_name, usec_value;
5614 uint32_t input_file_pos = profileDataExtractor.GetFilePos();
5615 if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) {
5616 if (usec_name == "thread_used_usec") {
5617 has_used_usec = true;
5618 usec_value.getAsInteger(0, curr_used_usec);
5619 } else {
5620 // We didn't find what we want, it is probably an older version. Bail
5621 // out.
5622 profileDataExtractor.SetFilePos(input_file_pos);
5623 }
5624 }
5625
5626 if (has_used_usec) {
5627 uint32_t prev_used_usec = 0;
5628 std::map<uint64_t, uint32_t>::iterator iterator =
5629 m_thread_id_to_used_usec_map.find(thread_id);
5630 if (iterator != m_thread_id_to_used_usec_map.end())
5631 prev_used_usec = iterator->second;
5632
5633 uint32_t real_used_usec = curr_used_usec - prev_used_usec;
5634 // A good first time record is one that runs for at least 0.25 sec
5635 bool good_first_time =
5636 (prev_used_usec == 0) && (real_used_usec > 250000);
5637 bool good_subsequent_time =
5638 (prev_used_usec > 0) &&
5639 ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id)));
5640
5641 if (good_first_time || good_subsequent_time) {
5642 // We try to avoid doing too many index id reservation, resulting in
5643 // fast increase of index ids.
5644
5645 output_stream << name << ":";
5646 int32_t index_id = AssignIndexIDToThread(thread_id);
5647 output_stream << index_id << ";";
5648
5649 output_stream << usec_name << ":" << usec_value << ";";
5650 } else {
5651 // Skip past 'thread_used_name'.
5652 llvm::StringRef local_name, local_value;
5653 profileDataExtractor.GetNameColonValue(local_name, local_value);
5654 }
5655
5656 // Store current time as previous time so that they can be compared
5657 // later.
5658 new_thread_id_to_used_usec_map[thread_id] = curr_used_usec;
5659 } else {
5660 // Bail out and use old string.
5661 output_stream << name << ":" << value << ";";
5662 }
5663 } else {
5664 output_stream << name << ":" << value << ";";
5665 }
5666 }
5667 output_stream << end_delimiter;
5668 m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map;
5669
5670 return output;
5671}
5672
5674 if (GetStopID() != 0)
5675 return;
5676
5677 if (GetID() == LLDB_INVALID_PROCESS_ID) {
5678 lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID();
5679 if (pid != LLDB_INVALID_PROCESS_ID)
5680 SetID(pid);
5681 }
5683}
5684
5685llvm::Expected<bool> ProcessGDBRemote::SaveCore(llvm::StringRef outfile) {
5686 if (!m_gdb_comm.GetSaveCoreSupported())
5687 return false;
5688
5689 StreamString packet;
5690 packet.PutCString("qSaveCore;path-hint:");
5691 packet.PutStringAsRawHex8(outfile);
5692
5693 StringExtractorGDBRemote response;
5694 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
5696 // TODO: grab error message from the packet? StringExtractor seems to
5697 // be missing a method for that
5698 if (response.IsErrorResponse())
5699 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5700 "qSaveCore returned an error");
5701
5702 std::string path;
5703
5704 // process the response
5705 for (auto x : llvm::split(response.GetStringRef(), ';')) {
5706 if (x.consume_front("core-path:"))
5708 }
5709
5710 // verify that we've gotten what we need
5711 if (path.empty())
5712 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5713 "qSaveCore returned no core path");
5714
5715 // now transfer the core file
5716 FileSpec remote_core{llvm::StringRef(path)};
5717 Platform &platform = *GetTarget().GetPlatform();
5718 Status error = platform.GetFile(remote_core, FileSpec(outfile));
5719
5720 if (platform.IsRemote()) {
5721 // NB: we unlink the file on error too
5722 platform.Unlink(remote_core);
5723 if (error.Fail())
5724 return error.ToError();
5725 }
5726
5727 return true;
5728 }
5729
5730 return llvm::createStringError(llvm::inconvertibleErrorCode(),
5731 "Unable to send qSaveCore");
5732}
5733
5734static const char *const s_async_json_packet_prefix = "JSON-async:";
5735
5737ParseStructuredDataPacket(llvm::StringRef packet) {
5738 Log *log = GetLog(GDBRLog::Process);
5739
5740 if (!packet.consume_front(s_async_json_packet_prefix)) {
5741 if (log) {
5742 LLDB_LOGF(
5743 log,
5744 "GDBRemoteCommunicationClientBase::%s() received $J packet "
5745 "but was not a StructuredData packet: packet starts with "
5746 "%s",
5747 __FUNCTION__,
5748 packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str());
5749 }
5750 return StructuredData::ObjectSP();
5751 }
5752
5753 // This is an asynchronous JSON packet, destined for a StructuredDataPlugin.
5755 if (log) {
5756 if (json_sp) {
5757 StreamString json_str;
5758 json_sp->Dump(json_str, true);
5759 json_str.Flush();
5760 LLDB_LOGF(log,
5761 "ProcessGDBRemote::%s() "
5762 "received Async StructuredData packet: %s",
5763 __FUNCTION__, json_str.GetData());
5764 } else {
5765 LLDB_LOGF(log,
5766 "ProcessGDBRemote::%s"
5767 "() received StructuredData packet:"
5768 " parse failure",
5769 __FUNCTION__);
5770 }
5771 }
5772 return json_sp;
5773}
5774
5776 auto structured_data_sp = ParseStructuredDataPacket(data);
5777 if (structured_data_sp)
5778 RouteAsyncStructuredData(structured_data_sp);
5779}
5780
5782public:
5784 : CommandObjectParsed(interpreter, "process plugin packet speed-test",
5785 "Tests packet speeds of various sizes to determine "
5786 "the performance characteristics of the GDB remote "
5787 "connection. ",
5788 nullptr),
5790 m_num_packets(LLDB_OPT_SET_1, false, "count", 'c', 0, eArgTypeCount,
5791 "The number of packets to send of each varying size "
5792 "(default is 1000).",
5793 1000),
5794 m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount,
5795 "The maximum number of bytes to send in a packet. Sizes "
5796 "increase in powers of 2 while the size is less than or "
5797 "equal to this option value. (default 1024).",
5798 1024),
5799 m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount,
5800 "The maximum number of bytes to receive in a packet. Sizes "
5801 "increase in powers of 2 while the size is less than or "
5802 "equal to this option value. (default 1024).",
5803 1024),
5804 m_json(LLDB_OPT_SET_1, false, "json", 'j',
5805 "Print the output as JSON data for easy parsing.", false, true) {
5810 m_option_group.Finalize();
5811 }
5812
5814
5815 Options *GetOptions() override { return &m_option_group; }
5816
5817 void DoExecute(Args &command, CommandReturnObject &result) override {
5818 const size_t argc = command.GetArgumentCount();
5819 if (argc == 0) {
5820 ProcessGDBRemote *process =
5821 (ProcessGDBRemote *)m_interpreter.GetExecutionContext()
5822 .GetProcessPtr();
5823 if (process) {
5824 StreamSP output_stream_sp = result.GetImmediateOutputStream();
5825 if (!output_stream_sp)
5826 output_stream_sp = m_interpreter.GetDebugger().GetAsyncOutputStream();
5827 result.SetImmediateOutputStream(output_stream_sp);
5828
5829 const uint32_t num_packets =
5830 (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue();
5831 const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue();
5832 const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue();
5833 const bool json = m_json.GetOptionValue().GetCurrentValue();
5834 const uint64_t k_recv_amount =
5835 4 * 1024 * 1024; // Receive amount in bytes
5836 process->GetGDBRemote().TestPacketSpeed(
5837 num_packets, max_send, max_recv, k_recv_amount, json,
5838 output_stream_sp ? *output_stream_sp : result.GetOutputStream());
5840 return;
5841 }
5842 } else {
5843 result.AppendErrorWithFormat("'%s' takes no arguments",
5844 m_cmd_name.c_str());
5845 }
5847 }
5848
5849protected:
5855};
5856
5858private:
5859public:
5861 : CommandObjectParsed(interpreter, "process plugin packet history",
5862 "Dumps the packet history buffer. ", nullptr) {}
5863
5865
5866 void DoExecute(Args &command, CommandReturnObject &result) override {
5867 ProcessGDBRemote *process =
5868 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5869 if (process) {
5870 process->DumpPluginHistory(result.GetOutputStream());
5872 return;
5873 }
5875 }
5876};
5877
5879private:
5880public:
5883 interpreter, "process plugin packet xfer-size",
5884 "Maximum size that lldb will try to read/write one one chunk.",
5885 nullptr) {
5887 }
5888
5890
5891 void DoExecute(Args &command, CommandReturnObject &result) override {
5892 const size_t argc = command.GetArgumentCount();
5893 if (argc == 0) {
5894 result.AppendErrorWithFormat("'%s' takes an argument to specify the max "
5895 "amount to be transferred when "
5896 "reading/writing",
5897 m_cmd_name.c_str());
5898 return;
5899 }
5900
5901 ProcessGDBRemote *process =
5902 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5903 if (process) {
5904 const char *packet_size = command.GetArgumentAtIndex(0);
5905 errno = 0;
5906 uint64_t user_specified_max = strtoul(packet_size, nullptr, 10);
5907 if (errno == 0 && user_specified_max != 0) {
5908 process->SetUserSpecifiedMaxMemoryTransferSize(user_specified_max);
5910 return;
5911 }
5912 }
5914 }
5915};
5916
5918private:
5919public:
5921 : CommandObjectParsed(interpreter, "process plugin packet send",
5922 "Send a custom packet through the GDB remote "
5923 "protocol and print the answer. "
5924 "The packet header and footer will automatically "
5925 "be added to the packet prior to sending and "
5926 "stripped from the result.",
5927 nullptr) {
5929 }
5930
5932
5933 void DoExecute(Args &command, CommandReturnObject &result) override {
5934 const size_t argc = command.GetArgumentCount();
5935 if (argc == 0) {
5936 result.AppendErrorWithFormat(
5937 "'%s' takes a one or more packet content arguments",
5938 m_cmd_name.c_str());
5939 return;
5940 }
5941
5942 ProcessGDBRemote *process =
5943 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5944 if (process) {
5945 for (size_t i = 0; i < argc; ++i) {
5946 const char *packet_cstr = command.GetArgumentAtIndex(0);
5947 StringExtractorGDBRemote response;
5949 packet_cstr, response, process->GetInterruptTimeout());
5951 Stream &output_strm = result.GetOutputStream();
5952 output_strm.Printf(" packet: %s\n", packet_cstr);
5953 std::string response_str = std::string(response.GetStringRef());
5954
5955 if (strstr(packet_cstr, "qGetProfileData") != nullptr) {
5956 response_str = process->HarmonizeThreadIdsForProfileData(response);
5957 }
5958
5959 if (response_str.empty())
5960 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
5961 else
5962 output_strm.Printf("response: %s\n", response.GetStringRef().data());
5963 }
5964 }
5965 }
5966};
5967
5969private:
5970public:
5972 : CommandObjectRaw(interpreter, "process plugin packet monitor",
5973 "Send a qRcmd packet through the GDB remote protocol "
5974 "and print the response. "
5975 "The argument passed to this command will be hex "
5976 "encoded into a valid 'qRcmd' packet, sent and the "
5977 "response will be printed.") {}
5978
5980
5981 void DoExecute(llvm::StringRef command,
5982 CommandReturnObject &result) override {
5983 if (command.empty()) {
5984 result.AppendErrorWithFormat("'%s' takes a command string argument",
5985 m_cmd_name.c_str());
5986 return;
5987 }
5988
5989 ProcessGDBRemote *process =
5990 (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr();
5991 if (process) {
5992 StreamString packet;
5993 packet.PutCString("qRcmd,");
5994 packet.PutBytesAsRawHex8(command.data(), command.size());
5995
5996 StringExtractorGDBRemote response;
5997 Stream &output_strm = result.GetOutputStream();
5999 packet.GetString(), response, process->GetInterruptTimeout(),
6000 [&output_strm](llvm::StringRef output) { output_strm << output; });
6002 output_strm.Printf(" packet: %s\n", packet.GetData());
6003 const std::string &response_str = std::string(response.GetStringRef());
6004
6005 if (response_str.empty())
6006 output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n");
6007 else
6008 output_strm.Printf("response: %s\n", response.GetStringRef().data());
6009 }
6010 }
6011};
6012
6014private:
6015public:
6017 : CommandObjectMultiword(interpreter, "process plugin packet",
6018 "Commands that deal with GDB remote packets.",
6019 nullptr) {
6021 "history",
6025 "send", CommandObjectSP(
6026 new CommandObjectProcessGDBRemotePacketSend(interpreter)));
6028 "monitor",
6032 "xfer-size",
6035 LoadSubCommand("speed-test",
6037 interpreter)));
6038 }
6039
6041};
6042
6044public:
6047 interpreter, "process plugin",
6048 "Commands for operating on a ProcessGDBRemote process.",
6049 "process plugin <subcommand> [<subcommand-options>]") {
6051 "packet",
6053 }
6054
6056};
6057
6059 if (!m_command_sp)
6060 m_command_sp = std::make_shared<CommandObjectMultiwordProcessGDBRemote>(
6061 GetTarget().GetDebugger().GetCommandInterpreter());
6062 return m_command_sp.get();
6063}
6064
6066 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
6067 if (bp_site->IsEnabled() &&
6068 (bp_site->GetType() == BreakpointSite::eSoftware ||
6069 bp_site->GetType() == BreakpointSite::eExternal)) {
6070 m_gdb_comm.SendGDBStoppointTypePacket(
6071 eBreakpointSoftware, enable, bp_site->GetLoadAddress(),
6073 }
6074 });
6075}
6076
6078 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) {
6079 GetBreakpointSiteList().ForEach([this, enable](BreakpointSite *bp_site) {
6080 if (bp_site->IsEnabled() &&
6081 bp_site->GetType() == BreakpointSite::eHardware) {
6082 m_gdb_comm.SendGDBStoppointTypePacket(
6083 eBreakpointHardware, enable, bp_site->GetLoadAddress(),
6085 }
6086 });
6087 }
6088
6089 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
6090 addr_t addr = wp_res_sp->GetLoadAddress();
6091 size_t size = wp_res_sp->GetByteSize();
6092 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
6093 m_gdb_comm.SendGDBStoppointTypePacket(type, enable, addr, size,
6095 }
6096}
6097
6099 Log *log = GetLog(GDBRLog::Process);
6100
6101 lldb::pid_t parent_pid = m_gdb_comm.GetCurrentProcessID();
6102 // Any valid TID will suffice, thread-relevant actions will set a proper TID
6103 // anyway.
6104 lldb::tid_t parent_tid = m_thread_ids.front();
6105
6106 lldb::pid_t follow_pid, detach_pid;
6107 lldb::tid_t follow_tid, detach_tid;
6108
6109 switch (GetFollowForkMode()) {
6110 case eFollowParent:
6111 follow_pid = parent_pid;
6112 follow_tid = parent_tid;
6113 detach_pid = child_pid;
6114 detach_tid = child_tid;
6115 break;
6116 case eFollowChild:
6117 follow_pid = child_pid;
6118 follow_tid = child_tid;
6119 detach_pid = parent_pid;
6120 detach_tid = parent_tid;
6121 break;
6122 }
6123
6124 // Switch to the process that is going to be detached.
6125 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
6126 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
6127 return;
6128 }
6129
6130 // Disable all software breakpoints in the forked process.
6131 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
6133
6134 // Remove hardware breakpoints / watchpoints from parent process if we're
6135 // following child.
6138
6139 // Switch to the process that is going to be followed
6140 if (!m_gdb_comm.SetCurrentThread(follow_tid, follow_pid) ||
6141 !m_gdb_comm.SetCurrentThreadForRun(follow_tid, follow_pid)) {
6142 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
6143 return;
6144 }
6145
6146 LLDB_LOG(log, "Detaching process {0}", detach_pid);
6147 Status error = m_gdb_comm.Detach(false, detach_pid);
6148 if (error.Fail()) {
6149 LLDB_LOG(log, "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
6150 error.AsCString() ? error.AsCString() : "<unknown error>");
6151 return;
6152 }
6153
6154 // Hardware breakpoints/watchpoints are not inherited implicitly,
6155 // so we need to readd them if we're following child.
6158 // Update our PID
6159 SetID(child_pid);
6160 }
6161}
6162
6164 Log *log = GetLog(GDBRLog::Process);
6165
6166 LLDB_LOG(
6167 log,
6168 "ProcessGDBRemote::DidFork() called for child_pid: {0}, child_tid {1}",
6169 child_pid, child_tid);
6171
6172 // Disable all software breakpoints for the duration of vfork.
6173 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
6175
6176 lldb::pid_t detach_pid;
6177 lldb::tid_t detach_tid;
6178
6179 switch (GetFollowForkMode()) {
6180 case eFollowParent:
6181 detach_pid = child_pid;
6182 detach_tid = child_tid;
6183 break;
6184 case eFollowChild:
6185 detach_pid = m_gdb_comm.GetCurrentProcessID();
6186 // Any valid TID will suffice, thread-relevant actions will set a proper TID
6187 // anyway.
6188 detach_tid = m_thread_ids.front();
6189
6190 // Switch to the parent process before detaching it.
6191 if (!m_gdb_comm.SetCurrentThread(detach_tid, detach_pid)) {
6192 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to set pid/tid");
6193 return;
6194 }
6195
6196 // Remove hardware breakpoints / watchpoints from the parent process.
6198
6199 // Switch to the child process.
6200 if (!m_gdb_comm.SetCurrentThread(child_tid, child_pid) ||
6201 !m_gdb_comm.SetCurrentThreadForRun(child_tid, child_pid)) {
6202 LLDB_LOG(log, "ProcessGDBRemote::DidFork() unable to reset pid/tid");
6203 return;
6204 }
6205 break;
6206 }
6207
6208 LLDB_LOG(log, "Detaching process {0}", detach_pid);
6209 Status error = m_gdb_comm.Detach(false, detach_pid);
6210 if (error.Fail()) {
6211 LLDB_LOG(log,
6212 "ProcessGDBRemote::DidFork() detach packet send failed: {0}",
6213 error.AsCString() ? error.AsCString() : "<unknown error>");
6214 return;
6215 }
6216
6218 // Update our PID
6219 SetID(child_pid);
6220 }
6221}
6222
6224 assert(m_vfork_in_progress_count > 0);
6226
6227 // Reenable all software breakpoints that were enabled before vfork.
6228 if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware))
6230}
6231
6233 // If we are following children, vfork is finished by exec (rather than
6234 // vforkdone that is submitted for parent).
6238 }
6240}
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:369
#define LLDB_LOGF(log,...)
Definition Log.h:376
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
#define LLDB_LOGV(log,...)
Definition Log.h:383
#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 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 FileSpec GetDebugserverPath(Platform &platform)
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:367
void Clear()
Clears the object state.
Definition ArchSpec.cpp:538
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:457
bool SetTriple(const llvm::Triple &triple)
Architecture triple setter.
Definition ArchSpec.cpp:739
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition ArchSpec.h:509
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:673
Core GetCore() const
Definition ArchSpec.h:448
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:548
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 IsEnabled() const
Tells whether the current breakpoint site is enabled or not.
void SetEnabled(bool enabled)
Sets whether the current breakpoint site is enabled or not.
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.
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
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.
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
Action GetAction() const
Definition FileAction.h:38
const FileSpec & GetFileSpec() const
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:375
void add(const LoadedModuleInfo &mod)
std::vector< LoadedModuleInfo > m_list
void PutCString(const char *cstr)
Definition Log.cpp:145
void void void void void Warning(const char *fmt,...) __attribute__((format(printf
Definition Log.cpp:211
bool GetVerbose() const
Definition Log.cpp:326
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:1188
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:78
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:817
virtual Status Unlink(const FileSpec &file_spec)
bool IsRemote() const
Definition Platform.h:509
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:369
std::chrono::seconds GetInterruptTimeout() const
Definition Process.cpp:332
A plug-in interface definition class for debugging a process.
Definition Process.h:354
StopPointSiteList< lldb_private::BreakpointSite > & GetBreakpointSiteList()
Definition Process.cpp:1536
virtual Status DisableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1810
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:537
ThreadList & GetThreadList()
Definition Process.h:2269
void SetAddressableBitMasks(AddressableBits bit_masks)
Definition Process.cpp:6941
Process(lldb::TargetSP target_sp, lldb::ListenerSP listener_sp)
Construct with a shared pointer to a target, and the Process listener.
Definition Process.cpp:425
void SetUnixSignals(lldb::UnixSignalsSP &&signals_sp)
Definition Process.cpp:3711
virtual void ModulesDidLoad(ModuleList &module_list)
Definition Process.cpp:6180
void ResumePrivateStateThread()
Definition Process.cpp:3962
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:6411
virtual SystemRuntime * GetSystemRuntime()
Get the system runtime plug-in for this process.
Definition Process.cpp:2937
std::map< uint64_t, uint32_t > m_thread_id_to_index_id_map
Definition Process.h:3372
lldb::StateType GetPrivateState() const
Definition Process.h:3329
lldb::DynamicLoaderUP m_dyld_up
Definition Process.h:3407
virtual Status WriteObjectFile(std::vector< ObjectFile::LoadableData > entries)
Definition Process.cpp:2501
StopPointSiteList< lldb_private::WatchpointResource > m_watchpoint_resource_list
Watchpoint resources currently in use.
Definition Process.h:3399
void AppendSTDOUT(const char *s, size_t len)
Definition Process.cpp:4652
bool HasAssignedIndexIDToThread(uint64_t sb_thread_id)
Definition Process.cpp:1243
lldb::ByteOrder GetByteOrder() const
Definition Process.cpp:3721
void UpdateThreadListIfNeeded()
Definition Process.cpp:1106
bool IsValid() const
Return whether this object is valid (i.e.
Definition Process.h:572
virtual void DidExec()
Called after a process re-execs itself.
Definition Process.cpp:6114
void BroadcastAsyncProfileData(const std::string &one_profile_data)
Definition Process.cpp:4666
lldb::UnixSignalsSP m_unix_signals_sp
Definition Process.h:3417
lldb::tid_t m_interrupt_tid
Definition Process.h:3445
virtual Status EnableSoftwareBreakpoint(BreakpointSite *bp_site)
Definition Process.cpp:1730
bool RouteAsyncStructuredData(const StructuredData::ObjectSP object_sp)
Route the incoming structured data dictionary to the right plugin.
Definition Process.cpp:6478
virtual bool IsAlive()
Check if a process is still alive.
Definition Process.cpp:1081
ThreadList m_thread_list_real
The threads for this process as are known to the protocol we are debugging with.
Definition Process.h:3378
void SetID(lldb::pid_t new_pid)
Sets the stored pid.
Definition Process.h:542
friend class Target
Definition Process.h:360
uint32_t AssignIndexIDToThread(uint64_t thread_id)
Definition Process.cpp:1248
virtual bool SetExitStatus(int exit_status, llvm::StringRef exit_string)
Set accessor for the process exit status (return code).
Definition Process.cpp:1023
MemoryCache m_memory_cache
Definition Process.h:3430
uint32_t GetAddressByteSize() const
Definition Process.cpp:3725
uint32_t GetStopID() const
Definition Process.h:1455
void SetPrivateState(lldb::StateType state)
Definition Process.cpp:1377
lldb::StateType GetPublicState() const
Definition Process.h:3323
void SetSTDIOFileDescriptor(int file_descriptor)
Associates a file descriptor with the process' STDIO handling and configures an asynchronous reading ...
Definition Process.cpp:4903
virtual void Finalize(bool destructing)
This object is about to be destroyed, do any necessary cleanup.
Definition Process.cpp:537
ThreadList m_thread_list
The threads for this process as the user will see them.
Definition Process.h:3380
const lldb::UnixSignalsSP & GetUnixSignals()
Definition Process.cpp:3716
std::weak_ptr< Target > m_target_wp
The target that owns this process.
Definition Process.h:3347
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:1952
Status GetMemoryRegionInfo(lldb::addr_t load_addr, MemoryRegionInfo &range_info)
Locate the memory region that contains load_addr.
Definition Process.cpp:6354
friend class DynamicLoader
Definition Process.h:357
size_t GetSoftwareBreakpointTrapOpcode(BreakpointSite *bp_site)
Definition Process.cpp:1723
friend class Debugger
Definition Process.h:356
ThreadedCommunication m_stdio_communication
Definition Process.h:3421
friend class ThreadList
Definition Process.h:361
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1250
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
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:28
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)
Definition Stream.h:364
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:65
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 ForEach(std::function< bool(llvm::StringRef key, Object *object)> const &callback) const
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
static ObjectSP ParseJSON(llvm::StringRef json_text)
std::shared_ptr< Array > ArraySP
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:1541
Debugger & GetDebugger() const
Definition Target.h:1224
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1705
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1525
lldb::PlatformSP GetPlatform()
Definition Target.h:1678
const ArchSpec & GetArchitecture() const
Definition Target.h:1183
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1576
bool MergeArchitecture(const ArchSpec &arch_spec)
Definition Target.cpp:1796
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.
Status LaunchAndConnectToDebugserver(const ProcessInfo &process_info)
virtual std::shared_ptr< ThreadGDBRemote > CreateThread(lldb::tid_t tid)
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)
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 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...
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.
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)
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::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.
void DidFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override
Called after a reported fork.
StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos() override
Status DoHalt(bool &caused_stop) override
Halts a running process.
llvm::Expected< TraceSupportedResponse > TraceSupported() override
Get the processor tracing type supported for this process.
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.
void DidVFork(lldb::pid_t child_pid, lldb::tid_t child_tid) override
Called after a reported vfork.
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 SetThreadDispatchQAddr(lldb::addr_t thread_dispatch_qaddr)
lldb::RegisterContextSP GetRegisterContext() override
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:332
bool InferiorCallMunmap(Process *proc, lldb::addr_t addr, lldb::addr_t length)
@ eMmapFlagsPrivate
Definition Platform.h:47
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
std::shared_ptr< lldb_private::Target > TargetSP
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