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