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