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
27#include "lldb/Core/Debugger.h"
28#include "lldb/Core/Module.h"
31#include "lldb/Core/Value.h"
36#include "lldb/Host/PosixApi.h"
40#include "lldb/Host/XML.h"
53#include "lldb/Target/ABI.h"
58#include "lldb/Target/Target.h"
61#include "lldb/Utility/Args.h"
64#include "lldb/Utility/State.h"
66#include "lldb/Utility/Timer.h"
67#include <algorithm>
68#include <csignal>
69#include <map>
70#include <memory>
71#include <mutex>
72#include <optional>
73#include <sstream>
74#include <thread>
75
81#include "ProcessGDBRemote.h"
82#include "ProcessGDBRemoteLog.h"
83#include "ThreadGDBRemote.h"
84#include "lldb/Host/Host.h"
86
87#include "llvm/ADT/ScopeExit.h"
88#include "llvm/ADT/StringMap.h"
89#include "llvm/ADT/StringSwitch.h"
90#include "llvm/Support/FormatAdapters.h"
91#include "llvm/Support/Threading.h"
92#include "llvm/Support/raw_ostream.h"
93
94#define DEBUGSERVER_BASENAME "debugserver"
95using namespace lldb;
96using namespace lldb_private;
98
100
101namespace lldb {
102// Provide a function that can easily dump the packet history if we know a
103// ProcessGDBRemote * value (which we can get from logs or from debugging). We
104// need the function in the lldb namespace so it makes it into the final
105// executable since the LLDB shared library only exports stuff in the lldb
106// namespace. This allows you to attach with a debugger and call this function
107// and get the packet history dumped to a file.
108void DumpProcessGDBRemotePacketHistory(void *p, const char *path) {
109 auto file = FileSystem::Instance().Open(
111 if (!file) {
112 llvm::consumeError(file.takeError());
113 return;
114 }
115 StreamFile stream(std::move(file.get()));
116 ((Process *)p)->DumpPluginHistory(stream);
117}
118} // namespace lldb
119
120namespace {
121
122#define LLDB_PROPERTIES_processgdbremote
123#include "ProcessGDBRemoteProperties.inc"
124
125enum {
126#define LLDB_PROPERTIES_processgdbremote
127#include "ProcessGDBRemotePropertiesEnum.inc"
128};
129
130class PluginProperties : public Properties {
131public:
132 static llvm::StringRef GetSettingName() {
134 }
135
136 PluginProperties() : Properties() {
137 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
138 m_collection_sp->Initialize(g_processgdbremote_properties);
139 }
140
141 ~PluginProperties() override = default;
142
143 uint64_t GetPacketTimeout() {
144 const uint32_t idx = ePropertyPacketTimeout;
145 return GetPropertyAtIndexAs<uint64_t>(
146 idx, g_processgdbremote_properties[idx].default_uint_value);
147 }
148
149 bool SetPacketTimeout(uint64_t timeout) {
150 const uint32_t idx = ePropertyPacketTimeout;
151 return SetPropertyAtIndex(idx, timeout);
152 }
153
154 FileSpec GetTargetDefinitionFile() const {
155 const uint32_t idx = ePropertyTargetDefinitionFile;
156 return GetPropertyAtIndexAs<FileSpec>(idx, {});
157 }
158
159 bool GetUseSVR4() const {
160 const uint32_t idx = ePropertyUseSVR4;
161 return GetPropertyAtIndexAs<bool>(
162 idx, g_processgdbremote_properties[idx].default_uint_value != 0);
163 }
164
165 bool GetUseGPacketForReading() const {
166 const uint32_t idx = ePropertyUseGPacketForReading;
167 return GetPropertyAtIndexAs<bool>(idx, true);
168 }
169};
170
171} // namespace
172
173static PluginProperties &GetGlobalPluginProperties() {
174 static PluginProperties g_settings;
175 return g_settings;
176}
177
178// TODO Randomly assigning a port is unsafe. We should get an unused
179// ephemeral port from the kernel and make sure we reserve it before passing it
180// to debugserver.
181
182#if defined(__APPLE__)
183#define LOW_PORT (IPPORT_RESERVED)
184#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
185#else
186#define LOW_PORT (1024u)
187#define HIGH_PORT (49151u)
188#endif
189
191 return "GDB Remote protocol based debugging plug-in.";
192}
193
196}
197
199 lldb::TargetSP target_sp, ListenerSP listener_sp,
200 const FileSpec *crash_file_path, bool can_connect) {
201 lldb::ProcessSP process_sp;
202 if (crash_file_path == nullptr)
203 process_sp = std::shared_ptr<ProcessGDBRemote>(
204 new ProcessGDBRemote(target_sp, listener_sp));
205 return process_sp;
206}
207
210 gdb_comm.DumpHistory(s);
211}
212
214 return std::chrono::seconds(GetGlobalPluginProperties().GetPacketTimeout());
215}
216
219}
220
222 bool plugin_specified_by_name) {
223 if (plugin_specified_by_name)
224 return true;
225
226 // For now we are just making sure the file exists for a given module
227 Module *exe_module = target_sp->GetExecutableModulePointer();
228 if (exe_module) {
229 ObjectFile *exe_objfile = exe_module->GetObjectFile();
230 // We can't debug core files...
231 switch (exe_objfile->GetType()) {
239 return false;
243 break;
244 }
245 return FileSystem::Instance().Exists(exe_module->GetFileSpec());
246 }
247 // However, if there is no executable module, we return true since we might
248 // be preparing to attach.
249 return true;
250}
251
252// ProcessGDBRemote constructor
254 ListenerSP listener_sp)
255 : Process(target_sp, listener_sp),
256 m_debugserver_pid(LLDB_INVALID_PROCESS_ID), m_register_info_sp(nullptr),
257 m_async_broadcaster(nullptr, "lldb.process.gdb-remote.async-broadcaster"),
258 m_async_listener_sp(
259 Listener::MakeListener("lldb.process.gdb-remote.async-listener")),
260 m_async_thread_state_mutex(), m_thread_ids(), m_thread_pcs(),
261 m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(),
262 m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(),
263 m_max_memory_size(0), m_remote_stub_max_memory_size(0),
264 m_addr_to_mmap_size(), m_thread_create_bp_sp(),
265 m_waiting_for_attach(false),
266 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(false) {
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();
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.equals("name")) {
452 reg_info.name.SetString(value);
453 } else if (name.equals("alt-name")) {
454 reg_info.alt_name.SetString(value);
455 } else if (name.equals("bitsize")) {
456 if (!value.getAsInteger(0, reg_info.byte_size))
457 reg_info.byte_size /= CHAR_BIT;
458 } else if (name.equals("offset")) {
459 value.getAsInteger(0, reg_info.byte_offset);
460 } else if (name.equals("encoding")) {
461 const Encoding encoding = Args::StringToEncoding(value);
462 if (encoding != eEncodingInvalid)
463 reg_info.encoding = encoding;
464 } else if (name.equals("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.equals("set")) {
484 reg_info.set_name.SetString(value);
485 } else if (name.equals("gcc") || name.equals("ehframe")) {
486 value.getAsInteger(0, reg_info.regnum_ehframe);
487 } else if (name.equals("dwarf")) {
488 value.getAsInteger(0, reg_info.regnum_dwarf);
489 } else if (name.equals("generic")) {
491 } else if (name.equals("container-regs")) {
493 } else if (name.equals("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 addressable_bits.SetProcessMasks(*this);
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);
1093 eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len));
1094 } else
1095 SetExitStatus(-1, error.AsCString());
1096 }
1097
1098 return error;
1099}
1100
1102 const char *process_name, const ProcessAttachInfo &attach_info) {
1103 Status error;
1104 // Clear out and clean up from any current state
1105 Clear();
1106
1107 if (process_name && process_name[0]) {
1108 error = EstablishConnectionIfNeeded(attach_info);
1109 if (error.Success()) {
1110 StreamString packet;
1111
1113
1114 if (attach_info.GetWaitForLaunch()) {
1116 packet.PutCString("vAttachWait");
1117 } else {
1118 if (attach_info.GetIgnoreExisting())
1119 packet.PutCString("vAttachWait");
1120 else
1121 packet.PutCString("vAttachOrWait");
1122 }
1123 } else
1124 packet.PutCString("vAttachName");
1125 packet.PutChar(';');
1126 packet.PutBytesAsRawHex8(process_name, strlen(process_name),
1129
1132 new EventDataBytes(packet.GetString().data(), packet.GetSize()));
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
1379 new EventDataBytes(continue_packet.GetString().data(),
1380 continue_packet.GetSize()));
1381
1382 if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) {
1383 error.SetErrorString("Resume timed out.");
1384 LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out.");
1385 } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
1386 error.SetErrorString("Broadcast continue, but the async thread was "
1387 "killed before we got an ack back.");
1388 LLDB_LOGF(log,
1389 "ProcessGDBRemote::DoResume: Broadcast continue, but the "
1390 "async thread was killed before we got an ack back.");
1391 return error;
1392 }
1393 }
1394 }
1395
1396 return error;
1397}
1398
1400 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1401 m_thread_ids.clear();
1402 m_thread_pcs.clear();
1403}
1404
1406 llvm::StringRef value) {
1407 m_thread_ids.clear();
1409 StringExtractorGDBRemote thread_ids{value};
1410
1411 do {
1412 auto pid_tid = thread_ids.GetPidTid(pid);
1413 if (pid_tid && pid_tid->first == pid) {
1414 lldb::tid_t tid = pid_tid->second;
1415 if (tid != LLDB_INVALID_THREAD_ID &&
1417 m_thread_ids.push_back(tid);
1418 }
1419 } while (thread_ids.GetChar() == ',');
1420
1421 return m_thread_ids.size();
1422}
1423
1425 llvm::StringRef value) {
1426 m_thread_pcs.clear();
1427 for (llvm::StringRef x : llvm::split(value, ',')) {
1429 if (llvm::to_integer(x, pc, 16))
1430 m_thread_pcs.push_back(pc);
1431 }
1432 return m_thread_pcs.size();
1433}
1434
1436 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1437
1438 if (m_jthreadsinfo_sp) {
1439 // If we have the JSON threads info, we can get the thread list from that
1440 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
1441 if (thread_infos && thread_infos->GetSize() > 0) {
1442 m_thread_ids.clear();
1443 m_thread_pcs.clear();
1444 thread_infos->ForEach([this](StructuredData::Object *object) -> bool {
1445 StructuredData::Dictionary *thread_dict = object->GetAsDictionary();
1446 if (thread_dict) {
1447 // Set the thread stop info from the JSON dictionary
1448 SetThreadStopInfo(thread_dict);
1450 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>("tid", tid))
1451 m_thread_ids.push_back(tid);
1452 }
1453 return true; // Keep iterating through all thread_info objects
1454 });
1455 }
1456 if (!m_thread_ids.empty())
1457 return true;
1458 } else {
1459 // See if we can get the thread IDs from the current stop reply packets
1460 // that might contain a "threads" key/value pair
1461
1462 if (m_last_stop_packet) {
1463 // Get the thread stop info
1465 const std::string &stop_info_str = std::string(stop_info.GetStringRef());
1466
1467 m_thread_pcs.clear();
1468 const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:");
1469 if (thread_pcs_pos != std::string::npos) {
1470 const size_t start = thread_pcs_pos + strlen(";thread-pcs:");
1471 const size_t end = stop_info_str.find(';', start);
1472 if (end != std::string::npos) {
1473 std::string value = stop_info_str.substr(start, end - start);
1475 }
1476 }
1477
1478 const size_t threads_pos = stop_info_str.find(";threads:");
1479 if (threads_pos != std::string::npos) {
1480 const size_t start = threads_pos + strlen(";threads:");
1481 const size_t end = stop_info_str.find(';', start);
1482 if (end != std::string::npos) {
1483 std::string value = stop_info_str.substr(start, end - start);
1485 return true;
1486 }
1487 }
1488 }
1489 }
1490
1491 bool sequence_mutex_unavailable = false;
1492 m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable);
1493 if (sequence_mutex_unavailable) {
1494 return false; // We just didn't get the list
1495 }
1496 return true;
1497}
1498
1500 ThreadList &new_thread_list) {
1501 // locker will keep a mutex locked until it goes out of scope
1502 Log *log = GetLog(GDBRLog::Thread);
1503 LLDB_LOGV(log, "pid = {0}", GetID());
1504
1505 size_t num_thread_ids = m_thread_ids.size();
1506 // The "m_thread_ids" thread ID list should always be updated after each stop
1507 // reply packet, but in case it isn't, update it here.
1508 if (num_thread_ids == 0) {
1509 if (!UpdateThreadIDList())
1510 return false;
1511 num_thread_ids = m_thread_ids.size();
1512 }
1513
1514 ThreadList old_thread_list_copy(old_thread_list);
1515 if (num_thread_ids > 0) {
1516 for (size_t i = 0; i < num_thread_ids; ++i) {
1517 tid_t tid = m_thread_ids[i];
1518 ThreadSP thread_sp(
1519 old_thread_list_copy.RemoveThreadByProtocolID(tid, false));
1520 if (!thread_sp) {
1521 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1522 LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.",
1523 thread_sp.get(), thread_sp->GetID());
1524 } else {
1525 LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.",
1526 thread_sp.get(), thread_sp->GetID());
1527 }
1528
1529 SetThreadPc(thread_sp, i);
1530 new_thread_list.AddThreadSortedByIndexID(thread_sp);
1531 }
1532 }
1533
1534 // Whatever that is left in old_thread_list_copy are not present in
1535 // new_thread_list. Remove non-existent threads from internal id table.
1536 size_t old_num_thread_ids = old_thread_list_copy.GetSize(false);
1537 for (size_t i = 0; i < old_num_thread_ids; i++) {
1538 ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false));
1539 if (old_thread_sp) {
1540 lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID();
1541 m_thread_id_to_index_id_map.erase(old_thread_id);
1542 }
1543 }
1544
1545 return true;
1546}
1547
1548void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) {
1549 if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() &&
1551 ThreadGDBRemote *gdb_thread =
1552 static_cast<ThreadGDBRemote *>(thread_sp.get());
1553 RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext());
1554 if (reg_ctx_sp) {
1555 uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1557 if (pc_regnum != LLDB_INVALID_REGNUM) {
1558 gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]);
1559 }
1560 }
1561 }
1562}
1563
1565 ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) {
1566 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1567 // packet
1568 if (thread_infos_sp) {
1569 StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray();
1570 if (thread_infos) {
1571 lldb::tid_t tid;
1572 const size_t n = thread_infos->GetSize();
1573 for (size_t i = 0; i < n; ++i) {
1574 StructuredData::Dictionary *thread_dict =
1575 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
1576 if (thread_dict) {
1577 if (thread_dict->GetValueForKeyAsInteger<lldb::tid_t>(
1578 "tid", tid, LLDB_INVALID_THREAD_ID)) {
1579 if (tid == thread->GetID())
1580 return (bool)SetThreadStopInfo(thread_dict);
1581 }
1582 }
1583 }
1584 }
1585 }
1586 return false;
1587}
1588
1590 // See if we got thread stop infos for all threads via the "jThreadsInfo"
1591 // packet
1593 return true;
1594
1595 // See if we got thread stop info for any threads valid stop info reasons
1596 // threads via the "jstopinfo" packet stop reply packet key/value pair?
1597 if (m_jstopinfo_sp) {
1598 // If we have "jstopinfo" then we have stop descriptions for all threads
1599 // that have stop reasons, and if there is no entry for a thread, then it
1600 // has no stop reason.
1601 thread->GetRegisterContext()->InvalidateIfNeeded(true);
1603 thread->SetStopInfo(StopInfoSP());
1604 }
1605 return true;
1606 }
1607
1608 // Fall back to using the qThreadStopInfo packet
1609 StringExtractorGDBRemote stop_packet;
1610 if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet))
1611 return SetThreadStopInfo(stop_packet) == eStateStopped;
1612 return false;
1613}
1614
1616 lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map,
1617 uint8_t signo, const std::string &thread_name, const std::string &reason,
1618 const std::string &description, uint32_t exc_type,
1619 const std::vector<addr_t> &exc_data, addr_t thread_dispatch_qaddr,
1620 bool queue_vars_valid, // Set to true if queue_name, queue_kind and
1621 // queue_serial are valid
1622 LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t,
1623 std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) {
1624
1625 if (tid == LLDB_INVALID_THREAD_ID)
1626 return nullptr;
1627
1628 ThreadSP thread_sp;
1629 // Scope for "locker" below
1630 {
1631 // m_thread_list_real does have its own mutex, but we need to hold onto the
1632 // mutex between the call to m_thread_list_real.FindThreadByID(...) and the
1633 // m_thread_list_real.AddThread(...) so it doesn't change on us
1634 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
1635 thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false);
1636
1637 if (!thread_sp) {
1638 // Create the thread if we need to
1639 thread_sp = std::make_shared<ThreadGDBRemote>(*this, tid);
1640 m_thread_list_real.AddThread(thread_sp);
1641 }
1642 }
1643
1644 ThreadGDBRemote *gdb_thread = static_cast<ThreadGDBRemote *>(thread_sp.get());
1645 RegisterContextSP gdb_reg_ctx_sp(gdb_thread->GetRegisterContext());
1646
1647 gdb_reg_ctx_sp->InvalidateIfNeeded(true);
1648
1649 auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid);
1650 if (iter != m_thread_ids.end())
1651 SetThreadPc(thread_sp, iter - m_thread_ids.begin());
1652
1653 for (const auto &pair : expedited_register_map) {
1654 StringExtractor reg_value_extractor(pair.second);
1655 WritableDataBufferSP buffer_sp(
1656 new DataBufferHeap(reg_value_extractor.GetStringRef().size() / 2, 0));
1657 reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc');
1658 uint32_t lldb_regnum = gdb_reg_ctx_sp->ConvertRegisterKindToRegisterNumber(
1659 eRegisterKindProcessPlugin, pair.first);
1660 gdb_thread->PrivateSetRegisterValue(lldb_regnum, buffer_sp->GetData());
1661 }
1662
1663 // AArch64 SVE/SME specific code below updates SVE and ZA register sizes and
1664 // offsets if value of VG or SVG registers has changed since last stop.
1665 const ArchSpec &arch = GetTarget().GetArchitecture();
1666 if (arch.IsValid() && arch.GetTriple().isAArch64()) {
1667 GDBRemoteRegisterContext *reg_ctx_sp =
1668 static_cast<GDBRemoteRegisterContext *>(
1669 gdb_thread->GetRegisterContext().get());
1670
1671 if (reg_ctx_sp) {
1672 reg_ctx_sp->AArch64Reconfigure();
1673 reg_ctx_sp->InvalidateAllRegisters();
1674 }
1675 }
1676
1677 thread_sp->SetName(thread_name.empty() ? nullptr : thread_name.c_str());
1678
1679 gdb_thread->SetThreadDispatchQAddr(thread_dispatch_qaddr);
1680 // Check if the GDB server was able to provide the queue name, kind and serial
1681 // number
1682 if (queue_vars_valid)
1683 gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial,
1684 dispatch_queue_t, associated_with_dispatch_queue);
1685 else
1686 gdb_thread->ClearQueueInfo();
1687
1688 gdb_thread->SetAssociatedWithLibdispatchQueue(associated_with_dispatch_queue);
1689
1690 if (dispatch_queue_t != LLDB_INVALID_ADDRESS)
1691 gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t);
1692
1693 // Make sure we update our thread stop reason just once, but don't overwrite
1694 // the stop info for threads that haven't moved:
1695 StopInfoSP current_stop_info_sp = thread_sp->GetPrivateStopInfo(false);
1696 if (thread_sp->GetTemporaryResumeState() == eStateSuspended &&
1697 current_stop_info_sp) {
1698 thread_sp->SetStopInfo(current_stop_info_sp);
1699 return thread_sp;
1700 }
1701
1702 if (!thread_sp->StopInfoIsUpToDate()) {
1703 thread_sp->SetStopInfo(StopInfoSP());
1704 // If there's a memory thread backed by this thread, we need to use it to
1705 // calculate StopInfo.
1706 if (ThreadSP memory_thread_sp = m_thread_list.GetBackingThread(thread_sp))
1707 thread_sp = memory_thread_sp;
1708
1709 if (exc_type != 0) {
1710 const size_t exc_data_size = exc_data.size();
1711
1712 thread_sp->SetStopInfo(
1714 *thread_sp, exc_type, exc_data_size,
1715 exc_data_size >= 1 ? exc_data[0] : 0,
1716 exc_data_size >= 2 ? exc_data[1] : 0,
1717 exc_data_size >= 3 ? exc_data[2] : 0));
1718 } else {
1719 bool handled = false;
1720 bool did_exec = false;
1721 if (!reason.empty()) {
1722 if (reason == "trace") {
1723 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1724 lldb::BreakpointSiteSP bp_site_sp =
1725 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1726 pc);
1727
1728 // If the current pc is a breakpoint site then the StopInfo should be
1729 // set to Breakpoint Otherwise, it will be set to Trace.
1730 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1731 thread_sp->SetStopInfo(
1733 *thread_sp, bp_site_sp->GetID()));
1734 } else
1735 thread_sp->SetStopInfo(
1737 handled = true;
1738 } else if (reason == "breakpoint") {
1739 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1740 lldb::BreakpointSiteSP bp_site_sp =
1741 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1742 pc);
1743 if (bp_site_sp) {
1744 // If the breakpoint is for this thread, then we'll report the hit,
1745 // but if it is for another thread, we can just report no reason.
1746 // We don't need to worry about stepping over the breakpoint here,
1747 // that will be taken care of when the thread resumes and notices
1748 // that there's a breakpoint under the pc.
1749 handled = true;
1750 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1751 thread_sp->SetStopInfo(
1753 *thread_sp, bp_site_sp->GetID()));
1754 } else {
1755 StopInfoSP invalid_stop_info_sp;
1756 thread_sp->SetStopInfo(invalid_stop_info_sp);
1757 }
1758 }
1759 } else if (reason == "trap") {
1760 // Let the trap just use the standard signal stop reason below...
1761 } else if (reason == "watchpoint") {
1762 // We will have between 1 and 3 fields in the description.
1763 //
1764 // \a wp_addr which is the original start address that
1765 // lldb requested be watched, or an address that the
1766 // hardware reported. This address should be within the
1767 // range of a currently active watchpoint region - lldb
1768 // should be able to find a watchpoint with this address.
1769 //
1770 // \a wp_index is the hardware watchpoint register number.
1771 //
1772 // \a wp_hit_addr is the actual address reported by the hardware,
1773 // which may be outside the range of a region we are watching.
1774 //
1775 // On MIPS, we may get a false watchpoint exception where an
1776 // access to the same 8 byte granule as a watchpoint will trigger,
1777 // even if the access was not within the range of the watched
1778 // region. When we get a \a wp_hit_addr outside the range of any
1779 // set watchpoint, continue execution without making it visible to
1780 // the user.
1781 //
1782 // On ARM, a related issue where a large access that starts
1783 // before the watched region (and extends into the watched
1784 // region) may report a hit address before the watched region.
1785 // lldb will not find the "nearest" watchpoint to
1786 // disable/step/re-enable it, so one of the valid watchpoint
1787 // addresses should be provided as \a wp_addr.
1788 StringExtractor desc_extractor(description.c_str());
1789 addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1790 uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32);
1791 addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS);
1793 bool silently_continue = false;
1794 WatchpointSP wp_sp;
1795 if (wp_hit_addr != LLDB_INVALID_ADDRESS) {
1796 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_hit_addr);
1797 // On MIPS, \a wp_hit_addr outside the range of a watched
1798 // region means we should silently continue, it is a false hit.
1800 if (!wp_sp && core >= ArchSpec::kCore_mips_first &&
1802 silently_continue = true;
1803 }
1804 if (!wp_sp && wp_addr != LLDB_INVALID_ADDRESS)
1805 wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr);
1806 if (wp_sp) {
1807 wp_sp->SetHardwareIndex(wp_index);
1808 watch_id = wp_sp->GetID();
1809 }
1810 if (watch_id == LLDB_INVALID_WATCH_ID) {
1812 LLDB_LOGF(log, "failed to find watchpoint");
1813 }
1814 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID(
1815 *thread_sp, watch_id, silently_continue));
1816 handled = true;
1817 } else if (reason == "exception") {
1818 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1819 *thread_sp, description.c_str()));
1820 handled = true;
1821 } else if (reason == "exec") {
1822 did_exec = true;
1823 thread_sp->SetStopInfo(
1825 handled = true;
1826 } else if (reason == "processor trace") {
1827 thread_sp->SetStopInfo(StopInfo::CreateStopReasonProcessorTrace(
1828 *thread_sp, description.c_str()));
1829 } else if (reason == "fork") {
1830 StringExtractor desc_extractor(description.c_str());
1831 lldb::pid_t child_pid =
1832 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1833 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1834 thread_sp->SetStopInfo(
1835 StopInfo::CreateStopReasonFork(*thread_sp, child_pid, child_tid));
1836 handled = true;
1837 } else if (reason == "vfork") {
1838 StringExtractor desc_extractor(description.c_str());
1839 lldb::pid_t child_pid =
1840 desc_extractor.GetU64(LLDB_INVALID_PROCESS_ID);
1841 lldb::tid_t child_tid = desc_extractor.GetU64(LLDB_INVALID_THREAD_ID);
1842 thread_sp->SetStopInfo(StopInfo::CreateStopReasonVFork(
1843 *thread_sp, child_pid, child_tid));
1844 handled = true;
1845 } else if (reason == "vforkdone") {
1846 thread_sp->SetStopInfo(
1848 handled = true;
1849 }
1850 } else if (!signo) {
1851 addr_t pc = thread_sp->GetRegisterContext()->GetPC();
1852 lldb::BreakpointSiteSP bp_site_sp =
1853 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(pc);
1854
1855 // If the current pc is a breakpoint site then the StopInfo should be
1856 // set to Breakpoint even though the remote stub did not set it as such.
1857 // This can happen when the thread is involuntarily interrupted (e.g.
1858 // due to stops on other threads) just as it is about to execute the
1859 // breakpoint instruction.
1860 if (bp_site_sp && bp_site_sp->ValidForThisThread(*thread_sp)) {
1862 *thread_sp, bp_site_sp->GetID()));
1863 handled = true;
1864 }
1865 }
1866
1867 if (!handled && signo && !did_exec) {
1868 if (signo == SIGTRAP) {
1869 // Currently we are going to assume SIGTRAP means we are either
1870 // hitting a breakpoint or hardware single stepping.
1871 handled = true;
1872 addr_t pc =
1873 thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset;
1874 lldb::BreakpointSiteSP bp_site_sp =
1875 thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress(
1876 pc);
1877
1878 if (bp_site_sp) {
1879 // If the breakpoint is for this thread, then we'll report the hit,
1880 // but if it is for another thread, we can just report no reason.
1881 // We don't need to worry about stepping over the breakpoint here,
1882 // that will be taken care of when the thread resumes and notices
1883 // that there's a breakpoint under the pc.
1884 if (bp_site_sp->ValidForThisThread(*thread_sp)) {
1885 if (m_breakpoint_pc_offset != 0)
1886 thread_sp->GetRegisterContext()->SetPC(pc);
1887 thread_sp->SetStopInfo(
1889 *thread_sp, bp_site_sp->GetID()));
1890 } else {
1891 StopInfoSP invalid_stop_info_sp;
1892 thread_sp->SetStopInfo(invalid_stop_info_sp);
1893 }
1894 } else {
1895 // If we were stepping then assume the stop was the result of the
1896 // trace. If we were not stepping then report the SIGTRAP.
1897 // FIXME: We are still missing the case where we single step over a
1898 // trap instruction.
1899 if (thread_sp->GetTemporaryResumeState() == eStateStepping)
1900 thread_sp->SetStopInfo(
1902 else
1903 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1904 *thread_sp, signo, description.c_str()));
1905 }
1906 }
1907 if (!handled)
1908 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal(
1909 *thread_sp, signo, description.c_str()));
1910 }
1911
1912 if (!description.empty()) {
1913 lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo());
1914 if (stop_info_sp) {
1915 const char *stop_info_desc = stop_info_sp->GetDescription();
1916 if (!stop_info_desc || !stop_info_desc[0])
1917 stop_info_sp->SetDescription(description.c_str());
1918 } else {
1919 thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException(
1920 *thread_sp, description.c_str()));
1921 }
1922 }
1923 }
1924 }
1925 return thread_sp;
1926}
1927
1930 static constexpr llvm::StringLiteral g_key_tid("tid");
1931 static constexpr llvm::StringLiteral g_key_name("name");
1932 static constexpr llvm::StringLiteral g_key_reason("reason");
1933 static constexpr llvm::StringLiteral g_key_metype("metype");
1934 static constexpr llvm::StringLiteral g_key_medata("medata");
1935 static constexpr llvm::StringLiteral g_key_qaddr("qaddr");
1936 static constexpr llvm::StringLiteral g_key_dispatch_queue_t(
1937 "dispatch_queue_t");
1938 static constexpr llvm::StringLiteral g_key_associated_with_dispatch_queue(
1939 "associated_with_dispatch_queue");
1940 static constexpr llvm::StringLiteral g_key_queue_name("qname");
1941 static constexpr llvm::StringLiteral g_key_queue_kind("qkind");
1942 static constexpr llvm::StringLiteral g_key_queue_serial_number("qserialnum");
1943 static constexpr llvm::StringLiteral g_key_registers("registers");
1944 static constexpr llvm::StringLiteral g_key_memory("memory");
1945 static constexpr llvm::StringLiteral g_key_description("description");
1946 static constexpr llvm::StringLiteral g_key_signal("signal");
1947
1948 // Stop with signal and thread info
1950 uint8_t signo = 0;
1951 std::string value;
1952 std::string thread_name;
1953 std::string reason;
1954 std::string description;
1955 uint32_t exc_type = 0;
1956 std::vector<addr_t> exc_data;
1957 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
1958 ExpeditedRegisterMap expedited_register_map;
1959 bool queue_vars_valid = false;
1960 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
1961 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
1962 std::string queue_name;
1963 QueueKind queue_kind = eQueueKindUnknown;
1964 uint64_t queue_serial_number = 0;
1965 // Iterate through all of the thread dictionary key/value pairs from the
1966 // structured data dictionary
1967
1968 // FIXME: we're silently ignoring invalid data here
1969 thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name,
1970 &signo, &reason, &description, &exc_type, &exc_data,
1971 &thread_dispatch_qaddr, &queue_vars_valid,
1972 &associated_with_dispatch_queue, &dispatch_queue_t,
1973 &queue_name, &queue_kind, &queue_serial_number](
1974 llvm::StringRef key,
1975 StructuredData::Object *object) -> bool {
1976 if (key == g_key_tid) {
1977 // thread in big endian hex
1978 tid = object->GetUnsignedIntegerValue(LLDB_INVALID_THREAD_ID);
1979 } else if (key == g_key_metype) {
1980 // exception type in big endian hex
1981 exc_type = object->GetUnsignedIntegerValue(0);
1982 } else if (key == g_key_medata) {
1983 // exception data in big endian hex
1984 StructuredData::Array *array = object->GetAsArray();
1985 if (array) {
1986 array->ForEach([&exc_data](StructuredData::Object *object) -> bool {
1987 exc_data.push_back(object->GetUnsignedIntegerValue());
1988 return true; // Keep iterating through all array items
1989 });
1990 }
1991 } else if (key == g_key_name) {
1992 thread_name = std::string(object->GetStringValue());
1993 } else if (key == g_key_qaddr) {
1994 thread_dispatch_qaddr =
1995 object->GetUnsignedIntegerValue(LLDB_INVALID_ADDRESS);
1996 } else if (key == g_key_queue_name) {
1997 queue_vars_valid = true;
1998 queue_name = std::string(object->GetStringValue());
1999 } else if (key == g_key_queue_kind) {
2000 std::string queue_kind_str = std::string(object->GetStringValue());
2001 if (queue_kind_str == "serial") {
2002 queue_vars_valid = true;
2003 queue_kind = eQueueKindSerial;
2004 } else if (queue_kind_str == "concurrent") {
2005 queue_vars_valid = true;
2006 queue_kind = eQueueKindConcurrent;
2007 }
2008 } else if (key == g_key_queue_serial_number) {
2009 queue_serial_number = object->GetUnsignedIntegerValue(0);
2010 if (queue_serial_number != 0)
2011 queue_vars_valid = true;
2012 } else if (key == g_key_dispatch_queue_t) {
2013 dispatch_queue_t = object->GetUnsignedIntegerValue(0);
2014 if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS)
2015 queue_vars_valid = true;
2016 } else if (key == g_key_associated_with_dispatch_queue) {
2017 queue_vars_valid = true;
2018 bool associated = object->GetBooleanValue();
2019 if (associated)
2020 associated_with_dispatch_queue = eLazyBoolYes;
2021 else
2022 associated_with_dispatch_queue = eLazyBoolNo;
2023 } else if (key == g_key_reason) {
2024 reason = std::string(object->GetStringValue());
2025 } else if (key == g_key_description) {
2026 description = std::string(object->GetStringValue());
2027 } else if (key == g_key_registers) {
2028 StructuredData::Dictionary *registers_dict = object->GetAsDictionary();
2029
2030 if (registers_dict) {
2031 registers_dict->ForEach(
2032 [&expedited_register_map](llvm::StringRef key,
2033 StructuredData::Object *object) -> bool {
2034 uint32_t reg;
2035 if (llvm::to_integer(key, reg))
2036 expedited_register_map[reg] =
2037 std::string(object->GetStringValue());
2038 return true; // Keep iterating through all array items
2039 });
2040 }
2041 } else if (key == g_key_memory) {
2042 StructuredData::Array *array = object->GetAsArray();
2043 if (array) {
2044 array->ForEach([this](StructuredData::Object *object) -> bool {
2045 StructuredData::Dictionary *mem_cache_dict =
2046 object->GetAsDictionary();
2047 if (mem_cache_dict) {
2048 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2049 if (mem_cache_dict->GetValueForKeyAsInteger<lldb::addr_t>(
2050 "address", mem_cache_addr)) {
2051 if (mem_cache_addr != LLDB_INVALID_ADDRESS) {
2052 llvm::StringRef str;
2053 if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) {
2054 StringExtractor bytes(str);
2055 bytes.SetFilePos(0);
2056
2057 const size_t byte_size = bytes.GetStringRef().size() / 2;
2058 WritableDataBufferSP data_buffer_sp(
2059 new DataBufferHeap(byte_size, 0));
2060 const size_t bytes_copied =
2061 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2062 if (bytes_copied == byte_size)
2063 m_memory_cache.AddL1CacheData(mem_cache_addr,
2064 data_buffer_sp);
2065 }
2066 }
2067 }
2068 }
2069 return true; // Keep iterating through all array items
2070 });
2071 }
2072
2073 } else if (key == g_key_signal)
2074 signo = object->GetUnsignedIntegerValue(LLDB_INVALID_SIGNAL_NUMBER);
2075 return true; // Keep iterating through all dictionary key/value pairs
2076 });
2077
2078 return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name,
2079 reason, description, exc_type, exc_data,
2080 thread_dispatch_qaddr, queue_vars_valid,
2081 associated_with_dispatch_queue, dispatch_queue_t,
2082 queue_name, queue_kind, queue_serial_number);
2083}
2084
2087 stop_packet.SetFilePos(0);
2088 const char stop_type = stop_packet.GetChar();
2089 switch (stop_type) {
2090 case 'T':
2091 case 'S': {
2092 // This is a bit of a hack, but it is required. If we did exec, we need to
2093 // clear our thread lists and also know to rebuild our dynamic register
2094 // info before we lookup and threads and populate the expedited register
2095 // values so we need to know this right away so we can cleanup and update
2096 // our registers.
2097 const uint32_t stop_id = GetStopID();
2098 if (stop_id == 0) {
2099 // Our first stop, make sure we have a process ID, and also make sure we
2100 // know about our registers
2102 SetID(pid);
2104 }
2105 // Stop with signal and thread info
2108 const uint8_t signo = stop_packet.GetHexU8();
2109 llvm::StringRef key;
2110 llvm::StringRef value;
2111 std::string thread_name;
2112 std::string reason;
2113 std::string description;
2114 uint32_t exc_type = 0;
2115 std::vector<addr_t> exc_data;
2116 addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS;
2117 bool queue_vars_valid =
2118 false; // says if locals below that start with "queue_" are valid
2119 addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS;
2120 LazyBool associated_with_dispatch_queue = eLazyBoolCalculate;
2121 std::string queue_name;
2122 QueueKind queue_kind = eQueueKindUnknown;
2123 uint64_t queue_serial_number = 0;
2124 ExpeditedRegisterMap expedited_register_map;
2125 AddressableBits addressable_bits;
2126 while (stop_packet.GetNameColonValue(key, value)) {
2127 if (key.compare("metype") == 0) {
2128 // exception type in big endian hex
2129 value.getAsInteger(16, exc_type);
2130 } else if (key.compare("medata") == 0) {
2131 // exception data in big endian hex
2132 uint64_t x;
2133 value.getAsInteger(16, x);
2134 exc_data.push_back(x);
2135 } else if (key.compare("thread") == 0) {
2136 // thread-id
2137 StringExtractorGDBRemote thread_id{value};
2138 auto pid_tid = thread_id.GetPidTid(pid);
2139 if (pid_tid) {
2140 stop_pid = pid_tid->first;
2141 tid = pid_tid->second;
2142 } else
2144 } else if (key.compare("threads") == 0) {
2145 std::lock_guard<std::recursive_mutex> guard(
2148 } else if (key.compare("thread-pcs") == 0) {
2149 m_thread_pcs.clear();
2150 // A comma separated list of all threads in the current
2151 // process that includes the thread for this stop reply packet
2153 while (!value.empty()) {
2154 llvm::StringRef pc_str;
2155 std::tie(pc_str, value) = value.split(',');
2156 if (pc_str.getAsInteger(16, pc))
2158 m_thread_pcs.push_back(pc);
2159 }
2160 } else if (key.compare("jstopinfo") == 0) {
2161 StringExtractor json_extractor(value);
2162 std::string json;
2163 // Now convert the HEX bytes into a string value
2164 json_extractor.GetHexByteString(json);
2165
2166 // This JSON contains thread IDs and thread stop info for all threads.
2167 // It doesn't contain expedited registers, memory or queue info.
2169 } else if (key.compare("hexname") == 0) {
2170 StringExtractor name_extractor(value);
2171 std::string name;
2172 // Now convert the HEX bytes into a string value
2173 name_extractor.GetHexByteString(thread_name);
2174 } else if (key.compare("name") == 0) {
2175 thread_name = std::string(value);
2176 } else if (key.compare("qaddr") == 0) {
2177 value.getAsInteger(16, thread_dispatch_qaddr);
2178 } else if (key.compare("dispatch_queue_t") == 0) {
2179 queue_vars_valid = true;
2180 value.getAsInteger(16, dispatch_queue_t);
2181 } else if (key.compare("qname") == 0) {
2182 queue_vars_valid = true;
2183 StringExtractor name_extractor(value);
2184 // Now convert the HEX bytes into a string value
2185 name_extractor.GetHexByteString(queue_name);
2186 } else if (key.compare("qkind") == 0) {
2187 queue_kind = llvm::StringSwitch<QueueKind>(value)
2188 .Case("serial", eQueueKindSerial)
2189 .Case("concurrent", eQueueKindConcurrent)
2190 .Default(eQueueKindUnknown);
2191 queue_vars_valid = queue_kind != eQueueKindUnknown;
2192 } else if (key.compare("qserialnum") == 0) {
2193 if (!value.getAsInteger(0, queue_serial_number))
2194 queue_vars_valid = true;
2195 } else if (key.compare("reason") == 0) {
2196 reason = std::string(value);
2197 } else if (key.compare("description") == 0) {
2198 StringExtractor desc_extractor(value);
2199 // Now convert the HEX bytes into a string value
2200 desc_extractor.GetHexByteString(description);
2201 } else if (key.compare("memory") == 0) {
2202 // Expedited memory. GDB servers can choose to send back expedited
2203 // memory that can populate the L1 memory cache in the process so that
2204 // things like the frame pointer backchain can be expedited. This will
2205 // help stack backtracing be more efficient by not having to send as
2206 // many memory read requests down the remote GDB server.
2207
2208 // Key/value pair format: memory:<addr>=<bytes>;
2209 // <addr> is a number whose base will be interpreted by the prefix:
2210 // "0x[0-9a-fA-F]+" for hex
2211 // "0[0-7]+" for octal
2212 // "[1-9]+" for decimal
2213 // <bytes> is native endian ASCII hex bytes just like the register
2214 // values
2215 llvm::StringRef addr_str, bytes_str;
2216 std::tie(addr_str, bytes_str) = value.split('=');
2217 if (!addr_str.empty() && !bytes_str.empty()) {
2218 lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS;
2219 if (!addr_str.getAsInteger(0, mem_cache_addr)) {
2220 StringExtractor bytes(bytes_str);
2221 const size_t byte_size = bytes.GetBytesLeft() / 2;
2222 WritableDataBufferSP data_buffer_sp(
2223 new DataBufferHeap(byte_size, 0));
2224 const size_t bytes_copied =
2225 bytes.GetHexBytes(data_buffer_sp->GetData(), 0);
2226 if (bytes_copied == byte_size)
2227 m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp);
2228 }
2229 }
2230 } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 ||
2231 key.compare("awatch") == 0) {
2232 // Support standard GDB remote stop reply packet 'TAAwatch:addr'
2234 value.getAsInteger(16, wp_addr);
2235
2236 WatchpointSP wp_sp =
2238 uint32_t wp_index = LLDB_INVALID_INDEX32;
2239
2240 if (wp_sp)
2241 wp_index = wp_sp->GetHardwareIndex();
2242
2243 // Rewrite gdb standard watch/rwatch/awatch to
2244 // "reason:watchpoint" + "description:ADDR",
2245 // which is parsed in SetThreadStopInfo.
2246 reason = "watchpoint";
2247 StreamString ostr;
2248 ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index);
2249 description = std::string(ostr.GetString());
2250 } else if (key.compare("library") == 0) {
2251 auto error = LoadModules();
2252 if (error) {
2254 LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}");
2255 }
2256 } else if (key.compare("fork") == 0 || key.compare("vfork") == 0) {
2257 // fork includes child pid/tid in thread-id format
2258 StringExtractorGDBRemote thread_id{value};
2259 auto pid_tid = thread_id.GetPidTid(LLDB_INVALID_PROCESS_ID);
2260 if (!pid_tid) {
2262 LLDB_LOG(log, "Invalid PID/TID to fork: {0}", value);
2264 }
2265
2266 reason = key.str();
2267 StreamString ostr;
2268 ostr.Printf("%" PRIu64 " %" PRIu64, pid_tid->first, pid_tid->second);
2269 description = std::string(ostr.GetString());
2270 } else if (key.compare("addressing_bits") == 0) {
2271 uint64_t addressing_bits;
2272 if (!value.getAsInteger(0, addressing_bits)) {
2273 addressable_bits.SetAddressableBits(addressing_bits);
2274 }
2275 } else if (key.compare("low_mem_addressing_bits") == 0) {
2276 uint64_t addressing_bits;
2277 if (!value.getAsInteger(0, addressing_bits)) {
2278 addressable_bits.SetLowmemAddressableBits(addressing_bits);
2279 }
2280 } else if (key.compare("high_mem_addressing_bits") == 0) {
2281 uint64_t addressing_bits;
2282 if (!value.getAsInteger(0, addressing_bits)) {
2283 addressable_bits.SetHighmemAddressableBits(addressing_bits);
2284 }
2285 } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) {
2286 uint32_t reg = UINT32_MAX;
2287 if (!key.getAsInteger(16, reg))
2288 expedited_register_map[reg] = std::string(std::move(value));
2289 }
2290 }
2291
2292 if (stop_pid != LLDB_INVALID_PROCESS_ID && stop_pid != pid) {
2293 Log *log = GetLog(GDBRLog::Process);
2294 LLDB_LOG(log,
2295 "Received stop for incorrect PID = {0} (inferior PID = {1})",
2296 stop_pid, pid);
2297 return eStateInvalid;
2298 }
2299
2300 if (tid == LLDB_INVALID_THREAD_ID) {
2301 // A thread id may be invalid if the response is old style 'S' packet
2302 // which does not provide the
2303 // thread information. So update the thread list and choose the first
2304 // one.
2306
2307 if (!m_thread_ids.empty()) {
2308 tid = m_thread_ids.front();
2309 }
2310 }
2311
2312 addressable_bits.SetProcessMasks(*this);
2313
2314 ThreadSP thread_sp = SetThreadStopInfo(
2315 tid, expedited_register_map, signo, thread_name, reason, description,
2316 exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid,
2317 associated_with_dispatch_queue, dispatch_queue_t, queue_name,
2318 queue_kind, queue_serial_number);
2319
2320 return eStateStopped;
2321 } break;
2322
2323 case 'W':
2324 case 'X':
2325 // process exited
2326 return eStateExited;
2327
2328 default:
2329 break;
2330 }
2331 return eStateInvalid;
2332}
2333
2335 std::lock_guard<std::recursive_mutex> guard(m_thread_list_real.GetMutex());
2336
2337 m_thread_ids.clear();
2338 m_thread_pcs.clear();
2339
2340 // Set the thread stop info. It might have a "threads" key whose value is a
2341 // list of all thread IDs in the current process, so m_thread_ids might get
2342 // set.
2343 // Check to see if SetThreadStopInfo() filled in m_thread_ids?
2344 if (m_thread_ids.empty()) {
2345 // No, we need to fetch the thread list manually
2347 }
2348
2349 // We might set some stop info's so make sure the thread list is up to
2350 // date before we do that or we might overwrite what was computed here.
2352
2355 m_last_stop_packet.reset();
2356
2357 // If we have queried for a default thread id
2361 }
2362
2363 // Let all threads recover from stopping and do any clean up based on the
2364 // previous thread state (if any).
2366}
2367
2369 Status error;
2370
2372 // We are being asked to halt during an attach. We need to just close our
2373 // file handle and debugserver will go away, and we can be done...
2375 } else
2376 caused_stop = m_gdb_comm.Interrupt(GetInterruptTimeout());
2377 return error;
2378}
2379
2381 Status error;
2382 Log *log = GetLog(GDBRLog::Process);
2383 LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped);
2384
2385 error = m_gdb_comm.Detach(keep_stopped);
2386 if (log) {
2387 if (error.Success())
2388 log->PutCString(
2389 "ProcessGDBRemote::DoDetach() detach packet sent successfully");
2390 else
2391 LLDB_LOGF(log,
2392 "ProcessGDBRemote::DoDetach() detach packet send failed: %s",
2393 error.AsCString() ? error.AsCString() : "<unknown error>");
2394 }
2395
2396 if (!error.Success())
2397 return error;
2398
2399 // Sleep for one second to let the process get all detached...
2401
2404
2405 // KillDebugserverProcess ();
2406 return error;
2407}
2408
2410 Log *log = GetLog(GDBRLog::Process);
2411 LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()");
2412
2413 // Interrupt if our inferior is running...
2414 int exit_status = SIGABRT;
2415 std::string exit_string;
2416
2417 if (m_gdb_comm.IsConnected()) {
2419 llvm::Expected<int> kill_res = m_gdb_comm.KillProcess(GetID());
2420
2421 if (kill_res) {
2422 exit_status = kill_res.get();
2423#if defined(__APPLE__)
2424 // For Native processes on Mac OS X, we launch through the Host
2425 // Platform, then hand the process off to debugserver, which becomes
2426 // the parent process through "PT_ATTACH". Then when we go to kill
2427 // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then
2428 // we call waitpid which returns with no error and the correct
2429 // status. But amusingly enough that doesn't seem to actually reap
2430 // the process, but instead it is left around as a Zombie. Probably
2431 // the kernel is in the process of switching ownership back to lldb
2432 // which was the original parent, and gets confused in the handoff.
2433 // Anyway, so call waitpid here to finally reap it.
2434 PlatformSP platform_sp(GetTarget().GetPlatform());
2435 if (platform_sp && platform_sp->IsHost()) {
2436 int status;
2437 ::pid_t reap_pid;
2438 reap_pid = waitpid(GetID(), &status, WNOHANG);
2439 LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status);
2440 }
2441#endif
2443 exit_string.assign("killed");
2444 } else {
2445 exit_string.assign(llvm::toString(kill_res.takeError()));
2446 }
2447 } else {
2448 exit_string.assign("killed or interrupted while attaching.");
2449 }
2450 } else {
2451 // If we missed setting the exit status on the way out, do it here.
2452 // NB set exit status can be called multiple times, the first one sets the
2453 // status.
2454 exit_string.assign("destroying when not connected to debugserver");
2455 }
2456
2457 SetExitStatus(exit_status, exit_string.c_str());
2458
2461 return Status();
2462}
2463
2465 const StringExtractorGDBRemote &response) {
2466 const bool did_exec =
2467 response.GetStringRef().find(";reason:exec;") != std::string::npos;
2468 if (did_exec) {
2469 Log *log = GetLog(GDBRLog::Process);
2470 LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec");
2471
2476 }
2477
2478 m_last_stop_packet = response;
2479}
2480
2482 Process::SetUnixSignals(std::make_shared<GDBRemoteSignals>(signals_sp));
2483}
2484
2485// Process Queries
2486
2489}
2490
2492 // request the link map address via the $qShlibInfoAddr packet
2494
2495 // the loaded module list can also provides a link map address
2496 if (addr == LLDB_INVALID_ADDRESS) {
2497 llvm::Expected<LoadedModuleInfoList> list = GetLoadedModuleList();
2498 if (!list) {
2499 Log *log = GetLog(GDBRLog::Process);
2500 LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}.");
2501 } else {
2502 addr = list->m_link_map;
2503 }
2504 }
2505
2506 return addr;
2507}
2508
2510 // See if the GDB remote client supports the JSON threads info. If so, we
2511 // gather stop info for all threads, expedited registers, expedited memory,
2512 // runtime queue information (iOS and MacOSX only), and more. Expediting
2513 // memory will help stack backtracing be much faster. Expediting registers
2514 // will make sure we don't have to read the thread registers for GPRs.
2516
2517 if (m_jthreadsinfo_sp) {
2518 // Now set the stop info for each thread and also expedite any registers
2519 // and memory that was in the jThreadsInfo response.
2520 StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray();
2521 if (thread_infos) {
2522 const size_t n = thread_infos->GetSize();
2523 for (size_t i = 0; i < n; ++i) {
2524 StructuredData::Dictionary *thread_dict =
2525 thread_infos->GetItemAtIndex(i)->GetAsDictionary();
2526 if (thread_dict)
2527 SetThreadStopInfo(thread_dict);
2528 }
2529 }
2530 }
2531}
2532
2533// Process Memory
2534size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size,
2535 Status &error) {
2537 bool binary_memory_read = m_gdb_comm.GetxPacketSupported();
2538 // M and m packets take 2 bytes for 1 byte of memory
2539 size_t max_memory_size =
2540 binary_memory_read ? m_max_memory_size : m_max_memory_size / 2;
2541 if (size > max_memory_size) {
2542 // Keep memory read sizes down to a sane limit. This function will be
2543 // called multiple times in order to complete the task by
2544 // lldb_private::Process so it is ok to do this.
2545 size = max_memory_size;
2546 }
2547
2548 char packet[64];
2549 int packet_len;
2550 packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64,
2551 binary_memory_read ? 'x' : 'm', (uint64_t)addr,
2552 (uint64_t)size);
2553 assert(packet_len + 1 < (int)sizeof(packet));
2554 UNUSED_IF_ASSERT_DISABLED(packet_len);
2555 StringExtractorGDBRemote response;
2556 if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response,
2559 if (response.IsNormalResponse()) {
2560 error.Clear();
2561 if (binary_memory_read) {
2562 // The lower level GDBRemoteCommunication packet receive layer has
2563 // already de-quoted any 0x7d character escaping that was present in
2564 // the packet
2565
2566 size_t data_received_size = response.GetBytesLeft();
2567 if (data_received_size > size) {
2568 // Don't write past the end of BUF if the remote debug server gave us
2569 // too much data for some reason.
2570 data_received_size = size;
2571 }
2572 memcpy(buf, response.GetStringRef().data(), data_received_size);
2573 return data_received_size;
2574 } else {
2575 return response.GetHexBytes(
2576 llvm::MutableArrayRef<uint8_t>((uint8_t *)buf, size), '\xdd');
2577 }
2578 } else if (response.IsErrorResponse())
2579 error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr);
2580 else if (response.IsUnsupportedResponse())
2581 error.SetErrorStringWithFormat(
2582 "GDB server does not support reading memory");
2583 else
2584 error.SetErrorStringWithFormat(
2585 "unexpected response to GDB server memory read packet '%s': '%s'",
2586 packet, response.GetStringRef().data());
2587 } else {
2588 error.SetErrorStringWithFormat("failed to send packet: '%s'", packet);
2589 }
2590 return 0;
2591}
2592
2595}
2596
2597llvm::Expected<std::vector<uint8_t>>
2599 int32_t type) {
2600 // By this point ReadMemoryTags has validated that tagging is enabled
2601 // for this target/process/address.
2602 DataBufferSP buffer_sp = m_gdb_comm.ReadMemoryTags(addr, len, type);
2603 if (!buffer_sp) {
2604 return llvm::createStringError(llvm::inconvertibleErrorCode(),
2605 "Error reading memory tags from remote");
2606 }
2607
2608 // Return the raw tag data
2609 llvm::ArrayRef<uint8_t> tag_data = buffer_sp->GetData();
2610 std::vector<uint8_t> got;
2611 got.reserve(tag_data.size());
2612 std::copy(tag_data.begin(), tag_data.end(), std::back_inserter(got));
2613 return got;
2614}
2615
2617 int32_t type,
2618 const std::vector<uint8_t> &tags) {
2619 // By now WriteMemoryTags should have validated that tagging is enabled
2620 // for this target/process.
2621 return m_gdb_comm.WriteMemoryTags(addr, len, type, tags);
2622}
2623
2625 std::vector<ObjectFile::LoadableData> entries) {
2626 Status error;
2627 // Sort the entries by address because some writes, like those to flash
2628 // memory, must happen in order of increasing address.
2629 std::stable_sort(
2630 std::begin(entries), std::end(entries),
2632 return a.Dest < b.Dest;
2633 });
2634 m_allow_flash_writes = true;
2636 if (error.Success())
2637 error = FlashDone();
2638 else
2639 // Even though some of the writing failed, try to send a flash done if some
2640 // of the writing succeeded so the flash state is reset to normal, but
2641 // don't stomp on the error status that was set in the write failure since
2642 // that's the one we want to report back.
2643 FlashDone();
2644 m_allow_flash_writes = false;
2645 return error;
2646}
2647
2649 auto size = m_erased_flash_ranges.GetSize();
2650 for (size_t i = 0; i < size; ++i)
2652 return true;
2653 return false;
2654}
2655
2657 Status status;
2658
2659 MemoryRegionInfo region;
2660 status = GetMemoryRegionInfo(addr, region);
2661 if (!status.Success())
2662 return status;
2663
2664 // The gdb spec doesn't say if erasures are allowed across multiple regions,
2665 // but we'll disallow it to be safe and to keep the logic simple by worring
2666 // about only one region's block size. DoMemoryWrite is this function's
2667 // primary user, and it can easily keep writes within a single memory region
2668 if (addr + size > region.GetRange().GetRangeEnd()) {
2669 status.SetErrorString("Unable to erase flash in multiple regions");
2670 return status;
2671 }
2672
2673 uint64_t blocksize = region.GetBlocksize();
2674 if (blocksize == 0) {
2675 status.SetErrorString("Unable to erase flash because blocksize is 0");
2676 return status;
2677 }
2678
2679 // Erasures can only be done on block boundary adresses, so round down addr
2680 // and round up size
2681 lldb::addr_t block_start_addr = addr - (addr % blocksize);
2682 size += (addr - block_start_addr);
2683 if ((size % blocksize) != 0)
2684 size += (blocksize - size % blocksize);
2685
2686 FlashRange range(block_start_addr, size);
2687
2688 if (HasErased(range))
2689 return status;
2690
2691 // We haven't erased the entire range, but we may have erased part of it.
2692 // (e.g., block A is already erased and range starts in A and ends in B). So,
2693 // adjust range if necessary to exclude already erased blocks.
2695 // Assuming that writes and erasures are done in increasing addr order,
2696 // because that is a requirement of the vFlashWrite command. Therefore, we
2697 // only need to look at the last range in the list for overlap.
2698 const auto &last_range = *m_erased_flash_ranges.Back();
2699 if (range.GetRangeBase() < last_range.GetRangeEnd()) {
2700 auto overlap = last_range.GetRangeEnd() - range.GetRangeBase();
2701 // overlap will be less than range.GetByteSize() or else HasErased()
2702 // would have been true
2703 range.SetByteSize(range.GetByteSize() - overlap);
2704 range.SetRangeBase(range.GetRangeBase() + overlap);
2705 }
2706 }
2707
2708 StreamString packet;
2709 packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(),
2710 (uint64_t)range.GetByteSize());
2711
2712 StringExtractorGDBRemote response;
2713 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2716 if (response.IsOKResponse()) {
2717 m_erased_flash_ranges.Insert(range, true);
2718 } else {
2719 if (response.IsErrorResponse())
2720 status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64,
2721 addr);
2722 else if (response.IsUnsupportedResponse())
2723 status.SetErrorStringWithFormat("GDB server does not support flashing");
2724 else
2726 "unexpected response to GDB server flash erase packet '%s': '%s'",
2727 packet.GetData(), response.GetStringRef().data());
2728 }
2729 } else {
2730 status.SetErrorStringWithFormat("failed to send packet: '%s'",
2731 packet.GetData());
2732 }
2733 return status;
2734}
2735
2737 Status status;
2738 // If we haven't erased any blocks, then we must not have written anything
2739 // either, so there is no need to actually send a vFlashDone command
2741 return status;
2742 StringExtractorGDBRemote response;
2743 if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response,
2746 if (response.IsOKResponse()) {
2748 } else {
2749 if (response.IsErrorResponse())
2750 status.SetErrorStringWithFormat("flash done failed");
2751 else if (response.IsUnsupportedResponse())
2752 status.SetErrorStringWithFormat("GDB server does not support flashing");
2753 else
2755 "unexpected response to GDB server flash done packet: '%s'",
2756 response.GetStringRef().data());
2757 }
2758 } else {
2759 status.SetErrorStringWithFormat("failed to send flash done packet");
2760 }
2761 return status;
2762}
2763
2764size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf,
2765 size_t size, Status &error) {
2767 // M and m packets take 2 bytes for 1 byte of memory
2768 size_t max_memory_size = m_max_memory_size / 2;
2769 if (size > max_memory_size) {
2770 // Keep memory read sizes down to a sane limit. This function will be
2771 // called multiple times in order to complete the task by
2772 // lldb_private::Process so it is ok to do this.
2773 size = max_memory_size;
2774 }
2775
2776 StreamGDBRemote packet;
2777
2778 MemoryRegionInfo region;
2779 Status region_status = GetMemoryRegionInfo(addr, region);
2780
2781 bool is_flash =
2782 region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes;
2783
2784 if (is_flash) {
2785 if (!m_allow_flash_writes) {
2786 error.SetErrorString("Writing to flash memory is not allowed");
2787 return 0;
2788 }
2789 // Keep the write within a flash memory region
2790 if (addr + size > region.GetRange().GetRangeEnd())
2791 size = region.GetRange().GetRangeEnd() - addr;
2792 // Flash memory must be erased before it can be written
2793 error = FlashErase(addr, size);
2794 if (!error.Success())
2795 return 0;
2796 packet.Printf("vFlashWrite:%" PRIx64 ":", addr);
2797 packet.PutEscapedBytes(buf, size);
2798 } else {
2799 packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size);
2800 packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(),
2802 }
2803 StringExtractorGDBRemote response;
2804 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response,
2807 if (response.IsOKResponse()) {
2808 error.Clear();
2809 return size;
2810 } else if (response.IsErrorResponse())
2811 error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64,
2812 addr);
2813 else if (response.IsUnsupportedResponse())
2814 error.SetErrorStringWithFormat(
2815 "GDB server does not support writing memory");
2816 else
2817 error.SetErrorStringWithFormat(
2818 "unexpected response to GDB server memory write packet '%s': '%s'",
2819 packet.GetData(), response.GetStringRef().data());
2820 } else {
2821 error.SetErrorStringWithFormat("failed to send packet: '%s'",
2822 packet.GetData());
2823 }
2824 return 0;
2825}
2826
2828 uint32_t permissions,
2829 Status &error) {
2831 addr_t allocated_addr = LLDB_INVALID_ADDRESS;
2832
2834 allocated_addr = m_gdb_comm.AllocateMemory(size, permissions);
2835 if (allocated_addr != LLDB_INVALID_ADDRESS ||
2837 return allocated_addr;
2838 }
2839
2841 // Call mmap() to create memory in the inferior..
2842 unsigned prot = 0;
2843 if (permissions & lldb::ePermissionsReadable)
2844 prot |= eMmapProtRead;
2845 if (permissions & lldb::ePermissionsWritable)
2846 prot |= eMmapProtWrite;
2847 if (permissions & lldb::ePermissionsExecutable)
2848 prot |= eMmapProtExec;
2849
2850 if (InferiorCallMmap(this, allocated_addr, 0, size, prot,
2852 m_addr_to_mmap_size[allocated_addr] = size;
2853 else {
2854 allocated_addr = LLDB_INVALID_ADDRESS;
2855 LLDB_LOGF(log,
2856 "ProcessGDBRemote::%s no direct stub support for memory "
2857 "allocation, and InferiorCallMmap also failed - is stub "
2858 "missing register context save/restore capability?",
2859 __FUNCTION__);
2860 }
2861 }
2862
2863 if (allocated_addr == LLDB_INVALID_ADDRESS)
2864 error.SetErrorStringWithFormat(
2865 "unable to allocate %" PRIu64 " bytes of memory with permissions %s",
2866 (uint64_t)size, GetPermissionsAsCString(permissions));
2867 else
2868 error.Clear();
2869 return allocated_addr;
2870}
2871
2873 MemoryRegionInfo &region_info) {
2874
2875 Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info));
2876 return error;
2877}
2878
2881}
2882
2885}
2886
2888 Status error;
2890
2891 switch (supported) {
2892 case eLazyBoolCalculate:
2893 // We should never be deallocating memory without allocating memory first
2894 // so we should never get eLazyBoolCalculate
2895 error.SetErrorString(
2896 "tried to deallocate memory without ever allocating memory");
2897 break;
2898
2899 case eLazyBoolYes:
2900 if (!m_gdb_comm.DeallocateMemory(addr))
2901 error.SetErrorStringWithFormat(
2902 "unable to deallocate memory at 0x%" PRIx64, addr);
2903 break;
2904
2905 case eLazyBoolNo:
2906 // Call munmap() to deallocate memory in the inferior..
2907 {
2908 MMapMap::iterator pos = m_addr_to_mmap_size.find(addr);
2909 if (pos != m_addr_to_mmap_size.end() &&
2910 InferiorCallMunmap(this, addr, pos->second))
2911 m_addr_to_mmap_size.erase(pos);
2912 else
2913 error.SetErrorStringWithFormat(
2914 "unable to deallocate memory at 0x%" PRIx64, addr);
2915 }
2916 break;
2917 }
2918
2919 return error;
2920}
2921
2922// Process STDIO
2923size_t ProcessGDBRemote::PutSTDIN(const char *src, size_t src_len,
2924 Status &error) {
2926 ConnectionStatus status;
2927 m_stdio_communication.WriteAll(src, src_len, status, nullptr);
2928 } else if (m_stdin_forward) {
2929 m_gdb_comm.SendStdinNotification(src, src_len);
2930 }
2931 return 0;
2932}
2933
2935 Status error;
2936 assert(bp_site != nullptr);
2937
2938 // Get logging info
2940 user_id_t site_id = bp_site->GetID();
2941
2942 // Get the breakpoint address
2943 const addr_t addr = bp_site->GetLoadAddress();
2944
2945 // Log that a breakpoint was requested
2946 LLDB_LOGF(log,
2947 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2948 ") address = 0x%" PRIx64,
2949 site_id, (uint64_t)addr);
2950
2951 // Breakpoint already exists and is enabled
2952 if (bp_site->IsEnabled()) {
2953 LLDB_LOGF(log,
2954 "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64
2955 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)",
2956 site_id, (uint64_t)addr);
2957 return error;
2958 }
2959
2960 // Get the software breakpoint trap opcode size
2961 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
2962
2963 // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this
2964 // breakpoint type is supported by the remote stub. These are set to true by
2965 // default, and later set to false only after we receive an unimplemented
2966 // response when sending a breakpoint packet. This means initially that
2967 // unless we were specifically instructed to use a hardware breakpoint, LLDB
2968 // will attempt to set a software breakpoint. HardwareRequired() also queries
2969 // a boolean variable which indicates if the user specifically asked for
2970 // hardware breakpoints. If true then we will skip over software
2971 // breakpoints.
2973 (!bp_site->HardwareRequired())) {
2974 // Try to send off a software breakpoint packet ($Z0)
2975 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
2976 eBreakpointSoftware, true, addr, bp_op_size, GetInterruptTimeout());
2977 if (error_no == 0) {
2978 // The breakpoint was placed successfully
2979 bp_site->SetEnabled(true);
2981 return error;
2982 }
2983
2984 // SendGDBStoppointTypePacket() will return an error if it was unable to
2985 // set this breakpoint. We need to differentiate between a error specific
2986 // to placing this breakpoint or if we have learned that this breakpoint
2987 // type is unsupported. To do this, we must test the support boolean for
2988 // this breakpoint type to see if it now indicates that this breakpoint
2989 // type is unsupported. If they are still supported then we should return
2990 // with the error code. If they are now unsupported, then we would like to
2991 // fall through and try another form of breakpoint.
2993 if (error_no != UINT8_MAX)
2994 error.SetErrorStringWithFormat(
2995 "error: %d sending the breakpoint request", error_no);
2996 else
2997 error.SetErrorString("error sending the breakpoint request");
2998 return error;
2999 }
3000
3001 // We reach here when software breakpoints have been found to be
3002 // unsupported. For future calls to set a breakpoint, we will not attempt
3003 // to set a breakpoint with a type that is known not to be supported.
3004 LLDB_LOGF(log, "Software breakpoints are unsupported");
3005
3006 // So we will fall through and try a hardware breakpoint
3007 }
3008
3009 // The process of setting a hardware breakpoint is much the same as above.
3010 // We check the supported boolean for this breakpoint type, and if it is
3011 // thought to be supported then we will try to set this breakpoint with a
3012 // hardware breakpoint.
3014 // Try to send off a hardware breakpoint packet ($Z1)
3015 uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket(
3016 eBreakpointHardware, true, addr, bp_op_size, GetInterruptTimeout());
3017 if (error_no == 0) {
3018 // The breakpoint was placed successfully
3019 bp_site->SetEnabled(true);
3021 return error;
3022 }
3023
3024 // Check if the error was something other then an unsupported breakpoint
3025 // type
3027 // Unable to set this hardware breakpoint
3028 if (error_no != UINT8_MAX)
3029 error.SetErrorStringWithFormat(
3030 "error: %d sending the hardware breakpoint request "
3031 "(hardware breakpoint resources might be exhausted or unavailable)",
3032 error_no);
3033 else
3034 error.SetErrorString("error sending the hardware breakpoint request "
3035 "(hardware breakpoint resources "
3036 "might be exhausted or unavailable)");
3037 return error;
3038 }
3039
3040 // We will reach here when the stub gives an unsupported response to a
3041 // hardware breakpoint
3042 LLDB_LOGF(log, "Hardware breakpoints are unsupported");
3043
3044 // Finally we will falling through to a #trap style breakpoint
3045 }
3046
3047 // Don't fall through when hardware breakpoints were specifically requested
3048 if (bp_site->HardwareRequired()) {
3049 error.SetErrorString("hardware breakpoints are not supported");
3050 return error;
3051 }
3052
3053 // As a last resort we want to place a manual breakpoint. An instruction is
3054 // placed into the process memory using memory write packets.
3055 return EnableSoftwareBreakpoint(bp_site);
3056}
3057
3059 Status error;
3060 assert(bp_site != nullptr);
3061 addr_t addr = bp_site->GetLoadAddress();
3062 user_id_t site_id = bp_site->GetID();
3064 LLDB_LOGF(log,
3065 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3066 ") addr = 0x%8.8" PRIx64,
3067 site_id, (uint64_t)addr);
3068
3069 if (bp_site->IsEnabled()) {
3070 const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site);
3071
3072 BreakpointSite::Type bp_type = bp_site->GetType();
3073 switch (bp_type) {
3076 break;
3077
3080 addr, bp_op_size,
3082 error.SetErrorToGenericError();
3083 break;
3084
3087 addr, bp_op_size,
3089 error.SetErrorToGenericError();
3090 } break;
3091 }
3092 if (error.Success())
3093 bp_site->SetEnabled(false);
3094 } else {
3095 LLDB_LOGF(log,
3096 "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64
3097 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3098 site_id, (uint64_t)addr);
3099 return error;
3100 }
3101
3102 if (error.Success())
3103 error.SetErrorToGenericError();
3104 return error;
3105}
3106
3107// Pre-requisite: wp != NULL.
3109 assert(wp);
3110 bool watch_read = wp->WatchpointRead();
3111 bool watch_write = wp->WatchpointWrite();
3112 bool watch_modify = wp->WatchpointModify();
3113
3114 // watch_read, watch_write, watch_modify cannot all be false.
3115 assert((watch_read || watch_write || watch_modify) &&
3116 "watch_read, watch_write, watch_modify cannot all be false.");
3117 if (watch_read && (watch_write || watch_modify))
3118 return eWatchpointReadWrite;
3119 else if (watch_read)
3120 return eWatchpointRead;
3121 else // Must be watch_write or watch_modify, then.
3122 return eWatchpointWrite;
3123}
3124
3126 Status error;
3127 if (wp) {
3128 user_id_t watchID = wp->GetID();
3129 addr_t addr = wp->GetLoadAddress();
3131 LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")",
3132 watchID);
3133 if (wp->IsEnabled()) {
3134 LLDB_LOGF(log,
3135 "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64
3136 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.",
3137 watchID, (uint64_t)addr);
3138 return error;
3139 }
3140
3142 // Pass down an appropriate z/Z packet...
3144 if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr,
3145 wp->GetByteSize(),
3146 GetInterruptTimeout()) == 0) {
3147 wp->SetEnabled(true, notify);
3148 return error;
3149 } else
3150 error.SetErrorString("sending gdb watchpoint packet failed");
3151 } else
3152 error.SetErrorString("watchpoints not supported");
3153 } else {
3154 error.SetErrorString("Watchpoint argument was NULL.");
3155 }
3156 if (error.Success())
3157 error.SetErrorToGenericError();
3158 return error;
3159}
3160
3162 Status error;
3163 if (wp) {
3164 user_id_t watchID = wp->GetID();
3165
3167
3168 addr_t addr = wp->GetLoadAddress();
3169
3170 LLDB_LOGF(log,
3171 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3172 ") addr = 0x%8.8" PRIx64,
3173 watchID, (uint64_t)addr);
3174
3175 if (!wp->IsEnabled()) {
3176 LLDB_LOGF(log,
3177 "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64
3178 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)",
3179 watchID, (uint64_t)addr);
3180 // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling
3181 // attempt might come from the user-supplied actions, we'll route it in
3182 // order for the watchpoint object to intelligently process this action.
3183 wp->SetEnabled(false, notify);
3184 return error;
3185 }
3186
3187 if (wp->IsHardware()) {
3189 // Pass down an appropriate z/Z packet...
3190 if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr,
3191 wp->GetByteSize(),
3192 GetInterruptTimeout()) == 0) {
3193 wp->SetEnabled(false, notify);
3194 return error;
3195 } else
3196 error.SetErrorString("sending gdb watchpoint packet failed");
3197 }
3198 // TODO: clear software watchpoints if we implement them
3199 } else {
3200 error.SetErrorString("Watchpoint argument was NULL.");
3201 }
3202 if (error.Success())
3203 error.SetErrorToGenericError();
3204 return error;
3205}
3206
3210}
3211
3213 Status error;
3214 Log *log = GetLog(GDBRLog::Process);
3215 LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo);
3216
3218 error.SetErrorStringWithFormat("failed to send signal %i", signo);
3219 return error;
3220}
3221
3222Status
3224 // Make sure we aren't already connected?
3225 if (m_gdb_comm.IsConnected())
3226 return Status();
3227
3228 PlatformSP platform_sp(GetTarget().GetPlatform());
3229 if (platform_sp && !platform_sp->IsHost())
3230 return Status("Lost debug server connection");
3231
3232 auto error = LaunchAndConnectToDebugserver(process_info);
3233 if (error.Fail()) {
3234 const char *error_string = error.AsCString();
3235 if (error_string == nullptr)
3236 error_string = "unable to launch " DEBUGSERVER_BASENAME;
3237 }
3238 return error;
3239}
3240#if !defined(_WIN32)
3241#define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1
3242#endif
3243
3244#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3245static bool SetCloexecFlag(int fd) {
3246#if defined(FD_CLOEXEC)
3247 int flags = ::fcntl(fd, F_GETFD);
3248 if (flags == -1)
3249 return false;
3250 return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0);
3251#else
3252 return false;
3253#endif
3254}
3255#endif
3256
3258 const ProcessInfo &process_info) {
3259 using namespace std::placeholders; // For _1, _2, etc.
3260
3261 Status error;
3263 // If we locate debugserver, keep that located version around
3264 static FileSpec g_debugserver_file_spec;
3265
3266 ProcessLaunchInfo debugserver_launch_info;
3267 // Make debugserver run in its own session so signals generated by special
3268 // terminal key sequences (^C) don't affect debugserver.
3269 debugserver_launch_info.SetLaunchInSeparateProcessGroup(true);
3270
3271 const std::weak_ptr<ProcessGDBRemote> this_wp =
3272 std::static_pointer_cast<ProcessGDBRemote>(shared_from_this());
3273 debugserver_launch_info.SetMonitorProcessCallback(
3274 std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3));
3275 debugserver_launch_info.SetUserID(process_info.GetUserID());
3276
3277#if defined(__APPLE__)
3278 // On macOS 11, we need to support x86_64 applications translated to
3279 // arm64. We check whether a binary is translated and spawn the correct
3280 // debugserver accordingly.
3281 int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID,
3282 static_cast<int>(process_info.GetProcessID()) };
3283 struct kinfo_proc processInfo;
3284 size_t bufsize = sizeof(processInfo);
3285 if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo,
3286 &bufsize, NULL, 0) == 0 && bufsize > 0) {
3287 if (processInfo.kp_proc.p_flag & P_TRANSLATED) {
3288 FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver");
3289 debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false);
3290 }
3291 }
3292#endif
3293
3294 int communication_fd = -1;
3295#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3296 // Use a socketpair on non-Windows systems for security and performance
3297 // reasons.
3298 int sockets[2]; /* the pair of socket descriptors */
3299 if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
3300 error.SetErrorToErrno();
3301 return error;
3302 }
3303
3304 int our_socket = sockets[0];
3305 int gdb_socket = sockets[1];
3306 auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); });
3307 auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); });
3308
3309 // Don't let any child processes inherit our communication socket
3310 SetCloexecFlag(our_socket);
3311 communication_fd = gdb_socket;
3312#endif
3313
3315 nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info,
3316 nullptr, nullptr, communication_fd);
3317
3318 if (error.Success())
3319 m_debugserver_pid = debugserver_launch_info.GetProcessID();
3320 else
3322
3324#ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION
3325 // Our process spawned correctly, we can now set our connection to use
3326 // our end of the socket pair
3327 cleanup_our.release();
3329 std::make_unique<ConnectionFileDescriptor>(our_socket, true));
3330#endif
3332 }
3333
3334 if (error.Fail()) {
3335 Log *log = GetLog(GDBRLog::Process);
3336
3337 LLDB_LOGF(log, "failed to start debugserver process: %s",
3338 error.AsCString());
3339 return error;
3340 }
3341
3342 if (m_gdb_comm.IsConnected()) {
3343 // Finish the connection process by doing the handshake without
3344 // connecting (send NULL URL)
3346 } else {
3347 error.SetErrorString("connection failed");
3348 }
3349 }
3350 return error;
3351}
3352
3354 std::weak_ptr<ProcessGDBRemote> process_wp, lldb::pid_t debugserver_pid,
3355 int signo, // Zero for no signal
3356 int exit_status // Exit value of process if signal is zero
3357) {
3358 // "debugserver_pid" argument passed in is the process ID for debugserver
3359 // that we are tracking...
3360 Log *log = GetLog(GDBRLog::Process);
3361
3362 LLDB_LOGF(log,
3363 "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64
3364 ", signo=%i (0x%x), exit_status=%i)",
3365 __FUNCTION__, debugserver_pid, signo, signo, exit_status);
3366
3367 std::shared_ptr<ProcessGDBRemote> process_sp = process_wp.lock();
3368 LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__,
3369 static_cast<void *>(process_sp.get()));
3370 if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid)
3371 return;
3372
3373 // Sleep for a half a second to make sure our inferior process has time to
3374 // set its exit status before we set it incorrectly when both the debugserver
3375 // and the inferior process shut down.
3376 std::this_thread::sleep_for(std::chrono::milliseconds(500));
3377
3378 // If our process hasn't yet exited, debugserver might have died. If the
3379 // process did exit, then we are reaping it.
3380 const StateType state = process_sp->GetState();
3381
3382 if (state != eStateInvalid && state != eStateUnloaded &&
3383 state != eStateExited && state != eStateDetached) {
3384 StreamString stream;
3385 if (signo == 0)
3386 stream.Format(DEBUGSERVER_BASENAME " died with an exit status of {0:x8}",
3387 exit_status);
3388 else {
3389 llvm::StringRef signal_name =
3390 process_sp->GetUnixSignals()->GetSignalAsStringRef(signo);
3391 const char *format_str = DEBUGSERVER_BASENAME " died with signal {0}";
3392 if (!signal_name.empty())
3393 stream.Format(format_str, signal_name);
3394 else
3395 stream.Format(format_str, signo);
3396 }
3397 process_sp->SetExitStatus(-1, stream.GetString());
3398 }
3399 // Debugserver has exited we need to let our ProcessGDBRemote know that it no
3400 // longer has a debugserver instance
3401 process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID;
3402}
3403
3409 }
3410}
3411
3413 static llvm::once_flag g_once_flag;
3414
3415 llvm::call_once(g_once_flag, []() {
3419 });
3420}
3421
3424 debugger, PluginProperties::GetSettingName())) {
3425 const bool is_global_setting = true;
3428 "Properties for the gdb-remote process plug-in.", is_global_setting);
3429 }
3430}
3431
3433 Log *log = GetLog(GDBRLog::Process);
3434
3435 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3436
3437 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3438 if (!m_async_thread.IsJoinable()) {
3439 // Create a thread that watches our internal state and controls which
3440 // events make it to clients (into the DCProcess event queue).
3441
3442 llvm::Expected<HostThread> async_thread =
3443 ThreadLauncher::LaunchThread("<lldb.process.gdb-remote.async>", [this] {
3445 });
3446 if (!async_thread) {
3447 LLDB_LOG_ERROR(GetLog(LLDBLog::Host), async_thread.takeError(),
3448 "failed to launch host thread: {0}");
3449 return false;
3450 }
3451 m_async_thread = *async_thread;
3452 } else
3453 LLDB_LOGF(log,
3454 "ProcessGDBRemote::%s () - Called when Async thread was "
3455 "already running.",
3456 __FUNCTION__);
3457
3458 return m_async_thread.IsJoinable();
3459}
3460
3462 Log *log = GetLog(GDBRLog::Process);
3463
3464 LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__);
3465
3466 std::lock_guard<std::recursive_mutex> guard(m_async_thread_state_mutex);
3467 if (m_async_thread.IsJoinable()) {
3469
3470 // This will shut down the async thread.
3471 m_gdb_comm.Disconnect(); // Disconnect from the debug server.
3472
3473 // Stop the stdio thread
3474 m_async_thread.Join(nullptr);
3476 } else
3477 LLDB_LOGF(
3478 log,
3479 "ProcessGDBRemote::%s () - Called when Async thread was not running.",
3480 __FUNCTION__);
3481}
3482
3484 Log *log = GetLog(GDBRLog::Process);
3485 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread starting...",
3486 __FUNCTION__, GetID());
3487
3488 EventSP event_sp;
3489
3490 // We need to ignore any packets that come in after we have
3491 // have decided the process has exited. There are some
3492 // situations, for instance when we try to interrupt a running
3493 // process and the interrupt fails, where another packet might
3494 // get delivered after we've decided to give up on the process.
3495 // But once we've decided we are done with the process we will
3496 // not be in a state to do anything useful with new packets.
3497 // So it is safer to simply ignore any remaining packets by
3498 // explicitly checking for eStateExited before reentering the
3499 // fetch loop.
3500
3501 bool done = false;
3502 while (!done && GetPrivateState() != eStateExited) {
3503 LLDB_LOGF(log,
3504 "ProcessGDBRemote::%s(pid = %" PRIu64
3505 ") listener.WaitForEvent (NULL, event_sp)...",
3506 __FUNCTION__, GetID());
3507
3508 if (m_async_listener_sp->GetEvent(event_sp, std::nullopt)) {
3509 const uint32_t event_type = event_sp->GetType();
3510 if (event_sp->BroadcasterIs(&m_async_broadcaster)) {
3511 LLDB_LOGF(log,
3512 "ProcessGDBRemote::%s(pid = %" PRIu64
3513 ") Got an event of type: %d...",
3514 __FUNCTION__, GetID(), event_type);
3515
3516 switch (event_type) {
3518 const EventDataBytes *continue_packet =
3520
3521 if (continue_packet) {
3522 const char *continue_cstr =
3523 (const char *)continue_packet->GetBytes();
3524 const size_t continue_cstr_len = continue_packet->GetByteSize();
3525 LLDB_LOGF(log,
3526 "ProcessGDBRemote::%s(pid = %" PRIu64
3527 ") got eBroadcastBitAsyncContinue: %s",
3528 __FUNCTION__, GetID(), continue_cstr);
3529
3530 if (::strstr(continue_cstr, "vAttach") == nullptr)
3532 StringExtractorGDBRemote response;
3533
3534 StateType stop_state =
3536 *this, *GetUnixSignals(),
3537 llvm::StringRef(continue_cstr, continue_cstr_len),
3538 GetInterruptTimeout(), response);
3539
3540 // We need to immediately clear the thread ID list so we are sure
3541 // to get a valid list of threads. The thread ID list might be
3542 // contained within the "response", or the stop reply packet that
3543 // caused the stop. So clear it now before we give the stop reply
3544 // packet to the process using the
3545 // SetLastStopPacket()...
3547
3548 switch (stop_state) {
3549 case eStateStopped:
3550 case eStateCrashed:
3551 case eStateSuspended:
3552 SetLastStopPacket(response);
3553 SetPrivateState(stop_state);
3554 break;
3555
3556 case eStateExited: {
3557 SetLastStopPacket(response);
3559 response.SetFilePos(1);
3560
3561 int exit_status = response.GetHexU8();
3562 std::string desc_string;
3563 if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') {
3564 llvm::StringRef desc_str;
3565 llvm::StringRef desc_token;
3566 while (response.GetNameColonValue(desc_token, desc_str)) {
3567 if (desc_token != "description")
3568 continue;
3569 StringExtractor extractor(desc_str);
3570 extractor.GetHexByteString(desc_string);
3571 }
3572 }
3573 SetExitStatus(exit_status, desc_string.c_str());
3574 done = true;
3575 break;
3576 }
3577 case eStateInvalid: {
3578 // Check to see if we were trying to attach and if we got back
3579 // the "E87" error code from debugserver -- this indicates that
3580 // the process is not debuggable. Return a slightly more
3581 // helpful error message about why the attach failed.
3582 if (::strstr(continue_cstr, "vAttach") != nullptr &&
3583 response.GetError() == 0x87) {
3584 SetExitStatus(-1, "cannot attach to process due to "
3585 "System Integrity Protection");
3586 } else if (::strstr(continue_cstr, "vAttach") != nullptr &&
3587 response.GetStatus().Fail()) {
3588 SetExitStatus(-1, response.GetStatus().AsCString());
3589 } else {
3590 SetExitStatus(-1, "lost connection");
3591 }
3592 done = true;
3593 break;
3594 }
3595
3596 default:
3597 SetPrivateState(stop_state);
3598 break;
3599 } // switch(stop_state)
3600 } // if (continue_packet)
3601 } // case eBroadcastBitAsyncContinue
3602 break;
3603
3605 LLDB_LOGF(log,
3606 "ProcessGDBRemote::%s(pid = %" PRIu64
3607 ") got eBroadcastBitAsyncThreadShouldExit...",
3608 __FUNCTION__, GetID());
3609 done = true;
3610 break;
3611
3612 default:
3613 LLDB_LOGF(log,
3614 "ProcessGDBRemote::%s(pid = %" PRIu64
3615 ") got unknown event 0x%8.8x",
3616 __FUNCTION__, GetID(), event_type);
3617 done = true;
3618 break;
3619 }
3620 }
3621 } else {
3622 LLDB_LOGF(log,
3623 "ProcessGDBRemote::%s(pid = %" PRIu64
3624 ") listener.WaitForEvent (NULL, event_sp) => false",
3625 __FUNCTION__, GetID());
3626 done = true;
3627 }
3628 }
3629
3630 LLDB_LOGF(log, "ProcessGDBRemote::%s(pid = %" PRIu64 ") thread exiting...",
3631 __FUNCTION__, GetID());
3632
3633 return {};
3634}
3635
3636// uint32_t
3637// ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList
3638// &matches, std::vector<lldb::pid_t> &pids)
3639//{
3640// // If we are planning to launch the debugserver remotely, then we need to
3641// fire up a debugserver
3642// // process and ask it for the list of processes. But if we are local, we
3643// can let the Host do it.
3644// if (m_local_debugserver)
3645// {
3646// return Host::ListProcessesMatchingName (name, matches, pids);
3647// }
3648// else
3649// {
3650// // FIXME: Implement talking to the remote debugserver.
3651// return 0;
3652// }
3653//
3654//}
3655//
3657 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
3658 lldb::user_id_t break_loc_id) {
3659 // I don't think I have to do anything here, just make sure I notice the new
3660 // thread when it starts to
3661 // run so I can stop it if that's what I want to do.
3662 Log *log = GetLog(LLDBLog::Step);
3663 LLDB_LOGF(log, "Hit New Thread Notification breakpoint.");
3664 return false;
3665}
3666
3668 Log *log = GetLog(GDBRLog::Process);
3669 LLDB_LOG(log, "Check if need to update ignored signals");
3670
3671 // QPassSignals package is not supported by the server, there is no way we
3672 // can ignore any signals on server side.
3674 return Status();
3675
3676 // No signals, nothing to send.
3677 if (m_unix_signals_sp == nullptr)
3678 return Status();
3679
3680 // Signals' version hasn't changed, no need to send anything.
3681 uint64_t new_signals_version = m_unix_signals_sp->GetVersion();
3682 if (new_signals_version == m_last_signals_version) {
3683 LLDB_LOG(log, "Signals' version hasn't changed. version={0}",
3685 return Status();
3686 }
3687
3688 auto signals_to_ignore =
3689 m_unix_signals_sp->GetFilteredSignals(false, false, false);
3690 Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore);
3691
3692 LLDB_LOG(log,
3693 "Signals' version changed. old version={0}, new version={1}, "
3694 "signals ignored={2}, update result={3}",
3695 m_last_signals_version, new_signals_version,
3696 signals_to_ignore.size(), error);
3697
3698 if (error.Success())
3699 m_last_signals_version = new_signals_version;
3700
3701 return error;
3702}
3703
3705 Log *log = GetLog(LLDBLog::Step);
3707 if (log && log->GetVerbose())
3708 LLDB_LOGF(log, "Enabled noticing new thread breakpoint.");
3709 m_thread_create_bp_sp->SetEnabled(true);
3710 } else {
3711 PlatformSP platform_sp(GetTarget().GetPlatform());
3712 if (platform_sp) {
3714 platform_sp->SetThreadCreationBreakpoint(GetTarget());
3716 if (log && log->GetVerbose())
3717 LLDB_LOGF(
3718 log, "Successfully created new thread notification breakpoint %i",
3719 m_thread_create_bp_sp->GetID());
3720 m_thread_create_bp_sp->SetCallback(
3722 } else {
3723 LLDB_LOGF(log, "Failed to create new thread notification breakpoint.");
3724 }
3725 }
3726 }
3727 return m_thread_create_bp_sp.get() != nullptr;
3728}
3729
3731 Log *log = GetLog(LLDBLog::Step);
3732 if (log && log->GetVerbose())
3733 LLDB_LOGF(log, "Disabling new thread notification breakpoint.");
3734
3736 m_thread_create_bp_sp->SetEnabled(false);
3737
3738 return true;
3739}
3740
3742 if (m_dyld_up.get() == nullptr)
3743 m_dyld_up.reset(DynamicLoader::FindPlugin(this, ""));
3744 return m_dyld_up.get();
3745}
3746
3748 int return_value;
3749 bool was_supported;
3750
3751 Status error;
3752
3753 return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported);
3754 if (return_value != 0) {
3755 if (!was_supported)
3756 error.SetErrorString("Sending events is not supported for this process.");
3757 else
3758 error.SetErrorStringWithFormat("Error sending event data: %d.",
3759 return_value);
3760 }
3761 return error;
3762}
3763
3765 DataBufferSP buf;
3767 llvm::Expected<std::string> response = m_gdb_comm.ReadExtFeature("auxv", "");
3768 if (response)
3769 buf = std::make_shared<DataBufferHeap>(response->c_str(),
3770 response->length());
3771 else
3772 LLDB_LOG_ERROR(GetLog(GDBRLog::Process), response.takeError(), "{0}");
3773 }
3775}
3776
3779 StructuredData::ObjectSP object_sp;
3780
3783 SystemRuntime *runtime = GetSystemRuntime();
3784 if (runtime) {
3785 runtime->AddThreadExtendedInfoPacketHints(args_dict);
3786 }
3787 args_dict->GetAsDictionary()->AddIntegerItem("thread", tid);
3788
3789 StreamString packet;
3790 packet << "jThreadExtendedInfo:";
3791 args_dict->Dump(packet, false);
3792
3793 // FIXME the final character of a JSON dictionary, '}', is the escape
3794 // character in gdb-remote binary mode. lldb currently doesn't escape
3795 // these characters in its packet output -- so we add the quoted version of
3796 // the } character here manually in case we talk to a debugserver which un-
3797 // escapes the characters at packet read time.
3798 packet << (char)(0x7d ^ 0x20);
3799
3800 StringExtractorGDBRemote response;
3801 response.SetResponseValidatorToJSON();
3802 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3805 response.GetResponseType();
3806 if (response_type == StringExtractorGDBRemote::eResponse) {
3807 if (!response.Empty()) {
3808 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3809 }
3810 }
3811 }
3812 }
3813 return object_sp;
3814}
3815
3817 lldb::addr_t image_list_address, lldb::addr_t image_count) {
3818
3820 args_dict->GetAsDictionary()->AddIntegerItem("image_list_address",
3821 image_list_address);
3822 args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count);
3823
3824 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3825}
3826
3829
3830 args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true);
3831
3832 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3833}
3834
3836 const std::vector<lldb::addr_t> &load_addresses) {
3839
3840 for (auto addr : load_addresses)
3841 addresses->AddIntegerItem(addr);
3842
3843 args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses);
3844
3845 return GetLoadedDynamicLibrariesInfos_sender(args_dict);
3846}
3847
3850 StructuredData::ObjectSP args_dict) {
3851 StructuredData::ObjectSP object_sp;
3852
3854 // Scope for the scoped timeout object
3856 std::chrono::seconds(10));
3857
3858 StreamString packet;
3859 packet << "jGetLoadedDynamicLibrariesInfos:";
3860 args_dict->Dump(packet, false);
3861
3862 // FIXME the final character of a JSON dictionary, '}', is the escape
3863 // character in gdb-remote binary mode. lldb currently doesn't escape
3864 // these characters in its packet output -- so we add the quoted version of
3865 // the } character here manually in case we talk to a debugserver which un-
3866 // escapes the characters at packet read time.
3867 packet << (char)(0x7d ^ 0x20);
3868
3869 StringExtractorGDBRemote response;
3870 response.SetResponseValidatorToJSON();
3871 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3874 response.GetResponseType();
3875 if (response_type == StringExtractorGDBRemote::eResponse) {
3876 if (!response.Empty()) {
3877 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3878 }
3879 }
3880 }
3881 }
3882 return object_sp;
3883}
3884
3886 StructuredData::ObjectSP object_sp;
3888
3890 StringExtractorGDBRemote response;
3891 response.SetResponseValidatorToJSON();
3892 if (m_gdb_comm.SendPacketAndWaitForResponse("jGetDyldProcessState",
3893 response) ==
3896 response.GetResponseType();
3897 if (response_type == StringExtractorGDBRemote::eResponse) {
3898 if (!response.Empty()) {
3899 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3900 }
3901 }
3902 }
3903 }
3904 return object_sp;
3905}
3906
3908 StructuredData::ObjectSP object_sp;
3910
3912 StreamString packet;
3913 packet << "jGetSharedCacheInfo:";
3914 args_dict->Dump(packet, false);
3915
3916 // FIXME the final character of a JSON dictionary, '}', is the escape
3917 // character in gdb-remote binary mode. lldb currently doesn't escape
3918 // these characters in its packet output -- so we add the quoted version of
3919 // the } character here manually in case we talk to a debugserver which un-
3920 // escapes the characters at packet read time.
3921 packet << (char)(0x7d ^ 0x20);
3922
3923 StringExtractorGDBRemote response;
3924 response.SetResponseValidatorToJSON();
3925 if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response) ==
3928 response.GetResponseType();
3929 if (response_type == StringExtractorGDBRemote::eResponse) {
3930 if (!response.Empty()) {
3931 object_sp = StructuredData::ParseJSON(response.GetStringRef());
3932 }
3933 }
3934 }
3935 }
3936 return object_sp;
3937}
3938
3940 llvm::StringRef type_name, const StructuredData::ObjectSP &config_sp) {
3941 return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp);
3942}
3943
3944// Establish the largest memory read/write payloads we should use. If the
3945// remote stub has a max packet size, stay under that size.
3946//
3947// If the remote stub's max packet size is crazy large, use a reasonable
3948// largeish default.
3949//
3950// If the remote stub doesn't advertise a max packet size, use a conservative
3951// default.
3952
3954 const uint64_t reasonable_largeish_default = 128 * 1024;
3955 const uint64_t conservative_default = 512;
3956
3957 if (m_max_memory_size == 0) {
3958 uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize();
3959 if (stub_max_size != UINT64_MAX && stub_max_size != 0) {
3960 // Save the stub's claimed maximum packet size
3961 m_remote_stub_max_memory_size = stub_max_size;
3962
3963 // Even if the stub says it can support ginormous packets, don't exceed
3964 // our reasonable largeish default packet size.
3965 if (stub_max_size > reasonable_largeish_default) {
3966 stub_max_size = reasonable_largeish_default;
3967 }
3968
3969 // Memory packet have other overheads too like Maddr,size:#NN Instead of
3970 // calculating the bytes taken by size and addr every time, we take a
3971 // maximum guess here.
3972 if (stub_max_size > 70)
3973 stub_max_size -= 32 + 32 + 6;
3974 else {
3975 // In unlikely scenario that max packet size is less then 70, we will
3976 // hope that data being written is small enough to fit.
3978 if (log)
3979 log->Warning("Packet size is too small. "
3980 "LLDB may face problems while writing memory");
3981 }
3982
3983 m_max_memory_size = stub_max_size;
3984 } else {
3985 m_max_memory_size = conservative_default;
3986 }
3987 }
3988}
3989
3991 uint64_t user_specified_max) {
3992 if (user_specified_max != 0) {
3994
3996 if (m_remote_stub_max_memory_size < user_specified_max) {
3998 // packet size too
3999 // big, go as big
4000 // as the remote stub says we can go.
4001 } else {
4002 m_max_memory_size = user_specified_max; // user's packet size is good
4003 }
4004 } else {
4006 user_specified_max; // user's packet size is probably fine
4007 }
4008 }
4009}
4010
4011bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec,
4012 const ArchSpec &arch,
4013 ModuleSpec &module_spec) {
4015
4016 const ModuleCacheKey key(module_file_spec.GetPath(),
4017 arch.GetTriple().getTriple());
4018 auto cached = m_cached_module_specs.find(key);
4019 if (cached != m_cached_module_specs.end()) {
4020 module_spec = cached->second;
4021 return bool(module_spec);
4022 }
4023
4024 if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) {
4025 LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s",
4026 __FUNCTION__, module_file_spec.GetPath().c_str(),
4027 arch.GetTriple().getTriple().c_str());
4028 return false;
4029 }
4030
4031 if (log) {
4032 StreamString stream;
4033 module_spec.Dump(stream);
4034 LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s",
4035 __FUNCTION__, module_file_spec.GetPath().c_str(),
4036 arch.GetTriple().getTriple().c_str(), stream.GetData());
4037 }
4038
4039 m_cached_module_specs[key] = module_spec;
4040 return true;
4041}
4042
4044 llvm::ArrayRef<FileSpec> module_file_specs, const llvm::Triple &triple) {
4045 auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple);
4046 if (module_specs) {
4047 for (const FileSpec &spec : module_file_specs)
4049 triple.getTriple())] = ModuleSpec();
4050 for (const ModuleSpec &spec : *module_specs)
4051 m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(),
4052 triple.getTriple())] = spec;
4053 }
4054}
4055
4057 return m_gdb_comm.GetOSVersion();
4058}
4059
4062}
4063
4064namespace {
4065
4066typedef std::vector<std::string> stringVec;
4067
4068typedef std::vector<struct GdbServerRegisterInfo> GDBServerRegisterVec;
4069struct RegisterSetInfo {
4070 ConstString name;
4071};
4072
4073typedef std::map<uint32_t, RegisterSetInfo> RegisterSetMap;
4074
4075struct GdbServerTargetInfo {
4076 std::string arch;
4077 std::string osabi;
4078 stringVec includes;
4079 RegisterSetMap reg_set_map;
4080};
4081
4082static std::vector<RegisterFlags::Field> ParseFlagsFields(XMLNode flags_node,
4083 unsigned size) {
4084 Log *log(GetLog(GDBRLog::Process));
4085 const unsigned max_start_bit = size * 8 - 1;
4086
4087 // Process the fields of this set of flags.
4088 std::vector<RegisterFlags::Field> fields;
4089 flags_node.ForEachChildElementWithName("field", [&fields, max_start_bit,
4090 &log](const XMLNode
4091 &field_node) {
4092 std::optional<llvm::StringRef> name;
4093 std::optional<unsigned> start;
4094 std::optional<unsigned> end;
4095
4096 field_node.ForEachAttribute([&name, &start, &end, max_start_bit,
4097 &log](const llvm::StringRef &attr_name,
4098 const llvm::StringRef &attr_value) {
4099 // Note that XML in general requires that each of these attributes only
4100 // appears once, so we don't have to handle that here.
4101 if (attr_name == "name") {
4102 LLDB_LOG(log,
4103 "ProcessGDBRemote::ParseFlags Found field node name \"{0}\"",
4104 attr_value.data());
4105 name = attr_value;
4106 } else if (attr_name == "start") {
4107 unsigned parsed_start = 0;
4108 if (llvm::to_integer(attr_value, parsed_start)) {
4109 if (parsed_start > max_start_bit) {
4110 LLDB_LOG(
4111 log,
4112 "ProcessGDBRemote::ParseFlags Invalid start {0} in field node, "
4113 "cannot be > {1}",
4114 parsed_start, max_start_bit);
4115 } else
4116 start = parsed_start;
4117 } else {
4118 LLDB_LOG(log,
4119 "ProcessGDBRemote::ParseFlags Invalid start \"{0}\" in "
4120 "field node",
4121 attr_value.data());
4122 }
4123 } else if (attr_name == "end") {
4124 unsigned parsed_end = 0;
4125 if (llvm::to_integer(attr_value, parsed_end))
4126 if (parsed_end > max_start_bit) {
4127 LLDB_LOG(
4128 log,
4129 "ProcessGDBRemote::ParseFlags Invalid end {0} in field node, "
4130 "cannot be > {1}",
4131 parsed_end, max_start_bit);
4132 } else
4133 end = parsed_end;
4134 else {
4135 LLDB_LOG(
4136 log,
4137 "ProcessGDBRemote::ParseFlags Invalid end \"{0}\" in field node",
4138 attr_value.data());
4139 }
4140 } else if (attr_name == "type") {
4141 // Type is a known attribute but we do not currently use it and it is
4142 // not required.
4143 } else {
4144 LLDB_LOG(log,
4145 "ProcessGDBRemote::ParseFlags Ignoring unknown attribute "
4146 "\"{0}\" in field node",
4147 attr_name.data());
4148 }
4149
4150 return true; // Walk all attributes of the field.
4151 });
4152
4153 if (name && start && end) {
4154 if (*start > *end) {
4155 LLDB_LOG(log,
4156 "ProcessGDBRemote::ParseFlags Start {0} > end {1} in field "
4157 "\"{2}\", ignoring",
4158 *start, *end, name->data());
4159 } else {
4160 fields.push_back(RegisterFlags::Field(name->str(), *start, *end));
4161 }
4162 }
4163
4164 return true; // Iterate all "field" nodes.
4165 });
4166 return fields;
4167}
4168
4169void ParseFlags(
4170 XMLNode feature_node,
4171 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types) {
4172 Log *log(GetLog(GDBRLog::Process));
4173
4174 feature_node.ForEachChildElementWithName(
4175 "flags",
4176 [&log, &registers_flags_types](const XMLNode &flags_node) -> bool {
4177 LLDB_LOG(log, "ProcessGDBRemote::ParseFlags Found flags node \"{0}\"",
4178 flags_node.GetAttributeValue("id").c_str());
4179
4180 std::optional<llvm::StringRef> id;
4181 std::optional<unsigned> size;
4182 flags_node.ForEachAttribute(
4183 [&id, &size, &log](const llvm::StringRef &name,
4184 const llvm::StringRef &value) {
4185 if (name == "id") {
4186 id = value;
4187 } else if (name == "size") {
4188 unsigned parsed_size = 0;
4189 if (llvm::to_integer(value, parsed_size))
4190 size = parsed_size;
4191 else {
4192 LLDB_LOG(log,
4193 "ProcessGDBRemote::ParseFlags Invalid size \"{0}\" "
4194 "in flags node",
4195 value.data());
4196 }
4197 } else {
4198 LLDB_LOG(log,
4199 "ProcessGDBRemote::ParseFlags Ignoring unknown "
4200 "attribute \"{0}\" in flags node",
4201 name.data());
4202 }
4203 return true; // Walk all attributes.
4204 });
4205
4206 if (id && size) {
4207 // Process the fields of this set of flags.
4208 std::vector<RegisterFlags::Field> fields =
4209 ParseFlagsFields(flags_node, *size);
4210 if (fields.size()) {
4211 // Sort so that the fields with the MSBs are first.
4212 std::sort(fields.rbegin(), fields.rend());
4213 std::vector<RegisterFlags::Field>::const_iterator overlap =
4214 std::adjacent_find(fields.begin(), fields.end(),
4215 [](const RegisterFlags::Field &lhs,
4216 const RegisterFlags::Field &rhs) {
4217 return lhs.Overlaps(rhs);
4218 });
4219
4220 // If no fields overlap, use them.
4221 if (overlap == fields.end()) {
4222 if (registers_flags_types.contains(*id)) {
4223 // In theory you could define some flag set, use it with a
4224 // register then redefine it. We do not know if anyone does
4225 // that, or what they would expect to happen in that case.
4226 //
4227 // LLDB chooses to take the first definition and ignore the rest
4228 // as waiting until everything has been processed is more
4229 // expensive and difficult. This means that pointers to flag
4230 // sets in the register info remain valid if later the flag set
4231 // is redefined. If we allowed redefinitions, LLDB would crash
4232 // when you tried to print a register that used the original
4233 // definition.
4234 LLDB_LOG(
4235 log,
4236 "ProcessGDBRemote::ParseFlags Definition of flags "
4237 "\"{0}\" shadows "
4238 "previous definition, using original definition instead.",
4239 id->data());
4240 } else {
4241 registers_flags_types.insert_or_assign(
4242 *id, std::make_unique<RegisterFlags>(id->str(), *size,
4243 std::move(fields)));
4244 }
4245 } else {
4246 // If any fields overlap, ignore the whole set of flags.
4247 std::vector<RegisterFlags::Field>::const_iterator next =
4248 std::next(overlap);
4249 LLDB_LOG(
4250 log,
4251 "ProcessGDBRemote::ParseFlags Ignoring flags because fields "
4252 "{0} (start: {1} end: {2}) and {3} (start: {4} end: {5}) "
4253 "overlap.",
4254 overlap->GetName().c_str(), overlap->GetStart(),
4255 overlap->GetEnd(), next->GetName().c_str(), next->GetStart(),
4256 next->GetEnd());
4257 }
4258 } else {
4259 LLDB_LOG(
4260 log,
4261 "ProcessGDBRemote::ParseFlags Ignoring definition of flags "
4262 "\"{0}\" because it contains no fields.",
4263 id->data());
4264 }
4265 }
4266
4267 return true; // Keep iterating through all "flags" elements.
4268 });
4269}
4270
4271bool ParseRegisters(
4272 XMLNode feature_node, GdbServerTargetInfo &target_info,
4273 std::vector<DynamicRegisterInfo::Register> &registers,
4274 llvm::StringMap<std::unique_ptr<RegisterFlags>> &registers_flags_types) {
4275 if (!feature_node)
4276 return false;
4277
4278 Log *log(GetLog(GDBRLog::Process));
4279
4280 ParseFlags(feature_node, registers_flags_types);
4281 for (const auto &flags : registers_flags_types)
4282 flags.second->log(log);
4283
4284 feature_node.ForEachChildElementWithName(
4285 "reg",
4286 [&target_info, &registers, &registers_flags_types,
4287 log](const XMLNode &reg_node) -> bool {
4288 std::string gdb_group;
4289 std::string gdb_type;
4291 bool encoding_set = false;
4292 bool format_set = false;
4293
4294 // FIXME: we're silently ignoring invalid data here
4295 reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type,
4296 &encoding_set, &format_set, &reg_info,
4297 log](const llvm::StringRef &name,
4298 const llvm::StringRef &value) -> bool {
4299 if (name == "name") {
4300 reg_info.name.SetString(value);
4301 } else if (name == "bitsize") {
4302 if (llvm::to_integer(value, reg_info.byte_size))
4303 reg_info.byte_size =
4304 llvm::divideCeil(reg_info.byte_size, CHAR_BIT);
4305 } else if (name == "type") {
4306 gdb_type = value.str();
4307 } else if (name == "group") {
4308 gdb_group = value.str();
4309 } else if (name == "regnum") {
4310 llvm::to_integer(value, reg_info.regnum_remote);
4311 } else if (name == "offset") {
4312 llvm::to_integer(value, reg_info.byte_offset);
4313 } else if (name == "altname") {
4314 reg_info.alt_name.SetString(value);
4315 } else if (name == "encoding") {
4316 encoding_set = true;
4318 } else if (name == "format") {
4319 format_set = true;
4320 if (!OptionArgParser::ToFormat(value.data(), reg_info.format,
4321 nullptr)
4322 .Success())
4323 reg_info.format =
4324 llvm::StringSwitch<lldb::Format>(value)
4325 .Case("vector-sint8", eFormatVectorOfSInt8)
4326 .Case("vector-uint8", eFormatVectorOfUInt8)
4327 .Case("vector-sint16", eFormatVectorOfSInt16)
4328 .Case("vector-uint16", eFormatVectorOfUInt16)
4329 .Case("vector-sint32", eFormatVectorOfSInt32)
4330 .Case("vector-uint32", eFormatVectorOfUInt32)
4331 .Case("vector-float32", eFormatVectorOfFloat32)
4332 .Case("vector-uint64", eFormatVectorOfUInt64)
4333 .Case("vector-uint128", eFormatVectorOfUInt128)
4334 .Default(eFormatInvalid);
4335 } else if (name == "group_id") {
4336 uint32_t set_id = UINT32_MAX;
4337 llvm::to_integer(value, set_id);
4338 RegisterSetMap::const_iterator pos =
4339 target_info.reg_set_map.find(set_id);
4340 if (pos != target_info.reg_set_map.end())
4341 reg_info.set_name = pos->second.name;
4342 } else if (name == "gcc_regnum" || name == "ehframe_regnum") {
4343 llvm::to_integer(value, reg_info.regnum_ehframe);
4344 } else if (name == "dwarf_regnum") {
4345 llvm::to_integer(value, reg_info.regnum_dwarf);
4346 } else if (name == "generic") {
4348 } else if (name == "value_regnums") {
4350 0);
4351 } else if (name == "invalidate_regnums") {
4353 value, reg_info.invalidate_regs, 0);
4354 } else {
4355 LLDB_LOGF(log,
4356 "ProcessGDBRemote::ParseRegisters unhandled reg "
4357 "attribute %s = %s",
4358 name.data(), value.data());
4359 }
4360 return true; // Keep iterating through all attributes
4361 });
4362
4363 if (!gdb_type.empty()) {
4364 // gdb_type could reference some flags type defined in XML.
4365 llvm::StringMap<std::unique_ptr<RegisterFlags>>::iterator it =
4366 registers_flags_types.find(gdb_type);
4367 if (it != registers_flags_types.end()) {
4368 auto flags_type = it->second.get();
4369 if (reg_info.byte_size == flags_type->GetSize())
4370 reg_info.flags_type = flags_type;
4371 else
4372 LLDB_LOGF(log,
4373 "ProcessGDBRemote::ParseRegisters Size of register "
4374 "flags %s (%d bytes) for "
4375 "register %s does not match the register size (%d "
4376 "bytes). Ignoring this set of flags.",
4377 flags_type->GetID().c_str(), flags_type->GetSize(),
4378 reg_info.name.AsCString(), reg_info.byte_size);
4379 }
4380
4381 // There's a slim chance that the gdb_type name is both a flags type
4382 // and a simple type. Just in case, look for that too (setting both
4383 // does no harm).
4384 if (!gdb_type.empty() && !(encoding_set || format_set)) {
4385 if (llvm::StringRef(gdb_type).startswith("int")) {
4386 reg_info.format = eFormatHex;
4387 reg_info.encoding = eEncodingUint;
4388 } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") {
4389 reg_info.format = eFormatAddressInfo;
4390 reg_info.encoding = eEncodingUint;
4391 } else if (gdb_type == "float") {
4392 reg_info.format = eFormatFloat;
4393 reg_info.encoding = eEncodingIEEE754;
4394 } else if (gdb_type == "aarch64v" ||
4395 llvm::StringRef(gdb_type).startswith("vec") ||
4396 gdb_type == "i387_ext" || gdb_type == "uint128") {
4397 // lldb doesn't handle 128-bit uints correctly (for ymm*h), so
4398 // treat them as vector (similarly to xmm/ymm)
4399 reg_info.format = eFormatVectorOfUInt8;
4400 reg_info.encoding = eEncodingVector;
4401 } else {
4402 LLDB_LOGF(
4403 log,
4404 "ProcessGDBRemote::ParseRegisters Could not determine lldb"
4405 "format and encoding for gdb type %s",
4406 gdb_type.c_str());
4407 }
4408 }
4409 }
4410
4411 // Only update the register set name if we didn't get a "reg_set"
4412 // attribute. "set_name" will be empty if we didn't have a "reg_set"
4413 // attribute.
4414 if (!reg_info.set_name) {
4415 if (!gdb_group.empty()) {
4416 reg_info.set_name.SetCString(gdb_group.c_str());
4417 } else {
4418 // If no register group name provided anywhere,
4419 // we'll create a 'general' register set
4420 reg_info.set_name.SetCString("general");
4421 }
4422 }
4423
4424 if (reg_info.byte_size == 0) {
4425 LLDB_LOGF(log,
4426 "ProcessGDBRemote::%s Skipping zero bitsize register %s",
4427 __FUNCTION__, reg_info.name.AsCString());
4428 } else
4429 registers.push_back(reg_info);
4430
4431 return true; // Keep iterating through all "reg" elements
4432 });
4433 return true;
4434}
4435
4436} // namespace
4437
4438// This method fetches a register description feature xml file from
4439// the remote stub and adds registers/register groupsets/architecture
4440// information to the current process. It will call itself recursively
4441// for nested register definition files. It returns true if it was able
4442// to fetch and parse an xml file.
4444 ArchSpec &arch_to_use, std::string xml_filename,
4445 std::vector<DynamicRegisterInfo::Register> &registers) {
4446 // request the target xml file
4447 llvm::Expected<std::string> raw = m_gdb_comm.ReadExtFeature("features", xml_filename);
4448 if (errorToBool(raw.takeError()))
4449 return false;
4450
4451 XMLDocument xml_document;
4452
4453 if (xml_document.ParseMemory(raw->c_str(), raw->size(),
4454 xml_filename.c_str())) {
4455 GdbServerTargetInfo target_info;
4456 std::vector<XMLNode> feature_nodes;
4457
4458 // The top level feature XML file will start with a <target> tag.
4459 XMLNode target_node = xml_document.GetRootElement("target");
4460 if (target_node) {
4461 target_node.ForEachChildElement([&target_info, &feature_nodes](
4462 const XMLNode &node) -> bool {
4463 llvm::StringRef name = node.GetName();
4464 if (name == "architecture") {
4465 node.GetElementText(target_info.arch);
4466 } else if (name == "osabi") {
4467 node.GetElementText(target_info.osabi);
4468 } else if (name == "xi:include" || name == "include") {
4469 std::string href = node.GetAttributeValue("href");
4470 if (!href.empty())
4471 target_info.includes.push_back(href);
4472 } else if (name == "feature") {
4473 feature_nodes.push_back(node);
4474 } else if (name == "groups") {
4476 "group", [&target_info](const XMLNode &node) -> bool {
4477 uint32_t set_id = UINT32_MAX;
4478 RegisterSetInfo set_info;
4479
4480 node.ForEachAttribute(
4481 [&set_id, &set_info](const llvm::StringRef &name,
4482 const llvm::StringRef &value) -> bool {
4483 // FIXME: we're silently ignoring invalid data here
4484 if (name == "id")
4485 llvm::to_integer(value, set_id);
4486 if (name == "name")
4487 set_info.name = ConstString(value);
4488 return true; // Keep iterating through all attributes
4489 });
4490
4491 if (set_id != UINT32_MAX)
4492 target_info.reg_set_map[set_id] = set_info;
4493 return true; // Keep iterating through all "group" elements
4494 });
4495 }
4496 return true; // Keep iterating through all children of the target_node
4497 });
4498 } else {
4499 // In an included XML feature file, we're already "inside" the <target>
4500 // tag of the initial XML file; this included file will likely only have
4501 // a <feature> tag. Need to check for any more included files in this
4502 // <feature> element.
4503 XMLNode feature_node = xml_document.GetRootElement("feature");
4504 if (feature_node) {
4505 feature_nodes.push_back(feature_node);
4506 feature_node.ForEachChildElement([&target_info](
4507 const XMLNode &node) -> bool {
4508 llvm::StringRef name = node.GetName();
4509 if (name == "xi:include" || name == "include") {
4510 std::string href = node.GetAttributeValue("href");
4511 if (!href.empty())
4512 target_info.includes.push_back(href);
4513 }
4514 return true;
4515 });
4516 }
4517 }
4518
4519 // gdbserver does not implement the LLDB packets used to determine host
4520 // or process architecture. If that is the case, attempt to use
4521 // the <architecture/> field from target.xml, e.g.:
4522 //
4523 // <architecture>i386:x86-64</architecture> (seen from VMWare ESXi)
4524 // <architecture>arm</architecture> (seen from Segger JLink on unspecified
4525 // arm board)
4526 if (!arch_to_use.IsValid() && !target_info.arch.empty()) {
4527 // We don't have any information about vendor or OS.
4528 arch_to_use.SetTriple(llvm::StringSwitch<std::string>(target_info.arch)
4529 .Case("i386:x86-64", "x86_64")
4530 .Default(target_info.arch) +
4531 "--");
4532
4533 if (arch_to_use.IsValid())
4534 GetTarget().MergeArchitecture(arch_to_use);
4535 }
4536
4537 if (arch_to_use.IsValid()) {
4538 for (auto &feature_node : feature_nodes) {
4539 ParseRegisters(feature_node, target_info, registers,
4541 }
4542
4543 for (const auto &include : target_info.includes) {
4544 GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include,
4545 registers);
4546 }
4547 }
4548 } else {
4549 return false;
4550 }
4551 return true;
4552}
4553
4555 std::vector<DynamicRegisterInfo::Register> &registers,
4556 const ArchSpec &arch_to_use) {
4557 std::map<uint32_t, uint32_t> remote_to_local_map;
4558 uint32_t remote_regnum = 0;
4559 for (auto it : llvm::enumerate(registers)) {
4560 DynamicRegisterInfo::Register &remote_reg_info = it.value();
4561
4562 // Assign successive remote regnums if missing.
4563 if (remote_reg_info.regnum_remote == LLDB_INVALID_REGNUM)
4564 remote_reg_info.regnum_remote = remote_regnum;
4565
4566 // Create a mapping from remote to local regnos.
4567 remote_to_local_map[remote_reg_info.regnum_remote] = it.index();
4568
4569 remote_regnum = remote_reg_info.regnum_remote + 1;
4570 }
4571
4572 for (DynamicRegisterInfo::Register &remote_reg_info : registers) {
4573 auto proc_to_lldb = [&remote_to_local_map](uint32_t process_regnum) {
4574 auto lldb_regit = remote_to_local_map.find(process_regnum);
4575 return lldb_regit != remote_to_local_map.end() ? lldb_regit->second
4577 };
4578
4579 llvm::transform(remote_reg_info.value_regs,
4580 remote_reg_info.value_regs.begin(), proc_to_lldb);
4581 llvm::transform(remote_reg_info.invalidate_regs,
4582 remote_reg_info.invalidate_regs.begin(), proc_to_lldb);
4583 }
4584
4585 // Don't use Process::GetABI, this code gets called from DidAttach, and
4586 // in that context we haven't set the Target's architecture yet, so the
4587 // ABI is also potentially incorrect.
4588 if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use))
4589 abi_sp->AugmentRegisterInfo(registers);
4590
4591 m_register_info_sp->SetRegisterInfo(std::move(registers), arch_to_use);
4592}
4593
4594// query the target of gdb-remote for extended target information returns
4595// true on success (got register definitions), false on failure (did not).
4597 // Make sure LLDB has an XML parser it can use first
4599 return false;
4600
4601 // check that we have extended feature read support
4603 return false;
4604
4605 // This holds register flags information for the whole of target.xml.
4606 // target.xml may include further documents that
4607 // GetGDBServerRegisterInfoXMLAndProcess will recurse to fetch and process.
4608 // That's why we clear the cache here, and not in
4609 // GetGDBServerRegisterInfoXMLAndProcess. To prevent it being cleared on every
4610 // include read.
4612 std::vector<DynamicRegisterInfo::Register> registers;
4613 if (GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, "target.xml",
4614 registers))
4615 AddRemoteRegisters(registers, arch_to_use);
4616
4617 return m_register_info_sp->GetNumRegisters() > 0;
4618}
4619
4620llvm::Expected<LoadedModuleInfoList> ProcessGDBRemote::GetLoadedModuleList() {
4621 // Make sure LLDB has an XML parser it can use first
4623 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4624 "XML parsing not available");
4625
4626 Log *log = GetLog(LLDBLog::Process);
4627 LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__);
4628
4631 bool can_use_svr4 = GetGlobalPluginProperties().GetUseSVR4();
4632
4633 // check that we have extended feature read support
4634 if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) {
4635 // request the loaded library list
4636 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries-svr4", "");
4637 if (!raw)
4638 return raw.takeError();
4639
4640 // parse the xml file in memory
4641 LLDB_LOGF(log, "parsing: %s", raw->c_str());
4642 XMLDocument doc;
4643
4644 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4645 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4646 "Error reading noname.xml");
4647
4648 XMLNode root_element = doc.GetRootElement("library-list-svr4");
4649 if (!root_element)
4650 return llvm::createStringError(
4651 llvm::inconvertibleErrorCode(),
4652 "Error finding library-list-svr4 xml element");
4653
4654 // main link map structure
4655 std::string main_lm = root_element.GetAttributeValue("main-lm");
4656 // FIXME: we're silently ignoring invalid data here
4657 if (!main_lm.empty())
4658 llvm::to_integer(main_lm, list.m_link_map);
4659
4660 root_element.ForEachChildElementWithName(
4661 "library", [log, &list](const XMLNode &library) -> bool {
4663
4664 // FIXME: we're silently ignoring invalid data here
4665 library.ForEachAttribute(
4666 [&module](const llvm::StringRef &name,
4667 const llvm::StringRef &value) -> bool {
4668 uint64_t uint_value = LLDB_INVALID_ADDRESS;
4669 if (name == "name")
4670 module.set_name(value.str());
4671 else if (name == "lm") {
4672 // the address of the link_map struct.
4673 llvm::to_integer(value, uint_value);
4674 module.set_link_map(uint_value);
4675 } else if (name == "l_addr") {
4676 // the displacement as read from the field 'l_addr' of the
4677 // link_map struct.
4678 llvm::to_integer(value, uint_value);
4679 module.set_base(uint_value);
4680 // base address is always a displacement, not an absolute
4681 // value.
4682 module.set_base_is_offset(true);
4683 } else if (name == "l_ld") {
4684 // the memory address of the libraries PT_DYNAMIC section.
4685 llvm::to_integer(value, uint_value);
4686 module.set_dynamic(uint_value);
4687 }
4688
4689 return true; // Keep iterating over all properties of "library"
4690 });
4691
4692 if (log) {
4693 std::string name;
4694 lldb::addr_t lm = 0, base = 0, ld = 0;
4695 bool base_is_offset;
4696
4697 module.get_name(name);
4698 module.get_link_map(lm);
4699 module.get_base(base);
4700 module.get_base_is_offset(base_is_offset);
4701 module.get_dynamic(ld);
4702
4703 LLDB_LOGF(log,
4704 "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64
4705 "[%s], ld:0x%08" PRIx64 ", name:'%s')",
4706 lm, base, (base_is_offset ? "offset" : "absolute"), ld,
4707 name.c_str());
4708 }
4709
4710 list.add(module);
4711 return true; // Keep iterating over all "library" elements in the root
4712 // node
4713 });
4714
4715 if (log)
4716 LLDB_LOGF(log, "found %" PRId32 " modules in total",
4717 (int)list.m_list.size());
4718 return list;
4719 } else if (comm.GetQXferLibrariesReadSupported()) {
4720 // request the loaded library list
4721 llvm::Expected<std::string> raw = comm.ReadExtFeature("libraries", "");
4722
4723 if (!raw)
4724 return raw.takeError();
4725
4726 LLDB_LOGF(log, "parsing: %s", raw->c_str());
4727 XMLDocument doc;
4728
4729 if (!doc.ParseMemory(raw->c_str(), raw->size(), "noname.xml"))
4730 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4731 "Error reading noname.xml");
4732
4733 XMLNode root_element = doc.GetRootElement("library-list");
4734 if (!root_element)
4735 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4736 "Error finding library-list xml element");
4737
4738 // FIXME: we're silently ignoring invalid data here
4739 root_element.ForEachChildElementWithName(
4740 "library", [log, &list](const XMLNode &library) -> bool {
4742
4743 std::string name = library.GetAttributeValue("name");
4744 module.set_name(name);
4745
4746 // The base address of a given library will be the address of its
4747 // first section. Most remotes send only one section for Windows
4748 // targets for example.
4749 const XMLNode &section =
4750 library.FindFirstChildElementWithName("section");
4751 std::string address = section.GetAttributeValue("address");
4752 uint64_t address_value = LLDB_INVALID_ADDRESS;
4753 llvm::to_integer(address, address_value);
4754 module.set_base(address_value);
4755 // These addresses are absolute values.
4756 module.set_base_is_offset(false);
4757
4758 if (log) {
4759 std::string name;
4760 lldb::addr_t base = 0;
4761 bool base_is_offset;
4762 module.get_name(name);
4763 module.get_base(base);
4764 module.get_base_is_offset(base_is_offset);
4765
4766 LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base,
4767 (base_is_offset ? "offset" : "absolute"), name.c_str());
4768 }
4769
4770 list.add(module);
4771 return true; // Keep iterating over all "library" elements in the root
4772 // node
4773 });
4774
4775 if (log)
4776 LLDB_LOGF(log, "found %" PRId32 " modules in total",
4777 (int)list.m_list.size());
4778 return list;
4779 } else {
4780 return llvm::createStringError(llvm::inconvertibleErrorCode(),
4781 "Remote libraries not supported");
4782 }
4783}
4784
4786 lldb::addr_t link_map,
4787 lldb::addr_t base_addr,
4788 bool value_is_offset) {
4789 DynamicLoader *loader = GetDynamicLoader();
4790 if (!loader)
4791 return nullptr;
4792
4793 return loader->LoadModuleAtAddress(file, link_map, base_addr,
4794 value_is_offset);
4795}
4796
4799
4800 // request a list of loaded libraries from GDBServer
4801 llvm::Expected<LoadedModuleInfoList> module_list = GetLoadedModuleList();
4802 if (!module_list)
4803 return module_list.takeError();
4804
4805 // get a list of all the modules
4806 ModuleList new_modules;
4807
4808 for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) {
4809 std::string mod_name;
4810 lldb::addr_t mod_base;
4811 lldb::addr_t link_map;
4812 bool mod_base_is_offset;
4813
4814 bool valid = true;
4815 valid &= modInfo.get_name(mod_name);
4816 valid &= modInfo.get_base(mod_base);
4817 valid &= modInfo.get_base_is_offset(mod_base_is_offset);
4818 if (!valid)
4819 continue;
4820
4821 if (!modInfo.get_link_map(link_map))
4822 link_map = LLDB_INVALID_ADDRESS;
4823
4824 FileSpec file(mod_name);
4826 lldb::ModuleSP module_sp =
4827 LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset);
4828
4829 if (module_sp.get())
4830 new_modules.Append(module_sp);
4831 }
4832
4833 if (new_modules.GetSize() > 0) {
4834 ModuleList removed_modules;
4835 Target &target = GetTarget();
4836 ModuleList &loaded_modules = m_process->GetTarget().GetImages();
4837
4838 for (size_t i = 0; i < loaded_modules.GetSize(); ++i) {
4839 const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i);
4840
4841 bool found = false;
4842 for (size_t j = 0; j < new_modules.GetSize(); ++j) {
4843 if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get())
4844 found = true;
4845 }
4846
4847 // The main executable will never be included in libraries-svr4, don't
4848 // remove it
4849 if (!found &&
4850 loaded_module.get() != target.GetExecutableModulePointer()) {
4851 removed_modules.Append(loaded_module);
4852 }
4853 }
4854
4855 loaded_modules.Remove(removed_modules);
4856 m_process->GetTarget().ModulesDidUnload(removed_modules, false);
4857
4858 new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool {
4859 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
4860 if (!obj)
4861 return true;
4862
4864 return true;
4865
4866 lldb::ModuleSP module_copy_sp = module_sp;
4867 target.SetExecutableModule(module_copy_sp, eLoadDependentsNo);
4868 return false;
4869 });
4870
4871 loaded_modules.AppendIfNeeded(new_modules);
4872 m_process->GetTarget().ModulesDidLoad(new_modules);
4873 }
4874
4875 return llvm::ErrorSuccess();
4876}
4877
4879 bool &is_loaded,
4880 lldb::addr_t &load_addr) {
4881 is_loaded = false;
4882 load_addr = LLDB_INVALID_ADDRESS;
4883
4884 std::string file_path = file.GetPath(false);
4885 if (file_path.empty())
<