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