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