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