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"
38#include "lldb/Host/PosixApi.h"
42#include "lldb/Host/XML.h"
54#include "lldb/Target/ABI.h"
59#include "lldb/Target/Target.h"
62#include "lldb/Utility/Args.h"
65#include "lldb/Utility/State.h"
67#include "lldb/Utility/Timer.h"
68#include <algorithm>
69#include <csignal>
70#include <map>
71#include <memory>
72#include <mutex>
73#include <optional>
74#include <sstream>
75#include <thread>
76
82#include "ProcessGDBRemote.h"
83#include "ProcessGDBRemoteLog.h"
84#include "ThreadGDBRemote.h"
85#include "lldb/Host/Host.h"
87
88#include "llvm/ADT/ScopeExit.h"
89#include "llvm/ADT/StringMap.h"
90#include "llvm/ADT/StringSwitch.h"
91#include "llvm/Support/FormatAdapters.h"
92#include "llvm/Support/Threading.h"
93#include "llvm/Support/raw_ostream.h"
94
95#define DEBUGSERVER_BASENAME "debugserver"
96using namespace lldb;
97using namespace lldb_private;
99
101
102namespace lldb {
103// Provide a function that can easily dump the packet history if we know a
104// ProcessGDBRemote * value (which we can get from logs or from debugging). We
105// need the function in the lldb namespace so it makes it into the final
106// executable since the LLDB shared library only exports stuff in the lldb
107// namespace. This allows you to attach with a debugger and call this function
108// and get the packet history dumped to a file.
109void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
110 auto file = FileSystem::Instance().Open(
112 if (!file) {
113 llvm::consumeError(file.takeError());
114 return;
115 }
116 StreamFile stream(std::move(file.get()));
117 ((Process *)p)->DumpPluginHistory(stream);
118}
119} // namespace lldb
120
121namespace {
122
123#define LLDB_PROPERTIES_processgdbremote
124#include "ProcessGDBRemoteProperties.inc"
125
126enum {
127#define LLDB_PROPERTIES_processgdbremote
128#include "ProcessGDBRemotePropertiesEnum.inc"
129};
130
131class PluginProperties : public Properties {
132public:
133 static llvm::StringRef GetSettingName() {
135 }
136
137 PluginProperties() : Properties() {
138 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
139 m_collection_sp->Initialize(g_processgdbremote_properties);
140 }
141
142 ~PluginProperties() override = default;
143
144 uint64_t GetPacketTimeout() {
145 const uint32_t idx = ePropertyPacketTimeout;
146 return GetPropertyAtIndexAs<uint64_t>(
147 idx, g_processgdbremote_properties[idx].default_uint_value);
148 }
149
150 bool SetPacketTimeout(uint64_t timeout) {
151 const uint32_t idx = ePropertyPacketTimeout;
152 return SetPropertyAtIndex(idx, timeout);
153 }
154
155 FileSpec GetTargetDefinitionFile() const {
156 const uint32_t idx = ePropertyTargetDefinitionFile;
157 return GetPropertyAtIndexAs<FileSpec>(idx, {});
158 }
159
160 bool GetUseSVR4() const {
161 const uint32_t idx = ePropertyUseSVR4;
162 return GetPropertyAtIndexAs<bool>(
163 idx, g_processgdbremote_properties[idx].default_uint_value != 0);
164 }
165
166 bool GetUseGPacketForReading() const {
167 const uint32_t idx = ePropertyUseGPacketForReading;
168 return GetPropertyAtIndexAs<bool>(idx, true);
169 }
170};
171
172} // namespace
173
174static PluginProperties &GetGlobalPluginProperties() {
175 static PluginProperties g_settings;
176 return g_settings;
177}
178
179// TODO Randomly assigning a port is unsafe. We should get an unused
180// ephemeral port from the kernel and make sure we reserve it before passing it
181// to debugserver.
182
183#if defined(__APPLE__)
184#define LOW_PORT (IPPORT_RESERVED)
185#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
186#else
187#define LOW_PORT (1024u)
188#define HIGH_PORT (49151u)
189#endif
190
192 return "GDB Remote protocol based debugging plug-in.";
193}
194
197}
198
200 lldb::TargetSP target_sp, ListenerSP listener_sp,
201 const FileSpec *crash_file_path, bool can_connect) {
202 lldb::ProcessSP process_sp;
203 if (crash_file_path == nullptr)
204 process_sp = std::shared_ptr<ProcessGDBRemote>(
205 new ProcessGDBRemote(target_sp, listener_sp));
206 return process_sp;
207}
208
211 gdb_comm.DumpHistory(s);
212}
213
215 return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
216}
217
220}
221
223 bool plugin_specified_by_name) {
224 if (plugin_specified_by_name)
225 return true;
226
227 // For now we are just making sure the file exists for a given module
228 Module *exe_module = target_sp->GetExecutableModulePointer();
229 if (exe_module) {
230 ObjectFile *exe_objfile = exe_module->GetObjectFile();
231 // We can't debug core files...
232 switch (exe_objfile->GetType()) {
240 return false;
244 break;
245 }
246 return FileSystem::Instance().Exists(exe_module->GetFileSpec());
247 }
248 // However, if there is no executable module, we return true since we might
249 // be preparing to attach.
250 return true;
251}
252
253// ProcessGDBRemote constructor
255 ListenerSP listener_sp)
256 : Process(target_sp, listener_sp),
257 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
258 m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
259 m_async_listener_sp(
260 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
261 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
262 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
263 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
264 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
265 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
266 m_waiting_for_attach(false), m_command_sp(), m_breakpoint_pc_offset(0),
267 m_initial_tid(LLDB_INVALID_THREAD_ID), m_allow_flash_writes(false),
268 m_erased_flash_ranges(), m_vfork_in_progress_count(0) {
270 "async thread should exit");
272 "async thread continue");
274 "async thread did exit");
275
276 Log *log = GetLog(GDBRLog::Async);
277
278 const uint32_t async_event_mask =
280
281 if (m_async_listener_sp->StartListeningForEvents(
282 &m_async_broadcaster, async_event_mask) != async_event_mask) {
283 LLDB_LOGF(log,
284 "ProcessGDBRemote::%s failed to listen for "
285 "m_async_broadcaster events",
286 __FUNCTION__);
287 }
288
289 const uint64_t timeout_seconds =
290 GetGlobalPluginProperties().GetPacketTimeout();
291 if (timeout_seconds > 0)
292 m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds));
293
295 GetGlobalPluginProperties().GetUseGPacketForReading();
296}
297
298// Destructor
300 // m_mach_process.UnregisterNotificationCallbacks (this);
301 Clear();
302 // We need to call finalize on the process before destroying ourselves to
303 // make sure all of the broadcaster cleanup goes as planned. If we destruct
304 // this class, then Process::~Process() might have problems trying to fully
305 // destroy the broadcaster.
306 Finalize(true /* destructing */);
307
308 // The general Finalize is going to try to destroy the process and that
309 // SHOULD shut down the async thread. However, if we don't kill it it will
310 // get stranded and its connection will go away so when it wakes up it will
311 // crash. So kill it for sure here.
314}
315
317 const FileSpec &target_definition_fspec) {
318 ScriptInterpreter *interpreter =
321 StructuredData::ObjectSP module_object_sp(
322 interpreter->LoadPluginModule(target_definition_fspec, error));
323 if (module_object_sp) {
324 StructuredData::DictionarySP target_definition_sp(
325 interpreter->GetDynamicSettings(module_object_sp, &GetTarget(),
326 "gdb-server-target-definition", error));
327
328 if (target_definition_sp) {
329 StructuredData::ObjectSP target_object(
330 target_definition_sp->GetValueForKey("host-info"));
331 if (target_object) {
332 if (auto host_info_dict = target_object->GetAsDictionary()) {
333 StructuredData::ObjectSP triple_value =
334 host_info_dict->GetValueForKey("triple");
335 if (auto triple_string_value = triple_value->GetAsString()) {
336 std::string triple_string =
337 std::string(triple_string_value->GetValue());
338 ArchSpec host_arch(triple_string.c_str());
339 if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) {
340 GetTarget().SetArchitecture(host_arch);
341 }
342 }
343 }
344 }
346 StructuredData::ObjectSP breakpoint_pc_offset_value =
347 target_definition_sp->GetValueForKey("breakpoint-pc-offset");
348 if (breakpoint_pc_offset_value) {
349 if (auto breakpoint_pc_int_value =
350 breakpoint_pc_offset_value->GetAsSignedInteger())
351 m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue();
352 }
353
354 if (m_register_info_sp->SetRegisterInfo(
355 *target_definition_sp, GetTarget().GetArchitecture()) > 0) {
356 return true;
357 }
358 }
359 }
360 return false;
361}
362
364 const llvm::StringRef &comma_separated_register_numbers,
365 std::vector<uint32_t> &regnums, int base) {
366 regnums.clear();
367 for (llvm::StringRef x : llvm::split(comma_separated_register_numbers, ',')) {
368 uint32_t reg;
369 if (llvm::to_integer(x, reg, base))
370 regnums.push_back(reg);
371 }
372 return regnums.size();
373}
374
376 if (!force && m_register_info_sp)
377 return;
378
379 m_register_info_sp = std::make_shared<GDBRemoteDynamicRegisterInfo>();
380
381 // Check if qHostInfo specified a specific packet timeout for this
382 // connection. If so then lets update our setting so the user knows what the
383 // timeout is and can see it.
384 const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout();
385 if (host_packet_timeout > std::chrono::seconds(0)) {
386 GetGlobalPluginProperties().SetPacketTimeout(host_packet_timeout.count());
387 }
388
389 // Register info search order:
390 // 1 - Use the target definition python file if one is specified.
391 // 2 - If the target definition doesn't have any of the info from the
392 // target.xml (registers) then proceed to read the target.xml.
393 // 3 - Fall back on the qRegisterInfo packets.
394 // 4 - Use hardcoded defaults if available.
395
396 FileSpec target_definition_fspec =
397 GetGlobalPluginProperties().GetTargetDefinitionFile();
398 if (!FileSystem::Instance().Exists(target_definition_fspec)) {
399 // If the filename doesn't exist, it may be a ~ not having been expanded -
400 // try to resolve it.
401 FileSystem::Instance().Resolve(target_definition_fspec);
402 }
403 if (target_definition_fspec) {
404 // See if we can get register definitions from a python file
405 if (ParsePythonTargetDefinition(target_definition_fspec))
406 return;
407
408 Debugger::ReportError("target description file " +
409 target_definition_fspec.GetPath() +
410 " failed to parse",
411 GetTarget().GetDebugger().GetID());
412 }
413
414 const ArchSpec &target_arch = GetTarget().GetArchitecture();
415 const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture();
416 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
417
418 // Use the process' architecture instead of the host arch, if available
419 ArchSpec arch_to_use;
420 if (remote_process_arch.IsValid())
421 arch_to_use = remote_process_arch;
422 else
423 arch_to_use = remote_host_arch;
424
425 if (!arch_to_use.IsValid())
426 arch_to_use = target_arch;
427
428 if (GetGDBServerRegisterInfo(arch_to_use))
429 return;
430
431 char packet[128];
432 std::vector<DynamicRegisterInfo::Register> registers;
433 uint32_t reg_num = 0;
434 for (StringExtractorGDBRemote::ResponseType response_type =
436 response_type == StringExtractorGDBRemote::eResponse; ++reg_num) {
437 const int packet_len =
438 ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num);
439 assert(packet_len < (int)sizeof(packet));
440 UNUSED_IF_ASSERT_DISABLED(packet_len);
442 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response) ==
444 response_type = response.GetResponseType();
445 if (response_type == StringExtractorGDBRemote::eResponse) {
446 llvm::StringRef name;
447 llvm::StringRef value;
449
450 while (response.GetNameColonValue(name, value)) {
451 if (name == "name") {
452 reg_info.name.SetString(value);
453 } else if (name == "alt-name") {
454 reg_info.alt_name.SetString(value);
455 } else if (name == "bitsize") {
456 if (!value.getAsInteger(0, reg_info.byte_size))
457 reg_info.byte_size /= CHAR_BIT;
458 } else if (name == "offset") {
459 value.getAsInteger(0, reg_info.byte_offset);
460 } else if (name == "encoding") {
461 const Encoding encoding = Args::StringToEncoding(value);
462 if (encoding != eEncodingInvalid)
463 reg_info.encoding = encoding;
464 } else if (name == "format") {
465 if (!OptionArgParser::ToFormat(value.str().c_str(), reg_info.format, nullptr)
466 .Success())
467 reg_info.format =
468 llvm::StringSwitch<Format>(value)
469 .Case("binary", eFormatBinary)
470 .Case("decimal", eFormatDecimal)
471 .Case("hex", eFormatHex)
472 .Case("float", eFormatFloat)
473 .Case("vector-sint8", eFormatVectorOfSInt8)
474 .Case("vector-uint8", eFormatVectorOfUInt8)
475 .Case("vector-sint16", eFormatVectorOfSInt16)
476 .Case("vector-uint16", eFormatVectorOfUInt16)
477 .Case("vector-sint32", eFormatVectorOfSInt32)
478 .Case("vector-uint32", eFormatVectorOfUInt32)
479 .Case("vector-float32", eFormatVectorOfFloat32)
480 .Case("vector-uint64", eFormatVectorOfUInt64)
481 .Case("vector-uint128", eFormatVectorOfUInt128)
482 .Default(eFormatInvalid);
483 } else if (name == "set") {
484 reg_info.set_name.SetString(value);
485 } else if (name == "gcc" || name == "ehframe") {
486 value.getAsInteger(0, reg_info.regnum_ehframe);
487 } else if (name == "dwarf") {
488 value.getAsInteger(0, reg_info.regnum_dwarf);
489 } else if (name == "generic") {
491 } else if (name == "container-regs") {
493 } else if (name == "invalidate-regs") {
495 }
496 }
497
498 assert(reg_info.byte_size != 0);
499 registers.push_back(reg_info);
500 } else {
501 break; // ensure exit before reg_num is incremented
502 }
503 } else {
504 break;
505 }
506 }
507
508 if (registers.empty())
509 registers = GetFallbackRegisters(arch_to_use);
510
511 AddRemoteRegisters(registers, arch_to_use);
512}
513
515 return WillLaunchOrAttach();
516}
517
519 return WillLaunchOrAttach();
520}
521
523 bool wait_for_launch) {
524 return WillLaunchOrAttach();
525}
526
527Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) {
529
531 if (error.Fail())
532 return error;
533
534 error = ConnectToDebugserver(remote_url);
535 if (error.Fail())
536 return error;
537
539
541 if (pid == LLDB_INVALID_PROCESS_ID) {
542 // We don't have a valid process ID, so note that we are connected and
543 // could now request to launch or attach, or get remote process listings...
545 } else {
546 // We have a valid process
547 SetID(pid);
550 if (m_gdb_comm.GetStopReply(response)) {
551 SetLastStopPacket(response);
552
553 Target &target = GetTarget();
554 if (!target.GetArchitecture().IsValid()) {
557 } else {
560 }
561 }
562 }
563
564 const StateType state = SetThreadStopInfo(response);
565 if (state != eStateInvalid) {
566 SetPrivateState(state);
567 } else
568 error.SetErrorStringWithFormat(
569 "Process %" PRIu64 " was reported after connecting to "
570 "'%s', but state was not stopped: %s",
571 pid, remote_url.str().c_str(), StateAsCString(state));
572 } else
573 error.SetErrorStringWithFormat("Process %" PRIu64
574 " was reported after connecting to '%s', "
575 "but no stop reply packet was received",
576 pid, remote_url.str().c_str());
577 }
578
579 LLDB_LOGF(log,
580 "ProcessGDBRemote::%s pid %" PRIu64
581 ": normalizing target architecture initial triple: %s "
582 "(GetTarget().GetArchitecture().IsValid() %s, "
583 "m_gdb_comm.GetHostArchitecture().IsValid(): %s)",
584 __FUNCTION__, GetID(),
585 GetTarget().GetArchitecture().GetTriple().getTriple().c_str(),
586 GetTarget().GetArchitecture().IsValid() ? "true" : "false",
587 m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false");
588
589 if (error.Success() && !GetTarget().GetArchitecture().IsValid() &&
591 // Prefer the *process'* architecture over that of the *host*, if
592 // available.
595 else
597 }
598
599 LLDB_LOGF(log,
600 "ProcessGDBRemote::%s pid %" PRIu64
601 ": normalized target architecture triple: %s",
602 __FUNCTION__, GetID(),
603 GetTarget().GetArchitecture().GetTriple().getTriple().c_str());
604
605 return error;
606}
607
611 return error;
612}
613
614// Process Control
616 ProcessLaunchInfo &launch_info) {
619
620 LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__);
621
622 uint32_t launch_flags = launch_info.GetFlags().Get();
623 FileSpec stdin_file_spec{};
624 FileSpec stdout_file_spec{};
625 FileSpec stderr_file_spec{};
626 FileSpec working_dir = launch_info.GetWorkingDirectory();
627
628 const FileAction *file_action;
629 file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
630 if (file_action) {
631 if (file_action->GetAction() == FileAction::eFileActionOpen)
632 stdin_file_spec = file_action->GetFileSpec();
633 }
634 file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
635 if (file_action) {
636 if (file_action->GetAction() == FileAction::eFileActionOpen)
637 stdout_file_spec = file_action->GetFileSpec();
638 }
639 file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
640 if (file_action) {
641 if (file_action->GetAction() == FileAction::eFileActionOpen)
642 stderr_file_spec = file_action->GetFileSpec();
643 }
644
645 if (log) {
646 if (stdin_file_spec || stdout_file_spec || stderr_file_spec)
647 LLDB_LOGF(log,
648 "ProcessGDBRemote::%s provided with STDIO paths via "
649 "launch_info: stdin=%s, stdout=%s, stderr=%s",
650 __FUNCTION__,
651 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
652 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
653 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
654 else
655 LLDB_LOGF(log,
656 "ProcessGDBRemote::%s no STDIO paths given via launch_info",
657 __FUNCTION__);
658 }
659
660 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
661 if (stdin_file_spec || disable_stdio) {
662 // the inferior will be reading stdin from the specified file or stdio is
663 // completely disabled
664 m_stdin_forward = false;
665 } else {
666 m_stdin_forward = true;
667 }
668
669 // ::LogSetBitMask (GDBR_LOG_DEFAULT);
670 // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE |
671 // LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
672 // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD);
673 // ::LogSetLogFile ("/dev/stdout");
674
675 error = EstablishConnectionIfNeeded(launch_info);
676 if (error.Success()) {
677 PseudoTerminal pty;
678 const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0;
679
680 PlatformSP platform_sp(GetTarget().GetPlatform());
681 if (disable_stdio) {
682 // set to /dev/null unless redirected to a file above
683 if (!stdin_file_spec)
684 stdin_file_spec.SetFile(FileSystem::DEV_NULL,
685 FileSpec::Style::native);
686 if (!stdout_file_spec)
687 stdout_file_spec.SetFile(FileSystem::DEV_NULL,
688 FileSpec::Style::native);
689 if (!stderr_file_spec)
690 stderr_file_spec.SetFile(FileSystem::DEV_NULL,
691 FileSpec::Style::native);
692 } else if (platform_sp && platform_sp->IsHost()) {
693 // If the debugserver is local and we aren't disabling STDIO, lets use
694 // a pseudo terminal to instead of relying on the 'O' packets for stdio
695 // since 'O' packets can really slow down debugging if the inferior
696 // does a lot of output.
697 if ((!stdin_file_spec || !stdout_file_spec || !stderr_file_spec) &&
698 !errorToBool(pty.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY))) {
699 FileSpec secondary_name(pty.GetSecondaryName());
700
701 if (!stdin_file_spec)
702 stdin_file_spec = secondary_name;
703
704 if (!stdout_file_spec)
705 stdout_file_spec = secondary_name;
706
707 if (!stderr_file_spec)
708 stderr_file_spec = secondary_name;
709 }
710 LLDB_LOGF(
711 log,
712 "ProcessGDBRemote::%s adjusted STDIO paths for local platform "
713 "(IsHost() is true) using secondary: stdin=%s, stdout=%s, "
714 "stderr=%s",
715 __FUNCTION__,
716 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
717 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
718 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
719 }
720
721 LLDB_LOGF(log,
722 "ProcessGDBRemote::%s final STDIO paths after all "
723 "adjustments: stdin=%s, stdout=%s, stderr=%s",
724 __FUNCTION__,
725 stdin_file_spec ? stdin_file_spec.GetPath().c_str() : "<null>",
726 stdout_file_spec ? stdout_file_spec.GetPath().c_str() : "<null>",
727 stderr_file_spec ? stderr_file_spec.GetPath().c_str() : "<null>");
728
729 if (stdin_file_spec)
730 m_gdb_comm.SetSTDIN(stdin_file_spec);
731 if (stdout_file_spec)
732 m_gdb_comm.SetSTDOUT(stdout_file_spec);
733 if (stderr_file_spec)
734 m_gdb_comm.SetSTDERR(stderr_file_spec);
735
736 m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR);
737 m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError);
738
740 GetTarget().GetArchitecture().GetArchitectureName());
741
742 const char *launch_event_data = launch_info.GetLaunchEventData();
743 if (launch_event_data != nullptr && *launch_event_data != '\0')
744 m_gdb_comm.SendLaunchEventDataPacket(launch_event_data);
745
746 if (working_dir) {
747 m_gdb_comm.SetWorkingDir(working_dir);
748 }
749
750 // Send the environment and the program + arguments after we connect
752
753 {
754 // Scope for the scoped timeout object
756 std::chrono::seconds(10));
757
758 // Since we can't send argv0 separate from the executable path, we need to
759 // make sure to use the actual executable path found in the launch_info...
760 Args args = launch_info.GetArguments();
761 if (FileSpec exe_file = launch_info.GetExecutableFile())
762 args.ReplaceArgumentAtIndex(0, exe_file.GetPath(false));
763 if (llvm::Error err = m_gdb_comm.LaunchProcess(args)) {
764 error.SetErrorStringWithFormatv("Cannot launch '{0}': {1}",
765 args.GetArgumentAtIndex(0),
766 llvm::fmt_consume(std::move(err)));
767 } else {
769 }
770 }
771
773 LLDB_LOGF(log, "failed to connect to debugserver: %s",
774 error.AsCString());
776 return error;
777 }
778
780 if (m_gdb_comm.GetStopReply(response)) {
781 SetLastStopPacket(response);
782
783 const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture();
784
785 if (process_arch.IsValid()) {
786 GetTarget().MergeArchitecture(process_arch);
787 } else {
788 const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture();
789 if (host_arch.IsValid())
790 GetTarget().MergeArchitecture(host_arch);
791 }
792
794
795 if (!disable_stdio) {
798 }
799 }
800 } else {
801 LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString());
802 }
803 return error;
804}
805
806Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) {
808 // Only connect if we have a valid connect URL
810
811 if (!connect_url.empty()) {
812 LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__,
813 connect_url.str().c_str());
814 std::unique_ptr<ConnectionFileDescriptor> conn_up(
816 if (conn_up) {
817 const uint32_t max_retry_count = 50;
818 uint32_t retry_count = 0;
819 while (!m_gdb_comm.IsConnected()) {
820 if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) {
821 m_gdb_comm.SetConnection(std::move(conn_up));
822 break;
823 }
824
825 retry_count++;
826
827 if (retry_count >= max_retry_count)
828 break;
829
830 std::this_thread::sleep_for(std::chrono::milliseconds(100));
831 }
832 }
833 }
834
835 if (!m_gdb_comm.IsConnected()) {
836 if (error.Success())
837 error.SetErrorString("not connected to remote gdb server");
838 return error;
839 }
840
841 // We always seem to be able to open a connection to a local port so we need
842 // to make sure we can then send data to it. If we can't then we aren't
843 // actually connected to anything, so try and do the handshake with the
844 // remote GDB server and make sure that goes alright.
847 if (error.Success())
848 error.SetErrorString("not connected to remote gdb server");
849 return error;
850 }
851
859
860 // First dispatch any commands from the platform:
861 auto handle_cmds = [&] (const Args &args) -> void {
862 for (const Args::ArgEntry &entry : args) {
865 entry.c_str(), response);
866 }
867 };
868
869 PlatformSP platform_sp = GetTarget().GetPlatform();
870 if (platform_sp) {
871 handle_cmds(platform_sp->GetExtraStartupCommands());
872 }
873
874 // Then dispatch any process commands:
875 handle_cmds(GetExtraStartupCommands());
876
877 return error;
878}
879
883
884 // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer
885 // qProcessInfo as it will be more specific to our process.
886
887 const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture();
888 if (remote_process_arch.IsValid()) {
889 process_arch = remote_process_arch;
890 LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}",
891 process_arch.GetArchitectureName(),
892 process_arch.GetTriple().getTriple());
893 } else {
894 process_arch = m_gdb_comm.GetHostArchitecture();
895 LLDB_LOG(log,
896 "gdb-remote did not have process architecture, using gdb-remote "
897 "host architecture {0} {1}",
898 process_arch.GetArchitectureName(),
899 process_arch.GetTriple().getTriple());
900 }
901
902 AddressableBits addressable_bits = m_gdb_comm.GetAddressableBits();
903 SetAddressableBitMasks(addressable_bits);
904
905 if (process_arch.IsValid()) {
906 const ArchSpec &target_arch = GetTarget().GetArchitecture();
907 if (target_arch.IsValid()) {
908 LLDB_LOG(log, "analyzing target arch, currently {0} {1}",
909 target_arch.GetArchitectureName(),
910 target_arch.GetTriple().getTriple());
911
912 // If the remote host is ARM and we have apple as the vendor, then
913 // ARM executables and shared libraries can have mixed ARM
914 // architectures.
915 // You can have an armv6 executable, and if the host is armv7, then the
916 // system will load the best possible architecture for all shared
917 // libraries it has, so we really need to take the remote host
918 // architecture as our defacto architecture in this case.
919
920 if ((process_arch.GetMachine() == llvm::Triple::arm ||
921 process_arch.GetMachine() == llvm::Triple::thumb) &&
922 process_arch.GetTriple().getVendor() == llvm::Triple::Apple) {
923 GetTarget().SetArchitecture(process_arch);
924 LLDB_LOG(log,
925 "remote process is ARM/Apple, "
926 "setting target arch to {0} {1}",
927 process_arch.GetArchitectureName(),
928 process_arch.GetTriple().getTriple());
929 } else {
930 // Fill in what is missing in the triple
931 const llvm::Triple &remote_triple = process_arch.GetTriple();
932 llvm::Triple new_target_triple = target_arch.GetTriple();
933 if (new_target_triple.getVendorName().size() == 0) {
934 new_target_triple.setVendor(remote_triple.getVendor());
935
936 if (new_target_triple.getOSName().size() == 0) {
937 new_target_triple.setOS(remote_triple.getOS());
938
939 if (new_target_triple.getEnvironmentName().size() == 0)
940 new_target_triple.setEnvironment(remote_triple.getEnvironment());
941 }
942
943 ArchSpec new_target_arch = target_arch;
944 new_target_arch.SetTriple(new_target_triple);
945 GetTarget().SetArchitecture(new_target_arch);
946 }
947 }
948
949 LLDB_LOG(log,
950 "final target arch after adjustments for remote architecture: "
951 "{0} {1}",
952 target_arch.GetArchitectureName(),
953 target_arch.GetTriple().getTriple());
954 } else {
955 // The target doesn't have a valid architecture yet, set it from the
956 // architecture we got from the remote GDB server
957 GetTarget().SetArchitecture(process_arch);
958 }
959 }
960
961 // Target and Process are reasonably initailized;
962 // load any binaries we have metadata for / set load address.
965
966 // Find out which StructuredDataPlugins are supported by the debug monitor.
967 // These plugins transmit data over async $J packets.
968 if (StructuredData::Array *supported_packets =
970 MapSupportedStructuredDataPlugins(*supported_packets);
971
972 // If connected to LLDB ("native-signals+"), use signal defs for
973 // the remote platform. If connected to GDB, just use the standard set.
975 SetUnixSignals(std::make_shared<GDBRemoteSignals>());
976 } else {
977 PlatformSP platform_sp = GetTarget().GetPlatform();
978 if (platform_sp && platform_sp->IsConnected())
979 SetUnixSignals(platform_sp->GetUnixSignals());
980 else
981 SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture()));
982 }
983}
984
986 // The remote stub may know about the "main binary" in
987 // the context of a firmware debug session, and can
988 // give us a UUID and an address/slide of where the
989 // binary is loaded in memory.
990 UUID standalone_uuid;
991 addr_t standalone_value;
992 bool standalone_value_is_offset;
993 if (m_gdb_comm.GetProcessStandaloneBinary(standalone_uuid, standalone_value,
994 standalone_value_is_offset)) {
995 ModuleSP module_sp;
996
997 if (standalone_uuid.IsValid()) {
998 const bool force_symbol_search = true;
999 const bool notify = true;
1000 const bool set_address_in_target = true;
1001 const bool allow_memory_image_last_resort = false;
1003 this, "", standalone_uuid, standalone_value,
1004 standalone_value_is_offset, force_symbol_search, notify,
1005 set_address_in_target, allow_memory_image_last_resort);
1006 }
1007 }
1008
1009 // The remote stub may know about a list of binaries to
1010 // force load into the process -- a firmware type situation
1011 // where multiple binaries are present in virtual memory,
1012 // and we are only given the addresses of the binaries.
1013 // Not intended for use with userland debugging, when we use
1014 // a DynamicLoader plugin that knows how to find the loaded
1015 // binaries, and will track updates as binaries are added.
1016
1017 std::vector<addr_t> bin_addrs = m_gdb_comm.GetProcessStandaloneBinaries();
1018 if (bin_addrs.size()) {
1019 UUID uuid;
1020 const bool value_is_slide = false;
1021 for (addr_t addr : bin_addrs) {
1022 const bool notify = true;
1023 // First see if this is a special platform
1024 // binary that may determine the DynamicLoader and
1025 // Platform to be used in this Process and Target.
1026 if (GetTarget()
1027 .GetDebugger()
1028 .GetPlatformList()
1029 .LoadPlatformBinaryAndSetup(this, addr, notify))
1030 continue;
1031
1032 const bool force_symbol_search = true;
1033 const bool set_address_in_target = true;
1034 const bool allow_memory_image_last_resort = false;
1035 // Second manually load this binary into the Target.
1037 this, llvm::StringRef(), uuid, addr, value_is_slide,
1038 force_symbol_search, notify, set_address_in_target,
1039 allow_memory_image_last_resort);
1040 }
1041 }
1042}
1043
1045 ModuleSP module_sp = GetTarget().GetExecutableModule();
1046 if (!module_sp)
1047 return;
1048
1049 std::optional<QOffsets> offsets = m_gdb_comm.GetQOffsets();
1050 if (!offsets)
1051 return;
1052
1053 bool is_uniform =
1054 size_t(llvm::count(offsets->offsets, offsets->offsets[0])) ==
1055 offsets->offsets.size();
1056 if (!is_uniform)
1057 return; // TODO: Handle non-uniform responses.
1058
1059 bool changed = false;
1060 module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0],
1061 /*value_is_offset=*/true, changed);
1062 if (changed) {
1063 ModuleList list;
1064 list.Append(module_sp);
1066 }
1067}
1068
1070 ArchSpec process_arch;
1071 DidLaunchOrAttach(process_arch);
1072}
1073
1075 lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) {
1076 Log *log = GetLog(GDBRLog::Process);
1077 Status error;
1078
1079 LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__);
1080
1081 // Clear out and clean up from any current state
1082 Clear();
1083 if (attach_pid != LLDB_INVALID_PROCESS_ID) {
1084 error = EstablishConnectionIfNeeded(attach_info);
1085 if (error.Success()) {
1087
1088 char packet[64];
1089 const int packet_len =
1090 ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid);
1091 SetID(attach_pid);
1092 auto data_sp =
1093 std::make_shared<EventDataBytes>(llvm::StringRef(packet, packet_len));
1095 } else
1096 SetExitStatus(-1, error.AsCString());
1097 }
1098
1099 return error;
1100}
1101
1103 const char *process_name, const ProcessAttachInfo &attach_info) {
1104 Status error;
1105 // Clear out and clean up from any current state
1106 Clear();
1107
1108 if (process_name && process_name[0]) {
1109 error = EstablishConnectionIfNeeded(attach_info);
1110 if (error.Success()) {
1111 StreamString packet;
1112
1114
1115 if (attach_info.GetWaitForLaunch()) {
1117 packet.PutCString("vAttachWait");
1118 } else {
1119 if (attach_info.GetIgnoreExisting())
1120 packet.PutCString("vAttachWait");
1121 else
1122 packet.PutCString("vAttachOrWait");
1123 }
1124 } else
1125 packet.PutCString("vAttachName");
1126 packet.PutChar(';');
1127 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1130
1131 auto data_sp = std::make_shared<EventDataBytes>(packet.GetString());
1133
1134 } else
1135 SetExitStatus(-1, error.AsCString());
1136 }
1137 return error;
1138}
1139
1140llvm::Expected<TraceSupportedResponse> ProcessGDBRemote::TraceSupported() {
1142}
1143
1145 return m_gdb_comm.SendTraceStop(request, GetInterruptTimeout());
1146}
1147
1148llvm::Error ProcessGDBRemote::TraceStart(const llvm::json::Value &request) {
1150}
1151
1152llvm::Expected<std::string>
1153ProcessGDBRemote::TraceGetState(llvm::StringRef type) {
1155}
1156
1157llvm::Expected<std::vector<uint8_t>>
1160}
1161
1163 // When we exit, disconnect from the GDB server communications
1165}
1166
1168 // If you can figure out what the architecture is, fill it in here.
1169 process_arch.Clear();
1170 DidLaunchOrAttach(process_arch);
1171}
1172
1174 m_continue_c_tids.clear();
1175 m_continue_C_tids.clear();
1176 m_continue_s_tids.clear();
1177 m_continue_S_tids.clear();
1178 m_jstopinfo_sp.reset();
1179 m_jthreadsinfo_sp.reset();
1180 return Status();
1181}
1182
1184 Status error;
1185 Log *log = GetLog(GDBRLog::Process);
1186 LLDB_LOGF(log, "ProcessGDBRemote::Resume()");
1187
1188 ListenerSP listener_sp(
1189 Listener::MakeListener("gdb-remote.resume-packet-sent"));
1190 if (listener_sp->StartListeningForEvents(
1192 listener_sp->StartListeningForEvents(
1195
1196 const size_t num_threads = GetThreadList().GetSize();
1197
1198 StreamString continue_packet;
1199 bool continue_packet_error = false;
1201 std::string pid_prefix;
1203 pid_prefix = llvm::formatv("p{0:x-}.", GetID());
1204
1205 if (m_continue_c_tids.size() == num_threads ||
1206 (m_continue_c_tids.empty() && m_continue_C_tids.empty() &&
1207 m_continue_s_tids.empty() && m_continue_S_tids.empty())) {
1208 // All threads are continuing
1210 continue_packet.Format("vCont;c:{0}-1", pid_prefix);
1211 else
1212 continue_packet.PutCString("c");
1213 } else {
1214 continue_packet.PutCString("vCont");
1215
1216 if (!m_continue_c_tids.empty()) {
1217 if (m_gdb_comm.GetVContSupported('c')) {
1218 for (tid_collection::const_iterator
1219 t_pos = m_continue_c_tids.begin(),
1220 t_end = m_continue_c_tids.end();
1221 t_pos != t_end; ++t_pos)
1222 continue_packet.Format(";c:{0}{1:x-}", pid_prefix, *t_pos);
1223 } else
1224 continue_packet_error = true;
1225 }
1226
1227 if (!continue_packet_error && !m_continue_C_tids.empty()) {
1228 if (m_gdb_comm.GetVContSupported('C')) {
1229 for (tid_sig_collection::const_iterator
1230 s_pos = m_continue_C_tids.begin(),
1231 s_end = m_continue_C_tids.end();
1232 s_pos != s_end; ++s_pos)
1233 continue_packet.Format(";C{0:x-2}:{1}{2:x-}", s_pos->second,
1234 pid_prefix, s_pos->first);
1235 } else
1236 continue_packet_error = true;
1237 }
1238
1239 if (!continue_packet_error && !m_continue_s_tids.empty()) {
1240 if (m_gdb_comm.GetVContSupported('s')) {
1241 for (tid_collection::const_iterator
1242 t_pos = m_continue_s_tids.begin(),
1243 t_end = m_continue_s_tids.end();
1244 t_pos != t_end; ++t_pos)
1245 continue_packet.Format(";s:{0}{1:x-}", pid_prefix, *t_pos);
1246 } else
1247 continue_packet_error = true;
1248 }
1249
1250 if (!continue_packet_error && !m_continue_S_tids.empty()) {
1251 if (m_gdb_comm.GetVContSupported('S')) {
1252 for (tid_sig_collection::const_iterator
1253 s_pos = m_continue_S_tids.begin(),
1254 s_end = m_continue_S_tids.end();
1255 s_pos != s_end; ++s_pos)
1256 continue_packet.Format(";S{0:x-2}:{1}{2:x-}", s_pos->second,
1257 pid_prefix, s_pos->first);
1258 } else
1259 continue_packet_error = true;
1260 }
1261
1262 if (continue_packet_error)
1263 continue_packet.Clear();
1264 }
1265 } else
1266 continue_packet_error = true;
1267
1268 if (continue_packet_error) {
1269 // Either no vCont support, or we tried to use part of the vCont packet
1270 // that wasn't supported by the remote GDB server. We need to try and
1271 // make a simple packet that can do our continue
1272 const size_t num_continue_c_tids = m_continue_c_tids.size();
1273 const size_t num_continue_C_tids = m_continue_C_tids.size();
1274 const size_t num_continue_s_tids = m_continue_s_tids.size();
1275 const size_t num_continue_S_tids = m_continue_S_tids.size();
1276 if (num_continue_c_tids > 0) {
1277 if (num_continue_c_tids == num_threads) {
1278 // All threads are resuming...
1280 continue_packet.PutChar('c');
1281 continue_packet_error = false;
1282 } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 &&
1283 num_continue_s_tids == 0 && num_continue_S_tids == 0) {
1284 // Only one thread is continuing
1286 continue_packet.PutChar('c');
1287 continue_packet_error = false;
1288 }
1289 }
1290
1291 if (continue_packet_error && num_continue_C_tids > 0) {
1292 if ((num_continue_C_tids + num_continue_c_tids) == num_threads &&
1293 num_continue_C_tids > 0 && num_continue_s_tids == 0 &&
1294 num_continue_S_tids == 0) {
1295 const int continue_signo = m_continue_C_tids.front().second;
1296 // Only one thread is continuing
1297 if (num_continue_C_tids > 1) {
1298 // More that one thread with a signal, yet we don't have vCont
1299 // support and we are being asked to resume each thread with a
1300 // signal, we need to make sure they are all the same signal, or we
1301 // can't issue the continue accurately with the current support...
1302 if (num_continue_C_tids > 1) {
1303 continue_packet_error = false;
1304 for (size_t i = 1; i < m_continue_C_tids.size(); ++i) {
1305 if (m_continue_C_tids[i].second != continue_signo)
1306 continue_packet_error = true;
1307 }
1308 }
1309 if (!continue_packet_error)
1311 } else {
1312 // Set the continue thread ID
1313 continue_packet_error = false;
1315 }
1316 if (!continue_packet_error) {
1317 // Add threads continuing with the same signo...
1318 continue_packet.Printf("C%2.2x", continue_signo);
1319 }
1320 }
1321 }
1322
1323 if (continue_packet_error && num_continue_s_tids > 0) {
1324 if (num_continue_s_tids == num_threads) {
1325 // All threads are resuming...
1327
1328 continue_packet.PutChar('s');
1329
1330 continue_packet_error = false;
1331 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1332 num_continue_s_tids == 1 && num_continue_S_tids == 0) {
1333 // Only one thread is stepping
1335 continue_packet.PutChar('s');
1336 continue_packet_error = false;
1337 }
1338 }
1339
1340 if (!continue_packet_error && num_continue_S_tids > 0) {
1341 if (num_continue_S_tids == num_threads) {
1342 const int step_signo = m_continue_S_tids.front().second;
1343 // Are all threads trying to step with the same signal?
1344 continue_packet_error = false;
1345 if (num_continue_S_tids > 1) {
1346 for (size_t i = 1; i < num_threads; ++i) {
1347 if (m_continue_S_tids[i].second != step_signo)
1348 continue_packet_error = true;
1349 }
1350 }
1351 if (!continue_packet_error) {
1352 // Add threads stepping with the same signo...
1354 continue_packet.Printf("S%2.2x", step_signo);
1355 }
1356 } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 &&
1357 num_continue_s_tids == 0 && num_continue_S_tids == 1) {
1358 // Only one thread is stepping with signal
1360 continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second);
1361 continue_packet_error = false;
1362 }
1363 }
1364 }
1365
1366 if (continue_packet_error) {
1367 error.SetErrorString("can't make continue packet for this resume");
1368 } else {
1369 EventSP event_sp;
1370 if (!m_async_thread.IsJoinable()) {
1371 error.SetErrorString("Trying to resume but the async thread is dead.");
1372 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the "
1373 "async thread is dead.");
1374 return error;
1375 }
1376
1377 auto data_sp =
1378 std::make_shared<EventDataBytes>(continue_packet.GetString());
1380
1381 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1382 error.SetErrorString("Resume timed out.");
1383 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1384 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1385 error.SetErrorString("Broadcast continue, but the async thread was "
1386 "killed before we got an ack back.");
1387 LLDB_LOGF(log,
1388 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1389 "async thread was killed before we got an ack back.");
1390 return error;
1391 }
1392 }
1393 }
1394
1395 return error;
1396}
1397
1399 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1400 m_thread_ids.clear();
1401 m_thread_pcs.clear();
1402}
1403
1405 llvm::StringRef value) {
1406 m_thread_ids.clear();
1408 StringExtractorGDBRemote thread_ids{value};
1409
1410 do {
1411 auto pid_tid = thread_ids.GetPidTid(pid);
1412 if (pid_tid && pid_tid->first == pid) {
1413 lldb::tid_t tid = pid_tid->second;
1414 if (tid != LLDB_INVALID_THREAD_ID &&
1416 m_thread_ids.push_back(tid);
1417 }
1418 } while (thread_ids.GetChar() == ',');
1419
1420 return m_thread_ids.size();
1421}
1422
1424 llvm::StringRef value) {
1425 m_thread_pcs.clear();
1426 for (llvm::StringRef x : llvm::split(value, ',')) {
1428 if (llvm::to_integer(x, pc, 16))
1429 m_thread_pcs.push_back(pc);
1430 }
1431 return m_thread_pcs.size();
1432}
1433
1435 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1436
1437 if (m_jthreadsinfo_sp) {
1438 // If we have the JSON threads info, we can get the thread list from that
1439 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1440 if (thread_infos && thread_infos->GetSize() > 0) {
1441 m_thread_ids.clear();
1442 m_thread_pcs.clear();
1443 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1444 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1445 if (thread_dict) {
1446 // Set the thread stop info from the JSON dictionary
1447 SetThreadStopInfo(thread_dict);
1449 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1450 m_thread_ids.push_back(tid);
1451 }
1452 return true; // Keep iterating through all thread_info objects
1453 });
1454 }
1455 if (!m_thread_ids.empty())
1456 return true;
1457 } else {
1458 // See if we can get the thread IDs from the current stop reply packets
1459 // that might contain a "threads" key/value pair
1460
1461 if (m_last_stop_packet) {
1462 // Get the thread stop info
1464 const std::string &stop_info_str = std::string(stop_info.GetStringRef());
1465
1466 m_thread_pcs.clear();
1467 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1468 if (thread_pcs_pos != std::string::npos) {
1469 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1470 const size_t end = stop_info_str.find(';', start);
1471 if (end != std::string::npos) {
1472 std::string value = stop_info_str.substr(start, end - start);
1474 }
1475 }
1476
1477 const size_t threads_pos = stop_info_str.find(";threads:");
1478 if (threads_pos != std::string::npos) {
1479 const size_t start = threads_pos + strlen(";threads:");
1480 const size_t end = stop_info_str.find(';', start);
1481 if (end != std::string::npos) {
1482 std::string value = stop_info_str.substr(start, end - start);
1484 return true;
1485 }
1486 }
1487 }
1488 }
1489
1490 bool sequence_mutex_unavailable = false;
1491 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1492 if (sequence_mutex_unavailable) {
1493 return false; // We just didn't get the list
1494 }
1495 return true;
1496}
1497
1499 ThreadList &new_thread_list) {
1500 // locker will keep a mutex locked until it goes out of scope
1501 Log *log = GetLog(GDBRLog::Thread);
1502 LLDB_LOGV(log, "pid = {0}", GetID());
1503
1504 size_t num_thread_ids = m_thread_ids.size();
1505 // The "m_thread_ids" thread ID list should always be updated after each stop
1506 // reply packet, but in case it isn't, update it here.
1507 if (num_thread_ids == 0) {
1508 if (!UpdateThreadIDList())
1509 return false;
1510 num_thread_ids = m_thread_ids.size();
1511 }
1512
1513 ThreadList old_thread_list_copy(old_thread_list);
1514 if (num_thread_ids > 0) {
1515 for (size_t i = 0; i < num_thread_ids; ++i) {
1516 tid_t tid = m_thread_ids[i];
1517 ThreadSP thread_sp(
1518 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1519 if (!thread_sp) {
1520 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1521 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1522 thread_sp.get(), thread_sp->GetID());
1523 } else {
1524 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1525 thread_sp.get(), thread_sp->GetID());
1526 }
1527
1528 SetThreadPc(thread_sp, i);
1529 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1530 }
1531 }
1532
1533 // Whatever that is left in old_thread_list_copy are not present in
1534 // new_thread_list. Remove non-existent threads from internal id table.
1535 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1536 for (size_t i = 0; i < old_num_thread_ids; i++) {
1537 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1538 if (old_thread_sp) {
1539 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1540 m_thread_id_to_index_id_map.erase(old_thread_id);
1541 }
1542 }
1543
1544 return true;
1545}
1546
1547void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1548 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1550 ThreadGDBRemote *gdb_thread =
1551 static_cast<ThreadGDBRemote *>(thread_sp.get());
1552 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1553 if (reg_ctx_sp) {
1554 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1556 if (pc_regnum != LLDB_INVALID_REGNUM) {
1557 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1558 }
1559 }
1560 }
1561}
1562
1564 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1565 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1566 // packet
1567 if (thread_infos_sp) {
1568 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1569 if (thread_infos) {
1570 lldb::tid_t tid;
1571 const size_t n = thread_infos->GetSize();
1572 for (size_t i = 0; i < n; ++i) {
1573 StructuredData::Dictionary *thread_dict =
1574 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1575 if (thread_dict) {
1576 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1577 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1578 if (tid == thread->GetID())
1579 return (bool)SetThreadStopInfo(thread_dict);
1580 }
1581 }
1582 }
1583 }
1584 }
1585 return false;
1586}
1587
1589 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1590 // packet
1592 return true;
1593
1594 // See if we got thread stop info for any threads valid stop info reasons
1595 // threads via the "jstopinfo" packet stop reply packet key/value pair?
1596 if (m_jstopinfo_sp) {
1597 // If we have "jstopinfo" then we have stop descriptions for all threads
1598 // that have stop reasons, and if there is no entry for a thread, then it
1599 // has no stop reason.
1600 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1602 // If a thread is stopped at a breakpoint site, set that as the stop
1603 // reason even if it hasn't executed the breakpoint instruction yet.
1604 // We will silently step over the breakpoint when we resume execution
1605 // and miss the fact that this thread hit the breakpoint.
1606 const size_t num_thread_ids = m_thread_ids.size();
1607 for (size_t i = 0; i < num_thread_ids; i++) {
1608 if (m_thread_ids[i] == thread->GetID() && m_thread_pcs.size() > i) {
1609 addr_t pc = m_thread_pcs[i];
1610 lldb::BreakpointSiteSP bp_site_sp =
1611 thread->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1612 if (bp_site_sp) {
1613 if (bp_site_sp->ValidForThisThread(*thread)) {
1614 thread->SetStopInfo(
1616 *thread, bp_site_sp->GetID()));
1617 return true;
1618 }
1619 }
1620 }
1621 }
1622 thread->SetStopInfo(StopInfoSP());
1623 }
1624 return true;
1625 }
1626
1627 // Fall back to using the qThreadStopInfo packet
1628 StringExtractorGDBRemote stop_packet;
1629 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1630 return SetThreadStopInfo(stop_packet) == eStateStopped;
1631 return false;
1632}
1633
1635 ExpeditedRegisterMap &expedited_register_map, ThreadSP thread_sp) {
1636 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1637 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1638
1639 for (const auto &pair : expedited_register_map) {
1640 StringExtractor reg_value_extractor(pair.second);
1641 WritableDataBufferSP buffer_sp(
1642 new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1643 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1644 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1645 eRegisterKindProcessPlugin, pair.first);
1646 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1647 }
1648}
1649
1651 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1652 uint8_t signo, const std::string &thread_name, const std::string &reason,
1653 const std::string &description, uint32_t exc_type,
1654 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1655 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1656 // queue_serial are valid
1657 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1658 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1659
1660 if (tid == LLDB_INVALID_THREAD_ID)
1661 return nullptr;
1662
1663 ThreadSP thread_sp;
1664 // Scope for "locker" below
1665 {
1666 // m_thread_list_real does have its own mutex, but we need to hold onto the
1667 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1668 // m_thread_list_real.AddThread(...) so it doesn't change on us
1669 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1670 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1671
1672 if (!thread_sp) {
1673 // Create the thread if we need to
1674 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1675 m_thread_list_real.AddThread(thread_sp);
1676 }
1677 }
1678
1679 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1680 RegisterContextSP reg_ctx_sp(gdb_thread->GetRegisterContext());
1681
1682 reg_ctx_sp->InvalidateIfNeeded(true);
1683
1684 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1685 if (iter != m_thread_ids.end())
1686 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1687
1688 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1689
1690 if (reg_ctx_sp->ReconfigureRegisterInfo()) {
1691 // Now we have changed the offsets of all the registers, so the values
1692 // will be corrupted.
1693 reg_ctx_sp->InvalidateAllRegisters();
1694 // Expedited registers values will never contain registers that would be
1695 // resized by a reconfigure. So we are safe to continue using these
1696 // values.
1697 ParseExpeditedRegisters(expedited_register_map, thread_sp);
1698 }
1699
1700 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1701
1702 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1703 // Check if the GDB server was able to provide the queue name, kind and serial
1704 // number
1705 if (queue_vars_valid)
1706 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1707 dispatch_queue_t, associated_with_dispatch_queue);
1708 else
1709 gdb_thread->ClearQueueInfo();
1710
1711 gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);
1712
1713 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1714 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1715
1716 // Make sure we update our thread stop reason just once, but don't overwrite
1717 // the stop info for threads that haven't moved:
1718 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1719 if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1720 current_stop_info_sp) {
1721 thread_sp->SetStopInfo(current_stop_info_sp);
1722 return thread_sp;
1723 }
1724
1725 if (!thread_sp->StopInfoIsUpToDate()) {
1726 thread_sp->SetStopInfo(StopInfoSP());
1727 // If there's a memory thread backed by this thread, we need to use it to
1728 // calculate StopInfo.
1729 if (ThreadSP memory_thread_sp = m_thread_list.GetBackingThread(thread_sp))
1730 thread_sp = memory_thread_sp;
1731
1732 if (exc_type != 0) {
1733 // For thread plan async interrupt, creating stop info on the
1734 // original async interrupt request thread instead. If interrupt thread
1735 // does not exist anymore we fallback to current signal receiving thread
1736 // instead.
1737 ThreadSP interrupt_thread;
1739 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
1740 if (interrupt_thread)
1741 thread_sp = interrupt_thread;
1742 else {
1743 const size_t exc_data_size = exc_data.size();
1744 thread_sp->SetStopInfo(
1746 *thread_sp, exc_type, exc_data_size,
1747 exc_data_size >= 1 ? exc_data[0] : 0,
1748 exc_data_size >= 2 ? exc_data[1] : 0,
1749 exc_data_size >= 3 ? exc_data[2] : 0));
1750 }
1751 } else {
1752 bool handled = false;
1753 bool did_exec = false;
1754 // debugserver can send reason = "none" which is equivalent
1755 // to no reason.
1756 if (!reason.empty() && reason != "none") {
1757 if (reason == "trace") {
1758 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1759 lldb::BreakpointSiteSP bp_site_sp =
1760 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1761 pc);
1762
1763 // If the current pc is a breakpoint site then the StopInfo should be
1764 // set to Breakpoint Otherwise, it will be set to Trace.
1765 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1766 thread_sp->SetStopInfo(
1768 *thread_sp, bp_site_sp->GetID()));
1769 } else
1770 thread_sp->SetStopInfo(
1772 handled = true;
1773 } else if (reason == "breakpoint") {
1774 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1775 lldb::BreakpointSiteSP bp_site_sp =
1776 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1777 pc);
1778 if (bp_site_sp) {
1779 // If the breakpoint is for this thread, then we'll report the hit,
1780 // but if it is for another thread, we can just report no reason.
1781 // We don't need to worry about stepping over the breakpoint here,
1782 // that will be taken care of when the thread resumes and notices
1783 // that there's a breakpoint under the pc.
1784 handled = true;
1785 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1786 thread_sp->SetStopInfo(
1788 *thread_sp, bp_site_sp->GetID()));
1789 } else {
1790 StopInfoSP invalid_stop_info_sp;
1791 thread_sp->SetStopInfo(invalid_stop_info_sp);
1792 }
1793 }
1794 } else if (reason == "trap") {
1795 // Let the trap just use the standard signal stop reason below...
1796 } else if (reason == "watchpoint") {
1797 // We will have between 1 and 3 fields in the description.
1798 //
1799 // \a wp_addr which is the original start address that
1800 // lldb requested be watched, or an address that the
1801 // hardware reported. This address should be within the
1802 // range of a currently active watchpoint region - lldb
1803 // should be able to find a watchpoint with this address.
1804 //
1805 // \a wp_index is the hardware watchpoint register number.
1806 //
1807 // \a wp_hit_addr is the actual address reported by the hardware,
1808 // which may be outside the range of a region we are watching.
1809 //
1810 // On MIPS, we may get a false watchpoint exception where an
1811 // access to the same 8 byte granule as a watchpoint will trigger,
1812 // even if the access was not within the range of the watched
1813 // region. When we get a \a wp_hit_addr outside the range of any
1814 // set watchpoint, continue execution without making it visible to
1815 // the user.
1816 //
1817 // On ARM, a related issue where a large access that starts
1818 // before the watched region (and extends into the watched
1819 // region) may report a hit address before the watched region.
1820 // lldb will not find the "nearest" watchpoint to
1821 // disable/step/re-enable it, so one of the valid watchpoint
1822 // addresses should be provided as \a wp_addr.
1823 StringExtractor desc_extractor(description.c_str());
1824 // FIXME NativeThreadLinux::SetStoppedByWatchpoint sends this
1825 // up as
1826 // <address within wp range> <wp hw index> <actual accessed addr>
1827 // but this is not reading the <wp hw index>. Seems like it
1828 // wouldn't work on MIPS, where that third field is important.
1829 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1830 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1832 bool silently_continue = false;
1833 WatchpointResourceSP wp_resource_sp;
1834 if (wp_hit_addr != LLDB_INVALID_ADDRESS) {
1835 wp_resource_sp =
1837 // On MIPS, \a wp_hit_addr outside the range of a watched
1838 // region means we should silently continue, it is a false hit.
1840 if (!wp_resource_sp && core >= ArchSpec::kCore_mips_first &&
1842 silently_continue = true;
1843 }
1844 if (!wp_resource_sp && wp_addr != LLDB_INVALID_ADDRESS)
1845 wp_resource_sp = m_watchpoint_resource_list.FindByAddress(wp_addr);
1846 if (!wp_resource_sp) {
1848 LLDB_LOGF(log, "failed to find watchpoint");
1849 watch_id = LLDB_INVALID_SITE_ID;
1850 } else {
1851 // LWP_TODO: This is hardcoding a single Watchpoint in a
1852 // Resource, need to add
1853 // StopInfo::CreateStopReasonWithWatchpointResource which
1854 // represents all watchpoints that were tripped at this stop.
1855 watch_id = wp_resource_sp->GetConstituentAtIndex(0)->GetID();
1856 }
1857 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1858 *thread_sp, watch_id, silently_continue));
1859 handled = true;
1860 } else if (reason == "exception") {
1861 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1862 *thread_sp, description.c_str()));
1863 handled = true;
1864 } else if (reason == "exec") {
1865 did_exec = true;
1866 thread_sp->SetStopInfo(
1868 handled = true;
1869 } else if (reason == "processor trace") {
1870 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1871 *thread_sp, description.c_str()));
1872 } else if (reason == "fork") {
1873 StringExtractor desc_extractor(description.c_str());
1874 lldb::pid_t child_pid =
1875 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1876 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1877 thread_sp->SetStopInfo(
1878 StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));
1879 handled = true;
1880 } else if (reason == "vfork") {
1881 StringExtractor desc_extractor(description.c_str());
1882 lldb::pid_t child_pid =
1883 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1884 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1885 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1886 *thread_sp, child_pid, child_tid));
1887 handled = true;
1888 } else if (reason == "vforkdone") {
1889 thread_sp->SetStopInfo(
1891 handled = true;
1892 }
1893 } else if (!signo) {
1894 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1895 lldb::BreakpointSiteSP bp_site_sp =
1896 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1897
1898 // If a thread is stopped at a breakpoint site, set that as the stop
1899 // reason even if it hasn't executed the breakpoint instruction yet.
1900 // We will silently step over the breakpoint when we resume execution
1901 // and miss the fact that this thread hit the breakpoint.
1902 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1904 *thread_sp, bp_site_sp->GetID()));
1905 handled = true;
1906 }
1907 }
1908
1909 if (!handled && signo && !did_exec) {
1910 if (signo == SIGTRAP) {
1911 // Currently we are going to assume SIGTRAP means we are either
1912 // hitting a breakpoint or hardware single stepping.
1913 handled = true;
1914 addr_t pc =
1915 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1916 lldb::BreakpointSiteSP bp_site_sp =
1917 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1918 pc);
1919
1920 if (bp_site_sp) {
1921 // If the breakpoint is for this thread, then we'll report the hit,
1922 // but if it is for another thread, we can just report no reason.
1923 // We don't need to worry about stepping over the breakpoint here,
1924 // that will be taken care of when the thread resumes and notices
1925 // that there's a breakpoint under the pc.
1926 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1927 if (m_breakpoint_pc_offset != 0)
1928 thread_sp->GetRegisterContext()->SetPC(pc);
1929 thread_sp->SetStopInfo(
1931 *thread_sp, bp_site_sp->GetID()));
1932 } else {
1933 StopInfoSP invalid_stop_info_sp;
1934 thread_sp->SetStopInfo(invalid_stop_info_sp);
1935 }
1936 } else {
1937 // If we were stepping then assume the stop was the result of the
1938 // trace. If we were not stepping then report the SIGTRAP.
1939 // FIXME: We are still missing the case where we single step over a
1940 // trap instruction.
1941 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1942 thread_sp->SetStopInfo(
1944 else
1945 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1946 *thread_sp, signo, description.c_str()));
1947 }
1948 }
1949 if (!handled) {
1950 // For thread plan async interrupt, creating stop info on the
1951 // original async interrupt request thread instead. If interrupt
1952 // thread does not exist anymore we fallback to current signal
1953 // receiving thread instead.
1954 ThreadSP interrupt_thread;
1956 interrupt_thread = HandleThreadAsyncInterrupt(signo, description);
1957 if (interrupt_thread)
1958 thread_sp = interrupt_thread;
1959 else
1960 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1961 *thread_sp, signo, description.c_str()));
1962 }
1963 }
1964
1965 if (!description.empty()) {
1966 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1967 if (stop_info_sp) {
1968 const char *stop_info_desc = stop_info_sp->GetDescription();
1969 if (!stop_info_desc || !stop_info_desc[0])
1970 stop_info_sp->SetDescription(description.c_str());
1971 } else {
1972 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1973 *thread_sp, description.c_str()));
1974 }
1975 }
1976 }
1977 }
1978 return thread_sp;
1979}
1980
1983 const std::string &description) {
1984 ThreadSP thread_sp;
1985 {
1986 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1988 /*can_update=*/false);
1989 }
1990 if (thread_sp)
1991 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithInterrupt(
1992 *thread_sp, signo, description.c_str()));
1993 // Clear m_interrupt_tid regardless we can find original interrupt thread or
1994 // not.
1996 return thread_sp;
1997}
1998
2001 static constexpr llvm::StringLiteral g_key_tid("tid");
2002 static constexpr llvm::StringLiteral g_key_name("name");
2003 static constexpr llvm::StringLiteral g_key_reason("reason");
2004 static constexpr llvm::StringLiteral g_key_metype("metype");
2005 static constexpr llvm::StringLiteral g_key_medata("medata");
2006 static constexpr llvm::StringLiteral g_key_qaddr("qaddr");
2007 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
2008 "dispatch_queue_t");
2009 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
2010 "associated_with_dispatch_queue");
2011 static constexpr llvm::StringLiteral g_key_queue_name("qname");
2012 static constexpr llvm::StringLiteral g_key_queue_kind("qkind");
2013 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");
2014 static constexpr llvm::StringLiteral g_key_registers("registers");
2015 static constexpr llvm::StringLiteral g_key_memory("memory");
2016 static constexpr llvm::StringLiteral g_key_description("description");
2017 static constexpr llvm::StringLiteral g_key_signal("signal");
2018
2019 // Stop with signal and thread info
2021 uint8_t signo = 0;
2022 std::string value;
2023 std::string thread_name;
2024 std::string reason;
2025 std::string description;
2026 uint32_t exc_type = 0;
2027 std::vector<addr_t> exc_data;
2028 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2029 ExpeditedRegisterMap expedited_register_map;
2030 bool queue_vars_valid = false;
2031 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2032 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2033 std::string queue_name;
2034 QueueKind queue_kind = eQueueKindUnknown;
2035 uint64_t queue_serial_number = 0;
2036 // Iterate through all of the thread dictionary key/value pairs from the
2037 // structured data dictionary
2038
2039 // FIXME: we're silently ignoring invalid data here
2040 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
2041 &signo, &reason, &description, &exc_type, &exc_data,
2042 &thread_dispatch_qaddr, &queue_vars_valid,
2043 &associated_with_dispatch_queue, &dispatch_queue_t,
2044 &queue_name, &queue_kind, &queue_serial_number](
2045 llvm::StringRef key,
2046 StructuredData::Object *object) -> bool {
2047 if (key == g_key_tid) {
2048 // thread in big endian hex
2049 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
2050 } else if (key == g_key_metype) {
2051 // exception type in big endian hex
2052 exc_type = object->GetUnsignedIntegerValue(0);
2053 } else if (key == g_key_medata) {
2054 // exception data in big endian hex
2055 StructuredData::Array *array = object->GetAsArray();
2056 if (array) {
2057 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
2058 exc_data.push_back(object->GetUnsignedIntegerValue());
2059 return true; // Keep iterating through all array items
2060 });
2061 }
2062 } else if (key == g_key_name) {
2063 thread_name = std::string(object->GetStringValue());
2064 } else if (key == g_key_qaddr) {
2065 thread_dispatch_qaddr =
2066 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
2067 } else if (key == g_key_queue_name) {
2068 queue_vars_valid = true;
2069 queue_name = std::string(object->GetStringValue());
2070 } else if (key == g_key_queue_kind) {
2071 std::string queue_kind_str = std::string(object->GetStringValue());
2072 if (queue_kind_str == "serial") {
2073 queue_vars_valid = true;
2074 queue_kind = eQueueKindSerial;
2075 } else if (queue_kind_str == "concurrent") {
2076 queue_vars_valid = true;
2077 queue_kind = eQueueKindConcurrent;
2078 }
2079 } else if (key == g_key_queue_serial_number) {
2080 queue_serial_number = object->GetUnsignedIntegerValue(0);
2081 if (queue_serial_number != 0)
2082 queue_vars_valid = true;
2083 } else if (key == g_key_dispatch_queue_t) {
2084 dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2085 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2086 queue_vars_valid = true;
2087 } else if (key == g_key_associated_with_dispatch_queue) {
2088 queue_vars_valid = true;
2089 bool associated = object->GetBooleanValue();
2090 if (associated)
2091 associated_with_dispatch_queue = eLazyBoolYes;
2092 else
2093 associated_with_dispatch_queue = eLazyBoolNo;
2094 } else if (key == g_key_reason) {
2095 reason = std::string(object->GetStringValue());
2096 } else if (key == g_key_description) {
2097 description = std::string(object->GetStringValue());
2098 } else if (key == g_key_registers) {
2099 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2100
2101 if (registers_dict) {
2102 registers_dict->ForEach(
2103 [&expedited_register_map](llvm::StringRef key,
2104 StructuredData::Object *object) -> bool {
2105 uint32_t reg;
2106 if (llvm::to_integer(key, reg))
2107 expedited_register_map[reg] =
2108 std::string(object->GetStringValue());
2109 return true; // Keep iterating through all array items
2110 });
2111 }
2112 } else if (key == g_key_memory) {
2113 StructuredData::Array *array = object->GetAsArray();
2114 if (array) {
2115 array->ForEach([this](StructuredData::Object *object) -> bool {
2116 StructuredData::Dictionary *mem_cache_dict =
2117 object->GetAsDictionary();
2118 if (mem_cache_dict) {
2119 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2120 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2121 "address", mem_cache_addr)) {
2122 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2123 llvm::StringRef str;
2124 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2125 StringExtractor bytes(str);
2126 bytes.SetFilePos(0);
2127
2128 const size_t byte_size = bytes.GetStringRef().size() / 2;
2129 WritableDataBufferSP data_buffer_sp(
2130 new DataBufferHeap(byte_size, 0));
2131 const size_t bytes_copied =
2132 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2133 if (bytes_copied == byte_size)
2134 m_memory_cache.AddL1CacheData(mem_cache_addr,
2135 data_buffer_sp);
2136 }
2137 }
2138 }
2139 }
2140 return true; // Keep iterating through all array items
2141 });
2142 }
2143
2144 } else if (key == g_key_signal)
2145 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2146 return true; // Keep iterating through all dictionary key/value pairs
2147 });
2148
2149 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2150 reason, description, exc_type, exc_data,
2151 thread_dispatch_qaddr, queue_vars_valid,
2152 associated_with_dispatch_queue, dispatch_queue_t,
2153 queue_name, queue_kind, queue_serial_number);
2154}
2155
2158 stop_packet.SetFilePos(0);
2159 const char stop_type = stop_packet.GetChar();
2160 switch (stop_type) {
2161 case 'T':
2162 case 'S': {
2163 // This is a bit of a hack, but it is required. If we did exec, we need to
2164 // clear our thread lists and also know to rebuild our dynamic register
2165 // info before we lookup and threads and populate the expedited register
2166 // values so we need to know this right away so we can cleanup and update
2167 // our registers.
2168 const uint32_t stop_id = GetStopID();
2169 if (stop_id == 0) {
2170 // Our first stop, make sure we have a process ID, and also make sure we
2171 // know about our registers
2173 SetID(pid);
2175 }
2176 // Stop with signal and thread info
2179 const uint8_t signo = stop_packet.GetHexU8();
2180 llvm::StringRef key;
2181 llvm::StringRef value;
2182 std::string thread_name;
2183 std::string reason;
2184 std::string description;
2185 uint32_t exc_type = 0;
2186 std::vector<addr_t> exc_data;
2187 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2188 bool queue_vars_valid =
2189 false; // says if locals below that start with "queue_" are valid
2190 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2191 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2192 std::string queue_name;
2193 QueueKind queue_kind = eQueueKindUnknown;
2194 uint64_t queue_serial_number = 0;
2195 ExpeditedRegisterMap expedited_register_map;
2196 AddressableBits addressable_bits;
2197 while (stop_packet.GetNameColonValue(key, value)) {
2198 if (key.compare("metype") == 0) {
2199 // exception type in big endian hex
2200 value.getAsInteger(16, exc_type);
2201 } else if (key.compare("medata") == 0) {
2202 // exception data in big endian hex
2203 uint64_t x;
2204 value.getAsInteger(16, x);
2205 exc_data.push_back(x);
2206 } else if (key.compare("thread") == 0) {
2207 // thread-id
2208 StringExtractorGDBRemote thread_id{value};
2209 auto pid_tid = thread_id.GetPidTid(pid);
2210 if (pid_tid) {
2211 stop_pid = pid_tid->first;
2212 tid = pid_tid->second;
2213 } else
2215 } else if (key.compare("threads") == 0) {
2216 std::lock_guard<std::recursive_mutex> guard(
2219 } else if (key.compare("thread-pcs") == 0) {
2220 m_thread_pcs.clear();
2221 // A comma separated list of all threads in the current
2222 // process that includes the thread for this stop reply packet
2224 while (!value.empty()) {
2225 llvm::StringRef pc_str;
2226 std::tie(pc_str, value) = value.split(',');
2227 if (pc_str.getAsInteger(16, pc))
2229 m_thread_pcs.push_back(pc);
2230 }
2231 } else if (key.compare("jstopinfo") == 0) {
2232 StringExtractor json_extractor(value);
2233 std::string json;
2234 // Now convert the HEX bytes into a string value
2235 json_extractor.GetHexByteString(json);
2236
2237 // This JSON contains thread IDs and thread stop info for all threads.
2238 // It doesn't contain expedited registers, memory or queue info.
2240 } else if (key.compare("hexname") == 0) {
2241 StringExtractor name_extractor(value);
2242 std::string name;
2243 // Now convert the HEX bytes into a string value
2244 name_extractor.GetHexByteString(thread_name);
2245 } else if (key.compare("name") == 0) {
2246 thread_name = std::string(value);
2247 } else if (key.compare("qaddr") == 0) {
2248 value.getAsInteger(16, thread_dispatch_qaddr);
2249 } else if (key.compare("dispatch_queue_t") == 0) {
2250 queue_vars_valid = true;
2251 value.getAsInteger(16, dispatch_queue_t);
2252 } else if (key.compare("qname") == 0) {
2253 queue_vars_valid = true;
2254 StringExtractor name_extractor(value);
2255 // Now convert the HEX bytes into a string value
2256 name_extractor.GetHexByteString(queue_name);
2257 } else if (key.compare("qkind") == 0) {
2258 queue_kind = llvm::StringSwitch<QueueKind>(value)
2259 .Case("serial", eQueueKindSerial)
2260 .Case("concurrent", eQueueKindConcurrent)
2261 .Default(eQueueKindUnknown);
2262 queue_vars_valid = queue_kind != eQueueKindUnknown;
2263 } else if (key.compare("qserialnum") == 0) {
2264 if (!value.getAsInteger(0, queue_serial_number))
2265 queue_vars_valid = true;
2266 } else if (key.compare("reason") == 0) {
2267 reason = std::string(value);
2268 } else if (key.compare("description") == 0) {
2269 StringExtractor desc_extractor(value);
2270 // Now convert the HEX bytes into a string value
2271 desc_extractor.GetHexByteString(description);
2272 } else if (key.compare("memory") == 0) {
2273 // Expedited memory. GDB servers can choose to send back expedited
2274 // memory that can populate the L1 memory cache in the process so that
2275 // things like the frame pointer backchain can be expedited. This will
2276 // help stack backtracing be more efficient by not having to send as
2277 // many memory read requests down the remote GDB server.
2278
2279 // Key/value pair format: memory:<addr>=<bytes>;
2280 // <addr> is a number whose base will be interpreted by the prefix:
2281 // "0x[0-9a-fA-F]+" for hex
2282 // "0[0-7]+" for octal
2283 // "[1-9]+" for decimal
2284 // <bytes> is native endian ASCII hex bytes just like the register
2285 // values
2286 llvm::StringRef addr_str, bytes_str;
2287 std::tie(addr_str, bytes_str) = value.split('=');
2288 if (!addr_str.empty() && !bytes_str.empty()) {
2289 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2290 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2291 StringExtractor bytes(bytes_str);
2292 const size_t byte_size = bytes.GetBytesLeft() / 2;
2293 WritableDataBufferSP data_buffer_sp(
2294 new DataBufferHeap(byte_size, 0));
2295 const size_t bytes_copied =
2296 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2297 if (bytes_copied == byte_size)
2298 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2299 }
2300 }
2301 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2302 key.compare("awatch") == 0) {
2303 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2305 value.getAsInteger(16, wp_addr);
2306
2307 WatchpointResourceSP wp_resource_sp =
2309
2310 // Rewrite gdb standard watch/rwatch/awatch to
2311 // "reason:watchpoint" + "description:ADDR",
2312 // which is parsed in SetThreadStopInfo.
2313 reason = "watchpoint";
2314 StreamString ostr;
2315 ostr.Printf("%" PRIu64, wp_addr);
2316 description = std::string(ostr.GetString());
2317 } else if (key.compare("library") == 0) {
2318 auto error = LoadModules();
2319 if (error) {
2321 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2322 }
2323 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2324 // fork includes child pid/tid in thread-id format
2325 StringExtractorGDBRemote thread_id{value};
2326 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2327 if (!pid_tid) {
2329 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2331 }
2332
2333 reason = key.str();
2334 StreamString ostr;
2335 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2336 description = std::string(ostr.GetString());
2337 } else if (key.compare("addressing_bits") == 0) {
2338 uint64_t addressing_bits;
2339 if (!value.getAsInteger(0, addressing_bits)) {
2340 addressable_bits.SetAddressableBits(addressing_bits);
2341 }
2342 } else if (key.compare("low_mem_addressing_bits") == 0) {
2343 uint64_t addressing_bits;
2344 if (!value.getAsInteger(0, addressing_bits)) {
2345 addressable_bits.SetLowmemAddressableBits(addressing_bits);
2346 }
2347 } else if (key.compare("high_mem_addressing_bits") == 0) {
2348 uint64_t addressing_bits;
2349 if (!value.getAsInteger(0, addressing_bits)) {
2350 addressable_bits.SetHighmemAddressableBits(addressing_bits);
2351 }
2352 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2353 uint32_t reg = UINT32_MAX;
2354 if (!key.getAsInteger(16, reg))
2355 expedited_register_map[reg] = std::string(std::move(value));
2356 }
2357 }
2358
2359 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2360 Log *log = GetLog(GDBRLog::Process);
2361 LLDB_LOG(log,
2362 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2363 stop_pid, pid);
2364 return eStateInvalid;
2365 }
2366
2367 if (tid == LLDB_INVALID_THREAD_ID) {
2368 // A thread id may be invalid if the response is old style 'S' packet
2369 // which does not provide the
2370 // thread information. So update the thread list and choose the first
2371 // one.
2373
2374 if (!m_thread_ids.empty()) {
2375 tid = m_thread_ids.front();
2376 }
2377 }
2378
2379 SetAddressableBitMasks(addressable_bits);
2380
2381 ThreadSP thread_sp = SetThreadStopInfo(
2382 tid, expedited_register_map, signo, thread_name, reason, description,
2383 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2384 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2385 queue_kind, queue_serial_number);
2386
2387 return eStateStopped;
2388 } break;
2389
2390 case 'W':
2391 case 'X':
2392 // process exited
2393 return eStateExited;
2394
2395 default:
2396 break;
2397 }
2398 return eStateInvalid;
2399}
2400
2402 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2403
2404 m_thread_ids.clear();
2405 m_thread_pcs.clear();
2406
2407 // Set the thread stop info. It might have a "threads" key whose value is a
2408 // list of all thread IDs in the current process, so m_thread_ids might get
2409 // set.
2410 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2411 if (m_thread_ids.empty()) {
2412 // No, we need to fetch the thread list manually
2414 }
2415
2416 // We might set some stop info's so make sure the thread list is up to
2417 // date before we do that or we might overwrite what was computed here.
2419
2422 m_last_stop_packet.reset();
2423
2424 // If we have queried for a default thread id
2428 }
2429
2430 // Let all threads recover from stopping and do any clean up based on the
2431 // previous thread state (if any).
2433}
2434
2436 Status error;
2437
2439 // We are being asked to halt during an attach. We used to just close our
2440 // file handle and debugserver will go away, but with remote proxies, it
2441 // is better to send a positive signal, so let's send the interrupt first...
2442 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2444 } else
2445 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2446 return error;
2447}
2448
2450 Status error;
2451 Log *log = GetLog(GDBRLog::Process);
2452 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2453
2454 error = m_gdb_comm.Detach(keep_stopped);
2455 if (log) {
2456 if (error.Success())
2457 log->PutCString(
2458 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2459 else
2460 LLDB_LOGF(log,
2461 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2462 error.AsCString() ? error.AsCString() : "<unknown error>");
2463 }
2464
2465 if (!error.Success())
2466 return error;
2467
2468 // Sleep for one second to let the process get all detached...
2470
2473
2474 // KillDebugserverProcess ();
2475 return error;
2476}
2477
2479 Log *log = GetLog(GDBRLog::Process);
2480 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2481
2482 // Interrupt if our inferior is running...
2483 int exit_status = SIGABRT;
2484 std::string exit_string;
2485
2486 if (m_gdb_comm.IsConnected()) {
2488 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2489
2490 if (kill_res) {
2491 exit_status = kill_res.get();
2492#if defined(__APPLE__)
2493 // For Native processes on Mac OS X, we launch through the Host
2494 // Platform, then hand the process off to debugserver, which becomes
2495 // the parent process through "PT_ATTACH". Then when we go to kill
2496 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2497 // we call waitpid which returns with no error and the correct
2498 // status. But amusingly enough that doesn't seem to actually reap
2499 // the process, but instead it is left around as a Zombie. Probably
2500 // the kernel is in the process of switching ownership back to lldb
2501 // which was the original parent, and gets confused in the handoff.
2502 // Anyway, so call waitpid here to finally reap it.
2503 PlatformSP platform_sp(GetTarget().GetPlatform());
2504 if (platform_sp && platform_sp->IsHost()) {
2505 int status;
2506 ::pid_t reap_pid;
2507 reap_pid = waitpid(GetID(), &status, WNOHANG);
2508 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2509 }
2510#endif
2512 exit_string.assign("killed");
2513 } else {
2514 exit_string.assign(llvm::toString(kill_res.takeError()));
2515 }
2516 } else {
2517 exit_string.assign("killed or interrupted while attaching.");
2518 }
2519 } else {
2520 // If we missed setting the exit status on the way out, do it here.
2521 // NB set exit status can be called multiple times, the first one sets the
2522 // status.
2523 exit_string.assign("destroying when not connected to debugserver");
2524 }
2525
2526 SetExitStatus(exit_status, exit_string.c_str());
2527
2530 return Status();
2531}
2532
2534 const StringExtractorGDBRemote &response) {
2535 const bool did_exec =
2536 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2537 if (did_exec) {
2538 Log *log = GetLog(GDBRLog::Process);
2539 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2540
2545 }
2546
2547 m_last_stop_packet = response;
2548}
2549
2551 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2552}
2553
2554// Process Queries
2555
2558}
2559
2561 // request the link map address via the $qShlibInfoAddr packet
2563
2564 // the loaded module list can also provides a link map address
2565 if (addr == LLDB_INVALID_ADDRESS) {
2566 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2567 if (!list) {
2568 Log *log = GetLog(GDBRLog::Process);
2569 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2570 } else {
2571 addr = list->m_link_map;
2572 }
2573 }
2574
2575 return addr;
2576}
2577
2579 // See if the GDB remote client supports the JSON threads info. If so, we
2580 // gather stop info for all threads, expedited registers, expedited memory,
2581 // runtime queue information (iOS and MacOSX only), and more. Expediting
2582 // memory will help stack backtracing be much faster. Expediting registers
2583 // will make sure we don't have to read the thread registers for GPRs.
2585
2586 if (m_jthreadsinfo_sp) {
2587 // Now set the stop info for each thread and also expedite any registers
2588 // and memory that was in the jThreadsInfo response.
2589 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2590 if (thread_infos) {
2591 const size_t n = thread_infos->GetSize();
2592 for (size_t i = 0; i < n; ++i) {
2593 StructuredData::Dictionary *thread_dict =
2594 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2595 if (thread_dict)
2596 SetThreadStopInfo(thread_dict);
2597 }
2598 }
2599 }
2600}
2601
2602// Process Memory
2603size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2604 Status &error) {
2606 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2607 // M and m packets take 2 bytes for 1 byte of memory
2608 size_t max_memory_size =
2609 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2610 if (size > max_memory_size) {
2611 // Keep memory read sizes down to a sane limit. This function will be
2612 // called multiple times in order to complete the task by
2613 // lldb_private::Process so it is ok to do this.
2614 size = max_memory_size;
2615 }
2616
2617 char packet[64];
2618 int packet_len;
2619 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2620 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2621 (uint64_t)size);
2622 assert(packet_len + 1 < (int)sizeof(packet));
2623 UNUSED_IF_ASSERT_DISABLED(packet_len);
2624 StringExtractorGDBRemote response;
2625 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2628 if (response.IsNormalResponse()) {
2629 error.Clear();
2630 if (binary_memory_read) {
2631 // The lower level GDBRemoteCommunication packet receive layer has
2632 // already de-quoted any 0x7d character escaping that was present in
2633 // the packet
2634
2635 size_t data_received_size = response.GetBytesLeft();
2636 if (data_received_size > size) {
2637 // Don't write past the end of BUF if the remote debug server gave us
2638 // too much data for some reason.
2639 data_received_size = size;
2640 }
2641 memcpy(buf, response.GetStringRef().data(), data_received_size);
2642 return data_received_size;
2643 } else {
2644 return response.GetHexBytes(
2645 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2646 }
2647 } else if (response.IsErrorResponse())
2648 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2649 else if (response.IsUnsupportedResponse())
2650 error.SetErrorStringWithFormat(
2651 "GDB server does not support reading memory");
2652 else
2653 error.SetErrorStringWithFormat(
2654 "unexpected response to GDB server memory read packet '%s': '%s'",
2655 packet, response.GetStringRef().data());
2656 } else {
2657 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2658 }
2659 return 0;
2660}
2661
2664}
2665
2666llvm::Expected<std::vector<uint8_t>>
2668 int32_t type) {
2669 // By this point ReadMemoryTags has validated that tagging is enabled
2670 // for this target/process/address.
2671 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2672 if (!buffer_sp) {
2673 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2674 "Error reading memory tags from remote");
2675 }
2676
2677 // Return the raw tag data
2678 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2679 std::vector<uint8_t> got;
2680 got.reserve(tag_data.size());
2681 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2682 return got;
2683}
2684
2686 int32_t type,
2687 const std::vector<uint8_t> &tags) {
2688 // By now WriteMemoryTags should have validated that tagging is enabled
2689 // for this target/process.
2690 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2691}
2692
2694 std::vector<ObjectFile::LoadableData> entries) {
2695 Status error;
2696 // Sort the entries by address because some writes, like those to flash
2697 // memory, must happen in order of increasing address.
2698 std::stable_sort(
2699 std::begin(entries), std::end(entries),
2701 return a.Dest < b.Dest;
2702 });
2703 m_allow_flash_writes = true;
2705 if (error.Success())
2706 error = FlashDone();
2707 else
2708 // Even though some of the writing failed, try to send a flash done if some
2709 // of the writing succeeded so the flash state is reset to normal, but
2710 // don't stomp on the error status that was set in the write failure since
2711 // that's the one we want to report back.
2712 FlashDone();
2713 m_allow_flash_writes = false;
2714 return error;
2715}
2716
2718 auto size = m_erased_flash_ranges.GetSize();
2719 for (size_t i = 0; i < size; ++i)
2721 return true;
2722 return false;
2723}
2724
2726 Status status;
2727
2728 MemoryRegionInfo region;
2729 status = GetMemoryRegionInfo(addr, region);
2730 if (!status.Success())
2731 return status;
2732
2733 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2734 // but we'll disallow it to be safe and to keep the logic simple by worring
2735 // about only one region's block size. DoMemoryWrite is this function's
2736 // primary user, and it can easily keep writes within a single memory region
2737 if (addr + size > region.GetRange().GetRangeEnd()) {
2738 status.SetErrorString("Unable to erase flash in multiple regions");
2739 return status;
2740 }
2741
2742 uint64_t blocksize = region.GetBlocksize();
2743 if (blocksize == 0) {
2744 status.SetErrorString("Unable to erase flash because blocksize is 0");
2745 return status;
2746 }
2747
2748 // Erasures can only be done on block boundary adresses, so round down addr
2749 // and round up size
2750 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2751 size += (addr - block_start_addr);
2752 if ((size % blocksize) != 0)
2753 size += (blocksize - size % blocksize);
2754
2755 FlashRange range(block_start_addr, size);
2756
2757 if (HasErased(range))
2758 return status;
2759
2760 // We haven't erased the entire range, but we may have erased part of it.
2761 // (e.g., block A is already erased and range starts in A and ends in B). So,
2762 // adjust range if necessary to exclude already erased blocks.
2764 // Assuming that writes and erasures are done in increasing addr order,
2765 // because that is a requirement of the vFlashWrite command. Therefore, we
2766 // only need to look at the last range in the list for overlap.
2767 const auto &last_range = *m_erased_flash_ranges.Back();
2768 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2769 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2770 // overlap will be less than range.GetByteSize() or else HasErased()
2771 // would have been true
2772 range.SetByteSize(range.GetByteSize() - overlap);
2773 range.SetRangeBase(range.GetRangeBase() + overlap);
2774 }
2775 }
2776
2777 StreamString packet;
2778 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2779 (uint64_t)range.GetByteSize());
2780
2781 StringExtractorGDBRemote response;
2782 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2785 if (response.IsOKResponse()) {
2786 m_erased_flash_ranges.Insert(range, true);
2787 } else {
2788 if (response.IsErrorResponse())
2789 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2790 addr);
2791 else if (response.IsUnsupportedResponse())
2792 status.SetErrorStringWithFormat("GDB server does not support flashing");
2793 else
2795 "unexpected response to GDB server flash erase packet '%s': '%s'",
2796 packet.GetData(), response.GetStringRef().data());
2797 }
2798 } else {
2799 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2800 packet.GetData());
2801 }
2802 return status;
2803}
2804
2806 Status status;
2807 // If we haven't erased any blocks, then we must not have written anything
2808 // either, so there is no need to actually send a vFlashDone command
2810 return status;
2811 StringExtractorGDBRemote response;
2812 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2815 if (response.IsOKResponse()) {
2817 } else {
2818 if (response.IsErrorResponse())
2819 status.SetErrorStringWithFormat("flash done failed");
2820 else if (response.IsUnsupportedResponse())
2821 status.SetErrorStringWithFormat("GDB server does not support flashing");
2822 else
2824 "unexpected response to GDB server flash done packet: '%s'",
2825 response.GetStringRef().data());
2826 }
2827 } else {
2828 status.SetErrorStringWithFormat("failed to send flash done packet");
2829 }
2830 return status;
2831}
2832
2833size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2834 size_t size, Status &error) {
2836 // M and m packets take 2 bytes for 1 byte of memory
2837 size_t max_memory_size = m_max_memory_size / 2;
2838 if (size > max_memory_size) {
2839 // Keep memory read sizes down to a sane limit. This function will be
2840 // called multiple times in order to complete the task by
2841 // lldb_private::Process so it is ok to do this.
2842 size = max_memory_size;
2843 }
2844
2845 StreamGDBRemote packet;
2846
2847 MemoryRegionInfo region;
2848 Status region_status = GetMemoryRegionInfo(addr, region);
2849
2850 bool is_flash =
2851 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2852
2853 if (is_flash) {
2854 if (!m_allow_flash_writes) {
2855 error.SetErrorString("Writing to flash memory is not allowed");
2856 return 0;
2857 }
2858 // Keep the write within a flash memory region
2859 if (addr + size > region.GetRange().GetRangeEnd())
2860 size = region.GetRange().GetRangeEnd() - addr;
2861 // Flash memory must be erased before it can be written
2862 error = FlashErase(addr, size);
2863 if (!error.Success())
2864 return 0;
2865 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2866 packet.PutEscapedBytes(buf, size);
2867 } else {
2868 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2869 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2871 }
2872 StringExtractorGDBRemote response;
2873 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2876 if (response.IsOKResponse()) {
2877 error.Clear();
2878 return size;
2879 } else if (response.IsErrorResponse())
2880 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2881 addr);
2882 else if (response.IsUnsupportedResponse())
2883 error.SetErrorStringWithFormat(
2884 "GDB server does not support writing memory");
2885 else
2886 error.SetErrorStringWithFormat(
2887 "unexpected response to GDB server memory write packet '%s': '%s'",
2888 packet.GetData(), response.GetStringRef().data());
2889 } else {
2890 error.SetErrorStringWithFormat("failed to send packet: '%s'",
2891 packet.GetData());
2892 }
2893 return 0;
2894}
2895
2897 uint32_t permissions,
2898 Status &error) {
2900 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2901
2903 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2904 if (allocated_addr != LLDB_INVALID_ADDRESS ||
2906 return allocated_addr;
2907 }
2908
2910 // Call mmap() to create memory in the inferior..
2911 unsigned prot = 0;
2912 if (permissions & lldb::ePermissionsReadable)
2913 prot |= eMmapProtRead;
2914 if (permissions & lldb::ePermissionsWritable)
2915 prot |= eMmapProtWrite;
2916 if (permissions & lldb::ePermissionsExecutable)
2917 prot |= eMmapProtExec;
2918
2919 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2921 m_addr_to_mmap_size[allocated_addr] = size;
2922 else {
2923 allocated_addr = LLDB_INVALID_ADDRESS;
2924 LLDB_LOGF(log,
2925 "ProcessGDBRemote::%s no direct stub support for memory "
2926 "allocation, and InferiorCallMmap also failed - is stub "
2927 "missing register context save/restore capability?",
2928 __FUNCTION__);
2929 }
2930 }
2931
2932 if (allocated_addr == LLDB_INVALID_ADDRESS)
2933 error.SetErrorStringWithFormat(
2934 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2935 (uint64_t)size, GetPermissionsAsCString(permissions));
2936 else
2937 error.Clear();
2938 return allocated_addr;
2939}
2940
2942 MemoryRegionInfo &region_info) {
2943
2944 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2945 return error;
2946}
2947
2950}
2951
2954}
2955
2957 Status error;
2959
2960 switch (supported) {
2961 case eLazyBoolCalculate:
2962 // We should never be deallocating memory without allocating memory first
2963 // so we should never get eLazyBoolCalculate
2964 error.SetErrorString(
2965 "tried to deallocate memory without ever allocating memory");
2966 break;
2967
2968 case eLazyBoolYes:
2969 if (!m_gdb_comm.DeallocateMemory(addr))
2970 error.SetErrorStringWithFormat(
2971 "unable to deallocate memory at 0x%" PRIx64, addr);
2972 break;
2973
2974 case eLazyBoolNo:
2975 // Call munmap() to deallocate memory in the inferior..
2976 {
2977 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2978 if (pos != m_addr_to_mmap_size.end() &&
2979 InferiorCallMunmap(this, addr, pos->second))
2980 m_addr_to_mmap_size.erase(pos);
2981 else
2982 error.SetErrorStringWithFormat(
2983 "unable to deallocate memory at 0x%" PRIx64, addr);
2984 }
2985 break;
2986 }
2987
2988 return error;
2989}
2990
2991// Process STDIO
2992size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2993 Status &error) {
2995 ConnectionStatus status;
2996 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
2997 } else if (m_stdin_forward) {
2998 m_gdb_comm.SendStdinNotification(src, src_len);
2999 }
3000 return 0;
3001}
3002
3004 Status error;
3005 assert(bp_site != nullptr);
3006
3007 // Get logging info
3009 user_id_t site_id = bp_site->GetID();
3010
3011 // Get the breakpoint address
3012 const addr_t addr = bp_site->GetLoadAddress();
3013
3014 // Log that a breakpoint was requested
3015 LLDB_LOGF(log,
3016 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3017 ") address = 0x%" PRIx64,
3018 site_id, (uint64_t)addr);
3019
3020 // Breakpoint already exists and is enabled
3021 if (bp_site->IsEnabled()) {
3022 LLDB_LOGF(log,
3023 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
3024 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
3025 site_id, (uint64_t)addr);
3026 return error;
3027 }
3028
3029 // Get the software breakpoint trap opcode size
3030 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3031
3032 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
3033 // breakpoint type is supported by the remote stub. These are set to true by
3034 // default, and later set to false only after we receive an unimplemented
3035 // response when sending a breakpoint packet. This means initially that
3036 // unless we were specifically instructed to use a hardware breakpoint, LLDB
3037 // will attempt to set a software breakpoint. HardwareRequired() also queries
3038 // a boolean variable which indicates if the user specifically asked for
3039 // hardware breakpoints. If true then we will skip over software
3040 // breakpoints.
3042 (!bp_site->HardwareRequired())) {
3043 // Try to send off a software breakpoint packet ($Z0)
3044 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3045 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
3046 if (error_no == 0) {
3047 // The breakpoint was placed successfully
3048 bp_site->SetEnabled(true);
3050 return error;
3051 }
3052
3053 // SendGDBStoppointTypePacket() will return an error if it was unable to
3054 // set this breakpoint. We need to differentiate between a error specific
3055 // to placing this breakpoint or if we have learned that this breakpoint
3056 // type is unsupported. To do this, we must test the support boolean for
3057 // this breakpoint type to see if it now indicates that this breakpoint
3058 // type is unsupported. If they are still supported then we should return
3059 // with the error code. If they are now unsupported, then we would like to
3060 // fall through and try another form of breakpoint.
3062 if (error_no != UINT8_MAX)
3063 error.SetErrorStringWithFormat(
3064 "error: %d sending the breakpoint request", error_no);
3065 else
3066 error.SetErrorString("error sending the breakpoint request");
3067 return error;
3068 }
3069
3070 // We reach here when software breakpoints have been found to be
3071 // unsupported. For future calls to set a breakpoint, we will not attempt
3072 // to set a breakpoint with a type that is known not to be supported.
3073 LLDB_LOGF(log, "Software breakpoints are unsupported");
3074
3075 // So we will fall through and try a hardware breakpoint
3076 }
3077
3078 // The process of setting a hardware breakpoint is much the same as above.
3079 // We check the supported boolean for this breakpoint type, and if it is
3080 // thought to be supported then we will try to set this breakpoint with a
3081 // hardware breakpoint.
3083 // Try to send off a hardware breakpoint packet ($Z1)
3084 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3085 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3086 if (error_no == 0) {
3087 // The breakpoint was placed successfully
3088 bp_site->SetEnabled(true);
3090 return error;
3091 }
3092
3093 // Check if the error was something other then an unsupported breakpoint
3094 // type
3096 // Unable to set this hardware breakpoint
3097 if (error_no != UINT8_MAX)
3098 error.SetErrorStringWithFormat(
3099 "error: %d sending the hardware breakpoint request "
3100 "(hardware breakpoint resources might be exhausted or unavailable)",
3101 error_no);
3102 else
3103 error.SetErrorString("error sending the hardware breakpoint request "
3104 "(hardware breakpoint resources "
3105 "might be exhausted or unavailable)");
3106 return error;
3107 }
3108
3109 // We will reach here when the stub gives an unsupported response to a
3110 // hardware breakpoint
3111 LLDB_LOGF(log, "Hardware breakpoints are unsupported");
3112
3113 // Finally we will falling through to a #trap style breakpoint
3114 }
3115
3116 // Don't fall through when hardware breakpoints were specifically requested
3117 if (bp_site->HardwareRequired()) {
3118 error.SetErrorString("hardware breakpoints are not supported");
3119 return error;
3120 }
3121
3122 // As a last resort we want to place a manual breakpoint. An instruction is
3123 // placed into the process memory using memory write packets.
3124 return EnableSoftwareBreakpoint(bp_site);
3125}
3126
3128 Status error;
3129 assert(bp_site != nullptr);
3130 addr_t addr = bp_site->GetLoadAddress();
3131 user_id_t site_id = bp_site->GetID();
3133 LLDB_LOGF(log,
3134 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3135 ") addr = 0x%8.8" PRIx64,
3136 site_id, (uint64_t)addr);
3137
3138 if (bp_site->IsEnabled()) {
3139 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3140
3141 BreakpointSite::Type bp_type = bp_site->GetType();
3142 switch (bp_type) {
3145 break;
3146
3149 addr, bp_op_size,
3151 error.SetErrorToGenericError();
3152 break;
3153
3156 addr, bp_op_size,
3158 error.SetErrorToGenericError();
3159 } break;
3160 }
3161 if (error.Success())
3162 bp_site->SetEnabled(false);
3163 } else {
3164 LLDB_LOGF(log,
3165 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3166 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3167 site_id, (uint64_t)addr);
3168 return error;
3169 }
3170
3171 if (error.Success())
3172 error.SetErrorToGenericError();
3173 return error;
3174}
3175
3176// Pre-requisite: wp != NULL.
3177static GDBStoppointType
3179 assert(wp_res_sp);
3180 bool read = wp_res_sp->WatchpointResourceRead();
3181 bool write = wp_res_sp->WatchpointResourceWrite();
3182
3183 assert((read || write) &&
3184 "WatchpointResource type is neither read nor write");
3185 if (read && write)
3186 return eWatchpointReadWrite;
3187 else if (read)
3188 return eWatchpointRead;
3189 else
3190 return eWatchpointWrite;
3191}
3192
3194 Status error;
3195 if (!wp_sp) {
3196 error.SetErrorString("No watchpoint specified");
3197 return error;
3198 }
3199 user_id_t watchID = wp_sp->GetID();
3200 addr_t addr = wp_sp->GetLoadAddress();
3202 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3203 watchID);
3204 if (wp_sp->IsEnabled()) {
3205 LLDB_LOGF(log,
3206 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3207 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3208 watchID, (uint64_t)addr);
3209 return error;
3210 }
3211
3212 bool read = wp_sp->WatchpointRead();
3213 bool write = wp_sp->WatchpointWrite() || wp_sp->WatchpointModify();
3214 size_t size = wp_sp->GetByteSize();
3215
3216 ArchSpec target_arch = GetTarget().GetArchitecture();
3217 WatchpointHardwareFeature supported_features =
3219
3220 std::vector<WatchpointResourceSP> resources =
3222 addr, size, read, write, supported_features, target_arch);
3223
3224 // LWP_TODO: Now that we know the WP Resources needed to implement this
3225 // Watchpoint, we need to look at currently allocated Resources in the
3226 // Process and if they match, or are within the same memory granule, or
3227 // overlapping memory ranges, then we need to combine them. e.g. one
3228 // Watchpoint watching 1 byte at 0x1002 and a second watchpoint watching 1
3229 // byte at 0x1003, they must use the same hardware watchpoint register
3230 // (Resource) to watch them.
3231
3232 // This may mean that an existing resource changes its type (read to
3233 // read+write) or address range it is watching, in which case the old
3234 // watchpoint needs to be disabled and the new Resource addr/size/type
3235 // watchpoint enabled.
3236
3237 // If we modify a shared Resource to accomodate this newly added Watchpoint,
3238 // and we are unable to set all of the Resources for it in the inferior, we
3239 // will return an error for this Watchpoint and the shared Resource should
3240 // be restored. e.g. this Watchpoint requires three Resources, one which
3241 // is shared with another Watchpoint. We extend the shared Resouce to
3242 // handle both Watchpoints and we try to set two new ones. But if we don't
3243 // have sufficient watchpoint register for all 3, we need to show an error
3244 // for creating this Watchpoint and we should reset the shared Resource to
3245 // its original configuration because it is no longer shared.
3246
3247 bool set_all_resources = true;
3248 std::vector<WatchpointResourceSP> succesfully_set_resources;
3249 for (const auto &wp_res_sp : resources) {
3250 addr_t addr = wp_res_sp->GetLoadAddress();
3251 size_t size = wp_res_sp->GetByteSize();
3252 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3254 m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, size,
3256 set_all_resources = false;
3257 break;
3258 } else {
3259 succesfully_set_resources.push_back(wp_res_sp);
3260 }
3261 }
3262 if (set_all_resources) {
3263 wp_sp->SetEnabled(true, notify);
3264 for (const auto &wp_res_sp : resources) {
3265 // LWP_TODO: If we expanded/reused an existing Resource,
3266 // it's already in the WatchpointResourceList.
3267 wp_res_sp->AddConstituent(wp_sp);
3269 }
3270 return error;
3271 } else {
3272 // We failed to allocate one of the resources. Unset all
3273 // of the new resources we did successfully set in the
3274 // process.
3275 for (const auto &wp_res_sp : succesfully_set_resources) {
3276 addr_t addr = wp_res_sp->GetLoadAddress();
3277 size_t size = wp_res_sp->GetByteSize();
3278 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3279 m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3281 }
3282 error.SetErrorString("Setting one of the watchpoint resources failed");
3283 }
3284 return error;
3285}
3286
3288 Status error;
3289 if (!wp_sp) {
3290 error.SetErrorString("Watchpoint argument was NULL.");
3291 return error;
3292 }
3293
3294 user_id_t watchID = wp_sp->GetID();
3295
3297
3298 addr_t addr = wp_sp->GetLoadAddress();
3299
3300 LLDB_LOGF(log,
3301 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3302 ") addr = 0x%8.8" PRIx64,
3303 watchID, (uint64_t)addr);
3304
3305 if (!wp_sp->IsEnabled()) {
3306 LLDB_LOGF(log,
3307 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3308 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3309 watchID, (uint64_t)addr);
3310 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3311 // attempt might come from the user-supplied actions, we'll route it in
3312 // order for the watchpoint object to intelligently process this action.
3313 wp_sp->SetEnabled(false, notify);
3314 return error;
3315 }
3316
3317 if (wp_sp->IsHardware()) {
3318 bool disabled_all = true;
3319
3320 std::vector<WatchpointResourceSP> unused_resources;
3321 for (const auto &wp_res_sp : m_watchpoint_resource_list.Sites()) {
3322 if (wp_res_sp->ConstituentsContains(wp_sp)) {
3323 GDBStoppointType type = GetGDBStoppointType(wp_res_sp);
3324 addr_t addr = wp_res_sp->GetLoadAddress();
3325 size_t size = wp_res_sp->GetByteSize();
3326 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, size,
3328 disabled_all = false;
3329 } else {
3330 wp_res_sp->RemoveConstituent(wp_sp);
3331 if (wp_res_sp->GetNumberOfConstituents() == 0)
3332 unused_resources.push_back(wp_res_sp);
3333 }
3334 }
3335 }
3336 for (auto &wp_res_sp : unused_resources)
3337 m_watchpoint_resource_list.Remove(wp_res_sp->GetID());
3338
3339 wp_sp->SetEnabled(false, notify);
3340 if (!disabled_all)
3341 error.SetErrorString("Failure disabling one of the watchpoint locations");
3342 }
3343 return error;
3344}
3345
3349}
3350
3352 Status error;
3353 Log *log = GetLog(GDBRLog::Process);
3354 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3355
3357 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3358 return error;
3359}
3360
3361Status
3363 // Make sure we aren't already connected?
3364 if (m_gdb_comm.IsConnected())
3365 return Status();
3366
3367 PlatformSP platform_sp(GetTarget().GetPlatform());
3368 if (platform_sp && !platform_sp->IsHost())
3369 return Status("Lost debug server connection");
3370
3371 auto error = LaunchAndConnectToDebugserver(process_info);
3372 if (error.Fail()) {
3373 const char *error_string = error.AsCString();
3374 if (error_string == nullptr)
3375 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3376 }
3377 return error;
3378}
3379#if !defined(_WIN32)
3380#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3381#endif
3382
3383#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3384static bool SetCloexecFlag(int fd) {
3385#if defined(FD_CLOEXEC)
3386 int flags = ::fcntl(fd, F_GETFD);
3387 if (flags == -1)
3388 return false;
3389 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3390#else
3391 return false;
3392#endif
3393}
3394#endif
3395
3397 const ProcessInfo &process_info) {
3398 using namespace std::placeholders; // For _1, _2, etc.
3399
3400 Status error;
3402 // If we locate debugserver, keep that located version around
3403 static FileSpec g_debugserver_file_spec;
3404
3405 ProcessLaunchInfo debugserver_launch_info;
3406 // Make debugserver run in its own session so signals generated by special
3407 // terminal key sequences (^C) don't affect debugserver.
3408 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3409
3410 const std::weak_ptr<ProcessGDBRemote> this_wp =
3411 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3412 debugserver_launch_info.SetMonitorProcessCallback(
3413 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3414 debugserver_launch_info.SetUserID(process_info.GetUserID());
3415
3416#if defined(__APPLE__)
3417 // On macOS 11, we need to support x86_64 applications translated to
3418 // arm64. We check whether a binary is translated and spawn the correct
3419 // debugserver accordingly.
3420 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3421 static_cast<int>(process_info.GetProcessID()) };
3422 struct kinfo_proc processInfo;
3423 size_t bufsize = sizeof(processInfo);
3424 if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3425 &bufsize, NULL, 0) == 0 && bufsize > 0) {
3426 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3427 FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3428 debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3429 }
3430 }
3431#endif
3432
3433 int communication_fd = -1;
3434#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3435 // Use a socketpair on non-Windows systems for security and performance
3436 // reasons.
3437 int sockets[2]; /* the pair of socket descriptors */
3438 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3439 error.SetErrorToErrno();
3440 return error;
3441 }
3442
3443 int our_socket = sockets[0];
3444 int gdb_socket = sockets[1];
3445 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3446 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3447
3448 // Don't let any child processes inherit our communication socket
3449 SetCloexecFlag(our_socket);
3450 communication_fd = gdb_socket;
3451#endif
3452
3454 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3455 nullptr, nullptr, communication_fd);
3456
3457 if (error.Success())
3458 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3459 else
3461
3463#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3464 // Our process spawned correctly, we can now set our connection to use
3465 // our end of the socket pair
3466 cleanup_our.release();
3468 std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3469#endif
3471 }
3472
3473 if (error.Fail()) {
3474 Log *log = GetLog(GDBRLog::Process);
3475
3476 LLDB_LOGF(log, "failed to start debugserver process: %s",
3477 error.AsCString());
3478 return error;
3479 }
3480
3481 if (m_gdb_comm.IsConnected()) {
3482 // Finish the connection process by doing the handshake without
3483 // connecting (send NULL URL)
3485 } else {
3486 error.SetErrorString("connection failed");
3487 }
3488 }
3489 return error;
3490}
3491
3493 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3494 int signo, // Zero for no signal
3495 int exit_status // Exit value of process if signal is zero
3496) {
3497 // "debugserver_pid" argument passed in is the process ID for debugserver
3498 // that we are tracking...
3499 Log *log = GetLog(GDBRLog::Process);
3500
3501 LLDB_LOGF(log,
3502 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3503 ", signo=%i (0x%x), exit_status=%i)",
3504 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3505
3506 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3507 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3508 static_cast<void *>(process_sp.get()));
3509 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3510 return;
3511
3512 // Sleep for a half a second to make sure our inferior process has time to
3513 // set its exit status before we set it incorrectly when both the debugserver
3514 // and the inferior process shut down.
3515 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3516
3517 // If our process hasn't yet exited, debugserver might have died. If the
3518 // process did exit, then we are reaping it.
3519 const StateType state = process_sp->GetState();
3520
3521 if (state != eStateInvalid && state != eStateUnloaded &&
3522 state != eStateExited && state != eStateDetached) {
3523 StreamString stream;
3524 if (signo == 0)
3525 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",
3526 exit_status);
3527 else {
3528 llvm::StringRef signal_name =
3529 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
3530 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";
3531 if (!signal_name.empty())
3532 stream.Format(format_str, signal_name);
3533 else
3534 stream.Format(format_str, signo);
3535 }
3536 process_sp->SetExitStatus(-1, stream.GetString());
3537 }
3538 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3539 // longer has a debugserver instance
3540 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3541}
3542
3548 }
3549}
3550
3552 static llvm::once_flag g_once_flag;
3553
3554 llvm::call_once(g_once_flag, []() {
3558 });
3559}
3560
3563 debugger, PluginProperties::GetSettingName())) {
3564 const bool is_global_setting = true;
3567 "Properties for the gdb-remote process plug-in.", is_global_setting);
3568 }
3569}
3570
3572 Log *log = GetLog(GDBRLog::Process);
3573
3574 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3575
3576 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3577 if (!m_async_thread.IsJoinable()) {
3578 // Create a thread that watches our internal state and controls which
3579 // events make it to clients (into the DCProcess event queue).
3580
3581 llvm::Expected<HostThread> async_thread =
3582 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3584 });
3585 if (!async_thread) {
3586 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3587 "failed to launch host thread: {0}");
3588 return false;
3589 }
3590 m_async_thread = *async_thread;
3591 } else
3592 LLDB_LOGF(log,
3593 "ProcessGDBRemote::%s () - Called when Async thread was "
3594 "already running.",
3595 __FUNCTION__);
3596
3597 return m_async_thread.IsJoinable();
3598}
3599
3601 Log *log = GetLog(GDBRLog::Process);
3602
3603 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3604
3605 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3606 if (m_async_thread.IsJoinable()) {
3608
3609 // This will shut down the async thread.
3610 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3611
3612 // Stop the stdio thread
3613 m_async_thread.Join(nullptr);
3615 } else
3616 LLDB_LOGF(
3617 log,
3618 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3619 __FUNCTION__);
3620}
3621
3623 Log *log = GetLog(GDBRLog::Process);
3624 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3625 __FUNCTION__, GetID());
3626
3627 EventSP event_sp;
3628
3629 // We need to ignore any packets that come in after we have
3630 // have decided the process has exited. There are some
3631 // situations, for instance when we try to interrupt a running
3632 // process and the interrupt fails, where another packet might
3633 // get delivered after we've decided to give up on the process.
3634 // But once we've decided we are done with the process we will
3635 // not be in a state to do anything useful with new packets.
3636 // So it is safer to simply ignore any remaining packets by
3637 // explicitly checking for eStateExited before reentering the
3638 // fetch loop.
3639
3640 bool done = false;
3641 while (!done && GetPrivateState() != eStateExited) {
3642 LLDB_LOGF(log,
3643 "ProcessGDBRemote::%s(pid = %" PRIu64
3644 ") listener.WaitForEvent (NULL, event_sp)...",
3645 __FUNCTION__, GetID());
3646
3647 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
3648 const uint32_t event_type = event_sp->GetType();
3649 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3650 LLDB_LOGF(log,
3651 "ProcessGDBRemote::%s(pid = %" PRIu64
3652 ") Got an event of type: %d...",
3653 __FUNCTION__, GetID(), event_type);
3654
3655 switch (event_type) {
3657 const EventDataBytes *continue_packet =
3659
3660 if (continue_packet) {
3661 const char *continue_cstr =
3662 (const char *)continue_packet->GetBytes();
3663 const size_t continue_cstr_len = continue_packet->GetByteSize();
3664 LLDB_LOGF(log,
3665 "ProcessGDBRemote::%s(pid = %" PRIu64
3666 ") got eBroadcastBitAsyncContinue: %s",
3667 __FUNCTION__, GetID(), continue_cstr);
3668
3669 if (::strstr(continue_cstr, "vAttach") == nullptr)
3671 StringExtractorGDBRemote response;
3672
3673 StateType stop_state =
3675 *this, *GetUnixSignals(),
3676 llvm::StringRef(continue_cstr, continue_cstr_len),
3677 GetInterruptTimeout(), response);
3678
3679 // We need to immediately clear the thread ID list so we are sure
3680 // to get a valid list of threads. The thread ID list might be
3681 // contained within the "response", or the stop reply packet that
3682 // caused the stop. So clear it now before we give the stop reply
3683 // packet to the process using the
3684 // SetLastStopPacket()...
3686
3687 switch (stop_state) {
3688 case eStateStopped:
3689 case eStateCrashed:
3690 case eStateSuspended:
3691 SetLastStopPacket(response);
3692 SetPrivateState(stop_state);
3693 break;
3694
3695 case eStateExited: {
3696 SetLastStopPacket(response);
3698 response.SetFilePos(1);
3699
3700 int exit_status = response.GetHexU8();
3701 std::string desc_string;
3702 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3703 llvm::StringRef desc_str;
3704 llvm::StringRef desc_token;
3705 while (response.GetNameColonValue(desc_token, desc_str)) {
3706 if (desc_token != "description")
3707 continue;
3708 StringExtractor extractor(desc_str);
3709 extractor.GetHexByteString(desc_string);
3710 }
3711 }
3712 SetExitStatus(exit_status, desc_string.c_str());
3713 done = true;
3714 break;
3715 }
3716 case eStateInvalid: {
3717 // Check to see if we were trying to attach and if we got back
3718 // the "E87" error code from debugserver -- this indicates that
3719 // the process is not debuggable. Return a slightly more
3720 // helpful error message about why the attach failed.
3721 if (::strstr(continue_cstr, "vAttach") != nullptr &&
3722 response.GetError() == 0x87) {
3723 SetExitStatus(-1, "cannot attach to process due to "
3724 "System Integrity Protection");
3725 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3726 response.GetStatus().Fail()) {
3727 SetExitStatus(-1, response.GetStatus().AsCString());
3728 } else {
3729 SetExitStatus(-1, "lost connection");
3730 }
3731 done = true;
3732 break;
3733 }
3734
3735 default:
3736 SetPrivateState(stop_state);
3737 break;
3738 } // switch(stop_state)
3739 } // if (continue_packet)
3740 } // case eBroadcastBitAsyncContinue
3741 break;
3742
3744 LLDB_LOGF(log,
3745 "ProcessGDBRemote::%s(pid = %" PRIu64
3746 ") got eBroadcastBitAsyncThreadShouldExit...",
3747 __FUNCTION__, GetID());
3748 done = true;
3749 break;
3750
3751 default:
3752 LLDB_LOGF(log,
3753 "ProcessGDBRemote::%s(pid = %" PRIu64
3754 ") got unknown event 0x%8.8x",
3755 __FUNCTION__, GetID(), event_type);
3756 done = true;
3757 break;
3758 }
3759 }
3760 } else {
3761 LLDB_LOGF(log,
3762 "ProcessGDBRemote::%s(pid = %" PRIu64
3763 ") listener.WaitForEvent (NULL, event_sp) => false",
3764 __FUNCTION__, GetID());
3765 done = true;
3766 }
3767 }
3768
3769 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
3770 __FUNCTION__, GetID());
3771
3772 return {};
3773}
3774
3775// uint32_t
3776// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3777// &matches, std::vector<lldb::pid_t> &pids)
3778//{
3779// // If we are planning to launch the debugserver remotely, then we need to
3780// fire up a debugserver
3781// // process and ask it for the list of processes. But if we are local, we
3782// can let the Host do it.
3783// if (m_local_debugserver)
3784// {
3785// return Host::ListProcessesMatchingName (name, matches, pids);
3786// }
3787// else
3788// {
3789// // FIXME: Implement talking to the remote debugserver.
3790// return 0;
3791// }
3792//
3793//}
3794//
3796 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3797 lldb::user_id_t break_loc_id) {
3798 // I don't think I have to do anything here, just make sure I notice the new
3799 // thread when it starts to
3800 // run so I can stop it if that's what I want to do.
3801 Log *log = GetLog(LLDBLog::Step);
3802 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3803 return false;
3804}
3805
3807 Log *log = GetLog(GDBRLog::Process);
3808 LLDB_LOG(log, "Check if need to update ignored signals");
3809
3810 // QPassSignals package is not supported by the server, there is no way we
3811 // can ignore any signals on server side.
3813 return Status();
3814
3815 // No signals, nothing to send.
3816 if (m_unix_signals_sp == nullptr)
3817 return Status();
3818
3819 // Signals' version hasn't changed, no need to send anything.
3820 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3821 if (new_signals_version == m_last_signals_version) {
3822 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3824 return Status();
3825 }
3826
3827 auto signals_to_ignore =
3828 m_unix_signals_sp->GetFilteredSignals(false, false, false);
3829 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3830
3831 LLDB_LOG(log,
3832 "Signals' version changed. old version={0}, new version={1}, "
3833 "signals ignored={2}, update result={3}",
3834 m_last_signals_version, new_signals_version,
3835 signals_to_ignore.size(), error);
3836
3837 if (error.Success())
3838 m_last_signals_version = new_signals_version;
3839
3840 return error;
3841}
3842
3844 Log *log = GetLog(LLDBLog::Step);
3846 if (log && log->GetVerbose())
3847 LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3848 m_thread_create_bp_sp->SetEnabled(true);
3849 } else {
3850 PlatformSP platform_sp(GetTarget().GetPlatform());
3851 if (platform_sp) {
3853 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3855 if (log && log->GetVerbose())
3856 LLDB_LOGF(
3857 log, "Successfully created new thread notification breakpoint %i",
3858 m_thread_create_bp_sp->GetID());
3859 m_thread_create_bp_sp->SetCallback(
3861 } else {
3862 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3863 }
3864 }
3865 }
3866 return m_thread_create_bp_sp.get() != nullptr;
3867}
3868
3870 Log *log = GetLog(LLDBLog::Step);
3871 if (log && log->GetVerbose())
3872 LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3873
3875 m_thread_create_bp_sp->SetEnabled(false);
3876
3877 return true;
3878}
3879
3881 if (m_dyld_up.get() == nullptr)
3882 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3883 return m_dyld_up.get();
3884}
3885
3887 int return_value;
3888 bool was_supported;
3889
3890 Status error;
3891
3892 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3893 if (return_value != 0) {
3894 if (!was_supported)
3895 error.SetErrorString("Sending events is not supported for this process.");
3896 else
3897 error.SetErrorStringWithFormat("Error sending event data: %d.",
3898 return_value);
3899 }
3900 return error;
3901}
3902
3904 DataBufferSP buf;
3906 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3907 if (response)
3908 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3909 response->length());
3910 else
3911 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
3912 }
3914}
3915
3918 StructuredData::ObjectSP object_sp;
3919
3922 SystemRuntime *runtime = GetSystemRuntime();
3923 if (runtime) {
3924 runtime->AddThreadExtendedInfoPacketHints(args_dict);
3925 }
3926 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3927
3928 StreamString packet;
3929 packet << "jThreadExtendedInfo:";
3930 args_dict->Dump(packet, false);
3931
3932 // FIXME the final character of a JSON dictionary, '}', is the escape
3933 // character in gdb-remote binary mode. lldb currently doesn't escape
3934 // these characters in its packet output -- so we add the quoted version of
3935 // the } character here manually in case we talk to a debugserver which un-
3936 // escapes the characters at packet read time.
3937 packet << (char)(0x7d ^ 0x20);
3938
3939 StringExtractorGDBRemote response;
3940 response.SetResponseValidatorToJSON();
3941 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3944 response.GetResponseType();
3945 if (response_type == StringExtractorGDBRemote::eResponse) {
3946 if (!response.Empty()) {
3947 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3948 }
3949 }
3950 }
3951 }
3952 return object_sp;
3953}
3954
3956 lldb::addr_t image_list_address, lldb::addr_t image_count) {
3957
3959 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3960 image_list_address);
3961 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3962
3963 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3964}
3965
3968
3969 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3970
3971 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3972}
3973
3975 const std::vector<lldb::addr_t> &load_addresses) {
3978
3979 for (auto addr : load_addresses)
3980 addresses->AddIntegerItem(addr);
3981
3982 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3983
3984 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3985}
3986
3989 StructuredData::ObjectSP args_dict) {
3990 StructuredData::ObjectSP object_sp;
3991
3993 // Scope for the scoped timeout object
3995 std::chrono::seconds(10));
3996
3997 StreamString packet;
3998 packet << "jGetLoadedDynamicLibrariesInfos:";
3999 args_dict->Dump(packet, false);
4000
4001 // FIXME the final character of a JSON dictionary, '}', is the escape
4002 // character in gdb-remote binary mode. lldb currently doesn't escape
4003 // these characters in its packet output -- so we add the quoted version of
4004 // the } character here manually in case we talk to a debugserver which un-
4005 // escapes the characters at packet read time.
4006 packet << (char)(0x7d ^ 0x20);
4007
4008 StringExtractorGDBRemote response;
4009 response.SetResponseValidatorToJSON();
4010 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
4013 response.GetResponseType();
4014 if (response_type == StringExtractorGDBRemote::eResponse) {
4015 if (!response.Empty()) {
4016 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4017 }
4018 }
4019 }
4020 }
4021 return object_sp;
4022}
4023
4025 StructuredData::ObjectSP object_sp;
4027
4029 StringExtractorGDBRemote response;
4030 response.SetResponseValidatorToJSON();
4031 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
4032 response) ==
4035 response.GetResponseType();
4036 if (response_type == StringExtractorGDBRemote::eResponse) {
4037 if (!response.Empty()) {
4038 object_sp = StructuredData::ParseJSON(response.GetStringRef());
4039 }
4040 }
4041 }
4042 }
4043 return object_sp;
4044}
4045
4047 StructuredData::ObjectSP object_sp;
4049
4051 StreamString packet;
4052 packet << "jGetSharedCacheInfo:";
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 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
4080 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
4081}
4082
4083// Establish the largest memory read/write payloads we should use. If the
4084// remote stub has a max packet size, stay under that size.
4085//
4086// If the remote stub's max packet size is crazy large, use a reasonable
4087// largeish default.
4088//
4089// If the remote stub doesn't advertise a max packet size, use a conservative
4090// default.
4091
4093 const uint64_t reasonable_largeish_default = 128 * 1024;
4094 const uint64_t conservative_default = 512;
4095
4096 if (m_max_memory_size == 0) {
4097 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
4098 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
4099 // Save the stub's claimed maximum packet size
4100 m_remote_stub_max_memory_size = stub_max_size;
4101
4102 // Even if the stub says it can support ginormous packets, don't exceed
4103 // our reasonable largeish default packet size.
4104 if (stub_max_size > reasonable_largeish_default) {
4105 stub_max_size = reasonable_largeish_default;
4106 }
4107
4108 // Memory packet have other overheads too like Maddr,size:#NN Instead of
4109 // calculating the bytes taken by size and addr every time, we take a
4110 // maximum guess here.
4111 if (stub_max_size > 70)
4112 stub_max_size -= 32 + 32 + 6;
4113 else {
4114 // In unlikely scenario that max packet size is less then 70, we will
4115 // hope that data being written is small enough to fit.
4117 if (log)
4118 log->Warning("Packet size is too small. "
4119 "LLDB may face problems while writing memory");
4120 }
4121
4122 m_max_memory_size = stub_max_size;
4123 } else {
4124 m_max_memory_size = conservative_default;
4125 }
4126 }
4127}
4128
4130 uint64_t user_specified_max) {
4131 if (user_specified_max != 0) {
4133
4135 if (m_remote_stub_max_memory_size < user_specified_max) {
4137 // packet size too
4138 // big, go as big
4139 // as the remote stub says we can go.
4140 } else {
4141 m_max_memory_size = user_specified_max; // user's packet size is good
4142 }
4143 } else {
4145 user_specified_max; // user's packet size is probably fine
4146 }
4147 }
4148}
4149
4150bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4151 const ArchSpec &arch,
4152 ModuleSpec &module_spec) {
4154
4155 const ModuleCacheKey key(module_file_spec.GetPath(),
4156 arch.GetTriple().getTriple());
4157 auto cached = m_cached_module_specs.find(key);
4158 if (cached != m_cached_module_specs.end()) {
4159 module_spec = cached->second;
4160 return bool(module_spec);
4161 }
4162
4163 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4164 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4165 __FUNCTION__, module_file_spec.GetPath().c_str(),
4166 arch.GetTriple().getTriple().c_str());
4167 return false;
4168 }
4169
4170 if (log) {
4171 StreamString stream;
4172 module_spec.Dump(stream);
4173 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4174 __FUNCTION__, module_file_spec.GetPath().c_str(),
4175 arch.GetTriple().getTriple().c_str(), stream.GetData());
4176 }
4177
4178 m_cached_module_specs[key] = module_spec;
4179 return true;
4180}
4181
4183 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4184 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4185 if (module_specs) {
4186 for (const FileSpec &spec : module_file_specs)
4188 triple.getTriple())] = ModuleSpec();
4189 for (const ModuleSpec &spec : *module_specs)
4190 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4191 triple.getTriple())] = spec;
4192 }
4193}
4194
4196 return m_gdb_comm.GetOSVersion();
4197}
4198
4201}
4202
4203namespace {
4204
4205typedef std::vector<std::string> stringVec;
4206
4207typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4208struct RegisterSetInfo {
4209 ConstString name;
4210};
4211
4212typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4213
4214struct GdbServerTargetInfo {
4215 std::string arch;
4216 std::string osabi;
4217 stringVec includes;
4218 RegisterSetMap reg_set_map;
4219};
4220
4221static FieldEnum::Enumerators ParseEnumEvalues(const XMLNode &enum_node) {
4222 Log *log(GetLog(GDBRLog::Process));
4223 // We will use the last instance of each value. Also we preserve the order
4224 // of declaration in the XML, as it may not be numerical.
4225 // For example, hardware may intially release with two states that softwware
4226 // can read from a register field:
4227 // 0 = startup, 1 = running
4228 // If in a future hardware release, the designers added a pre-startup state:
4229 // 0 = startup, 1 = running, 2 = pre-startup
4230 // Now it makes more sense to list them in this logical order as opposed to
4231 // numerical order:
4232 // 2 = pre-startup, 1 = startup, 0 = startup
4233 // This only matters for "register info" but let's trust what the server
4234 // chose regardless.
4235 std::map<uint64_t, FieldEnum::Enumerator> enumerators;
4236
4238 "evalue", [&enumerators, &log](const XMLNode &enumerator_node) {
4239 std::optional<llvm::StringRef> name;
4240 std::optional<uint64_t> value;
4241
4242 enumerator_node.ForEachAttribute(
4243 [&name, &value, &log](const llvm::StringRef &attr_name,
4244 const llvm::StringRef &attr_value) {
4245 if (attr_name == "name") {
4246 if (attr_value.size())
4247 name = attr_value;
4248 else
4249 LLDB_LOG(log, "ProcessGDBRemote::ParseEnumEvalues "
4250 "Ignoring empty name in evalue");
4251 } else if (attr_name == "value") {
4252 uint64_t parsed_value = 0;
4253 if (llvm::to_integer(attr_value, parsed_value))
4254 value = parsed_value;
4255 else
4256 LLDB_LOG(log,
4257 "ProcessGDBRemote::ParseEnumEvalues "
4258 "Invalid value \"{0}\" in "
4259 "evalue",
4260 attr_value.data());
4261 } else
4262 LLDB_LOG(log,
4263 "ProcessGDBRemote::ParseEnumEvalues Ignoring "
4264 "unknown attribute "
4265 "\"{0}\" in evalue",
4266 attr_name.data());
4267
4268 // Keep walking attributes.
4269 return true;
4270 });
4271
4272 if (value && name)
4273 enumerators.insert_or_assign(
4274 *value, FieldEnum::Enumerator(*value, name->str()));
4275
4276 // Find all evalue elements.
4277 return true;
4278 });
4279
4280 FieldEnum::Enumerators final_enumerators;
4281 for (auto [_, enumerator] : enumerators)
4282 final_enumerators.push_back(enumerator);
4283
4284 return final_enumerators;
4285}
4286
4287static void
4288ParseEnums(XMLNode feature_node,
4289 llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4290 Log *log(GetLog(GDBRLog::Process));
4291
4292 // The top level element is "<enum...".
4293 feature_node.ForEachChildElementWithName(
4294 "enum", [log, &registers_enum_types](const XMLNode &enum_node) {
4295 std::string id;
4296
4297 enum_node.ForEachAttribute([&id](const llvm::StringRef &attr_name,
4298 const llvm::StringRef &attr_value) {
4299 if (attr_name == "id")
4300 id = attr_value;
4301
4302 // There is also a "size" attribute that is supposed to be the size in
4303 // bytes of the register this applies to. However:
4304 // * LLDB doesn't need this information.
4305 // * It is difficult to verify because you have to wait until the
4306 // enum is applied to a field.
4307 //
4308 // So we will emit this attribute in XML for GDB's sake, but will not
4309 // bother ingesting it.
4310
4311 // Walk all attributes.
4312 return true;
4313 });
4314
4315 if (!id.empty()) {
4316 FieldEnum::Enumerators enumerators = ParseEnumEvalues(enum_node);
4317 if (!enumerators.empty()) {
4318 LLDB_LOG(log,
4319 "ProcessGDBRemote::ParseEnums Found enum type \"{0}\"",
4320 id);
4321 registers_enum_types.insert_or_assign(
4322 id, std::make_unique<FieldEnum>(id, enumerators));
4323 }
4324 }
4325
4326 // Find all <enum> elements.
4327 return true;
4328 });
4329}
4330
4331static std::vector<RegisterFlags::Field> ParseFlagsFields(
4332 XMLNode flags_node, unsigned size,
4333 const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4334 Log *log(GetLog(GDBRLog::Process));
4335 const unsigned max_start_bit = size * 8 - 1;
4336
4337 // Process the fields of this set of flags.
4338 std::vector<RegisterFlags::Field> fields;
4339 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit, &log,
4340 &registers_enum_types](
4341 const XMLNode
4342 &field_node) {
4343 std::optional<llvm::StringRef> name;
4344 std::optional<unsigned> start;
4345 std::optional<unsigned> end;
4346 std::optional<llvm::StringRef> type;
4347
4348 field_node.ForEachAttribute([&name, &start, &end, &type, max_start_bit,
4349 &log](const llvm::StringRef &attr_name,
4350 const llvm::StringRef &attr_value) {
4351 // Note that XML in general requires that each of these attributes only
4352 // appears once, so we don't have to handle that here.
4353 if (attr_name == "name") {
4354 LLDB_LOG(
4355 log,
4356 "ProcessGDBRemote::ParseFlagsFields Found field node name \"{0}\"",
4357 attr_value.data());
4358 name = attr_value;
4359 } else if (attr_name == "start") {
4360 unsigned parsed_start = 0;
4361 if (llvm::to_integer(attr_value, parsed_start)) {
4362 if (parsed_start > max_start_bit) {
4363 LLDB_LOG(log,
4364 "ProcessGDBRemote::ParseFlagsFields Invalid start {0} in "
4365 "field node, "
4366 "cannot be > {1}",
4367 parsed_start, max_start_bit);
4368 } else
4369 start = parsed_start;
4370 } else {
4371 LLDB_LOG(
4372 log,
4373 "ProcessGDBRemote::ParseFlagsFields Invalid start \"{0}\" in "
4374 "field node",
4375 attr_value.data());
4376 }
4377 } else if (attr_name == "end") {
4378 unsigned parsed_end = 0;
4379 if (llvm::to_integer(attr_value, parsed_end))
4380 if (parsed_end > max_start_bit) {
4381 LLDB_LOG(log,
4382 "ProcessGDBRemote::ParseFlagsFields Invalid end {0} in "
4383 "field node, "
4384 "cannot be > {1}",
4385 parsed_end, max_start_bit);
4386 } else
4387 end = parsed_end;
4388 else {
4389 LLDB_LOG(log,
4390 "ProcessGDBRemote::ParseFlagsFields Invalid end \"{0}\" in "
4391 "field node",
4392 attr_value.data());
4393 }
4394 } else if (attr_name == "type") {
4395 type = attr_value;
4396 } else {
4397 LLDB_LOG(
4398 log,
4399 "ProcessGDBRemote::ParseFlagsFields Ignoring unknown attribute "
4400 "\"{0}\" in field node",
4401 attr_name.data());
4402 }
4403
4404 return true; // Walk all attributes of the field.
4405 });
4406
4407 if (name && start && end) {
4408 if (*start > *end)
4409 LLDB_LOG(
4410 log,
4411 "ProcessGDBRemote::ParseFlagsFields Start {0} > end {1} in field "
4412 "\"{2}\", ignoring",
4413 *start, *end, name->data());
4414 else {
4415 if (RegisterFlags::Field::GetSizeInBits(*start, *end) > 64)
4416 LLDB_LOG(log,
4417 "ProcessGDBRemote::ParseFlagsFields Ignoring field \"{2}\" "
4418 "that has "
4419 "size > 64 bits, this is not supported",
4420 name->data());
4421 else {
4422 // A field's type may be set to the name of an enum type.
4423 const FieldEnum *enum_type = nullptr;
4424 if (type && !type->empty()) {
4425 auto found = registers_enum_types.find(*type);
4426 if (found != registers_enum_types.end()) {
4427 enum_type = found->second.get();
4428
4429 // No enumerator can exceed the range of the field itself.
4430 uint64_t max_value =
4432 for (const auto &enumerator : enum_type->GetEnumerators()) {
4433 if (enumerator.m_value > max_value) {
4434 enum_type = nullptr;
4435 LLDB_LOG(
4436 log,
4437 "ProcessGDBRemote::ParseFlagsFields In enum \"{0}\" "
4438 "evalue \"{1}\" with value {2} exceeds the maximum value "
4439 "of field \"{3}\" ({4}), ignoring enum",
4440 type->data(), enumerator.m_name, enumerator.m_value,
4441 name->data(), max_value);
4442 break;
4443 }
4444 }
4445 } else {
4446 LLDB_LOG(log,
4447 "ProcessGDBRemote::ParseFlagsFields Could not find type "
4448 "\"{0}\" "
4449 "for field \"{1}\", ignoring",
4450 type->data(), name->data());
4451 }
4452 }
4453
4454 fields.push_back(
4455 RegisterFlags::Field(name->str(), *start, *end, enum_type));
4456 }
4457 }
4458 }
4459
4460 return true; // Iterate all "field" nodes.
4461 });
4462 return fields;
4463}
4464
4465void ParseFlags(
4466 XMLNode feature_node,
4467 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,
4468 const llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4469 Log *log(GetLog(GDBRLog::Process));
4470
4471 feature_node.ForEachChildElementWithName(
4472 "flags",
4473 [&log, &registers_flags_types,
4474 &registers_enum_types](const XMLNode &flags_node) -> bool {
4475 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4476 flags_node.GetAttributeValue("id").c_str());
4477
4478 std::optional<llvm::StringRef> id;
4479 std::optional<unsigned> size;
4480 flags_node.ForEachAttribute(
4481 [&id, &size, &log](const llvm::StringRef &name,
4482 const llvm::StringRef &value) {
4483 if (name == "id") {
4484 id = value;
4485 } else if (name == "size") {
4486 unsigned parsed_size = 0;
4487 if (llvm::to_integer(value, parsed_size))
4488 size = parsed_size;
4489 else {
4490 LLDB_LOG(log,
4491 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4492 "in flags node",
4493 value.data());
4494 }
4495 } else {
4496 LLDB_LOG(log,
4497 "ProcessGDBRemote::ParseFlags Ignoring unknown "
4498 "attribute \"{0}\" in flags node",
4499 name.data());
4500 }
4501 return true; // Walk all attributes.
4502 });
4503
4504 if (id && size) {
4505 // Process the fields of this set of flags.
4506 std::vector<RegisterFlags::Field> fields =
4507 ParseFlagsFields(flags_node, *size, registers_enum_types);
4508 if (fields.size()) {
4509 // Sort so that the fields with the MSBs are first.
4510 std::sort(fields.rbegin(), fields.rend());
4511 std::vector<RegisterFlags::Field>::const_iterator overlap =
4512 std::adjacent_find(fields.begin(), fields.end(),
4513 [](const RegisterFlags::Field &lhs,
4514 const RegisterFlags::Field &rhs) {
4515 return lhs.Overlaps(rhs);
4516 });
4517
4518 // If no fields overlap, use them.
4519 if (overlap == fields.end()) {
4520 if (registers_flags_types.contains(*id)) {
4521 // In theory you could define some flag set, use it with a
4522 // register then redefine it. We do not know if anyone does
4523 // that, or what they would expect to happen in that case.
4524 //
4525 // LLDB chooses to take the first definition and ignore the rest
4526 // as waiting until everything has been processed is more
4527 // expensive and difficult. This means that pointers to flag
4528 // sets in the register info remain valid if later the flag set
4529 // is redefined. If we allowed redefinitions, LLDB would crash
4530 // when you tried to print a register that used the original
4531 // definition.
4532 LLDB_LOG(
4533 log,
4534 "ProcessGDBRemote::ParseFlags Definition of flags "
4535 "\"{0}\" shadows "
4536 "previous definition, using original definition instead.",
4537 id->data());
4538 } else {
4539 registers_flags_types.insert_or_assign(
4540 *id, std::make_unique<RegisterFlags>(id->str(), *size,
4541 std::move(fields)));
4542 }
4543 } else {
4544 // If any fields overlap, ignore the whole set of flags.
4545 std::vector<RegisterFlags::Field>::const_iterator next =
4546 std::next(overlap);
4547 LLDB_LOG(
4548 log,
4549 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4550 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4551 "overlap.",
4552 overlap->GetName().c_str(), overlap->GetStart(),
4553 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4554 next->GetEnd());
4555 }
4556 } else {
4557 LLDB_LOG(
4558 log,
4559 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4560 "\"{0}\" because it contains no fields.",
4561 id->data());
4562 }
4563 }
4564
4565 return true; // Keep iterating through all "flags" elements.
4566 });
4567}
4568
4569bool ParseRegisters(
4570 XMLNode feature_node, GdbServerTargetInfo &target_info,
4571 std::vector<DynamicRegisterInfo::Register> &registers,
4572 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types,
4573 llvm::StringMap<std::unique_ptr<FieldEnum>> &registers_enum_types) {
4574 if (!feature_node)
4575 return false;
4576
4577 Log *log(GetLog(GDBRLog::Process));
4578
4579 // Enums first because they are referenced by fields in the flags.
4580 ParseEnums(feature_node, registers_enum_types);
4581 for (const auto &enum_type : registers_enum_types)
4582 enum_type.second->DumpToLog(log);
4583
4584 ParseFlags(feature_node, registers_flags_types, registers_enum_types);
4585 for (const auto &flags : registers_flags_types)
4586 flags.second->DumpToLog(log);
4587
4588 feature_node.ForEachChildElementWithName(
4589 "reg",
4590 [&target_info, &registers, &registers_flags_types,
4591 log](const XMLNode &reg_node) -> bool {
4592 std::string gdb_group;
4593 std::string gdb_type;
4595 bool encoding_set = false;
4596 bool format_set = false;
4597
4598 // FIXME: we're silently ignoring invalid data here
4599 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4600 &encoding_set, &format_set, &reg_info,
4601 log](const llvm::StringRef &name,
4602 const llvm::StringRef &value) -> bool {
4603 if (name == "name") {
4604 reg_info.name.SetString(value);
4605 } else if (name == "bitsize") {
4606 if (llvm::to_integer(value, reg_info.byte_size))
4607 reg_info.byte_size =
4608 llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4609 } else if (name == "type") {
4610 gdb_type = value.str();
4611 } else if (name == "group") {
4612 gdb_group = value.str();
4613 } else if (name == "regnum") {
4614 llvm::to_integer(value, reg_info.regnum_remote);
4615 } else if (name == "offset") {
4616 llvm::to_integer(value, reg_info.byte_offset);
4617 } else if (name == "altname") {
4618 reg_info.alt_name.SetString(value);
4619 } else if (name == "encoding") {
4620 encoding_set = true;
4622 } else if (name == "format") {
4623 format_set = true;
4624 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4625 nullptr)
4626 .Success())
4627 reg_info.format =
4628 llvm::StringSwitch<lldb::Format>(value)
4629 .Case("vector-sint8", eFormatVectorOfSInt8)
4630 .Case("vector-uint8", eFormatVectorOfUInt8)
4631 .Case("vector-sint16", eFormatVectorOfSInt16)
4632 .Case("vector-uint16", eFormatVectorOfUInt16)
4633 .Case("vector-sint32", eFormatVectorOfSInt32)
4634 .Case("vector-uint32", eFormatVectorOfUInt32)
4635 .Case("vector-float32", eFormatVectorOfFloat32)
4636 .Case("vector-uint64", eFormatVectorOfUInt64)
4637 .Case("vector-uint128", eFormatVectorOfUInt128)
4638 .Default(eFormatInvalid);
4639 } else if (name == "group_id") {
4640 uint32_t set_id = UINT32_MAX;
4641 llvm::to_integer(value, set_id);
4642 RegisterSetMap::const_iterator pos =
4643 target_info.reg_set_map.find(set_id);
4644 if (pos != target_info.reg_set_map.end())
4645 reg_info.set_name = pos->second.name;
4646 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4647 llvm::to_integer(value, reg_info.regnum_ehframe);
4648 } else if (name == "dwarf_regnum") {
4649 llvm::to_integer(value, reg_info.regnum_dwarf);
4650 } else if (name == "generic") {
4652 } else if (name == "value_regnums") {
4654 0);
4655 } else if (name == "invalidate_regnums") {
4657 value, reg_info.invalidate_regs, 0);
4658 } else {
4659 LLDB_LOGF(log,
4660 "ProcessGDBRemote::ParseRegisters unhandled reg "
4661 "attribute %s = %s",
4662 name.data(), value.data());
4663 }
4664 return true; // Keep iterating through all attributes
4665 });
4666
4667 if (!gdb_type.empty()) {
4668 // gdb_type could reference some flags type defined in XML.
4669 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4670 registers_flags_types.find(gdb_type);
4671 if (it != registers_flags_types.end()) {
4672 auto flags_type = it->second.get();
4673 if (reg_info.byte_size == flags_type->GetSize())
4674 reg_info.flags_type = flags_type;
4675 else
4676 LLDB_LOGF(log,
4677 "ProcessGDBRemote::ParseRegisters Size of register "
4678 "flags %s (%d bytes) for "
4679 "register %s does not match the register size (%d "
4680 "bytes). Ignoring this set of flags.",
4681 flags_type->GetID().c_str(), flags_type->GetSize(),
4682 reg_info.name.AsCString(), reg_info.byte_size);
4683 }
4684
4685 // There's a slim chance that the gdb_type name is both a flags type
4686 // and a simple type. Just in case, look for that too (setting both
4687 // does no harm).
4688 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4689 if (llvm::StringRef(gdb_type).starts_with("int")) {
4690 reg_info.format = eFormatHex;
4691 reg_info.encoding = eEncodingUint;
4692 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4693 reg_info.format = eFormatAddressInfo;
4694 reg_info.encoding = eEncodingUint;
4695 } else if (gdb_type == "float") {
4696 reg_info.format = eFormatFloat;
4697 reg_info.encoding = eEncodingIEEE754;
4698 } else if (gdb_type == "aarch64v" ||
4699 llvm::StringRef(gdb_type).starts_with("vec") ||
4700 gdb_type == "i387_ext" || gdb_type == "uint128") {
4701 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
4702 // treat them as vector (similarly to xmm/ymm)
4703 reg_info.format = eFormatVectorOfUInt8;
4704 reg_info.encoding = eEncodingVector;
4705 } else {
4706 LLDB_LOGF(
4707 log,
4708 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4709 "format and encoding for gdb type %s",
4710 gdb_type.c_str());
4711 }
4712 }
4713 }
4714
4715 // Only update the register set name if we didn't get a "reg_set"
4716 // attribute. "set_name" will be empty if we didn't have a "reg_set"
4717 // attribute.
4718 if (!reg_info.set_name) {
4719 if (!gdb_group.empty()) {
4720 reg_info.set_name.SetCString(gdb_group.c_str());
4721 } else {
4722 // If no register group name provided anywhere,
4723 // we'll create a 'general' register set
4724 reg_info.set_name.SetCString("general");
4725 }
4726 }
4727
4728 if (reg_info.byte_size == 0) {
4729 LLDB_LOGF(log,
4730 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4731 __FUNCTION__, reg_info.name.AsCString());
4732 } else
4733 registers.push_back(reg_info);
4734
4735 return true; // Keep iterating through all "reg" elements
4736 });
4737 return true;
4738}
4739
4740} // namespace
4741
4742// This method fetches a register description feature xml file from
4743// the remote stub and adds registers/register groupsets/architecture
4744// information to the current process. It will call itself recursively
4745// for nested register definition files. It returns true if it was able
4746// to fetch and parse an xml file.
4748 ArchSpec &arch_to_use, std::string xml_filename,
4749 std::vector<DynamicRegisterInfo::Register> &registers) {
4750 // request the target xml file
4751 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4752 if (errorToBool(raw.takeError()))
4753 return false;
4754
4755 XMLDocument xml_document;
4756
4757 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4758 xml_filename.c_str())) {
4759 GdbServerTargetInfo target_info;
4760 std::vector<XMLNode> feature_nodes;
4761
4762 // The top level feature XML file will start with a <target> tag.
4763 XMLNode target_node = xml_document.GetRootElement("target");
4764 if (target_node) {
4765 target_node.ForEachChildElement([&target_info, &feature_nodes](
4766 const XMLNode &node) -> bool {
4767 llvm::StringRef name = node.GetName();
4768 if (name == "architecture") {
4769 node.GetElementText(target_info.arch);
4770 } else if (name == "osabi") {
4771 node.GetElementText(target_info.osabi);
4772 } else if (name == "xi:include" || name == "include") {
4773 std::string href = node.GetAttributeValue("href");
4774 if (!href.empty())
4775 target_info.includes.push_back(href);
4776 } else if (name == "feature") {
4777 feature_nodes.push_back(node);
4778 } else if (name == "groups") {
4780 "group", [&target_info](const XMLNode &node) -> bool {
4781 uint32_t set_id = UINT32_MAX;
4782 RegisterSetInfo set_info;
4783
4784 node.ForEachAttribute(
4785 [&set_id, &set_info](const llvm::StringRef &name,
4786 const llvm::StringRef &value) -> bool {
4787 // FIXME: we're silently ignoring invalid data here
4788 if (name == "id")
4789 llvm::to_integer(value, set_id);
4790 if (name == "name")
4791 set_info.name = ConstString(value);
4792 return true; // Keep iterating through all attributes
4793 });
4794
4795 if (set_id != UINT32_MAX)
4796 target_info.reg_set_map[set_id] = set_info;
4797 return true; // Keep iterating through all "group" elements
4798 });
4799 }
4800 return true; // Keep iterating through all children of the target_node
4801 });
4802 } else {
4803 // In an included XML feature file, we're already "inside" the <target>
4804 // tag of the initial XML file; this included file will likely only have
4805 // a <feature> tag. Need to check for any more included files in this
4806 // <feature> element.
4807 XMLNode feature_node = xml_document.GetRootElement("feature");
4808 if (feature_node) {
4809 feature_nodes.push_back(feature_node);
4810 feature_node.ForEachChildElement([&target_info](
4811 const XMLNode &node) -> bool {
4812 llvm::StringRef name = node.GetName();
4813 if (name == "xi:include" || name == "include") {
4814 std::string href = node.GetAttributeValue("href");
4815 if (!href.empty())
4816 target_info.includes.push_back(href);
4817 }
4818 return true;
4819 });
4820 }
4821 }
4822
4823 // gdbserver does not implement the LLDB packets used to determine host
4824 // or process architecture. If that is the case, attempt to use
4825 // the <architecture/> field from target.xml, e.g.:
4826 //
4827 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4828 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
4829 // arm board)
4830 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4831 // We don't have any information about vendor or OS.
4832 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4833 .Case("i386:x86-64", "x86_64")
4834 .Case("riscv:rv64", "riscv64")
4835 .Case("riscv:rv32", "riscv32")
4836 .Default(target_info.arch) +
4837 "--");
4838
4839 if (arch_to_use.IsValid())
4840 GetTarget().MergeArchitecture(arch_to_use);
4841 }
4842
4843 if (arch_to_use.IsValid()) {
4844 for (auto &feature_node : feature_nodes) {
4845 ParseRegisters(feature_node, target_info, registers,
4847 }
4848
4849 for (const auto &include : target_info.includes) {
4850 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4851 registers);
4852 }
4853 }
4854 } else {
4855 return false;
4856 }
4857 return true;
4858}
4859
4861 std::vector<DynamicRegisterInfo::Register> &registers,
4862 const ArchSpec &arch_to_use) {
4863 std::map<uint32_t, uint32_t> remote_to_local_map;
4864 uint32_t remote_regnum = 0;
4865 for (auto it : llvm::enumerate(registers)) {
4866 DynamicRegisterInfo::Register &remote_reg_info = it.value();
4867
4868 // Assign successive remote regnums if missing.
4869 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4870 remote_reg_info.regnum_remote = remote_regnum;
4871
4872 // Create a mapping from remote to local regnos.
4873 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4874
4875 remote_regnum = remote_reg_info.regnum_remote + 1;
4876 }
4877
4878 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4879 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4880 auto lldb_regit = remote_to_local_map.find(process_regnum);
4881 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4883 };
4884
4885 llvm::transform(remote_reg_info.value_regs,
4886 remote_reg_info.value_regs.begin(), proc_to_lldb);
4887 llvm::transform(remote_reg_info.invalidate_regs,
4888 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4889 }
4890
4891 // Don't use Process::GetABI, this code gets called from DidAttach, and
4892 // in that context we haven't set the Target's architecture yet, so the
4893 // ABI is also potentially incorrect.
4894 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4895 abi_sp->AugmentRegisterInfo(registers);
4896
4897 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4898}
4899
4900// query the target of gdb-remote for extended target information returns
4901// true on success (got register definitions), false on failure (did not).
4903 // Make sure LLDB has an XML parser it can use first
4905 return false;
4906
4907 // check that we have extended feature read support
4909 return false;
4910
4911 // These hold register type information for the whole of target.xml.
4912 // target.xml may include further documents that
4913 // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.
4914 // That's why we clear the cache here, and not in
4915 // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every
4916 // include read.
4918 m_registers_enum_types.clear();
4919 std::vector<DynamicRegisterInfo::Register> registers;
4920 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4921 registers) &&
4922 // Target XML is not required to include register information.
4923 !registers.empty())