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