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