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