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