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