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