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